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