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