]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
60c5915d09c67aa101a2a595d83c36798e7160e0
[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, file_access how)
284 {
285         // CreateFileW and GetShortPathNameW needs the path in utf16 encoding.
286         if (how == CREATE) {
287                 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
288                                 GENERIC_WRITE, 0, NULL, CREATE_NEW,
289                                 FILE_ATTRIBUTE_NORMAL, NULL);
290                 if (h == INVALID_HANDLE_VALUE
291                     && GetLastError() != ERROR_FILE_EXISTS)
292                         return long_path;
293                 CloseHandle(h);
294         }
295         vector<wchar_t> short_path(MAX_PATH);
296         DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
297                                        &short_path[0], short_path.size());
298
299         if (result > short_path.size()) {
300                 short_path.resize(result);
301                 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
302                                          &short_path[0], short_path.size());
303                 LASSERT(result <= short_path.size(), /**/);
304         }
305
306         return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
307 }
308
309
310 string internal_path(string const & p)
311 {
312         return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
313 }
314
315
316 string safe_internal_path(string const & p, file_access how)
317 {
318         return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
319 }
320
321
322 string external_path_list(string const & p)
323 {
324         return subst(p, '/', '\\');
325 }
326
327
328 string internal_path_list(string const & p)
329 {
330         return subst(p, '\\', '/');
331 }
332
333
334 string latex_path(string const & p)
335 {
336         // We may need a posix style path or a windows style path (depending
337         // on windows_style_tex_paths_), but we use always forward slashes,
338         // since it gets written into a .tex file.
339
340         if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
341                 string const drive = p.substr(0, 2);
342                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
343                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
344                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
345                         << p << "]->>[" << cygpath << ']');
346                 return cygpath;
347         }
348         return subst(p, '\\', '/');
349 }
350
351
352 bool is_valid_strftime(string const & p)
353 {
354         string::size_type pos = p.find_first_of('%');
355         while (pos != string::npos) {
356                 if (pos + 1 == string::npos)
357                         break;
358                 if (!containsOnly(p.substr(pos + 1, 1),
359                         "aAbBcdfHIjmMpSUwWxXyYzZ%"))
360                         return false;
361                 if (pos + 2 == string::npos)
362                       break;
363                 pos = p.find_first_of('%', pos + 2);
364         }
365         return true;
366 }
367
368
369 // returns a string suitable to be passed to popen when
370 // reading a pipe
371 char const * popen_read_mode()
372 {
373         return "r";
374 }
375
376
377 string const & nulldev()
378 {
379         static string const nulldev_ = "nul";
380         return nulldev_;
381 }
382
383
384 bool is_terminal(io_channel channel)
385 {
386         switch (channel) {
387         case STDIN:
388                 if (GetStdHandle(STD_INPUT_HANDLE) == NULL)
389                         return false;
390                 break;
391         case STDOUT:
392                 if (GetStdHandle(STD_OUTPUT_HANDLE) == NULL)
393                         return false;
394                 break;
395         case STDERR:
396                 if (GetStdHandle(STD_ERROR_HANDLE) == NULL)
397                         return false;
398                 break;
399         }
400         return true;
401 }
402
403
404 shell_type shell()
405 {
406         return CMD_EXE;
407 }
408
409
410 char path_separator()
411 {
412         return ';';
413 }
414
415
416 void windows_style_tex_paths(bool use_windows_paths)
417 {
418         windows_style_tex_paths_ = use_windows_paths;
419 }
420
421
422 GetFolderPath::GetFolderPath()
423         : folder_module_(0),
424           folder_path_func_(0)
425 {
426         folder_module_ = LoadLibrary("shfolder.dll");
427         if (!folder_module_) {
428                 throw ExceptionMessage(ErrorException, _("System file not found"),
429                         _("Unable to load shfolder.dll\nPlease install."));
430         }
431
432         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
433         if (folder_path_func_ == 0) {
434                 throw ExceptionMessage(ErrorException, _("System function not found"),
435                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
436                           "Don't know how to proceed. Sorry."));
437         }
438 }
439
440
441 GetFolderPath::~GetFolderPath()
442 {
443         if (folder_module_)
444                 FreeLibrary(folder_module_);
445 }
446
447
448 // Given a folder ID, returns the folder name (in unix-style format).
449 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
450 string const GetFolderPath::operator()(folder_id _id) const
451 {
452         char folder_path[MAX_PATH];
453
454         int id = 0;
455         switch (_id) {
456         case PERSONAL:
457                 id = CSIDL_PERSONAL;
458                 break;
459         case APPDATA:
460                 id = CSIDL_APPDATA;
461                 break;
462         default:
463                 LASSERT(false, /**/);
464         }
465         HRESULT const result = (folder_path_func_)(0, id, 0,
466                                                    SHGFP_TYPE_CURRENT,
467                                                    folder_path);
468         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
469 }
470
471
472 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
473 {
474         if (ext.empty())
475                 return false;
476
477         string const full_ext = "." + ext;
478
479         DWORD bufSize = MAX_PATH + 100;
480         TCHAR buf[MAX_PATH + 100];
481         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
482         char const * action = (mode == VIEW) ? "open" : "edit";
483         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
484                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
485 }
486
487
488 bool autoOpenFile(string const & filename, auto_open_mode const mode)
489 {
490         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
491         char const * action = (mode == VIEW) ? "open" : "edit";
492         return reinterpret_cast<int>(ShellExecute(NULL, action,
493                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
494 }
495
496
497 string real_path(string const & path)
498 {
499         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
500         QString const qpath = get_long_path(toqstr(path));
501         HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
502                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
503
504         if (hpath == INVALID_HANDLE_VALUE) {
505                 // The file cannot be accessed.
506                 return path;
507         }
508
509         // Get the file size.
510         DWORD size_hi = 0;
511         DWORD size_lo = GetFileSize(hpath, &size_hi);
512
513         if (size_lo == 0 && size_hi == 0) {
514                 // A zero-length file cannot be mapped.
515                 CloseHandle(hpath);
516                 return path;
517         }
518
519         // Create a file mapping object.
520         HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
521
522         if (!hmap) {
523                 CloseHandle(hpath);
524                 return path;
525         }
526
527         // Create a file mapping to get the file name.
528         void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
529
530         if (!pmem) {
531                 CloseHandle(hmap);
532                 CloseHandle(hpath);
533                 return path;
534         }
535
536         TCHAR realpath[MAX_PATH + 1];
537
538         if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
539                 UnmapViewOfFile(pmem);
540                 CloseHandle(hmap);
541                 CloseHandle(hpath);
542                 return path;
543         }
544
545         // Translate device name to UNC prefix or drive letters.
546         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
547         UINT namelen = _tcslen(tmpbuf);
548         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
549                 // UNC path
550                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
551                 strncpy(realpath, tmpbuf, MAX_PATH);
552                 realpath[MAX_PATH] = '\0';
553         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
554                 // Check whether device name corresponds to some local drive.
555                 TCHAR name[MAX_PATH];
556                 TCHAR drive[3] = TEXT(" :");
557                 bool found = false;
558                 TCHAR * p = tmpbuf;
559                 do {
560                         // Copy the drive letter to the template string
561                         drive[0] = *p;
562                         // Look up each device name
563                         if (QueryDosDevice(drive, name, MAX_PATH)) {
564                                 namelen = _tcslen(name);
565                                 if (namelen < MAX_PATH) {
566                                         found = _tcsnicmp(realpath, name, namelen) == 0;
567                                         if (found) {
568                                                 // Repl. device spec with drive
569                                                 TCHAR tempfile[MAX_PATH];
570                                                 _snprintf(tempfile,
571                                                         MAX_PATH,
572                                                         "%s%s",
573                                                         drive,
574                                                         realpath + namelen);
575                                                 strncpy(realpath,
576                                                         tempfile,
577                                                         MAX_PATH);
578                                                 realpath[MAX_PATH] = '\0';
579                                         }
580                                 }
581                         }
582                         // Advance p to the next NULL character.
583                         while (*p++) ;
584                 } while (!found && *p);
585         }
586         UnmapViewOfFile(pmem);
587         CloseHandle(hmap);
588         CloseHandle(hpath);
589         string const retpath = subst(string(realpath), '\\', '/');
590         return FileName::fromFilesystemEncoding(retpath).absFilename();
591 }
592
593 } // namespace os
594 } // namespace support
595 } // namespace lyx