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