]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
Add support for the newly released Cygwin 1.7.
[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 emergencyCleanup();
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::emergencyCleanup();
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         HKEY regKey;
159         LONG retVal;
160
161         // Check for Cygwin 1.7 or later
162         retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
163                         "Software\\Cygwin\\setup",
164                         0, KEY_QUERY_VALUE, &regKey);
165         if (retVal != ERROR_SUCCESS)
166                 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
167                                 "Software\\Cygwin\\setup",
168                                 0, KEY_QUERY_VALUE, &regKey);
169
170         // Check for older Cygwin versions
171         if (retVal != ERROR_SUCCESS)
172                 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
173                                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
174                                 0, KEY_QUERY_VALUE, &regKey);
175         if (retVal != ERROR_SUCCESS)
176                         retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
177                                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
178                                 0, KEY_QUERY_VALUE, &regKey);
179
180         if (retVal == ERROR_SUCCESS) {
181                 RegCloseKey(regKey);
182                 cmd_ret const p = runCommand("mount --show-cygdrive-prefix");
183                 // The output of the mount command is as follows:
184                 // Prefix              Type         Flags
185                 // /cygdrive           system       binmode
186                 // So, we use the inner split to pass the second line to the
187                 // outer split which sets cygdrive with its contents until
188                 // the first blank, discarding the unneeded return value.
189                 if (p.first != -1 && prefixIs(p.second, "Prefix"))
190                         split(split(p.second, '\n'), cygdrive, ' ');
191         }
192
193         // Catch shutdown events.
194         SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
195 }
196
197
198 string current_root()
199 {
200         // _getdrive returns the current drive (1=A, 2=B, and so on).
201         char const drive = ::_getdrive() + 'A' - 1;
202         return string(1, drive) + ":/";
203 }
204
205
206 bool isFilesystemCaseSensitive()
207 {
208         return false;
209 }
210
211
212 docstring::size_type common_path(docstring const & p1, docstring const & p2)
213 {
214         size_t i = 0;
215         size_t const p1_len = p1.length();
216         size_t const p2_len = p2.length();
217         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
218                 ++i;
219         if ((i < p1_len && i < p2_len)
220             || (i < p1_len && p1[i] != '/' && i == p2_len)
221             || (i < p2_len && p2[i] != '/' && i == p1_len))
222         {
223                 if (i)
224                         --i;     // here was the last match
225                 while (i && p1[i] != '/')
226                         --i;
227         }
228         return i;
229 }
230
231
232 bool path_prefix_is(string const & path, string const & pre)
233 {
234         return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
235 }
236
237
238 bool path_prefix_is(string & path, string const & pre, path_case how)
239 {
240         docstring const p1 = from_utf8(path);
241         docstring const p2 = from_utf8(pre);
242         docstring::size_type const p1_len = p1.length();
243         docstring::size_type const p2_len = p2.length();
244         docstring::size_type common_len = common_path(p1, p2);
245
246         if (p2[p2_len - 1] == '/' && p1_len != p2_len)
247                 ++common_len;
248
249         if (common_len != p2_len)
250                 return false;
251
252         if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
253                 if (p1_len < common_len)
254                         path = to_utf8(p2.substr(0, p1_len));
255                 else
256                         path = to_utf8(p2 + p1.substr(common_len,
257                                                         p1_len - common_len));
258         }
259
260         return true;
261 }
262
263
264 string external_path(string const & p)
265 {
266         string const dos_path = subst(p, "/", "\\");
267
268         LYXERR(Debug::LATEX, "<Win32 path correction> ["
269                 << p << "]->>[" << dos_path << ']');
270         return dos_path;
271 }
272
273
274 static string const get_long_path(string const & short_path)
275 {
276         // GetLongPathName needs the path in file system encoding.
277         // We can use to_local8bit, since file system encoding and the
278         // local 8 bit encoding are identical on windows.
279         vector<char> long_path(MAX_PATH);
280         DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
281                                        &long_path[0], long_path.size());
282
283         if (result > long_path.size()) {
284                 long_path.resize(result);
285                 result = GetLongPathName(short_path.c_str(),
286                                          &long_path[0], long_path.size());
287                 LASSERT(result <= long_path.size(), /**/);
288         }
289
290         return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
291 }
292
293
294 string internal_path(string const & p)
295 {
296         return subst(get_long_path(p), "\\", "/");
297 }
298
299
300 string external_path_list(string const & p)
301 {
302         return subst(p, '/', '\\');
303 }
304
305
306 string internal_path_list(string const & p)
307 {
308         return subst(p, '\\', '/');
309 }
310
311
312 string latex_path(string const & p)
313 {
314         // We may need a posix style path or a windows style path (depending
315         // on windows_style_tex_paths_), but we use always forward slashes,
316         // since it gets written into a .tex file.
317
318         if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
319                 string const drive = p.substr(0, 2);
320                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
321                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
322                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
323                         << p << "]->>[" << cygpath << ']');
324                 return cygpath;
325         }
326         return subst(p, '\\', '/');
327 }
328
329
330 bool is_valid_strftime(string const & p)
331 {
332         string::size_type pos = p.find_first_of('%');
333         while (pos != string::npos) {
334                 if (pos + 1 == string::npos)
335                         break;
336                 if (!containsOnly(p.substr(pos + 1, 1),
337                         "aAbBcdfHIjmMpSUwWxXyYzZ%"))
338                         return false;
339                 if (pos + 2 == string::npos)
340                       break;
341                 pos = p.find_first_of('%', pos + 2);
342         }
343         return true;
344 }
345
346
347 // returns a string suitable to be passed to popen when
348 // reading a pipe
349 char const * popen_read_mode()
350 {
351         return "r";
352 }
353
354
355 string const & nulldev()
356 {
357         static string const nulldev_ = "nul";
358         return nulldev_;
359 }
360
361
362 bool is_terminal(io_channel channel)
363 {
364         switch (channel) {
365         case STDIN:
366                 if (GetStdHandle(STD_INPUT_HANDLE) == NULL)
367                         return false;
368                 break;
369         case STDOUT:
370                 if (GetStdHandle(STD_OUTPUT_HANDLE) == NULL)
371                         return false;
372                 break;
373         case STDERR:
374                 if (GetStdHandle(STD_ERROR_HANDLE) == NULL)
375                         return false;
376                 break;
377         }
378         return true;
379 }
380
381
382 shell_type shell()
383 {
384         return CMD_EXE;
385 }
386
387
388 char path_separator()
389 {
390         return ';';
391 }
392
393
394 void windows_style_tex_paths(bool use_windows_paths)
395 {
396         windows_style_tex_paths_ = use_windows_paths;
397 }
398
399
400 GetFolderPath::GetFolderPath()
401         : folder_module_(0),
402           folder_path_func_(0)
403 {
404         folder_module_ = LoadLibrary("shfolder.dll");
405         if (!folder_module_) {
406                 throw ExceptionMessage(ErrorException, _("System file not found"),
407                         _("Unable to load shfolder.dll\nPlease install."));
408         }
409
410         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
411         if (folder_path_func_ == 0) {
412                 throw ExceptionMessage(ErrorException, _("System function not found"),
413                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
414                           "Don't know how to proceed. Sorry."));
415         }
416 }
417
418
419 GetFolderPath::~GetFolderPath()
420 {
421         if (folder_module_)
422                 FreeLibrary(folder_module_);
423 }
424
425
426 // Given a folder ID, returns the folder name (in unix-style format).
427 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
428 string const GetFolderPath::operator()(folder_id _id) const
429 {
430         char folder_path[MAX_PATH];
431
432         int id = 0;
433         switch (_id) {
434         case PERSONAL:
435                 id = CSIDL_PERSONAL;
436                 break;
437         case APPDATA:
438                 id = CSIDL_APPDATA;
439                 break;
440         default:
441                 LASSERT(false, /**/);
442         }
443         HRESULT const result = (folder_path_func_)(0, id, 0,
444                                                    SHGFP_TYPE_CURRENT,
445                                                    folder_path);
446         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
447 }
448
449
450 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
451 {
452         if (ext.empty())
453                 return false;
454
455         string const full_ext = "." + ext;
456
457         DWORD bufSize = MAX_PATH + 100;
458         TCHAR buf[MAX_PATH + 100];
459         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
460         char const * action = (mode == VIEW) ? "open" : "edit";
461         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
462                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
463 }
464
465
466 bool autoOpenFile(string const & filename, auto_open_mode const mode)
467 {
468         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
469         char const * action = (mode == VIEW) ? "open" : "edit";
470         return reinterpret_cast<int>(ShellExecute(NULL, action,
471                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
472 }
473
474
475 string real_path(string const & path)
476 {
477         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
478         HANDLE hpath = CreateFile(subst(path, '/', '\\').c_str(), GENERIC_READ,
479                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
480
481         if (hpath == INVALID_HANDLE_VALUE) {
482                 // The file cannot be accessed.
483                 return FileName::fromFilesystemEncoding(path).absFilename();
484         }
485
486         // Get the file size.
487         DWORD size_hi = 0;
488         DWORD size_lo = GetFileSize(hpath, &size_hi);
489
490         if (size_lo == 0 && size_hi == 0) {
491                 // A zero-length file cannot be mapped.
492                 CloseHandle(hpath);
493                 return FileName::fromFilesystemEncoding(path).absFilename();
494         }
495
496         // Create a file mapping object.
497         HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
498
499         if (!hmap) {
500                 CloseHandle(hpath);
501                 return FileName::fromFilesystemEncoding(path).absFilename();
502         }
503
504         // Create a file mapping to get the file name.
505         void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
506
507         if (!pmem) {
508                 CloseHandle(hmap);
509                 CloseHandle(hpath);
510                 return FileName::fromFilesystemEncoding(path).absFilename();
511         }
512
513         TCHAR realpath[MAX_PATH + 1];
514
515         if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
516                 UnmapViewOfFile(pmem);
517                 CloseHandle(hmap);
518                 CloseHandle(hpath);
519                 return FileName::fromFilesystemEncoding(path).absFilename();
520         }
521
522         // Translate device name to UNC prefix or drive letters.
523         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
524         UINT namelen = _tcslen(tmpbuf);
525         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
526                 // UNC path
527                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
528                 strncpy(realpath, tmpbuf, MAX_PATH);
529                 realpath[MAX_PATH] = '\0';
530         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
531                 // Check whether device name corresponds to some local drive.
532                 TCHAR name[MAX_PATH];
533                 TCHAR drive[3] = TEXT(" :");
534                 bool found = false;
535                 TCHAR * p = tmpbuf;
536                 do {
537                         // Copy the drive letter to the template string
538                         drive[0] = *p;
539                         // Look up each device name
540                         if (QueryDosDevice(drive, name, MAX_PATH)) {
541                                 namelen = _tcslen(name);
542                                 if (namelen < MAX_PATH) {
543                                         found = _tcsnicmp(realpath, name, namelen) == 0;
544                                         if (found) {
545                                                 // Repl. device spec with drive
546                                                 TCHAR tempfile[MAX_PATH];
547                                                 _snprintf(tempfile,
548                                                         MAX_PATH,
549                                                         "%s%s",
550                                                         drive,
551                                                         realpath + namelen);
552                                                 strncpy(realpath,
553                                                         tempfile,
554                                                         MAX_PATH);
555                                                 realpath[MAX_PATH] = '\0';
556                                         }
557                                 }
558                         }
559                         // Advance p to the next NULL character.
560                         while (*p++) ;
561                 } while (!found && *p);
562         }
563         UnmapViewOfFile(pmem);
564         CloseHandle(hmap);
565         CloseHandle(hpath);
566         string const retpath = subst(string(realpath), '\\', '/');
567         return FileName::fromFilesystemEncoding(retpath).absFilename();
568 }
569
570 } // namespace os
571 } // namespace support
572 } // namespace lyx