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.h"
19 #include "support/os_win32.h"
21 #include "support/debug.h"
22 #include "support/FileName.h"
23 #include "support/gettext.h"
24 #include "support/filetools.h"
25 #include "support/lstrings.h"
26 #include "support/ExceptionMessage.h"
27 #include "support/qstring_helpers.h"
29 #include "support/lassert.h"
37 #include <direct.h> // _getdrive
38 #include <shlobj.h> // SHGetFolderPath
43 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
44 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
46 # if __W32API_MAJOR_VERSION < 3 || \
47 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
48 # define SHGFP_TYPE_CURRENT 0
52 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
53 #define ASSOCF_INIT_IGNOREUNKNOWN 0
57 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
58 int expand_wildcards, int * new_mode);
75 bool windows_style_tex_paths_ = true;
77 string cygdrive = "/cygdrive";
79 BOOL terminate_handler(DWORD event)
81 if (event == CTRL_CLOSE_EVENT
82 || event == CTRL_LOGOFF_EVENT
83 || event == CTRL_SHUTDOWN_EVENT) {
92 void init(int argc, char * argv[])
94 /* Note from Angus, 17 Jan 2005:
96 * The code below is taken verbatim from Ruurd's original patch
97 * porting LyX to Win32.
99 * Windows allows us to define LyX either as a console-based app
100 * or as a GUI-based app. Ruurd decided to define LyX as a
101 * console-based app with a "main" function rather than a "WinMain"
102 * function as the point of entry to the program, but to
103 * immediately close the console window that Windows helpfully
104 * opens for us. Doing so allows the user to see all of LyX's
105 * debug output simply by running LyX from a DOS or MSYS-shell
108 * The alternative approach is to define LyX as a genuine
109 * GUI-based app, with a "WinMain" function as the entry point to the
110 * executable rather than a "main" function, so:
112 * #if defined (_WIN32)
113 * # define WIN32_LEAN_AND_MEAN
114 * # include <stdlib.h> // for __argc, __argv
115 * # include <windows.h> // for WinMain
118 * // This will require the "-mwindows" flag when linking with
119 * // gcc under MinGW.
120 * // For MSVC, use "/subsystem:windows".
121 * #if defined (_WIN32)
122 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
124 * return mymain(__argc, __argv);
128 * where "mymain" is just a renamed "main".
130 * However, doing so means that the lyxerr messages would mysteriously
131 * disappear. They could be resurrected with something like:
135 * freopen("conin$","r",stdin);
136 * freopen("conout$","w",stdout);
137 * freopen("conout$","w",stderr);
140 * This code could be invoked (say) the first time that lyxerr
141 * is called. However, Ruurd has tried this route and found that some
142 * shell scripts failed, for mysterious reasons...
144 * I've chosen for now, therefore, to simply add Ruurd's original
145 * code as-is. A wrapper program hidecmd.c has been added to
146 * development/Win32 which hides the console window of lyx when
147 * lyx is invoked as a parameter of hidecmd.exe.
151 // Get the wide program arguments array
154 __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
155 LASSERT(argc == argc_, /**/);
157 // If Cygwin is detected, query the cygdrive prefix.
158 // The cygdrive prefix is needed for translating windows style paths
159 // to posix style paths in LaTeX files when the Cygwin teTeX is used.
163 DWORD bufsize = sizeof(buf);
164 LONG retval = ERROR_FILE_NOT_FOUND;
165 HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
166 char const * const subkey[2] = {
167 "Software\\Cygwin\\setup", // Cygwin 1.7
168 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
170 char const * const valuename[2] = {
171 "rootdir", // Cygwin 1.7 or later
172 "native" // Previous versions
174 // Check for newer Cygwin versions first, then older ones
175 for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
176 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
177 retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
179 if (retval == ERROR_SUCCESS) {
180 // Query the Cygwin root directory
181 retval = RegQueryValueEx(hkey, valuename[i - 1],
182 NULL, NULL, (LPBYTE) buf, &bufsize);
184 string const mount = string(buf) + "\\bin\\mount.exe";
185 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
187 runCommand(mount + " --show-cygdrive-prefix");
188 // The output of the mount command is as follows:
190 // /cygdrive system binmode
191 // So, we use the inner split to pass the second line
192 // to the outer split which sets cygdrive with its
193 // contents until the first blank, discarding the
194 // unneeded return value.
195 if (p.first != -1 && prefixIs(p.second, "Prefix"))
196 split(split(p.second, '\n'), cygdrive, ' ');
200 // Catch shutdown events.
201 SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
205 string utf8_argv(int i)
207 LASSERT(i < argc_, /**/);
208 return fromqstr(QString::fromWCharArray(argv_[i]));
212 string current_root()
214 // _getdrive returns the current drive (1=A, 2=B, and so on).
215 char const drive = ::_getdrive() + 'A' - 1;
216 return string(1, drive) + ":/";
220 bool isFilesystemCaseSensitive()
226 docstring::size_type common_path(docstring const & p1, docstring const & p2)
229 size_t const p1_len = p1.length();
230 size_t const p2_len = p2.length();
231 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
233 if ((i < p1_len && i < p2_len)
234 || (i < p1_len && p1[i] != '/' && i == p2_len)
235 || (i < p2_len && p2[i] != '/' && i == p1_len))
238 --i; // here was the last match
239 while (i && p1[i] != '/')
246 bool path_prefix_is(string const & path, string const & pre)
248 return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
252 bool path_prefix_is(string & path, string const & pre, path_case how)
254 docstring const p1 = from_utf8(path);
255 docstring const p2 = from_utf8(pre);
256 docstring::size_type const p1_len = p1.length();
257 docstring::size_type const p2_len = p2.length();
258 docstring::size_type common_len = common_path(p1, p2);
260 if (p2[p2_len - 1] == '/' && p1_len != p2_len)
263 if (common_len != p2_len)
266 if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
267 if (p1_len < common_len)
268 path = to_utf8(p2.substr(0, p1_len));
270 path = to_utf8(p2 + p1.substr(common_len,
271 p1_len - common_len));
278 string external_path(string const & p)
280 string const dos_path = subst(p, "/", "\\");
282 LYXERR(Debug::LATEX, "<Win32 path correction> ["
283 << p << "]->>[" << dos_path << ']');
288 static QString const get_long_path(QString const & short_path)
290 // GetLongPathNameW needs the path in utf16 encoding.
291 vector<wchar_t> long_path(MAX_PATH);
292 DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
293 &long_path[0], long_path.size());
295 if (result > long_path.size()) {
296 long_path.resize(result);
297 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
298 &long_path[0], long_path.size());
299 LASSERT(result <= long_path.size(), /**/);
302 return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
306 static QString const get_short_path(QString const & long_path, file_access how)
308 // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
310 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
311 GENERIC_WRITE, 0, NULL, CREATE_NEW,
312 FILE_ATTRIBUTE_NORMAL, NULL);
313 if (h == INVALID_HANDLE_VALUE
314 && GetLastError() != ERROR_FILE_EXISTS)
318 vector<wchar_t> short_path(MAX_PATH);
319 DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
320 &short_path[0], short_path.size());
322 if (result > short_path.size()) {
323 short_path.resize(result);
324 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
325 &short_path[0], short_path.size());
326 LASSERT(result <= short_path.size(), /**/);
329 return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
333 string internal_path(string const & p)
335 return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
339 string safe_internal_path(string const & p, file_access how)
341 return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
345 string external_path_list(string const & p)
347 return subst(p, '/', '\\');
351 string internal_path_list(string const & p)
353 return subst(p, '\\', '/');
357 string latex_path(string const & p)
359 // We may need a posix style path or a windows style path (depending
360 // on windows_style_tex_paths_), but we use always forward slashes,
361 // since it gets written into a .tex file.
363 if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
364 string const drive = p.substr(0, 2);
365 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
366 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
367 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
368 << p << "]->>[" << cygpath << ']');
371 return subst(p, '\\', '/');
375 bool is_valid_strftime(string const & p)
377 string::size_type pos = p.find_first_of('%');
378 while (pos != string::npos) {
379 if (pos + 1 == string::npos)
381 if (!containsOnly(p.substr(pos + 1, 1),
382 "aAbBcdfHIjmMpSUwWxXyYzZ%"))
384 if (pos + 2 == string::npos)
386 pos = p.find_first_of('%', pos + 2);
392 // returns a string suitable to be passed to popen when
394 char const * popen_read_mode()
400 string const & nulldev()
402 static string const nulldev_ = "nul";
407 bool is_terminal(io_channel channel)
411 if (GetStdHandle(STD_INPUT_HANDLE) == NULL)
415 if (GetStdHandle(STD_OUTPUT_HANDLE) == NULL)
419 if (GetStdHandle(STD_ERROR_HANDLE) == NULL)
433 char path_separator()
439 void windows_style_tex_paths(bool use_windows_paths)
441 windows_style_tex_paths_ = use_windows_paths;
445 GetFolderPath::GetFolderPath()
449 folder_module_ = LoadLibrary("shfolder.dll");
450 if (!folder_module_) {
451 throw ExceptionMessage(ErrorException, _("System file not found"),
452 _("Unable to load shfolder.dll\nPlease install."));
455 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
456 if (folder_path_func_ == 0) {
457 throw ExceptionMessage(ErrorException, _("System function not found"),
458 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
459 "Don't know how to proceed. Sorry."));
464 GetFolderPath::~GetFolderPath()
467 FreeLibrary(folder_module_);
471 // Given a folder ID, returns the folder name (in unix-style format).
472 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
473 string const GetFolderPath::operator()(folder_id _id) const
475 char folder_path[MAX_PATH];
486 LASSERT(false, /**/);
488 HRESULT const result = (folder_path_func_)(0, id, 0,
491 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
495 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
500 string const full_ext = "." + ext;
502 DWORD bufSize = MAX_PATH + 100;
503 TCHAR buf[MAX_PATH + 100];
504 // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
505 char const * action = (mode == VIEW) ? "open" : "edit";
506 return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
507 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
511 bool autoOpenFile(string const & filename, auto_open_mode const mode)
513 // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
514 char const * action = (mode == VIEW) ? "open" : "edit";
515 return reinterpret_cast<int>(ShellExecute(NULL, action,
516 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
520 string real_path(string const & path)
522 // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
523 QString const qpath = get_long_path(toqstr(path));
524 HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
525 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
527 if (hpath == INVALID_HANDLE_VALUE) {
528 // The file cannot be accessed.
532 // Get the file size.
534 DWORD size_lo = GetFileSize(hpath, &size_hi);
536 if (size_lo == 0 && size_hi == 0) {
537 // A zero-length file cannot be mapped.
542 // Create a file mapping object.
543 HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
550 // Create a file mapping to get the file name.
551 void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
559 TCHAR realpath[MAX_PATH + 1];
561 if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
562 UnmapViewOfFile(pmem);
568 // Translate device name to UNC prefix or drive letters.
569 TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
570 UINT namelen = _tcslen(tmpbuf);
571 if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
573 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
574 strncpy(realpath, tmpbuf, MAX_PATH);
575 realpath[MAX_PATH] = '\0';
576 } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
577 // Check whether device name corresponds to some local drive.
578 TCHAR name[MAX_PATH];
579 TCHAR drive[3] = TEXT(" :");
583 // Copy the drive letter to the template string
585 // Look up each device name
586 if (QueryDosDevice(drive, name, MAX_PATH)) {
587 namelen = _tcslen(name);
588 if (namelen < MAX_PATH) {
589 found = _tcsnicmp(realpath, name, namelen) == 0;
591 // Repl. device spec with drive
592 TCHAR tempfile[MAX_PATH];
601 realpath[MAX_PATH] = '\0';
605 // Advance p to the next NULL character.
607 } while (!found && *p);
609 UnmapViewOfFile(pmem);
612 string const retpath = subst(string(realpath), '\\', '/');
613 return FileName::fromFilesystemEncoding(retpath).absFilename();
617 } // namespace support