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"
40 #include <direct.h> // _getdrive
41 #include <shlobj.h> // SHGetFolderPath
46 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
47 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
49 # if __W32API_MAJOR_VERSION < 3 || \
50 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
51 # define SHGFP_TYPE_CURRENT 0
55 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
56 #define ASSOCF_INIT_IGNOREUNKNOWN 0
59 #if defined(__MINGW32__)
65 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
66 int expand_wildcards, int * new_mode);
83 bool windows_style_tex_paths_ = true;
85 string cygdrive = "/cygdrive";
87 BOOL terminate_handler(DWORD event)
89 if (event == CTRL_CLOSE_EVENT
90 || event == CTRL_LOGOFF_EVENT
91 || event == CTRL_SHUTDOWN_EVENT) {
100 void init(int argc, char * argv[])
102 /* Note from Angus, 17 Jan 2005:
104 * The code below is taken verbatim from Ruurd's original patch
105 * porting LyX to Win32.
107 * Windows allows us to define LyX either as a console-based app
108 * or as a GUI-based app. Ruurd decided to define LyX as a
109 * console-based app with a "main" function rather than a "WinMain"
110 * function as the point of entry to the program, but to
111 * immediately close the console window that Windows helpfully
112 * opens for us. Doing so allows the user to see all of LyX's
113 * debug output simply by running LyX from a DOS or MSYS-shell
116 * The alternative approach is to define LyX as a genuine
117 * GUI-based app, with a "WinMain" function as the entry point to the
118 * executable rather than a "main" function, so:
120 * #if defined (_WIN32)
121 * # define WIN32_LEAN_AND_MEAN
122 * # include <stdlib.h> // for __argc, __argv
123 * # include <windows.h> // for WinMain
126 * // This will require the "-mwindows" flag when linking with
127 * // gcc under MinGW.
128 * // For MSVC, use "/subsystem:windows".
129 * #if defined (_WIN32)
130 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
132 * return mymain(__argc, __argv);
136 * where "mymain" is just a renamed "main".
138 * However, doing so means that the lyxerr messages would mysteriously
139 * disappear. They could be resurrected with something like:
143 * freopen("conin$","r",stdin);
144 * freopen("conout$","w",stdout);
145 * freopen("conout$","w",stderr);
148 * This code could be invoked (say) the first time that lyxerr
149 * is called. However, Ruurd has tried this route and found that some
150 * shell scripts failed, for mysterious reasons...
152 * I've chosen for now, therefore, to simply add Ruurd's original
153 * code as-is. A wrapper program hidecmd.c has been added to
154 * development/Win32 which hides the console window of lyx when
155 * lyx is invoked as a parameter of hidecmd.exe.
159 // Get the wide program arguments array
162 __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
163 LASSERT(argc == argc_, /**/);
165 // If Cygwin is detected, query the cygdrive prefix.
166 // The cygdrive prefix is needed for translating windows style paths
167 // to posix style paths in LaTeX files when the Cygwin teTeX is used.
171 DWORD bufsize = sizeof(buf);
172 LONG retval = ERROR_FILE_NOT_FOUND;
173 HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
174 char const * const subkey[2] = {
175 "Software\\Cygwin\\setup", // Cygwin 1.7
176 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
178 char const * const valuename[2] = {
179 "rootdir", // Cygwin 1.7 or later
180 "native" // Previous versions
182 // Check for newer Cygwin versions first, then older ones
183 for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
184 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
185 retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
187 if (retval == ERROR_SUCCESS) {
188 // Query the Cygwin root directory
189 retval = RegQueryValueEx(hkey, valuename[i - 1],
190 NULL, NULL, (LPBYTE) buf, &bufsize);
192 string const mount = string(buf) + "\\bin\\mount.exe";
193 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
195 runCommand(mount + " --show-cygdrive-prefix");
196 // The output of the mount command is as follows:
198 // /cygdrive system binmode
199 // So, we use the inner split to pass the second line
200 // to the outer split which sets cygdrive with its
201 // contents until the first blank, discarding the
202 // unneeded return value.
203 if (p.first != -1 && prefixIs(p.second, "Prefix"))
204 split(split(p.second, '\n'), cygdrive, ' ');
208 // Catch shutdown events.
209 SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
213 string utf8_argv(int i)
215 LASSERT(i < argc_, /**/);
216 return fromqstr(QString::fromWCharArray(argv_[i]));
220 void remove_internal_args(int i, int num)
223 for (int j = i; j < argc_; ++j)
224 argv_[j] = argv_[j + num];
228 string current_root()
230 // _getdrive returns the current drive (1=A, 2=B, and so on).
231 char const drive = ::_getdrive() + 'A' - 1;
232 return string(1, drive) + ":/";
236 bool isFilesystemCaseSensitive()
242 docstring::size_type common_path(docstring const & p1, docstring const & p2)
245 size_t const p1_len = p1.length();
246 size_t const p2_len = p2.length();
247 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
249 if ((i < p1_len && i < p2_len)
250 || (i < p1_len && p1[i] != '/' && i == p2_len)
251 || (i < p2_len && p2[i] != '/' && i == p1_len))
254 --i; // here was the last match
255 while (i && p1[i] != '/')
262 bool path_prefix_is(string const & path, string const & pre)
264 return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
268 bool path_prefix_is(string & path, string const & pre, path_case how)
270 docstring const p1 = from_utf8(path);
271 docstring const p2 = from_utf8(pre);
272 docstring::size_type const p1_len = p1.length();
273 docstring::size_type const p2_len = p2.length();
274 docstring::size_type common_len = common_path(p1, p2);
276 if (p2[p2_len - 1] == '/' && p1_len != p2_len)
279 if (common_len != p2_len)
282 if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
283 if (p1_len < common_len)
284 path = to_utf8(p2.substr(0, p1_len));
286 path = to_utf8(p2 + p1.substr(common_len,
287 p1_len - common_len));
294 string external_path(string const & p)
296 string const dos_path = subst(p, "/", "\\");
298 LYXERR(Debug::LATEX, "<Win32 path correction> ["
299 << p << "]->>[" << dos_path << ']');
304 static QString const get_long_path(QString const & short_path)
306 // GetLongPathNameW needs the path in utf16 encoding.
307 vector<wchar_t> long_path(MAX_PATH);
308 DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
309 &long_path[0], long_path.size());
311 if (result > long_path.size()) {
312 long_path.resize(result);
313 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
314 &long_path[0], long_path.size());
315 LASSERT(result <= long_path.size(), /**/);
318 return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
322 static QString const get_short_path(QString const & long_path, file_access how)
324 // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
326 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
327 GENERIC_WRITE, 0, NULL, CREATE_NEW,
328 FILE_ATTRIBUTE_NORMAL, NULL);
329 if (h == INVALID_HANDLE_VALUE
330 && GetLastError() != ERROR_FILE_EXISTS)
334 vector<wchar_t> short_path(MAX_PATH);
335 DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
336 &short_path[0], short_path.size());
338 if (result > short_path.size()) {
339 short_path.resize(result);
340 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
341 &short_path[0], short_path.size());
342 LASSERT(result <= short_path.size(), /**/);
345 return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
349 string internal_path(string const & p)
351 return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
355 string safe_internal_path(string const & p, file_access how)
357 return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
361 string external_path_list(string const & p)
363 return subst(p, '/', '\\');
367 string internal_path_list(string const & p)
369 return subst(p, '\\', '/');
373 string latex_path(string const & p)
375 // We may need a posix style path or a windows style path (depending
376 // on windows_style_tex_paths_), but we use always forward slashes,
377 // since it gets written into a .tex file.
379 if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
380 string const drive = p.substr(0, 2);
381 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
382 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
383 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
384 << p << "]->>[" << cygpath << ']');
387 return subst(p, '\\', '/');
391 string latex_path_list(string const & p)
396 // We may need a posix style path or a windows style path (depending
397 // on windows_style_tex_paths_), but we use always forward slashes,
398 // since this is standard for all tex engines.
400 if (!windows_style_tex_paths_) {
402 for (size_t i = 0, k = 0; i != string::npos; k = i) {
404 string path = subst(p.substr(k, i - k), '\\', '/');
405 if (FileName::isAbsolute(path)) {
406 string const drive = path.substr(0, 2);
407 string const cygprefix = cygdrive + "/"
408 + drive.substr(0, 1);
409 path = subst(path, drive, cygprefix);
412 if (i != string::npos) {
419 return subst(p, '\\', '/');
423 bool is_valid_strftime(string const & p)
425 string::size_type pos = p.find_first_of('%');
426 while (pos != string::npos) {
427 if (pos + 1 == string::npos)
429 if (!containsOnly(p.substr(pos + 1, 1),
430 "aAbBcdfHIjmMpSUwWxXyYzZ%"))
432 if (pos + 2 == string::npos)
434 pos = p.find_first_of('%', pos + 2);
440 // returns a string suitable to be passed to popen when
442 char const * popen_read_mode()
448 string const & nulldev()
450 static string const nulldev_ = "nul";
461 char path_separator(path_type type)
463 if (type == TEXENGINE)
464 return windows_style_tex_paths_ ? ';' : ':';
470 void windows_style_tex_paths(bool use_windows_paths)
472 windows_style_tex_paths_ = use_windows_paths;
476 GetFolderPath::GetFolderPath()
480 folder_module_ = LoadLibrary("shfolder.dll");
481 if (!folder_module_) {
482 throw ExceptionMessage(ErrorException, _("System file not found"),
483 _("Unable to load shfolder.dll\nPlease install."));
486 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
487 if (folder_path_func_ == 0) {
488 throw ExceptionMessage(ErrorException, _("System function not found"),
489 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
490 "Don't know how to proceed. Sorry."));
495 GetFolderPath::~GetFolderPath()
498 FreeLibrary(folder_module_);
502 // Given a folder ID, returns the folder name (in unix-style format).
503 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
504 string const GetFolderPath::operator()(folder_id _id) const
506 char folder_path[MAX_PATH];
517 LASSERT(false, /**/);
519 HRESULT const result = (folder_path_func_)(0, id, 0,
522 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
526 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
531 string const full_ext = "." + ext;
533 DWORD bufSize = MAX_PATH + 100;
534 TCHAR buf[MAX_PATH + 100];
535 // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
536 char const * action = (mode == VIEW) ? "open" : "edit";
537 return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
538 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
542 bool autoOpenFile(string const & filename, auto_open_mode const mode,
545 string const texinputs = os::latex_path_list(
546 replaceCurdirPath(path, lyxrc.texinputs_prefix));
547 string const sep = windows_style_tex_paths_ ? ";" : ":";
548 string const oldval = getEnv("TEXINPUTS");
549 string const newval = "." + sep + texinputs + sep + oldval;
550 if (!path.empty() && !lyxrc.texinputs_prefix.empty())
551 setEnv("TEXINPUTS", newval);
553 // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
554 char const * action = (mode == VIEW) ? "open" : "edit";
555 bool success = reinterpret_cast<int>(ShellExecute(NULL, action,
556 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
558 if (!path.empty() && !lyxrc.texinputs_prefix.empty())
559 setEnv("TEXINPUTS", oldval);
564 string real_path(string const & path)
566 // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
567 QString const qpath = get_long_path(toqstr(path));
568 HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
569 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
571 if (hpath == INVALID_HANDLE_VALUE) {
572 // The file cannot be accessed.
576 // Get the file size.
578 DWORD size_lo = GetFileSize(hpath, &size_hi);
580 if (size_lo == 0 && size_hi == 0) {
581 // A zero-length file cannot be mapped.
586 // Create a file mapping object.
587 HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
594 // Create a file mapping to get the file name.
595 void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
603 TCHAR realpath[MAX_PATH + 1];
605 if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
606 UnmapViewOfFile(pmem);
612 // Translate device name to UNC prefix or drive letters.
613 TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
614 UINT namelen = _tcslen(tmpbuf);
615 if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
617 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
618 strncpy(realpath, tmpbuf, MAX_PATH);
619 realpath[MAX_PATH] = '\0';
620 } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
621 // Check whether device name corresponds to some local drive.
622 TCHAR name[MAX_PATH];
623 TCHAR drive[3] = TEXT(" :");
627 // Copy the drive letter to the template string
629 // Look up each device name
630 if (QueryDosDevice(drive, name, MAX_PATH)) {
631 namelen = _tcslen(name);
632 if (namelen < MAX_PATH) {
633 found = _tcsnicmp(realpath, name, namelen) == 0;
635 // Repl. device spec with drive
636 TCHAR tempfile[MAX_PATH];
645 realpath[MAX_PATH] = '\0';
649 // Advance p to the next NULL character.
651 } while (!found && *p);
653 UnmapViewOfFile(pmem);
656 string const retpath = subst(string(realpath), '\\', '/');
657 return FileName::fromFilesystemEncoding(retpath).absFileName();
661 } // namespace support