]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
Fix bug #5435: DEPM is not executed when leaving an inset.
[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         }
197         return i;
198 }
199
200
201 string external_path(string const & p)
202 {
203         string const dos_path = subst(p, "/", "\\");
204
205         LYXERR(Debug::LATEX, "<Win32 path correction> ["
206                 << p << "]->>[" << dos_path << ']');
207         return dos_path;
208 }
209
210
211 static string const get_long_path(string const & short_path)
212 {
213         // GetLongPathName needs the path in file system encoding.
214         // We can use to_local8bit, since file system encoding and the
215         // local 8 bit encoding are identical on windows.
216         vector<char> long_path(MAX_PATH);
217         DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
218                                        &long_path[0], long_path.size());
219
220         if (result > long_path.size()) {
221                 long_path.resize(result);
222                 result = GetLongPathName(short_path.c_str(),
223                                          &long_path[0], long_path.size());
224                 LASSERT(result <= long_path.size(), /**/);
225         }
226
227         return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
228 }
229
230
231 string internal_path(string const & p)
232 {
233         return subst(get_long_path(p), "\\", "/");
234 }
235
236
237 string external_path_list(string const & p)
238 {
239         return subst(p, '/', '\\');
240 }
241
242
243 string internal_path_list(string const & p)
244 {
245         return subst(p, '\\', '/');
246 }
247
248
249 string latex_path(string const & p)
250 {
251         // We may need a posix style path or a windows style path (depending
252         // on windows_style_tex_paths_), but we use always forward slashes,
253         // since it gets written into a .tex file.
254
255         if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
256                 string const drive = p.substr(0, 2);
257                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
258                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
259                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
260                         << p << "]->>[" << cygpath << ']');
261                 return cygpath;
262         }
263         return subst(p, '\\', '/');
264 }
265
266
267 bool is_valid_strftime(string const & p)
268 {
269         string::size_type pos = p.find_first_of('%');
270         while (pos != string::npos) {
271                 if (pos + 1 == string::npos)
272                         break;
273                 if (!containsOnly(p.substr(pos + 1, 1),
274                         "aAbBcdfHIjmMpSUwWxXyYzZ%"))
275                         return false;
276                 if (pos + 2 == string::npos)
277                       break;
278                 pos = p.find_first_of('%', pos + 2);
279         }
280         return true;
281 }
282
283
284 // returns a string suitable to be passed to popen when
285 // reading a pipe
286 char const * popen_read_mode()
287 {
288         return "r";
289 }
290
291
292 string const & nulldev()
293 {
294         static string const nulldev_ = "nul";
295         return nulldev_;
296 }
297
298
299 shell_type shell()
300 {
301         return CMD_EXE;
302 }
303
304
305 char path_separator()
306 {
307         return ';';
308 }
309
310
311 void windows_style_tex_paths(bool use_windows_paths)
312 {
313         windows_style_tex_paths_ = use_windows_paths;
314 }
315
316
317 GetFolderPath::GetFolderPath()
318         : folder_module_(0),
319           folder_path_func_(0)
320 {
321         folder_module_ = LoadLibrary("shfolder.dll");
322         if (!folder_module_) {
323                 throw ExceptionMessage(ErrorException, _("System file not found"),
324                         _("Unable to load shfolder.dll\nPlease install."));
325         }
326
327         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
328         if (folder_path_func_ == 0) {
329                 throw ExceptionMessage(ErrorException, _("System function not found"),
330                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
331                           "Don't know how to proceed. Sorry."));
332         }
333 }
334
335
336 GetFolderPath::~GetFolderPath()
337 {
338         if (folder_module_)
339                 FreeLibrary(folder_module_);
340 }
341
342
343 // Given a folder ID, returns the folder name (in unix-style format).
344 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
345 string const GetFolderPath::operator()(folder_id _id) const
346 {
347         char folder_path[MAX_PATH];
348
349         int id = 0;
350         switch (_id) {
351         case PERSONAL:
352                 id = CSIDL_PERSONAL;
353                 break;
354         case APPDATA:
355                 id = CSIDL_APPDATA;
356                 break;
357         default:
358                 LASSERT(false, /**/);
359         }
360         HRESULT const result = (folder_path_func_)(0, id, 0,
361                                                    SHGFP_TYPE_CURRENT,
362                                                    folder_path);
363         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
364 }
365
366
367 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
368 {
369         if (ext.empty())
370                 return false;
371
372         string const full_ext = "." + ext;
373
374         DWORD bufSize = MAX_PATH + 100;
375         TCHAR buf[MAX_PATH + 100];
376         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
377         char const * action = (mode == VIEW) ? "open" : "edit";
378         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
379                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
380 }
381
382
383 bool autoOpenFile(string const & filename, auto_open_mode const mode)
384 {
385         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
386         char const * action = (mode == VIEW) ? "open" : "edit";
387         return reinterpret_cast<int>(ShellExecute(NULL, action,
388                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
389 }
390
391
392 string real_path(string const & path)
393 {
394         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
395         HANDLE hpath = CreateFile(subst(path, '/', '\\').c_str(), GENERIC_READ,
396                                 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
397
398         if (hpath == INVALID_HANDLE_VALUE) {
399                 // The file cannot be accessed.
400                 return FileName::fromFilesystemEncoding(path).absFilename();
401         }
402
403         // Get the file size.
404         DWORD size_hi = 0;
405         DWORD size_lo = GetFileSize(hpath, &size_hi);
406
407         if (size_lo == 0 && size_hi == 0) {
408                 // A zero-length file cannot be mapped.
409                 CloseHandle(hpath);
410                 return FileName::fromFilesystemEncoding(path).absFilename();
411         }
412
413         // Create a file mapping object.
414         HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
415
416         if (!hmap) {
417                 CloseHandle(hpath);
418                 return FileName::fromFilesystemEncoding(path).absFilename();
419         }
420
421         // Create a file mapping to get the file name.
422         void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
423
424         if (!pmem) {
425                 CloseHandle(hmap);
426                 CloseHandle(hpath);
427                 return FileName::fromFilesystemEncoding(path).absFilename();
428         }
429
430         TCHAR realpath[MAX_PATH + 1];
431
432         if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
433                 UnmapViewOfFile(pmem);
434                 CloseHandle(hmap);
435                 CloseHandle(hpath);
436                 return FileName::fromFilesystemEncoding(path).absFilename();
437         }
438
439         // Translate device name to UNC prefix or drive letters.
440         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
441         UINT namelen = _tcslen(tmpbuf);
442         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
443                 // UNC path
444                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
445                 strncpy(realpath, tmpbuf, MAX_PATH);
446                 realpath[MAX_PATH] = '\0';
447         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
448                 // Check whether device name corresponds to some local drive.
449                 TCHAR name[MAX_PATH];
450                 TCHAR drive[3] = TEXT(" :");
451                 bool found = false;
452                 TCHAR * p = tmpbuf;
453                 do {
454                         // Copy the drive letter to the template string
455                         drive[0] = *p;
456                         // Look up each device name
457                         if (QueryDosDevice(drive, name, MAX_PATH)) {
458                                 namelen = _tcslen(name);
459                                 if (namelen < MAX_PATH) {
460                                         found = _tcsnicmp(realpath, name, namelen) == 0;
461                                         if (found) {
462                                                 // Repl. device spec with drive
463                                                 TCHAR tempfile[MAX_PATH];
464                                                 _snprintf(tempfile,
465                                                         MAX_PATH,
466                                                         "%s%s",
467                                                         drive,
468                                                         realpath + namelen);
469                                                 strncpy(realpath,
470                                                         tempfile,
471                                                         MAX_PATH);
472                                                 realpath[MAX_PATH] = '\0';
473                                         }
474                                 }
475                         }
476                         // Advance p to the next NULL character.
477                         while (*p++) ;
478                 } while (!found && *p);
479         }
480         UnmapViewOfFile(pmem);
481         CloseHandle(hmap);
482         CloseHandle(hpath);
483         string const retpath = subst(string(realpath), '\\', '/');
484         return FileName::fromFilesystemEncoding(retpath).absFilename();
485 }
486
487 } // namespace os
488 } // namespace support
489 } // namespace lyx