]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
Let paragraph::requestSpellcheck() consider contained insets
[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  * \author Enrico Forestieri
10  *
11  * Full author contact details are available in file CREDITS.
12  *
13  * Various OS specific functions
14  */
15
16 #include <config.h>
17
18 #include "support/os_win32.h"
19
20 #include "LyXRC.h"
21
22 #include "support/os.h"
23
24 #include "support/debug.h"
25 #include "support/environment.h"
26 #include "support/FileName.h"
27 #include "support/gettext.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/qstring_helpers.h"
32
33 #include "support/lassert.h"
34
35 #include <cstdlib>
36 #include <iostream>
37 #include <vector>
38
39 #include <QString>
40
41 #include <io.h>
42 #include <direct.h> // _getdrive
43 #include <fileapi.h> // GetFinalPathNameByHandle
44 #include <shlobj.h>  // SHGetFolderPath
45 #include <windef.h>
46 #include <shellapi.h>
47 #include <shlwapi.h>
48
49 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
50 #if defined(__MINGW32__)  || defined(__CYGWIN__) || defined(__CYGWIN32__)
51 # include <w32api.h>
52 # if __W32API_MAJOR_VERSION < 3 || \
53      __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION  < 2
54 #  define SHGFP_TYPE_CURRENT 0
55 # endif
56 #endif
57
58 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
59 #define ASSOCF_INIT_IGNOREUNKNOWN 0
60 #endif
61
62 #if defined(__MINGW32__)
63 #include <stdio.h>
64 #endif
65
66 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
67 #else
68 extern "C" {
69 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
70                            int expand_wildcards, int * new_mode);
71 }
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 int argc_ = 0;
86 wchar_t ** argv_ = 0;
87
88 bool windows_style_tex_paths_ = true;
89
90 string cygdrive = "/cygdrive";
91
92 BOOL terminate_handler(DWORD event)
93 {
94         if (event == CTRL_CLOSE_EVENT
95             || event == CTRL_LOGOFF_EVENT
96             || event == CTRL_SHUTDOWN_EVENT) {
97                 lyx::lyx_exit(1);
98                 return TRUE;
99         }
100         return FALSE;
101 }
102
103 } // namespace
104
105 void init(int argc, char ** argv[])
106 {
107         /* Note from Angus, 17 Jan 2005:
108          *
109          * The code below is taken verbatim from Ruurd's original patch
110          * porting LyX to Win32.
111          *
112          * Windows allows us to define LyX either as a console-based app
113          * or as a GUI-based app. Ruurd decided to define LyX as a
114          * console-based app with a "main" function rather than a "WinMain"
115          * function as the point of entry to the program, but to
116          * immediately close the console window that Windows helpfully
117          * opens for us. Doing so allows the user to see all of LyX's
118          * debug output simply by running LyX from a DOS or MSYS-shell
119          * prompt.
120          *
121          * The alternative approach is to define LyX as a genuine
122          * GUI-based app, with a "WinMain" function as the entry point to the
123          * executable rather than a "main" function, so:
124          *
125          * #if defined (_WIN32)
126          * # define WIN32_LEAN_AND_MEAN
127          * # include <stdlib.h>  // for __argc, __argv
128          * # include <windows.h> // for WinMain
129          * #endif
130          *
131          * // This will require the "-mwindows" flag when linking with
132          * // gcc under MinGW.
133          * // For MSVC, use "/subsystem:windows".
134          * #if defined (_WIN32)
135          * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
136          * {
137          *     return mymain(__argc, __argv);
138          * }
139          * #endif
140          *
141          * where "mymain" is just a renamed "main".
142          *
143          * However, doing so means that the lyxerr messages would mysteriously
144          * disappear. They could be resurrected with something like:
145          *
146          * #ifdef WIN32
147          *  AllocConsole();
148          *  freopen("conin$","r",stdin);
149          *  freopen("conout$","w",stdout);
150          *  freopen("conout$","w",stderr);
151          * #endif
152          *
153          * This code could be invoked (say) the first time that lyxerr
154          * is called. However, Ruurd has tried this route and found that some
155          * shell scripts failed, for mysterious reasons...
156          *
157          * I've chosen for now, therefore, to simply add Ruurd's original
158          * code as-is. A wrapper program hidecmd.c has been added to
159          * development/Win32 which hides the console window of lyx when
160          * lyx is invoked as a parameter of hidecmd.exe.
161          */
162
163
164         // Remove PYTHONPATH from the environment as it may point to an
165         // external python installation and cause reconfigure failures.
166         unsetEnv("PYTHONPATH");
167
168
169 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
170         // Removing an argument from argv leads to an assertion on Windows
171         // when compiling with MSVC 2015 in debug mode (see bug #10440).
172         // To avoid this we make a copy of the array of pointers.
173         char ** newargv = (char **) malloc((argc + 1) * sizeof(char *));
174         if (newargv) {
175                 memcpy(newargv, *argv, (argc + 1) * sizeof(char *));
176                 *argv = newargv;
177         } else {
178                 lyxerr << "LyX warning: Cannot make a copy of "
179                           "command line arguments!"
180                        << endl;
181         }
182 #endif
183
184
185         // Get the wide program arguments array
186 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
187         argv_ = CommandLineToArgvW(GetCommandLineW(), &argc_);
188 #else
189         wchar_t ** envp = 0;
190         int newmode = 0;
191         __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
192 #endif
193         LATTEST(argc == argc_);
194
195         // If Cygwin is detected, query the cygdrive prefix.
196         // The cygdrive prefix is needed for translating windows style paths
197         // to posix style paths in LaTeX files when the Cygwin teTeX is used.
198         int i;
199         HKEY hkey;
200         char buf[MAX_PATH];
201         DWORD bufsize = sizeof(buf);
202         LONG retval = ERROR_FILE_NOT_FOUND;
203         HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
204         char const * const subkey[2] = {
205                 "Software\\Cygwin\\setup",                         // Cygwin 1.7
206                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
207         };
208         char const * const valuename[2] = {
209                 "rootdir", // Cygwin 1.7 or later
210                 "native"   // Previous versions
211         };
212         // Check for newer Cygwin versions first, then older ones
213         for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
214                 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
215                         retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
216         }
217         if (retval == ERROR_SUCCESS) {
218                 // Query the Cygwin root directory
219                 retval = RegQueryValueEx(hkey, valuename[i - 1],
220                                 NULL, NULL, (LPBYTE) buf, &bufsize);
221                 RegCloseKey(hkey);
222                 string const mount = string(buf) + "\\bin\\mount.exe";
223                 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
224                         cmd_ret const p =
225                                 runCommand(mount + " --show-cygdrive-prefix");
226                         // The output of the mount command is as follows:
227                         // Prefix              Type         Flags
228                         // /cygdrive           system       binmode
229                         // So, we use the inner split to pass the second line
230                         // to the outer split which sets cygdrive with its
231                         // contents until the first blank, discarding the
232                         // unneeded return value.
233                         if (p.valid && prefixIs(p.result, "Prefix"))
234                                 split(split(p.result, '\n'), cygdrive, ' ');
235                 }
236         }
237
238         // Catch shutdown events.
239         SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
240 }
241
242
243 string utf8_argv(int i)
244 {
245         LASSERT(i < argc_, return "");
246         return fromqstr(QString::fromWCharArray(argv_[i]));
247 }
248
249
250 void remove_internal_args(int i, int num)
251 {
252         argc_ -= num;
253         for (int j = i; j < argc_; ++j)
254                 argv_[j] = argv_[j + num];
255 }
256
257
258 string current_root()
259 {
260         // _getdrive returns the current drive (1=A, 2=B, and so on).
261         char const drive = ::_getdrive() + 'A' - 1;
262         return string(1, drive) + ":/";
263 }
264
265
266 bool isFilesystemCaseSensitive()
267 {
268         return false;
269 }
270
271
272 docstring::size_type common_path(docstring const & p1, docstring const & p2)
273 {
274         size_t i = 0;
275         size_t const p1_len = p1.length();
276         size_t const p2_len = p2.length();
277         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
278                 ++i;
279         if ((i < p1_len && i < p2_len)
280             || (i < p1_len && p1[i] != '/' && i == p2_len)
281             || (i < p2_len && p2[i] != '/' && i == p1_len))
282         {
283                 if (i)
284                         --i;     // here was the last match
285                 while (i && p1[i] != '/')
286                         --i;
287         }
288         return i;
289 }
290
291
292 bool path_prefix_is(string const & path, string const & pre)
293 {
294         return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
295 }
296
297
298 bool path_prefix_is(string & path, string const & pre, path_case how)
299 {
300         docstring const p1 = from_utf8(path);
301         docstring const p2 = from_utf8(pre);
302         docstring::size_type const p1_len = p1.length();
303         docstring::size_type const p2_len = p2.length();
304         docstring::size_type common_len = common_path(p1, p2);
305
306         if (p2[p2_len - 1] == '/' && p1_len != p2_len)
307                 ++common_len;
308
309         if (common_len != p2_len)
310                 return false;
311
312         if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
313                 if (p1_len < common_len)
314                         path = to_utf8(p2.substr(0, p1_len));
315                 else
316                         path = to_utf8(p2 + p1.substr(common_len,
317                                                         p1_len - common_len));
318         }
319
320         return true;
321 }
322
323
324 string external_path(string const & p)
325 {
326         string const dos_path = subst(p, "/", "\\");
327
328         LYXERR(Debug::LATEX, "<Win32 path correction> ["
329                 << p << "]->>[" << dos_path << ']');
330         return dos_path;
331 }
332
333
334 static QString const get_long_path(QString const & short_path)
335 {
336         // GetLongPathNameW needs the path in utf16 encoding.
337         vector<wchar_t> long_path(MAX_PATH);
338         DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
339                                        &long_path[0], long_path.size());
340
341         if (result > long_path.size()) {
342                 long_path.resize(result);
343                 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
344                                          &long_path[0], long_path.size());
345                 LATTEST(result <= long_path.size());
346         }
347
348         return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
349 }
350
351
352 static QString const get_short_path(QString const & long_path, file_access how)
353 {
354         // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
355         if (how == CREATE) {
356                 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
357                                 GENERIC_WRITE, 0, NULL, CREATE_NEW,
358                                 FILE_ATTRIBUTE_NORMAL, NULL);
359                 if (h == INVALID_HANDLE_VALUE
360                     && GetLastError() != ERROR_FILE_EXISTS)
361                         return long_path;
362                 CloseHandle(h);
363         }
364         vector<wchar_t> short_path(MAX_PATH);
365         DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
366                                        &short_path[0], short_path.size());
367
368         if (result > short_path.size()) {
369                 short_path.resize(result);
370                 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
371                                          &short_path[0], short_path.size());
372                 LATTEST(result <= short_path.size());
373         }
374
375         return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
376 }
377
378
379 string internal_path(string const & p)
380 {
381         return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
382 }
383
384
385 string safe_internal_path(string const & p, file_access how)
386 {
387         return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
388 }
389
390
391 string external_path_list(string const & p)
392 {
393         return subst(p, '/', '\\');
394 }
395
396
397 string internal_path_list(string const & p)
398 {
399         return subst(p, '\\', '/');
400 }
401
402
403 string latex_path(string const & p)
404 {
405         // We may need a posix style path or a windows style path (depending
406         // on windows_style_tex_paths_), but we use always forward slashes,
407         // since it gets written into a .tex file.
408
409         if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
410                 string const drive = p.substr(0, 2);
411                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
412                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
413                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
414                         << p << "]->>[" << cygpath << ']');
415                 return cygpath;
416         }
417         return subst(p, '\\', '/');
418 }
419
420
421 string latex_path_list(string const & p)
422 {
423         if (p.empty())
424                 return p;
425
426         // We may need a posix style path or a windows style path (depending
427         // on windows_style_tex_paths_), but we use always forward slashes,
428         // since this is standard for all tex engines.
429
430         if (!windows_style_tex_paths_) {
431                 string pathlist;
432                 for (size_t i = 0, k = 0; i != string::npos; k = i) {
433                         i = p.find(';', i);
434                         string path = subst(p.substr(k, i - k), '\\', '/');
435                         if (FileName::isAbsolute(path)) {
436                                 string const drive = path.substr(0, 2);
437                                 string const cygprefix = cygdrive + "/"
438                                                         + drive.substr(0, 1);
439                                 path = subst(path, drive, cygprefix);
440                         }
441                         pathlist += path;
442                         if (i != string::npos) {
443                                 pathlist += ':';
444                                 ++i;
445                         }
446                 }
447                 return pathlist;
448         }
449         return subst(p, '\\', '/');
450 }
451
452
453 // returns a string suitable to be passed to popen when
454 // reading a pipe
455 char const * popen_read_mode()
456 {
457         return "r";
458 }
459
460
461 string const & nulldev()
462 {
463         static string const nulldev_ = "nul";
464         return nulldev_;
465 }
466
467
468 shell_type shell()
469 {
470         return CMD_EXE;
471 }
472
473
474 char path_separator(path_type type)
475 {
476         if (type == TEXENGINE)
477                 return windows_style_tex_paths_ ? ';' : ':';
478
479         return ';';
480 }
481
482
483 void windows_style_tex_paths(bool use_windows_paths)
484 {
485         windows_style_tex_paths_ = use_windows_paths;
486 }
487
488
489 GetFolderPath::GetFolderPath()
490         : folder_module_(0),
491           folder_path_func_(0)
492 {
493         folder_module_ = LoadLibrary("shfolder.dll");
494         if (!folder_module_) {
495                 throw ExceptionMessage(ErrorException, _("System file not found"),
496                         _("Unable to load shfolder.dll\nPlease install."));
497         }
498
499         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
500         if (folder_path_func_ == 0) {
501                 throw ExceptionMessage(ErrorException, _("System function not found"),
502                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
503                           "Don't know how to proceed. Sorry."));
504         }
505 }
506
507
508 GetFolderPath::~GetFolderPath()
509 {
510         if (folder_module_)
511                 FreeLibrary(folder_module_);
512 }
513
514
515 // Given a folder ID, returns the folder name (in unix-style format).
516 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
517 string const GetFolderPath::operator()(folder_id _id) const
518 {
519         char folder_path[MAX_PATH];
520
521         int id = 0;
522         switch (_id) {
523         case PERSONAL:
524                 id = CSIDL_PERSONAL;
525                 break;
526         case APPDATA:
527                 id = CSIDL_APPDATA;
528                 break;
529         default:
530                 LASSERT(false, return string());
531         }
532         HRESULT const result = (folder_path_func_)(0, id, 0,
533                                                    SHGFP_TYPE_CURRENT,
534                                                    folder_path);
535         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
536 }
537
538
539 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
540 {
541         if (ext.empty())
542                 return false;
543
544         string const full_ext = "." + ext;
545
546         DWORD bufSize = MAX_PATH + 100;
547         TCHAR buf[MAX_PATH + 100];
548         // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
549         char const * action = (mode == VIEW) ? "open" : "edit";
550         return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
551                 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
552 }
553
554
555 bool autoOpenFile(string const & filename, auto_open_mode const mode,
556                   string const & path)
557 {
558         string const texinputs = os::latex_path_list(
559                         replaceCurdirPath(path, lyxrc.texinputs_prefix));
560         string const otherinputs = os::latex_path_list(path);
561         string const sep = windows_style_tex_paths_ ? ";" : ":";
562         string const oldtexinputs = getEnv("TEXINPUTS");
563         string const newtexinputs = "." + sep + texinputs + sep + oldtexinputs;
564         string const oldbibinputs = getEnv("BIBINPUTS");
565         string const newbibinputs = "." + sep + otherinputs + sep + oldbibinputs;
566         string const oldbstinputs = getEnv("BSTINPUTS");
567         string const newbstinputs = "." + sep + otherinputs + sep + oldbstinputs;
568         string const oldtexfonts = getEnv("TEXFONTS");
569         string const newtexfonts = "." + sep + otherinputs + sep + oldtexfonts;
570         if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
571                 setEnv("TEXINPUTS", newtexinputs);
572                 setEnv("BIBINPUTS", newbibinputs);
573                 setEnv("BSTINPUTS", newbstinputs);
574                 setEnv("TEXFONTS", newtexfonts);
575         }
576
577         QString const wname = toqstr(filename);
578
579         // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
580         wchar_t const * action = (mode == VIEW) ? L"open" : L"edit";
581         bool success = reinterpret_cast<intptr_t>(ShellExecuteW(NULL, action,
582                         reinterpret_cast<wchar_t const *>(wname.utf16()),
583                         NULL, NULL, 1)) > 32;
584
585         if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
586                 setEnv("TEXINPUTS", oldtexinputs);
587                 setEnv("BIBINPUTS", oldbibinputs);
588                 setEnv("BSTINPUTS", oldbstinputs);
589                 setEnv("TEXFONTS", oldtexfonts);
590         }
591         return success;
592 }
593
594
595 string real_path(string const & path)
596 {
597         // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
598         QString const qpath = get_long_path(toqstr(path));
599         HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
600                                 FILE_SHARE_READ, NULL, OPEN_EXISTING,
601                                 FILE_FLAG_BACKUP_SEMANTICS, NULL);
602
603         if (hpath == INVALID_HANDLE_VALUE) {
604                 // The file cannot be accessed.
605                 return path;
606         }
607
608         TCHAR realpath[MAX_PATH + 1];
609
610         DWORD size = GetFinalPathNameByHandle(hpath, realpath, MAX_PATH, VOLUME_NAME_NT);
611         if (size > MAX_PATH) {
612                 CloseHandle(hpath);
613                 return path;
614         }
615
616         // Translate device name to UNC prefix or drive letters.
617         TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
618         UINT namelen = _tcslen(tmpbuf);
619         if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
620                 // UNC path
621                 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
622                 strncpy(realpath, tmpbuf, MAX_PATH);
623                 realpath[MAX_PATH] = '\0';
624         } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
625                 // Check whether device name corresponds to some local drive.
626                 TCHAR name[MAX_PATH];
627                 TCHAR drive[3] = TEXT(" :");
628                 bool found = false;
629                 TCHAR * p = tmpbuf;
630                 do {
631                         // Copy the drive letter to the template string
632                         drive[0] = *p;
633                         // Look up each device name
634                         if (QueryDosDevice(drive, name, MAX_PATH)) {
635                                 namelen = _tcslen(name);
636                                 if (namelen < MAX_PATH) {
637                                         found = _tcsnicmp(realpath, name, namelen) == 0;
638                                         if (found) {
639                                                 // Repl. device spec with drive
640                                                 TCHAR tempfile[MAX_PATH];
641                                                 _snprintf(tempfile,
642                                                         MAX_PATH,
643                                                         "%s%s",
644                                                         drive,
645                                                         realpath + namelen);
646                                                 strncpy(realpath,
647                                                         tempfile,
648                                                         MAX_PATH);
649                                                 realpath[MAX_PATH] = '\0';
650                                         }
651                                 }
652                         }
653                         // Advance p to the next NULL character.
654                         while (*p++) ;
655                 } while (!found && *p);
656         }
657         CloseHandle(hpath);
658         string const retpath = subst(string(realpath), '\\', '/');
659         return FileName::fromFilesystemEncoding(retpath).absFileName();
660 }
661
662 } // namespace os
663 } // namespace support
664 } // namespace lyx