]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
TR1: check in cmake for GCC version, fallback in checktr1.h for other build systems...
[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 bool is_terminal(io_channel channel)
421 {
422         switch (channel) {
423         case STDIN:
424                 if (GetStdHandle(STD_INPUT_HANDLE) == NULL)
425                         return false;
426                 break;
427         case STDOUT:
428                 if (GetStdHandle(STD_OUTPUT_HANDLE) == NULL)
429                         return false;
430                 break;
431         case STDERR:
432                 if (GetStdHandle(STD_ERROR_HANDLE) == NULL)
433                         return false;
434                 break;
435         }
436         return true;
437 }
438
439
440 shell_type shell()
441 {
442         return CMD_EXE;
443 }
444
445
446 char path_separator()
447 {
448         return ';';
449 }
450
451
452 void windows_style_tex_paths(bool use_windows_paths)
453 {
454         windows_style_tex_paths_ = use_windows_paths;
455 }
456
457
458 GetFolderPath::GetFolderPath()
459         : folder_module_(0),
460           folder_path_func_(0)
461 {
462         folder_module_ = LoadLibrary("shfolder.dll");
463         if (!folder_module_) {
464                 throw ExceptionMessage(ErrorException, _("System file not found"),
465                         _("Unable to load shfolder.dll\nPlease install."));
466         }
467
468         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
469         if (folder_path_func_ == 0) {
470                 throw ExceptionMessage(ErrorException, _("System function not found"),
471                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
472                           "Don't know how to proceed. Sorry."));
473         }
474 }
475
476
477 GetFolderPath::~GetFolderPath()
478 {
479         if (folder_module_)
480                 FreeLibrary(folder_module_);
481 }
482
483
484 // Given a folder ID, returns the folder name (in unix-style format).
485 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
486 string const GetFolderPath::operator()(folder_id _id) const
487 {
488         char folder_path[MAX_PATH];
489
490         int id = 0;
491         switch (_id) {
492         case PERSONAL:
493                 id = CSIDL_PERSONAL;
494                 break;
495         case APPDATA:
496                 id = CSIDL_APPDATA;
497                 break;
498         default:
499                 LASSERT(false, /**/);
500         }
501         HRESULT const result = (folder_path_func_)(0, id, 0,
502                                                    SHGFP_TYPE_CURRENT,
503                                                    folder_path);
504         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
505 }
506
507
508 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
509 {
510         if (ext.empty())
511                 return false;
512
513         string const full_ext = "." + ext;
514
515         DWORD bufSize = MAX_PATH + 100;
516         TCHAR buf[MAX_PATH + 100];
517         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
518         char const * action = (mode == VIEW) ? "open" : "edit";
519         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
520                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
521 }
522
523
524 bool autoOpenFile(string const & filename, auto_open_mode const mode)
525 {
526         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
527         char const * action = (mode == VIEW) ? "open" : "edit";
528         return reinterpret_cast<int>(ShellExecute(NULL, action,
529                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
530 }
531
532
533 string real_path(string const & path)
534 {
535         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
536         QString const qpath = get_long_path(toqstr(path));
537         HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
538                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
539
540         if (hpath == INVALID_HANDLE_VALUE) {
541                 // The file cannot be accessed.
542                 return path;
543         }
544
545         // Get the file size.
546         DWORD size_hi = 0;
547         DWORD size_lo = GetFileSize(hpath, &size_hi);
548
549         if (size_lo == 0 && size_hi == 0) {
550                 // A zero-length file cannot be mapped.
551                 CloseHandle(hpath);
552                 return path;
553         }
554
555         // Create a file mapping object.
556         HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
557
558         if (!hmap) {
559                 CloseHandle(hpath);
560                 return path;
561         }
562
563         // Create a file mapping to get the file name.
564         void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
565
566         if (!pmem) {
567                 CloseHandle(hmap);
568                 CloseHandle(hpath);
569                 return path;
570         }
571
572         TCHAR realpath[MAX_PATH + 1];
573
574         if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
575                 UnmapViewOfFile(pmem);
576                 CloseHandle(hmap);
577                 CloseHandle(hpath);
578                 return path;
579         }
580
581         // Translate device name to UNC prefix or drive letters.
582         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
583         UINT namelen = _tcslen(tmpbuf);
584         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
585                 // UNC path
586                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
587                 strncpy(realpath, tmpbuf, MAX_PATH);
588                 realpath[MAX_PATH] = '\0';
589         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
590                 // Check whether device name corresponds to some local drive.
591                 TCHAR name[MAX_PATH];
592                 TCHAR drive[3] = TEXT(" :");
593                 bool found = false;
594                 TCHAR * p = tmpbuf;
595                 do {
596                         // Copy the drive letter to the template string
597                         drive[0] = *p;
598                         // Look up each device name
599                         if (QueryDosDevice(drive, name, MAX_PATH)) {
600                                 namelen = _tcslen(name);
601                                 if (namelen < MAX_PATH) {
602                                         found = _tcsnicmp(realpath, name, namelen) == 0;
603                                         if (found) {
604                                                 // Repl. device spec with drive
605                                                 TCHAR tempfile[MAX_PATH];
606                                                 _snprintf(tempfile,
607                                                         MAX_PATH,
608                                                         "%s%s",
609                                                         drive,
610                                                         realpath + namelen);
611                                                 strncpy(realpath,
612                                                         tempfile,
613                                                         MAX_PATH);
614                                                 realpath[MAX_PATH] = '\0';
615                                         }
616                                 }
617                         }
618                         // Advance p to the next NULL character.
619                         while (*p++) ;
620                 } while (!found && *p);
621         }
622         UnmapViewOfFile(pmem);
623         CloseHandle(hmap);
624         CloseHandle(hpath);
625         string const retpath = subst(string(realpath), '\\', '/');
626         return FileName::fromFilesystemEncoding(retpath).absFileName();
627 }
628
629 } // namespace os
630 } // namespace support
631 } // namespace lyx