]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
Remove debugging code. Thanks Scott!
[lyx.git] / src / support / os_win32.cpp
1 /**
2  * \file os_win32.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Ruurd A. Reitsma
7  * \author Claus Hentschel
8  * \author Angus Leeming
9  * \author Enrico Forestieri
10  *
11  * Full author contact details are available in file CREDITS.
12  *
13  * Various OS specific functions
14  */
15
16 #include <config.h>
17
18 #include "LyXRC.h"
19
20 #include "support/os.h"
21 #include "support/os_win32.h"
22
23 #include "support/debug.h"
24 #include "support/environment.h"
25 #include "support/FileName.h"
26 #include "support/gettext.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/qstring_helpers.h"
31
32 #include "support/lassert.h"
33
34 #include <cstdlib>
35 #include <vector>
36
37 #include <QString>
38
39 #include <io.h>
40 #include <direct.h> // _getdrive
41 #include <fileapi.h> // GetFinalPathNameByHandle
42 #include <shlobj.h>  // SHGetFolderPath
43 #include <windef.h>
44 #include <shellapi.h>
45 #include <shlwapi.h>
46
47 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
48 #if defined(__MINGW32__)  || defined(__CYGWIN__) || defined(__CYGWIN32__)
49 # include <w32api.h>
50 # if __W32API_MAJOR_VERSION < 3 || \
51      __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION  < 2
52 #  define SHGFP_TYPE_CURRENT 0
53 # endif
54 #endif
55
56 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
57 #define ASSOCF_INIT_IGNOREUNKNOWN 0
58 #endif
59
60 #if defined(__MINGW32__)
61 #include <stdio.h>
62 #endif
63
64 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
65 #else
66 extern "C" {
67 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
68                            int expand_wildcards, int * new_mode);
69 }
70 #endif
71
72 using namespace std;
73
74 namespace lyx {
75
76 void lyx_exit(int);
77
78 namespace support {
79 namespace os {
80
81 namespace {
82
83 int argc_ = 0;
84 wchar_t ** argv_ = 0;
85
86 bool windows_style_tex_paths_ = true;
87
88 string cygdrive = "/cygdrive";
89
90 BOOL terminate_handler(DWORD event)
91 {
92         if (event == CTRL_CLOSE_EVENT
93             || event == CTRL_LOGOFF_EVENT
94             || event == CTRL_SHUTDOWN_EVENT) {
95                 lyx::lyx_exit(1);
96                 return TRUE;
97         }
98         return FALSE;
99 }
100
101 } // namespace
102
103 void init(int argc, char ** argv[])
104 {
105         /* Note from Angus, 17 Jan 2005:
106          *
107          * The code below is taken verbatim from Ruurd's original patch
108          * porting LyX to Win32.
109          *
110          * Windows allows us to define LyX either as a console-based app
111          * or as a GUI-based app. Ruurd decided to define LyX as a
112          * console-based app with a "main" function rather than a "WinMain"
113          * function as the point of entry to the program, but to
114          * immediately close the console window that Windows helpfully
115          * opens for us. Doing so allows the user to see all of LyX's
116          * debug output simply by running LyX from a DOS or MSYS-shell
117          * prompt.
118          *
119          * The alternative approach is to define LyX as a genuine
120          * GUI-based app, with a "WinMain" function as the entry point to the
121          * executable rather than a "main" function, so:
122          *
123          * #if defined (_WIN32)
124          * # define WIN32_LEAN_AND_MEAN
125          * # include <stdlib.h>  // for __argc, __argv
126          * # include <windows.h> // for WinMain
127          * #endif
128          *
129          * // This will require the "-mwindows" flag when linking with
130          * // gcc under MinGW.
131          * // For MSVC, use "/subsystem:windows".
132          * #if defined (_WIN32)
133          * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
134          * {
135          *     return mymain(__argc, __argv);
136          * }
137          * #endif
138          *
139          * where "mymain" is just a renamed "main".
140          *
141          * However, doing so means that the lyxerr messages would mysteriously
142          * disappear. They could be resurrected with something like:
143          *
144          * #ifdef WIN32
145          *  AllocConsole();
146          *  freopen("conin$","r",stdin);
147          *  freopen("conout$","w",stdout);
148          *  freopen("conout$","w",stderr);
149          * #endif
150          *
151          * This code could be invoked (say) the first time that lyxerr
152          * is called. However, Ruurd has tried this route and found that some
153          * shell scripts failed, for mysterious reasons...
154          *
155          * I've chosen for now, therefore, to simply add Ruurd's original
156          * code as-is. A wrapper program hidecmd.c has been added to
157          * development/Win32 which hides the console window of lyx when
158          * lyx is invoked as a parameter of hidecmd.exe.
159          */
160
161
162         // Remove PYTHONPATH from the environment as it may point to an
163         // external python installation and cause reconfigure failures.
164         unsetEnv("PYTHONPATH");
165
166
167 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
168         // Removing an argument from argv leads to an assertion on Windows
169         // when compiling with MSVC 2015 in debug mode (see bug #10440).
170         // To avoid this we make a copy of the array of pointers.
171         char ** newargv = (char **) malloc((argc + 1) * sizeof(char *));
172         if (newargv) {
173                 memcpy(newargv, *argv, (argc + 1) * sizeof(char *));
174                 *argv = newargv;
175         } else {
176                 lyxerr << "LyX warning: Cannot make a copy of "
177                           "command line arguments!"
178                        << endl;
179         }
180 #endif
181
182
183         // Get the wide program arguments array
184 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
185         argv_ = CommandLineToArgvW(GetCommandLineW(), &argc_);
186 #else
187         wchar_t ** envp = 0;
188         int newmode = 0;
189         __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
190 #endif
191         LATTEST(argc == argc_);
192
193         // If Cygwin is detected, query the cygdrive prefix.
194         // The cygdrive prefix is needed for translating windows style paths
195         // to posix style paths in LaTeX files when the Cygwin teTeX is used.
196         int i;
197         HKEY hkey;
198         char buf[MAX_PATH];
199         DWORD bufsize = sizeof(buf);
200         LONG retval = ERROR_FILE_NOT_FOUND;
201         HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
202         char const * const subkey[2] = {
203                 "Software\\Cygwin\\setup",                         // Cygwin 1.7
204                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
205         };
206         char const * const valuename[2] = {
207                 "rootdir", // Cygwin 1.7 or later
208                 "native"   // Previous versions
209         };
210         // Check for newer Cygwin versions first, then older ones
211         for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
212                 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
213                         retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
214         }
215         if (retval == ERROR_SUCCESS) {
216                 // Query the Cygwin root directory
217                 retval = RegQueryValueEx(hkey, valuename[i - 1],
218                                 NULL, NULL, (LPBYTE) buf, &bufsize);
219                 RegCloseKey(hkey);
220                 string const mount = string(buf) + "\\bin\\mount.exe";
221                 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
222                         cmd_ret const p =
223                                 runCommand(mount + " --show-cygdrive-prefix");
224                         // The output of the mount command is as follows:
225                         // Prefix              Type         Flags
226                         // /cygdrive           system       binmode
227                         // So, we use the inner split to pass the second line
228                         // to the outer split which sets cygdrive with its
229                         // contents until the first blank, discarding the
230                         // unneeded return value.
231                         if (p.first != -1 && prefixIs(p.second, "Prefix"))
232                                 split(split(p.second, '\n'), cygdrive, ' ');
233                 }
234         }
235
236         // Catch shutdown events.
237         SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
238 }
239
240
241 string utf8_argv(int i)
242 {
243         LASSERT(i < argc_, return "");
244         return fromqstr(QString::fromWCharArray(argv_[i]));
245 }
246
247
248 void remove_internal_args(int i, int num)
249 {
250         argc_ -= num;
251         for (int j = i; j < argc_; ++j)
252                 argv_[j] = argv_[j + num];
253 }
254
255
256 string current_root()
257 {
258         // _getdrive returns the current drive (1=A, 2=B, and so on).
259         char const drive = ::_getdrive() + 'A' - 1;
260         return string(1, drive) + ":/";
261 }
262
263
264 bool isFilesystemCaseSensitive()
265 {
266         return false;
267 }
268
269
270 docstring::size_type common_path(docstring const & p1, docstring const & p2)
271 {
272         size_t i = 0;
273         size_t const p1_len = p1.length();
274         size_t const p2_len = p2.length();
275         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
276                 ++i;
277         if ((i < p1_len && i < p2_len)
278             || (i < p1_len && p1[i] != '/' && i == p2_len)
279             || (i < p2_len && p2[i] != '/' && i == p1_len))
280         {
281                 if (i)
282                         --i;     // here was the last match
283                 while (i && p1[i] != '/')
284                         --i;
285         }
286         return i;
287 }
288
289
290 bool path_prefix_is(string const & path, string const & pre)
291 {
292         return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
293 }
294
295
296 bool path_prefix_is(string & path, string const & pre, path_case how)
297 {
298         docstring const p1 = from_utf8(path);
299         docstring const p2 = from_utf8(pre);
300         docstring::size_type const p1_len = p1.length();
301         docstring::size_type const p2_len = p2.length();
302         docstring::size_type common_len = common_path(p1, p2);
303
304         if (p2[p2_len - 1] == '/' && p1_len != p2_len)
305                 ++common_len;
306
307         if (common_len != p2_len)
308                 return false;
309
310         if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
311                 if (p1_len < common_len)
312                         path = to_utf8(p2.substr(0, p1_len));
313                 else
314                         path = to_utf8(p2 + p1.substr(common_len,
315                                                         p1_len - common_len));
316         }
317
318         return true;
319 }
320
321
322 string external_path(string const & p)
323 {
324         string const dos_path = subst(p, "/", "\\");
325
326         LYXERR(Debug::LATEX, "<Win32 path correction> ["
327                 << p << "]->>[" << dos_path << ']');
328         return dos_path;
329 }
330
331
332 static QString const get_long_path(QString const & short_path)
333 {
334         // GetLongPathNameW needs the path in utf16 encoding.
335         vector<wchar_t> long_path(MAX_PATH);
336         DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
337                                        &long_path[0], long_path.size());
338
339         if (result > long_path.size()) {
340                 long_path.resize(result);
341                 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
342                                          &long_path[0], long_path.size());
343                 LATTEST(result <= long_path.size());
344         }
345
346         return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
347 }
348
349
350 static QString const get_short_path(QString const & long_path, file_access how)
351 {
352         // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
353         if (how == CREATE) {
354                 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
355                                 GENERIC_WRITE, 0, NULL, CREATE_NEW,
356                                 FILE_ATTRIBUTE_NORMAL, NULL);
357                 if (h == INVALID_HANDLE_VALUE
358                     && GetLastError() != ERROR_FILE_EXISTS)
359                         return long_path;
360                 CloseHandle(h);
361         }
362         vector<wchar_t> short_path(MAX_PATH);
363         DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
364                                        &short_path[0], short_path.size());
365
366         if (result > short_path.size()) {
367                 short_path.resize(result);
368                 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
369                                          &short_path[0], short_path.size());
370                 LATTEST(result <= short_path.size());
371         }
372
373         return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
374 }
375
376
377 string internal_path(string const & p)
378 {
379         return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
380 }
381
382
383 string safe_internal_path(string const & p, file_access how)
384 {
385         return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
386 }
387
388
389 string external_path_list(string const & p)
390 {
391         return subst(p, '/', '\\');
392 }
393
394
395 string internal_path_list(string const & p)
396 {
397         return subst(p, '\\', '/');
398 }
399
400
401 string latex_path(string const & p)
402 {
403         // We may need a posix style path or a windows style path (depending
404         // on windows_style_tex_paths_), but we use always forward slashes,
405         // since it gets written into a .tex file.
406
407         if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
408                 string const drive = p.substr(0, 2);
409                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
410                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
411                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
412                         << p << "]->>[" << cygpath << ']');
413                 return cygpath;
414         }
415         return subst(p, '\\', '/');
416 }
417
418
419 string latex_path_list(string const & p)
420 {
421         if (p.empty())
422                 return p;
423
424         // We may need a posix style path or a windows style path (depending
425         // on windows_style_tex_paths_), but we use always forward slashes,
426         // since this is standard for all tex engines.
427
428         if (!windows_style_tex_paths_) {
429                 string pathlist;
430                 for (size_t i = 0, k = 0; i != string::npos; k = i) {
431                         i = p.find(';', i);
432                         string path = subst(p.substr(k, i - k), '\\', '/');
433                         if (FileName::isAbsolute(path)) {
434                                 string const drive = path.substr(0, 2);
435                                 string const cygprefix = cygdrive + "/"
436                                                         + drive.substr(0, 1);
437                                 path = subst(path, drive, cygprefix);
438                         }
439                         pathlist += path;
440                         if (i != string::npos) {
441                                 pathlist += ':';
442                                 ++i;
443                         }
444                 }
445                 return pathlist;
446         }
447         return subst(p, '\\', '/');
448 }
449
450
451 // returns a string suitable to be passed to popen when
452 // reading a pipe
453 char const * popen_read_mode()
454 {
455         return "r";
456 }
457
458
459 string const & nulldev()
460 {
461         static string const nulldev_ = "nul";
462         return nulldev_;
463 }
464
465
466 shell_type shell()
467 {
468         return CMD_EXE;
469 }
470
471
472 char path_separator(path_type type)
473 {
474         if (type == TEXENGINE)
475                 return windows_style_tex_paths_ ? ';' : ':';
476
477         return ';';
478 }
479
480
481 void windows_style_tex_paths(bool use_windows_paths)
482 {
483         windows_style_tex_paths_ = use_windows_paths;
484 }
485
486
487 GetFolderPath::GetFolderPath()
488         : folder_module_(0),
489           folder_path_func_(0)
490 {
491         folder_module_ = LoadLibrary("shfolder.dll");
492         if (!folder_module_) {
493                 throw ExceptionMessage(ErrorException, _("System file not found"),
494                         _("Unable to load shfolder.dll\nPlease install."));
495         }
496
497         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
498         if (folder_path_func_ == 0) {
499                 throw ExceptionMessage(ErrorException, _("System function not found"),
500                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
501                           "Don't know how to proceed. Sorry."));
502         }
503 }
504
505
506 GetFolderPath::~GetFolderPath()
507 {
508         if (folder_module_)
509                 FreeLibrary(folder_module_);
510 }
511
512
513 // Given a folder ID, returns the folder name (in unix-style format).
514 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
515 string const GetFolderPath::operator()(folder_id _id) const
516 {
517         char folder_path[MAX_PATH];
518
519         int id = 0;
520         switch (_id) {
521         case PERSONAL:
522                 id = CSIDL_PERSONAL;
523                 break;
524         case APPDATA:
525                 id = CSIDL_APPDATA;
526                 break;
527         default:
528                 LASSERT(false, return string());
529         }
530         HRESULT const result = (folder_path_func_)(0, id, 0,
531                                                    SHGFP_TYPE_CURRENT,
532                                                    folder_path);
533         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
534 }
535
536
537 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
538 {
539         if (ext.empty())
540                 return false;
541
542         string const full_ext = "." + ext;
543
544         DWORD bufSize = MAX_PATH + 100;
545         TCHAR buf[MAX_PATH + 100];
546         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
547         char const * action = (mode == VIEW) ? "open" : "edit";
548         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
549                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
550 }
551
552
553 bool autoOpenFile(string const & filename, auto_open_mode const mode,
554                   string const & path)
555 {
556         string const texinputs = os::latex_path_list(
557                         replaceCurdirPath(path, lyxrc.texinputs_prefix));
558         string const otherinputs = os::latex_path_list(path);
559         string const sep = windows_style_tex_paths_ ? ";" : ":";
560         string const oldtexinputs = getEnv("TEXINPUTS");
561         string const newtexinputs = "." + sep + texinputs + sep + oldtexinputs;
562         string const oldbibinputs = getEnv("BIBINPUTS");
563         string const newbibinputs = "." + sep + otherinputs + sep + oldbibinputs;
564         string const oldbstinputs = getEnv("BSTINPUTS");
565         string const newbstinputs = "." + sep + otherinputs + sep + oldbstinputs;
566         string const oldtexfonts = getEnv("TEXFONTS");
567         string const newtexfonts = "." + sep + otherinputs + sep + oldtexfonts;
568         if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
569                 setEnv("TEXINPUTS", newtexinputs);
570                 setEnv("BIBINPUTS", newbibinputs);
571                 setEnv("BSTINPUTS", newbstinputs);
572                 setEnv("TEXFONTS", newtexfonts);
573         }
574
575         QString const wname = toqstr(filename);
576
577         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
578         wchar_t const * action = (mode == VIEW) ? L"open" : L"edit";
579         bool success = reinterpret_cast<intptr_t>(ShellExecuteW(NULL, action,
580                         reinterpret_cast<wchar_t const *>(wname.utf16()),
581                         NULL, NULL, 1)) > 32;
582
583         if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
584                 setEnv("TEXINPUTS", oldtexinputs);
585                 setEnv("BIBINPUTS", oldbibinputs);
586                 setEnv("BSTINPUTS", oldbstinputs);
587                 setEnv("TEXFONTS", oldtexfonts);
588         }
589         return success;
590 }
591
592
593 string real_path(string const & path)
594 {
595         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
596         QString const qpath = get_long_path(toqstr(path));
597         HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
598                                 FILE_SHARE_READ, NULL, OPEN_EXISTING,
599                                 FILE_FLAG_BACKUP_SEMANTICS, NULL);
600
601         if (hpath == INVALID_HANDLE_VALUE) {
602                 // The file cannot be accessed.
603                 return path;
604         }
605
606         TCHAR realpath[MAX_PATH + 1];
607
608         DWORD size = GetFinalPathNameByHandle(hpath, realpath, MAX_PATH, VOLUME_NAME_NT);
609         if (size > MAX_PATH) {
610                 CloseHandle(hpath);
611                 return path;
612         }
613
614         // Translate device name to UNC prefix or drive letters.
615         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
616         UINT namelen = _tcslen(tmpbuf);
617         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
618                 // UNC path
619                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
620                 strncpy(realpath, tmpbuf, MAX_PATH);
621                 realpath[MAX_PATH] = '\0';
622         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
623                 // Check whether device name corresponds to some local drive.
624                 TCHAR name[MAX_PATH];
625                 TCHAR drive[3] = TEXT(" :");
626                 bool found = false;
627                 TCHAR * p = tmpbuf;
628                 do {
629                         // Copy the drive letter to the template string
630                         drive[0] = *p;
631                         // Look up each device name
632                         if (QueryDosDevice(drive, name, MAX_PATH)) {
633                                 namelen = _tcslen(name);
634                                 if (namelen < MAX_PATH) {
635                                         found = _tcsnicmp(realpath, name, namelen) == 0;
636                                         if (found) {
637                                                 // Repl. device spec with drive
638                                                 TCHAR tempfile[MAX_PATH];
639                                                 _snprintf(tempfile,
640                                                         MAX_PATH,
641                                                         "%s%s",
642                                                         drive,
643                                                         realpath + namelen);
644                                                 strncpy(realpath,
645                                                         tempfile,
646                                                         MAX_PATH);
647                                                 realpath[MAX_PATH] = '\0';
648                                         }
649                                 }
650                         }
651                         // Advance p to the next NULL character.
652                         while (*p++) ;
653                 } while (!found && *p);
654         }
655         CloseHandle(hpath);
656         string const retpath = subst(string(realpath), '\\', '/');
657         return FileName::fromFilesystemEncoding(retpath).absFileName();
658 }
659
660 } // namespace os
661 } // namespace support
662 } // namespace lyx