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