3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Ruurd A. Reitsma
7 * \author Claus Hentschel
8 * \author Angus Leeming
9 * \author Enrico Forestieri
11 * Full author contact details are available in file CREDITS.
13 * Various OS specific functions
20 #include "support/os.h"
21 #include "support/os_win32.h"
23 #include "support/debug.h"
24 #include "support/environment.h"
25 #include "support/FileName.h"
26 #include "support/gettext.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/qstring_helpers.h"
32 #include "support/lassert.h"
41 #include <direct.h> // _getdrive
42 #include <fileapi.h> // GetFinalPathNameByHandle
43 #include <shlobj.h> // SHGetFolderPath
48 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
49 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
51 # if __W32API_MAJOR_VERSION < 3 || \
52 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
53 # define SHGFP_TYPE_CURRENT 0
57 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
58 #define ASSOCF_INIT_IGNOREUNKNOWN 0
61 #if defined(__MINGW32__)
65 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
68 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
69 int expand_wildcards, int * new_mode);
87 bool windows_style_tex_paths_ = true;
89 string cygdrive = "/cygdrive";
91 BOOL terminate_handler(DWORD event)
93 if (event == CTRL_CLOSE_EVENT
94 || event == CTRL_LOGOFF_EVENT
95 || event == CTRL_SHUTDOWN_EVENT) {
104 void init(int argc, char ** argv[])
106 /* Note from Angus, 17 Jan 2005:
108 * The code below is taken verbatim from Ruurd's original patch
109 * porting LyX to Win32.
111 * Windows allows us to define LyX either as a console-based app
112 * or as a GUI-based app. Ruurd decided to define LyX as a
113 * console-based app with a "main" function rather than a "WinMain"
114 * function as the point of entry to the program, but to
115 * immediately close the console window that Windows helpfully
116 * opens for us. Doing so allows the user to see all of LyX's
117 * debug output simply by running LyX from a DOS or MSYS-shell
120 * The alternative approach is to define LyX as a genuine
121 * GUI-based app, with a "WinMain" function as the entry point to the
122 * executable rather than a "main" function, so:
124 * #if defined (_WIN32)
125 * # define WIN32_LEAN_AND_MEAN
126 * # include <stdlib.h> // for __argc, __argv
127 * # include <windows.h> // for WinMain
130 * // This will require the "-mwindows" flag when linking with
131 * // gcc under MinGW.
132 * // For MSVC, use "/subsystem:windows".
133 * #if defined (_WIN32)
134 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
136 * return mymain(__argc, __argv);
140 * where "mymain" is just a renamed "main".
142 * However, doing so means that the lyxerr messages would mysteriously
143 * disappear. They could be resurrected with something like:
147 * freopen("conin$","r",stdin);
148 * freopen("conout$","w",stdout);
149 * freopen("conout$","w",stderr);
152 * This code could be invoked (say) the first time that lyxerr
153 * is called. However, Ruurd has tried this route and found that some
154 * shell scripts failed, for mysterious reasons...
156 * I've chosen for now, therefore, to simply add Ruurd's original
157 * code as-is. A wrapper program hidecmd.c has been added to
158 * development/Win32 which hides the console window of lyx when
159 * lyx is invoked as a parameter of hidecmd.exe.
163 // Remove PYTHONPATH from the environment as it may point to an
164 // external python installation and cause reconfigure failures.
165 unsetEnv("PYTHONPATH");
168 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
169 // Removing an argument from argv leads to an assertion on Windows
170 // when compiling with MSVC 2015 in debug mode (see bug #10440).
171 // To avoid this we make a copy of the array of pointers.
172 char ** newargv = (char **) malloc((argc + 1) * sizeof(char *));
174 memcpy(newargv, *argv, (argc + 1) * sizeof(char *));
177 lyxerr << "LyX warning: Cannot make a copy of "
178 "command line arguments!"
184 // Get the wide program arguments array
185 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
186 argv_ = CommandLineToArgvW(GetCommandLineW(), &argc_);
190 __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
192 LATTEST(argc == argc_);
194 // If Cygwin is detected, query the cygdrive prefix.
195 // The cygdrive prefix is needed for translating windows style paths
196 // to posix style paths in LaTeX files when the Cygwin teTeX is used.
200 DWORD bufsize = sizeof(buf);
201 LONG retval = ERROR_FILE_NOT_FOUND;
202 HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
203 char const * const subkey[2] = {
204 "Software\\Cygwin\\setup", // Cygwin 1.7
205 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
207 char const * const valuename[2] = {
208 "rootdir", // Cygwin 1.7 or later
209 "native" // Previous versions
211 // Check for newer Cygwin versions first, then older ones
212 for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
213 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
214 retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
216 if (retval == ERROR_SUCCESS) {
217 // Query the Cygwin root directory
218 retval = RegQueryValueEx(hkey, valuename[i - 1],
219 NULL, NULL, (LPBYTE) buf, &bufsize);
221 string const mount = string(buf) + "\\bin\\mount.exe";
222 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
224 runCommand(mount + " --show-cygdrive-prefix");
225 // The output of the mount command is as follows:
227 // /cygdrive system binmode
228 // So, we use the inner split to pass the second line
229 // to the outer split which sets cygdrive with its
230 // contents until the first blank, discarding the
231 // unneeded return value.
232 if (p.first != -1 && prefixIs(p.second, "Prefix"))
233 split(split(p.second, '\n'), cygdrive, ' ');
237 // Catch shutdown events.
238 SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
242 string utf8_argv(int i)
244 LASSERT(i < argc_, return "");
245 return fromqstr(QString::fromWCharArray(argv_[i]));
249 void remove_internal_args(int i, int num)
252 for (int j = i; j < argc_; ++j)
253 argv_[j] = argv_[j + num];
257 string current_root()
259 // _getdrive returns the current drive (1=A, 2=B, and so on).
260 char const drive = ::_getdrive() + 'A' - 1;
261 return string(1, drive) + ":/";
265 bool isFilesystemCaseSensitive()
271 docstring::size_type common_path(docstring const & p1, docstring const & p2)
274 size_t const p1_len = p1.length();
275 size_t const p2_len = p2.length();
276 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
278 if ((i < p1_len && i < p2_len)
279 || (i < p1_len && p1[i] != '/' && i == p2_len)
280 || (i < p2_len && p2[i] != '/' && i == p1_len))
283 --i; // here was the last match
284 while (i && p1[i] != '/')
291 bool path_prefix_is(string const & path, string const & pre)
293 return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
297 bool path_prefix_is(string & path, string const & pre, path_case how)
299 docstring const p1 = from_utf8(path);
300 docstring const p2 = from_utf8(pre);
301 docstring::size_type const p1_len = p1.length();
302 docstring::size_type const p2_len = p2.length();
303 docstring::size_type common_len = common_path(p1, p2);
305 if (p2[p2_len - 1] == '/' && p1_len != p2_len)
308 if (common_len != p2_len)
311 if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
312 if (p1_len < common_len)
313 path = to_utf8(p2.substr(0, p1_len));
315 path = to_utf8(p2 + p1.substr(common_len,
316 p1_len - common_len));
323 string external_path(string const & p)
325 string const dos_path = subst(p, "/", "\\");
327 LYXERR(Debug::LATEX, "<Win32 path correction> ["
328 << p << "]->>[" << dos_path << ']');
333 static QString const get_long_path(QString const & short_path)
335 // GetLongPathNameW needs the path in utf16 encoding.
336 vector<wchar_t> long_path(MAX_PATH);
337 DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
338 &long_path[0], long_path.size());
340 if (result > long_path.size()) {
341 long_path.resize(result);
342 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
343 &long_path[0], long_path.size());
344 LATTEST(result <= long_path.size());
347 return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
351 static QString const get_short_path(QString const & long_path, file_access how)
353 // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
355 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
356 GENERIC_WRITE, 0, NULL, CREATE_NEW,
357 FILE_ATTRIBUTE_NORMAL, NULL);
358 if (h == INVALID_HANDLE_VALUE
359 && GetLastError() != ERROR_FILE_EXISTS)
363 vector<wchar_t> short_path(MAX_PATH);
364 DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
365 &short_path[0], short_path.size());
367 if (result > short_path.size()) {
368 short_path.resize(result);
369 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
370 &short_path[0], short_path.size());
371 LATTEST(result <= short_path.size());
374 return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
378 string internal_path(string const & p)
380 return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
384 string safe_internal_path(string const & p, file_access how)
386 return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
390 string external_path_list(string const & p)
392 return subst(p, '/', '\\');
396 string internal_path_list(string const & p)
398 return subst(p, '\\', '/');
402 string latex_path(string const & p)
404 // We may need a posix style path or a windows style path (depending
405 // on windows_style_tex_paths_), but we use always forward slashes,
406 // since it gets written into a .tex file.
408 if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
409 string const drive = p.substr(0, 2);
410 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
411 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
412 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
413 << p << "]->>[" << cygpath << ']');
416 return subst(p, '\\', '/');
420 string latex_path_list(string const & p)
425 // We may need a posix style path or a windows style path (depending
426 // on windows_style_tex_paths_), but we use always forward slashes,
427 // since this is standard for all tex engines.
429 if (!windows_style_tex_paths_) {
431 for (size_t i = 0, k = 0; i != string::npos; k = i) {
433 string path = subst(p.substr(k, i - k), '\\', '/');
434 if (FileName::isAbsolute(path)) {
435 string const drive = path.substr(0, 2);
436 string const cygprefix = cygdrive + "/"
437 + drive.substr(0, 1);
438 path = subst(path, drive, cygprefix);
441 if (i != string::npos) {
448 return subst(p, '\\', '/');
452 // returns a string suitable to be passed to popen when
454 char const * popen_read_mode()
460 string const & nulldev()
462 static string const nulldev_ = "nul";
473 char path_separator(path_type type)
475 if (type == TEXENGINE)
476 return windows_style_tex_paths_ ? ';' : ':';
482 void windows_style_tex_paths(bool use_windows_paths)
484 windows_style_tex_paths_ = use_windows_paths;
488 GetFolderPath::GetFolderPath()
492 folder_module_ = LoadLibrary("shfolder.dll");
493 if (!folder_module_) {
494 throw ExceptionMessage(ErrorException, _("System file not found"),
495 _("Unable to load shfolder.dll\nPlease install."));
498 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
499 if (folder_path_func_ == 0) {
500 throw ExceptionMessage(ErrorException, _("System function not found"),
501 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
502 "Don't know how to proceed. Sorry."));
507 GetFolderPath::~GetFolderPath()
510 FreeLibrary(folder_module_);
514 // Given a folder ID, returns the folder name (in unix-style format).
515 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
516 string const GetFolderPath::operator()(folder_id _id) const
518 char folder_path[MAX_PATH];
529 LASSERT(false, return string());
531 HRESULT const result = (folder_path_func_)(0, id, 0,
534 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
538 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
543 string const full_ext = "." + ext;
545 DWORD bufSize = MAX_PATH + 100;
546 TCHAR buf[MAX_PATH + 100];
547 // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
548 char const * action = (mode == VIEW) ? "open" : "edit";
549 return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
550 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
554 bool autoOpenFile(string const & filename, auto_open_mode const mode,
557 string const texinputs = os::latex_path_list(
558 replaceCurdirPath(path, lyxrc.texinputs_prefix));
559 string const otherinputs = os::latex_path_list(path);
560 string const sep = windows_style_tex_paths_ ? ";" : ":";
561 string const oldtexinputs = getEnv("TEXINPUTS");
562 string const newtexinputs = "." + sep + texinputs + sep + oldtexinputs;
563 string const oldbibinputs = getEnv("BIBINPUTS");
564 string const newbibinputs = "." + sep + otherinputs + sep + oldbibinputs;
565 string const oldbstinputs = getEnv("BSTINPUTS");
566 string const newbstinputs = "." + sep + otherinputs + sep + oldbstinputs;
567 string const oldtexfonts = getEnv("TEXFONTS");
568 string const newtexfonts = "." + sep + otherinputs + sep + oldtexfonts;
569 if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
570 setEnv("TEXINPUTS", newtexinputs);
571 setEnv("BIBINPUTS", newbibinputs);
572 setEnv("BSTINPUTS", newbstinputs);
573 setEnv("TEXFONTS", newtexfonts);
576 QString const wname = toqstr(filename);
578 // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
579 wchar_t const * action = (mode == VIEW) ? L"open" : L"edit";
580 bool success = reinterpret_cast<intptr_t>(ShellExecuteW(NULL, action,
581 reinterpret_cast<wchar_t const *>(wname.utf16()),
582 NULL, NULL, 1)) > 32;
584 if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
585 setEnv("TEXINPUTS", oldtexinputs);
586 setEnv("BIBINPUTS", oldbibinputs);
587 setEnv("BSTINPUTS", oldbstinputs);
588 setEnv("TEXFONTS", oldtexfonts);
594 string real_path(string const & path)
596 // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
597 QString const qpath = get_long_path(toqstr(path));
598 HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
599 FILE_SHARE_READ, NULL, OPEN_EXISTING,
600 FILE_FLAG_BACKUP_SEMANTICS, NULL);
602 if (hpath == INVALID_HANDLE_VALUE) {
603 // The file cannot be accessed.
607 TCHAR realpath[MAX_PATH + 1];
609 DWORD size = GetFinalPathNameByHandle(hpath, realpath, MAX_PATH, VOLUME_NAME_NT);
610 if (size > MAX_PATH) {
615 // Translate device name to UNC prefix or drive letters.
616 TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
617 UINT namelen = _tcslen(tmpbuf);
618 if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
620 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
621 strncpy(realpath, tmpbuf, MAX_PATH);
622 realpath[MAX_PATH] = '\0';
623 } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
624 // Check whether device name corresponds to some local drive.
625 TCHAR name[MAX_PATH];
626 TCHAR drive[3] = TEXT(" :");
630 // Copy the drive letter to the template string
632 // Look up each device name
633 if (QueryDosDevice(drive, name, MAX_PATH)) {
634 namelen = _tcslen(name);
635 if (namelen < MAX_PATH) {
636 found = _tcsnicmp(realpath, name, namelen) == 0;
638 // Repl. device spec with drive
639 TCHAR tempfile[MAX_PATH];
648 realpath[MAX_PATH] = '\0';
652 // Advance p to the next NULL character.
654 } while (!found && *p);
657 string const retpath = subst(string(realpath), '\\', '/');
658 return FileName::fromFilesystemEncoding(retpath).absFileName();
662 } // namespace support