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