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