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