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