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
18 #include "support/os_win32.h"
22 #include "support/os.h"
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"
33 #include "support/lassert.h"
42 #include <direct.h> // _getdrive
43 #include <fileapi.h> // GetFinalPathNameByHandle
44 #include <shlobj.h> // SHGetFolderPath
49 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
50 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
52 # if __W32API_MAJOR_VERSION < 3 || \
53 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
54 # define SHGFP_TYPE_CURRENT 0
58 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
59 #define ASSOCF_INIT_IGNOREUNKNOWN 0
62 #if defined(__MINGW32__)
66 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
69 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
70 int expand_wildcards, int * new_mode);
88 bool windows_style_tex_paths_ = true;
90 string cygdrive = "/cygdrive";
92 BOOL terminate_handler(DWORD event)
94 if (event == CTRL_CLOSE_EVENT
95 || event == CTRL_LOGOFF_EVENT
96 || event == CTRL_SHUTDOWN_EVENT) {
105 void init(int argc, char ** argv[])
107 /* Note from Angus, 17 Jan 2005:
109 * The code below is taken verbatim from Ruurd's original patch
110 * porting LyX to Win32.
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
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:
125 * #if defined (_WIN32)
126 * # define WIN32_LEAN_AND_MEAN
127 * # include <stdlib.h> // for __argc, __argv
128 * # include <windows.h> // for WinMain
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)
137 * return mymain(__argc, __argv);
141 * where "mymain" is just a renamed "main".
143 * However, doing so means that the lyxerr messages would mysteriously
144 * disappear. They could be resurrected with something like:
148 * freopen("conin$","r",stdin);
149 * freopen("conout$","w",stdout);
150 * freopen("conout$","w",stderr);
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...
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.
164 // Remove PYTHONPATH from the environment as it may point to an
165 // external python installation and cause reconfigure failures.
166 unsetEnv("PYTHONPATH");
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 *));
175 memcpy(newargv, *argv, (argc + 1) * sizeof(char *));
178 lyxerr << "LyX warning: Cannot make a copy of "
179 "command line arguments!"
185 // Get the wide program arguments array
186 #if defined(_MSC_VER) && (_MSC_VER >= 1900)
187 argv_ = CommandLineToArgvW(GetCommandLineW(), &argc_);
191 __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
193 LATTEST(argc == argc_);
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.
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.
208 char const * const valuename[2] = {
209 "rootdir", // Cygwin 1.7 or later
210 "native" // Previous versions
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);
217 if (retval == ERROR_SUCCESS) {
218 // Query the Cygwin root directory
219 retval = RegQueryValueEx(hkey, valuename[i - 1],
220 NULL, NULL, (LPBYTE) buf, &bufsize);
222 string const mount = string(buf) + "\\bin\\mount.exe";
223 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
225 runCommand(mount + " --show-cygdrive-prefix");
226 // The output of the mount command is as follows:
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, ' ');
238 // Catch shutdown events.
239 SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
243 string utf8_argv(int i)
245 LASSERT(i < argc_, return "");
246 return fromqstr(QString::fromWCharArray(argv_[i]));
250 void remove_internal_args(int i, int num)
253 for (int j = i; j < argc_; ++j)
254 argv_[j] = argv_[j + num];
258 string current_root()
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) + ":/";
266 bool isFilesystemCaseSensitive()
272 docstring::size_type common_path(docstring const & p1, docstring const & p2)
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]))
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))
284 --i; // here was the last match
285 while (i && p1[i] != '/')
292 bool path_prefix_is(string const & path, string const & pre)
294 return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
298 bool path_prefix_is(string & path, string const & pre, path_case how)
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);
306 if (p2[p2_len - 1] == '/' && p1_len != p2_len)
309 if (common_len != p2_len)
312 if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
313 if (p1_len < common_len)
314 path = to_utf8(p2.substr(0, p1_len));
316 path = to_utf8(p2 + p1.substr(common_len,
317 p1_len - common_len));
324 string external_path(string const & p)
326 string const dos_path = subst(p, "/", "\\");
328 LYXERR(Debug::OUTFILE, "<Win32 path correction> ["
329 << p << "]->>[" << dos_path << ']');
334 static QString const get_long_path(QString const & short_path)
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());
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());
348 return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
352 static QString const get_short_path(QString const & long_path, file_access how)
354 // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
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)
364 vector<wchar_t> short_path(MAX_PATH);
365 DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
366 &short_path[0], short_path.size());
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());
375 return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
379 string internal_path(string const & p)
381 return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
385 string safe_internal_path(string const & p, file_access how)
387 return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
391 string external_path_list(string const & p)
393 return subst(p, '/', '\\');
397 string internal_path_list(string const & p)
399 return subst(p, '\\', '/');
403 string latex_path(string const & p)
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.
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::OUTFILE, "<Path correction for LaTeX> ["
414 << p << "]->>[" << cygpath << ']');
417 return subst(p, '\\', '/');
421 string latex_path_list(string const & p)
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.
430 if (!windows_style_tex_paths_) {
432 for (size_t i = 0, k = 0; i != string::npos; k = 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);
442 if (i != string::npos) {
449 return subst(p, '\\', '/');
453 // returns a string suitable to be passed to popen when
455 char const * popen_read_mode()
461 string const & nulldev()
463 static string const nulldev_ = "nul";
474 char path_separator(path_type type)
476 if (type == TEXENGINE)
477 return windows_style_tex_paths_ ? ';' : ':';
483 void windows_style_tex_paths(bool use_windows_paths)
485 windows_style_tex_paths_ = use_windows_paths;
489 GetFolderPath::GetFolderPath()
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."));
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."));
508 GetFolderPath::~GetFolderPath()
511 FreeLibrary(folder_module_);
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
519 char folder_path[MAX_PATH];
530 LASSERT(false, return string());
532 HRESULT const result = (folder_path_func_)(0, id, 0,
535 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
539 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
544 string const full_ext = "." + ext;
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);
555 bool autoOpenFile(string const & filename, auto_open_mode const mode,
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);
577 QString const wname = toqstr(filename);
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;
585 if (!path.empty() && !lyxrc.texinputs_prefix.empty()) {
586 setEnv("TEXINPUTS", oldtexinputs);
587 setEnv("BIBINPUTS", oldbibinputs);
588 setEnv("BSTINPUTS", oldbstinputs);
589 setEnv("TEXFONTS", oldtexfonts);
595 string real_path(string const & path)
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);
603 if (hpath == INVALID_HANDLE_VALUE) {
604 // The file cannot be accessed.
608 TCHAR realpath[MAX_PATH + 1];
610 DWORD size = GetFinalPathNameByHandle(hpath, realpath, MAX_PATH, VOLUME_NAME_NT);
611 if (size > MAX_PATH) {
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) {
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(" :");
631 // Copy the drive letter to the template string
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;
639 // Repl. device spec with drive
640 TCHAR tempfile[MAX_PATH];
649 realpath[MAX_PATH] = '\0';
653 // Advance p to the next NULL character.
655 } while (!found && *p);
658 string const retpath = subst(string(realpath), '\\', '/');
659 return FileName::fromFilesystemEncoding(retpath).absFileName();
663 } // namespace support