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
56 #if defined(__MINGW32__)
62 extern void __wgetmainargs(int * argc, wchar_t *** argv, wchar_t *** envp,
63 int expand_wildcards, int * new_mode);
80 bool windows_style_tex_paths_ = true;
82 string cygdrive = "/cygdrive";
84 BOOL terminate_handler(DWORD event)
86 if (event == CTRL_CLOSE_EVENT
87 || event == CTRL_LOGOFF_EVENT
88 || event == CTRL_SHUTDOWN_EVENT) {
97 void init(int argc, char * argv[])
99 /* Note from Angus, 17 Jan 2005:
101 * The code below is taken verbatim from Ruurd's original patch
102 * porting LyX to Win32.
104 * Windows allows us to define LyX either as a console-based app
105 * or as a GUI-based app. Ruurd decided to define LyX as a
106 * console-based app with a "main" function rather than a "WinMain"
107 * function as the point of entry to the program, but to
108 * immediately close the console window that Windows helpfully
109 * opens for us. Doing so allows the user to see all of LyX's
110 * debug output simply by running LyX from a DOS or MSYS-shell
113 * The alternative approach is to define LyX as a genuine
114 * GUI-based app, with a "WinMain" function as the entry point to the
115 * executable rather than a "main" function, so:
117 * #if defined (_WIN32)
118 * # define WIN32_LEAN_AND_MEAN
119 * # include <stdlib.h> // for __argc, __argv
120 * # include <windows.h> // for WinMain
123 * // This will require the "-mwindows" flag when linking with
124 * // gcc under MinGW.
125 * // For MSVC, use "/subsystem:windows".
126 * #if defined (_WIN32)
127 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
129 * return mymain(__argc, __argv);
133 * where "mymain" is just a renamed "main".
135 * However, doing so means that the lyxerr messages would mysteriously
136 * disappear. They could be resurrected with something like:
140 * freopen("conin$","r",stdin);
141 * freopen("conout$","w",stdout);
142 * freopen("conout$","w",stderr);
145 * This code could be invoked (say) the first time that lyxerr
146 * is called. However, Ruurd has tried this route and found that some
147 * shell scripts failed, for mysterious reasons...
149 * I've chosen for now, therefore, to simply add Ruurd's original
150 * code as-is. A wrapper program hidecmd.c has been added to
151 * development/Win32 which hides the console window of lyx when
152 * lyx is invoked as a parameter of hidecmd.exe.
156 // Get the wide program arguments array
159 __wgetmainargs(&argc_, &argv_, &envp, -1, &newmode);
160 LASSERT(argc == argc_, /**/);
162 // If Cygwin is detected, query the cygdrive prefix.
163 // The cygdrive prefix is needed for translating windows style paths
164 // to posix style paths in LaTeX files when the Cygwin teTeX is used.
168 DWORD bufsize = sizeof(buf);
169 LONG retval = ERROR_FILE_NOT_FOUND;
170 HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
171 char const * const subkey[2] = {
172 "Software\\Cygwin\\setup", // Cygwin 1.7
173 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
175 char const * const valuename[2] = {
176 "rootdir", // Cygwin 1.7 or later
177 "native" // Previous versions
179 // Check for newer Cygwin versions first, then older ones
180 for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
181 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
182 retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
184 if (retval == ERROR_SUCCESS) {
185 // Query the Cygwin root directory
186 retval = RegQueryValueEx(hkey, valuename[i - 1],
187 NULL, NULL, (LPBYTE) buf, &bufsize);
189 string const mount = string(buf) + "\\bin\\mount.exe";
190 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
192 runCommand(mount + " --show-cygdrive-prefix");
193 // The output of the mount command is as follows:
195 // /cygdrive system binmode
196 // So, we use the inner split to pass the second line
197 // to the outer split which sets cygdrive with its
198 // contents until the first blank, discarding the
199 // unneeded return value.
200 if (p.first != -1 && prefixIs(p.second, "Prefix"))
201 split(split(p.second, '\n'), cygdrive, ' ');
205 // Catch shutdown events.
206 SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
210 string utf8_argv(int i)
212 LASSERT(i < argc_, /**/);
213 return fromqstr(QString::fromWCharArray(argv_[i]));
217 void remove_internal_args(int i, int num)
220 for (int j = i; j < argc_; ++j)
221 argv_[j] = argv_[j + num];
225 string current_root()
227 // _getdrive returns the current drive (1=A, 2=B, and so on).
228 char const drive = ::_getdrive() + 'A' - 1;
229 return string(1, drive) + ":/";
233 bool isFilesystemCaseSensitive()
239 docstring::size_type common_path(docstring const & p1, docstring const & p2)
242 size_t const p1_len = p1.length();
243 size_t const p2_len = p2.length();
244 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
246 if ((i < p1_len && i < p2_len)
247 || (i < p1_len && p1[i] != '/' && i == p2_len)
248 || (i < p2_len && p2[i] != '/' && i == p1_len))
251 --i; // here was the last match
252 while (i && p1[i] != '/')
259 bool path_prefix_is(string const & path, string const & pre)
261 return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
265 bool path_prefix_is(string & path, string const & pre, path_case how)
267 docstring const p1 = from_utf8(path);
268 docstring const p2 = from_utf8(pre);
269 docstring::size_type const p1_len = p1.length();
270 docstring::size_type const p2_len = p2.length();
271 docstring::size_type common_len = common_path(p1, p2);
273 if (p2[p2_len - 1] == '/' && p1_len != p2_len)
276 if (common_len != p2_len)
279 if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
280 if (p1_len < common_len)
281 path = to_utf8(p2.substr(0, p1_len));
283 path = to_utf8(p2 + p1.substr(common_len,
284 p1_len - common_len));
291 string external_path(string const & p)
293 string const dos_path = subst(p, "/", "\\");
295 LYXERR(Debug::LATEX, "<Win32 path correction> ["
296 << p << "]->>[" << dos_path << ']');
301 static QString const get_long_path(QString const & short_path)
303 // GetLongPathNameW needs the path in utf16 encoding.
304 vector<wchar_t> long_path(MAX_PATH);
305 DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
306 &long_path[0], long_path.size());
308 if (result > long_path.size()) {
309 long_path.resize(result);
310 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
311 &long_path[0], long_path.size());
312 LASSERT(result <= long_path.size(), /**/);
315 return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
319 static QString const get_short_path(QString const & long_path, file_access how)
321 // CreateFileW and GetShortPathNameW need the path in utf16 encoding.
323 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
324 GENERIC_WRITE, 0, NULL, CREATE_NEW,
325 FILE_ATTRIBUTE_NORMAL, NULL);
326 if (h == INVALID_HANDLE_VALUE
327 && GetLastError() != ERROR_FILE_EXISTS)
331 vector<wchar_t> short_path(MAX_PATH);
332 DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
333 &short_path[0], short_path.size());
335 if (result > short_path.size()) {
336 short_path.resize(result);
337 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
338 &short_path[0], short_path.size());
339 LASSERT(result <= short_path.size(), /**/);
342 return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
346 string internal_path(string const & p)
348 return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
352 string safe_internal_path(string const & p, file_access how)
354 return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
358 string external_path_list(string const & p)
360 return subst(p, '/', '\\');
364 string internal_path_list(string const & p)
366 return subst(p, '\\', '/');
370 string latex_path(string const & p)
372 // We may need a posix style path or a windows style path (depending
373 // on windows_style_tex_paths_), but we use always forward slashes,
374 // since it gets written into a .tex file.
376 if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
377 string const drive = p.substr(0, 2);
378 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
379 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
380 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
381 << p << "]->>[" << cygpath << ']');
384 return subst(p, '\\', '/');
388 bool is_valid_strftime(string const & p)
390 string::size_type pos = p.find_first_of('%');
391 while (pos != string::npos) {
392 if (pos + 1 == string::npos)
394 if (!containsOnly(p.substr(pos + 1, 1),
395 "aAbBcdfHIjmMpSUwWxXyYzZ%"))
397 if (pos + 2 == string::npos)
399 pos = p.find_first_of('%', pos + 2);
405 // returns a string suitable to be passed to popen when
407 char const * popen_read_mode()
413 string const & nulldev()
415 static string const nulldev_ = "nul";
426 char path_separator()
432 void windows_style_tex_paths(bool use_windows_paths)
434 windows_style_tex_paths_ = use_windows_paths;
438 GetFolderPath::GetFolderPath()
442 folder_module_ = LoadLibrary("shfolder.dll");
443 if (!folder_module_) {
444 throw ExceptionMessage(ErrorException, _("System file not found"),
445 _("Unable to load shfolder.dll\nPlease install."));
448 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
449 if (folder_path_func_ == 0) {
450 throw ExceptionMessage(ErrorException, _("System function not found"),
451 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
452 "Don't know how to proceed. Sorry."));
457 GetFolderPath::~GetFolderPath()
460 FreeLibrary(folder_module_);
464 // Given a folder ID, returns the folder name (in unix-style format).
465 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
466 string const GetFolderPath::operator()(folder_id _id) const
468 char folder_path[MAX_PATH];
479 LASSERT(false, /**/);
481 HRESULT const result = (folder_path_func_)(0, id, 0,
484 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
488 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
493 string const full_ext = "." + ext;
495 DWORD bufSize = MAX_PATH + 100;
496 TCHAR buf[MAX_PATH + 100];
497 // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
498 char const * action = (mode == VIEW) ? "open" : "edit";
499 return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
500 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
504 bool autoOpenFile(string const & filename, auto_open_mode const mode)
506 // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
507 char const * action = (mode == VIEW) ? "open" : "edit";
508 return reinterpret_cast<int>(ShellExecute(NULL, action,
509 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
513 string real_path(string const & path)
515 // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
516 QString const qpath = get_long_path(toqstr(path));
517 HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
518 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
520 if (hpath == INVALID_HANDLE_VALUE) {
521 // The file cannot be accessed.
525 // Get the file size.
527 DWORD size_lo = GetFileSize(hpath, &size_hi);
529 if (size_lo == 0 && size_hi == 0) {
530 // A zero-length file cannot be mapped.
535 // Create a file mapping object.
536 HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
543 // Create a file mapping to get the file name.
544 void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
552 TCHAR realpath[MAX_PATH + 1];
554 if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
555 UnmapViewOfFile(pmem);
561 // Translate device name to UNC prefix or drive letters.
562 TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
563 UINT namelen = _tcslen(tmpbuf);
564 if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
566 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
567 strncpy(realpath, tmpbuf, MAX_PATH);
568 realpath[MAX_PATH] = '\0';
569 } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
570 // Check whether device name corresponds to some local drive.
571 TCHAR name[MAX_PATH];
572 TCHAR drive[3] = TEXT(" :");
576 // Copy the drive letter to the template string
578 // Look up each device name
579 if (QueryDosDevice(drive, name, MAX_PATH)) {
580 namelen = _tcslen(name);
581 if (namelen < MAX_PATH) {
582 found = _tcsnicmp(realpath, name, namelen) == 0;
584 // Repl. device spec with drive
585 TCHAR tempfile[MAX_PATH];
594 realpath[MAX_PATH] = '\0';
598 // Advance p to the next NULL character.
600 } while (!found && *p);
602 UnmapViewOfFile(pmem);
605 string const retpath = subst(string(realpath), '\\', '/');
606 return FileName::fromFilesystemEncoding(retpath).absFileName();
610 } // namespace support