]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
722895b1cf6c0051b6fbf8e2e173f90be0b2df5c
[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 namespace support {
75 namespace os {
76
77 namespace {
78
79 bool windows_style_tex_paths_ = true;
80
81 string cygdrive = "/cygdrive";
82
83 } // namespace anon
84
85 void init(int /* argc */, char * argv[])
86 {
87         /* Note from Angus, 17 Jan 2005:
88          *
89          * The code below is taken verbatim from Ruurd's original patch
90          * porting LyX to Win32.
91          *
92          * Windows allows us to define LyX either as a console-based app
93          * or as a GUI-based app. Ruurd decided to define LyX as a
94          * console-based app with a "main" function rather than a "WinMain"
95          * function as the point of entry to the program, but to
96          * immediately close the console window that Windows helpfully
97          * opens for us. Doing so allows the user to see all of LyX's
98          * debug output simply by running LyX from a DOS or MSYS-shell
99          * prompt.
100          *
101          * The alternative approach is to define LyX as a genuine
102          * GUI-based app, with a "WinMain" function as the entry point to the
103          * executable rather than a "main" function, so:
104          *
105          * #if defined (_WIN32)
106          * # define WIN32_LEAN_AND_MEAN
107          * # include <stdlib.h>  // for __argc, __argv
108          * # include <windows.h> // for WinMain
109          * #endif
110          *
111          * // This will require the "-mwindows" flag when linking with
112          * // gcc under MinGW.
113          * // For MSVC, use "/subsystem:windows".
114          * #if defined (_WIN32)
115          * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
116          * {
117          *     return mymain(__argc, __argv);
118          * }
119          * #endif
120          *
121          * where "mymain" is just a renamed "main".
122          *
123          * However, doing so means that the lyxerr messages would mysteriously
124          * disappear. They could be resurrected with something like:
125          *
126          * #ifdef WIN32
127          *  AllocConsole();
128          *  freopen("conin$","r",stdin);
129          *  freopen("conout$","w",stdout);
130          *  freopen("conout$","w",stderr);
131          * #endif
132          *
133          * This code could be invoked (say) the first time that lyxerr
134          * is called. However, Ruurd has tried this route and found that some
135          * shell scripts failed, for mysterious reasons...
136          *
137          * I've chosen for now, therefore, to simply add Ruurd's original
138          * code as-is. A wrapper program hidecmd.c has been added to
139          * development/Win32 which hides the console window of lyx when
140          * lyx is invoked as a parameter of hidecmd.exe.
141          */
142
143         // If cygwin is detected, query the cygdrive prefix
144         HKEY regKey;
145         char buf[MAX_PATH];
146         DWORD bufSize = sizeof(buf);
147         LONG retVal;
148
149         retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
150                         "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
151                         0, KEY_QUERY_VALUE, &regKey);
152         if (retVal != ERROR_SUCCESS) {
153                 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
154                                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
155                                 0, KEY_QUERY_VALUE, &regKey);
156         }
157         if (retVal == ERROR_SUCCESS) {
158                 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
159                                 (LPBYTE) buf, &bufSize);
160                 RegCloseKey(regKey);
161                 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
162                         cygdrive = rtrim(string(buf), "/");
163         }
164 }
165
166
167 string current_root()
168 {
169         // _getdrive returns the current drive (1=A, 2=B, and so on).
170         char const drive = ::_getdrive() + 'A' - 1;
171         return string(1, drive) + ":/";
172 }
173
174
175 bool isFilesystemCaseSensitive()
176 {
177         return false;
178 }
179
180
181 docstring::size_type common_path(docstring const & p1, docstring const & p2)
182 {
183         size_t i = 0;
184         size_t const p1_len = p1.length();
185         size_t const p2_len = p2.length();
186         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
187                 ++i;
188         if ((i < p1_len && i < p2_len)
189             || (i < p1_len && p1[i] != '/' && i == p2_len)
190             || (i < p2_len && p2[i] != '/' && i == p1_len))
191         {
192                 if (i)
193                         --i;     // here was the last match
194                 while (i && p1[i] != '/')
195                         --i;
196         } else
197                 --i;
198
199         return i;
200 }
201
202
203 bool path_prefix_is(string const & path, string const & pre)
204 {
205         string tmp = path;
206         return path_prefix_is(tmp, pre, CASE_UNCHANGED);
207 }
208
209
210 bool path_prefix_is(string & path, string const & pre, path_case how)
211 {
212         docstring const p1 = from_utf8(path);
213         docstring const p2 = from_utf8(pre);
214         docstring::size_type i = common_path(p1, p2);
215
216         if (i + 1 != p2.length())
217                 return false;
218
219         if (how == CASE_ADJUSTED && !prefixIs(path, pre))
220                 path = to_utf8(p2 + p1.substr(i + 1, p1.length() - i + 1));
221
222         return true;
223 }
224
225
226 string external_path(string const & p)
227 {
228         string const dos_path = subst(p, "/", "\\");
229
230         LYXERR(Debug::LATEX, "<Win32 path correction> ["
231                 << p << "]->>[" << dos_path << ']');
232         return dos_path;
233 }
234
235
236 static string const get_long_path(string const & short_path)
237 {
238         // GetLongPathName needs the path in file system encoding.
239         // We can use to_local8bit, since file system encoding and the
240         // local 8 bit encoding are identical on windows.
241         vector<char> long_path(MAX_PATH);
242         DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
243                                        &long_path[0], long_path.size());
244
245         if (result > long_path.size()) {
246                 long_path.resize(result);
247                 result = GetLongPathName(short_path.c_str(),
248                                          &long_path[0], long_path.size());
249                 LASSERT(result <= long_path.size(), /**/);
250         }
251
252         return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
253 }
254
255
256 string internal_path(string const & p)
257 {
258         return subst(get_long_path(p), "\\", "/");
259 }
260
261
262 string external_path_list(string const & p)
263 {
264         return subst(p, '/', '\\');
265 }
266
267
268 string internal_path_list(string const & p)
269 {
270         return subst(p, '\\', '/');
271 }
272
273
274 string latex_path(string const & p)
275 {
276         // We may need a posix style path or a windows style path (depending
277         // on windows_style_tex_paths_), but we use always forward slashes,
278         // since it gets written into a .tex file.
279
280         if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
281                 string const drive = p.substr(0, 2);
282                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
283                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
284                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
285                         << p << "]->>[" << cygpath << ']');
286                 return cygpath;
287         }
288         return subst(p, '\\', '/');
289 }
290
291
292 bool is_valid_strftime(string const & p)
293 {
294         string::size_type pos = p.find_first_of('%');
295         while (pos != string::npos) {
296                 if (pos + 1 == string::npos)
297                         break;
298                 if (!containsOnly(p.substr(pos + 1, 1),
299                         "aAbBcdfHIjmMpSUwWxXyYzZ%"))
300                         return false;
301                 if (pos + 2 == string::npos)
302                       break;
303                 pos = p.find_first_of('%', pos + 2);
304         }
305         return true;
306 }
307
308
309 // returns a string suitable to be passed to popen when
310 // reading a pipe
311 char const * popen_read_mode()
312 {
313         return "r";
314 }
315
316
317 string const & nulldev()
318 {
319         static string const nulldev_ = "nul";
320         return nulldev_;
321 }
322
323
324 bool is_terminal(io_channel channel)
325 {
326         switch (channel) {
327         case STDIN:
328                 if (GetStdHandle(STD_INPUT_HANDLE) == NULL)
329                         return false;
330                 break;
331         case STDOUT:
332                 if (GetStdHandle(STD_OUTPUT_HANDLE) == NULL)
333                         return false;
334                 break;
335         case STDERR:
336                 if (GetStdHandle(STD_ERROR_HANDLE) == NULL)
337                         return false;
338                 break;
339         }
340         return true;
341 }
342
343
344 shell_type shell()
345 {
346         return CMD_EXE;
347 }
348
349
350 char path_separator()
351 {
352         return ';';
353 }
354
355
356 void windows_style_tex_paths(bool use_windows_paths)
357 {
358         windows_style_tex_paths_ = use_windows_paths;
359 }
360
361
362 GetFolderPath::GetFolderPath()
363         : folder_module_(0),
364           folder_path_func_(0)
365 {
366         folder_module_ = LoadLibrary("shfolder.dll");
367         if (!folder_module_) {
368                 throw ExceptionMessage(ErrorException, _("System file not found"),
369                         _("Unable to load shfolder.dll\nPlease install."));
370         }
371
372         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
373         if (folder_path_func_ == 0) {
374                 throw ExceptionMessage(ErrorException, _("System function not found"),
375                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
376                           "Don't know how to proceed. Sorry."));
377         }
378 }
379
380
381 GetFolderPath::~GetFolderPath()
382 {
383         if (folder_module_)
384                 FreeLibrary(folder_module_);
385 }
386
387
388 // Given a folder ID, returns the folder name (in unix-style format).
389 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
390 string const GetFolderPath::operator()(folder_id _id) const
391 {
392         char folder_path[MAX_PATH];
393
394         int id = 0;
395         switch (_id) {
396         case PERSONAL:
397                 id = CSIDL_PERSONAL;
398                 break;
399         case APPDATA:
400                 id = CSIDL_APPDATA;
401                 break;
402         default:
403                 LASSERT(false, /**/);
404         }
405         HRESULT const result = (folder_path_func_)(0, id, 0,
406                                                    SHGFP_TYPE_CURRENT,
407                                                    folder_path);
408         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
409 }
410
411
412 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
413 {
414         if (ext.empty())
415                 return false;
416
417         string const full_ext = "." + ext;
418
419         DWORD bufSize = MAX_PATH + 100;
420         TCHAR buf[MAX_PATH + 100];
421         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
422         char const * action = (mode == VIEW) ? "open" : "edit";
423         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
424                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
425 }
426
427
428 bool autoOpenFile(string const & filename, auto_open_mode const mode)
429 {
430         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
431         char const * action = (mode == VIEW) ? "open" : "edit";
432         return reinterpret_cast<int>(ShellExecute(NULL, action,
433                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
434 }
435
436
437 string real_path(string const & path)
438 {
439         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
440         HANDLE hpath = CreateFile(subst(path, '/', '\\').c_str(), GENERIC_READ,
441                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
442
443         if (hpath == INVALID_HANDLE_VALUE) {
444                 // The file cannot be accessed.
445                 return FileName::fromFilesystemEncoding(path).absFilename();
446         }
447
448         // Get the file size.
449         DWORD size_hi = 0;
450         DWORD size_lo = GetFileSize(hpath, &size_hi);
451
452         if (size_lo == 0 && size_hi == 0) {
453                 // A zero-length file cannot be mapped.
454                 CloseHandle(hpath);
455                 return FileName::fromFilesystemEncoding(path).absFilename();
456         }
457
458         // Create a file mapping object.
459         HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
460
461         if (!hmap) {
462                 CloseHandle(hpath);
463                 return FileName::fromFilesystemEncoding(path).absFilename();
464         }
465
466         // Create a file mapping to get the file name.
467         void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
468
469         if (!pmem) {
470                 CloseHandle(hmap);
471                 CloseHandle(hpath);
472                 return FileName::fromFilesystemEncoding(path).absFilename();
473         }
474
475         TCHAR realpath[MAX_PATH + 1];
476
477         if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
478                 UnmapViewOfFile(pmem);
479                 CloseHandle(hmap);
480                 CloseHandle(hpath);
481                 return FileName::fromFilesystemEncoding(path).absFilename();
482         }
483
484         // Translate device name to UNC prefix or drive letters.
485         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
486         UINT namelen = _tcslen(tmpbuf);
487         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
488                 // UNC path
489                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
490                 strncpy(realpath, tmpbuf, MAX_PATH);
491                 realpath[MAX_PATH] = '\0';
492         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
493                 // Check whether device name corresponds to some local drive.
494                 TCHAR name[MAX_PATH];
495                 TCHAR drive[3] = TEXT(" :");
496                 bool found = false;
497                 TCHAR * p = tmpbuf;
498                 do {
499                         // Copy the drive letter to the template string
500                         drive[0] = *p;
501                         // Look up each device name
502                         if (QueryDosDevice(drive, name, MAX_PATH)) {
503                                 namelen = _tcslen(name);
504                                 if (namelen < MAX_PATH) {
505                                         found = _tcsnicmp(realpath, name, namelen) == 0;
506                                         if (found) {
507                                                 // Repl. device spec with drive
508                                                 TCHAR tempfile[MAX_PATH];
509                                                 _snprintf(tempfile,
510                                                         MAX_PATH,
511                                                         "%s%s",
512                                                         drive,
513                                                         realpath + namelen);
514                                                 strncpy(realpath,
515                                                         tempfile,
516                                                         MAX_PATH);
517                                                 realpath[MAX_PATH] = '\0';
518                                         }
519                                 }
520                         }
521                         // Advance p to the next NULL character.
522                         while (*p++) ;
523                 } while (!found && *p);
524         }
525         UnmapViewOfFile(pmem);
526         CloseHandle(hmap);
527         CloseHandle(hpath);
528         string const retpath = subst(string(realpath), '\\', '/');
529         return FileName::fromFilesystemEncoding(retpath).absFilename();
530 }
531
532 } // namespace os
533 } // namespace support
534 } // namespace lyx