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