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
10 * Full author contact details are available in file CREDITS.
12 * Various OS specific functions
17 #include "support/os.h"
18 #include "support/os_win32.h"
20 #include "support/debug.h"
21 #include "support/FileName.h"
22 #include "support/gettext.h"
23 #include "support/filetools.h"
24 #include "support/lstrings.h"
25 #include "support/ExceptionMessage.h"
26 #include "support/qstring_helpers.h"
28 #include "support/lassert.h"
36 #include <direct.h> // _getdrive
37 #include <shlobj.h> // SHGetFolderPath
42 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
43 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
45 # if __W32API_MAJOR_VERSION < 3 || \
46 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
47 # define SHGFP_TYPE_CURRENT 0
51 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
52 #define ASSOCF_INIT_IGNOREUNKNOWN 0
66 bool windows_style_tex_paths_ = true;
68 string cygdrive = "/cygdrive";
70 BOOL terminate_handler(DWORD event)
72 if (event == CTRL_CLOSE_EVENT
73 || event == CTRL_LOGOFF_EVENT
74 || event == CTRL_SHUTDOWN_EVENT) {
83 void init(int /* argc */, char * argv[])
85 /* Note from Angus, 17 Jan 2005:
87 * The code below is taken verbatim from Ruurd's original patch
88 * porting LyX to Win32.
90 * Windows allows us to define LyX either as a console-based app
91 * or as a GUI-based app. Ruurd decided to define LyX as a
92 * console-based app with a "main" function rather than a "WinMain"
93 * function as the point of entry to the program, but to
94 * immediately close the console window that Windows helpfully
95 * opens for us. Doing so allows the user to see all of LyX's
96 * debug output simply by running LyX from a DOS or MSYS-shell
99 * The alternative approach is to define LyX as a genuine
100 * GUI-based app, with a "WinMain" function as the entry point to the
101 * executable rather than a "main" function, so:
103 * #if defined (_WIN32)
104 * # define WIN32_LEAN_AND_MEAN
105 * # include <stdlib.h> // for __argc, __argv
106 * # include <windows.h> // for WinMain
109 * // This will require the "-mwindows" flag when linking with
110 * // gcc under MinGW.
111 * // For MSVC, use "/subsystem:windows".
112 * #if defined (_WIN32)
113 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
115 * return mymain(__argc, __argv);
119 * where "mymain" is just a renamed "main".
121 * However, doing so means that the lyxerr messages would mysteriously
122 * disappear. They could be resurrected with something like:
126 * freopen("conin$","r",stdin);
127 * freopen("conout$","w",stdout);
128 * freopen("conout$","w",stderr);
131 * This code could be invoked (say) the first time that lyxerr
132 * is called. However, Ruurd has tried this route and found that some
133 * shell scripts failed, for mysterious reasons...
135 * I've chosen for now, therefore, to simply add Ruurd's original
136 * code as-is. A wrapper program hidecmd.c has been added to
137 * development/Win32 which hides the console window of lyx when
138 * lyx is invoked as a parameter of hidecmd.exe.
141 // If Cygwin is detected, query the cygdrive prefix.
142 // The cygdrive prefix is needed for translating windows style paths
143 // to posix style paths in LaTeX files when the Cygwin teTeX is used.
147 DWORD bufsize = sizeof(buf);
148 LONG retval = ERROR_FILE_NOT_FOUND;
149 HKEY const mainkey[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
150 char const * const subkey[2] = {
151 "Software\\Cygwin\\setup", // Cygwin 1.7
152 "Software\\Cygnus Solutions\\Cygwin\\mounts v2\\/" // Prev. ver.
154 char const * const valuename[2] = {
155 "rootdir", // Cygwin 1.7 or later
156 "native" // Previous versions
158 // Check for newer Cygwin versions first, then older ones
159 for (i = 0; i < 2 && retval != ERROR_SUCCESS; ++i) {
160 for (int k = 0; k < 2 && retval != ERROR_SUCCESS; ++k)
161 retval = RegOpenKey(mainkey[k], subkey[i], &hkey);
163 if (retval == ERROR_SUCCESS) {
164 // Query the Cygwin root directory
165 retval = RegQueryValueEx(hkey, valuename[i - 1],
166 NULL, NULL, (LPBYTE) buf, &bufsize);
168 string const mount = string(buf) + "\\bin\\mount.exe";
169 if (retval == ERROR_SUCCESS && FileName(mount).exists()) {
171 runCommand(mount + " --show-cygdrive-prefix");
172 // The output of the mount command is as follows:
174 // /cygdrive system binmode
175 // So, we use the inner split to pass the second line
176 // to the outer split which sets cygdrive with its
177 // contents until the first blank, discarding the
178 // unneeded return value.
179 if (p.first != -1 && prefixIs(p.second, "Prefix"))
180 split(split(p.second, '\n'), cygdrive, ' ');
184 // Catch shutdown events.
185 SetConsoleCtrlHandler((PHANDLER_ROUTINE)terminate_handler, TRUE);
189 string current_root()
191 // _getdrive returns the current drive (1=A, 2=B, and so on).
192 char const drive = ::_getdrive() + 'A' - 1;
193 return string(1, drive) + ":/";
197 bool isFilesystemCaseSensitive()
203 docstring::size_type common_path(docstring const & p1, docstring const & p2)
206 size_t const p1_len = p1.length();
207 size_t const p2_len = p2.length();
208 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
210 if ((i < p1_len && i < p2_len)
211 || (i < p1_len && p1[i] != '/' && i == p2_len)
212 || (i < p2_len && p2[i] != '/' && i == p1_len))
215 --i; // here was the last match
216 while (i && p1[i] != '/')
223 bool path_prefix_is(string const & path, string const & pre)
225 return path_prefix_is(const_cast<string &>(path), pre, CASE_UNCHANGED);
229 bool path_prefix_is(string & path, string const & pre, path_case how)
231 docstring const p1 = from_utf8(path);
232 docstring const p2 = from_utf8(pre);
233 docstring::size_type const p1_len = p1.length();
234 docstring::size_type const p2_len = p2.length();
235 docstring::size_type common_len = common_path(p1, p2);
237 if (p2[p2_len - 1] == '/' && p1_len != p2_len)
240 if (common_len != p2_len)
243 if (how == CASE_ADJUSTED && !prefixIs(path, pre)) {
244 if (p1_len < common_len)
245 path = to_utf8(p2.substr(0, p1_len));
247 path = to_utf8(p2 + p1.substr(common_len,
248 p1_len - common_len));
255 string external_path(string const & p)
257 string const dos_path = subst(p, "/", "\\");
259 LYXERR(Debug::LATEX, "<Win32 path correction> ["
260 << p << "]->>[" << dos_path << ']');
265 static QString const get_long_path(QString const & short_path)
267 // GetLongPathNameW needs the path in utf16 encoding.
268 vector<wchar_t> long_path(MAX_PATH);
269 DWORD result = GetLongPathNameW((wchar_t *) short_path.utf16(),
270 &long_path[0], long_path.size());
272 if (result > long_path.size()) {
273 long_path.resize(result);
274 result = GetLongPathNameW((wchar_t *) short_path.utf16(),
275 &long_path[0], long_path.size());
276 LASSERT(result <= long_path.size(), /**/);
279 return (result == 0) ? short_path : QString::fromWCharArray(&long_path[0]);
283 static QString const get_short_path(QString const & long_path, file_access how)
285 // CreateFileW and GetShortPathNameW needs the path in utf16 encoding.
287 HANDLE h = CreateFileW((wchar_t *) long_path.utf16(),
288 GENERIC_WRITE, 0, NULL, CREATE_NEW,
289 FILE_ATTRIBUTE_NORMAL, NULL);
290 if (h == INVALID_HANDLE_VALUE
291 && GetLastError() != ERROR_FILE_EXISTS)
295 vector<wchar_t> short_path(MAX_PATH);
296 DWORD result = GetShortPathNameW((wchar_t *) long_path.utf16(),
297 &short_path[0], short_path.size());
299 if (result > short_path.size()) {
300 short_path.resize(result);
301 result = GetShortPathNameW((wchar_t *) long_path.utf16(),
302 &short_path[0], short_path.size());
303 LASSERT(result <= short_path.size(), /**/);
306 return (result == 0) ? long_path : QString::fromWCharArray(&short_path[0]);
310 string internal_path(string const & p)
312 return subst(fromqstr(get_long_path(toqstr(p))), "\\", "/");
316 string safe_internal_path(string const & p, file_access how)
318 return subst(fromqstr(get_short_path(toqstr(p), how)), "\\", "/");
322 string external_path_list(string const & p)
324 return subst(p, '/', '\\');
328 string internal_path_list(string const & p)
330 return subst(p, '\\', '/');
334 string latex_path(string const & p)
336 // We may need a posix style path or a windows style path (depending
337 // on windows_style_tex_paths_), but we use always forward slashes,
338 // since it gets written into a .tex file.
340 if (!windows_style_tex_paths_ && FileName::isAbsolute(p)) {
341 string const drive = p.substr(0, 2);
342 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
343 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
344 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
345 << p << "]->>[" << cygpath << ']');
348 return subst(p, '\\', '/');
352 bool is_valid_strftime(string const & p)
354 string::size_type pos = p.find_first_of('%');
355 while (pos != string::npos) {
356 if (pos + 1 == string::npos)
358 if (!containsOnly(p.substr(pos + 1, 1),
359 "aAbBcdfHIjmMpSUwWxXyYzZ%"))
361 if (pos + 2 == string::npos)
363 pos = p.find_first_of('%', pos + 2);
369 // returns a string suitable to be passed to popen when
371 char const * popen_read_mode()
377 string const & nulldev()
379 static string const nulldev_ = "nul";
384 bool is_terminal(io_channel channel)
388 if (GetStdHandle(STD_INPUT_HANDLE) == NULL)
392 if (GetStdHandle(STD_OUTPUT_HANDLE) == NULL)
396 if (GetStdHandle(STD_ERROR_HANDLE) == NULL)
410 char path_separator()
416 void windows_style_tex_paths(bool use_windows_paths)
418 windows_style_tex_paths_ = use_windows_paths;
422 GetFolderPath::GetFolderPath()
426 folder_module_ = LoadLibrary("shfolder.dll");
427 if (!folder_module_) {
428 throw ExceptionMessage(ErrorException, _("System file not found"),
429 _("Unable to load shfolder.dll\nPlease install."));
432 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
433 if (folder_path_func_ == 0) {
434 throw ExceptionMessage(ErrorException, _("System function not found"),
435 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
436 "Don't know how to proceed. Sorry."));
441 GetFolderPath::~GetFolderPath()
444 FreeLibrary(folder_module_);
448 // Given a folder ID, returns the folder name (in unix-style format).
449 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
450 string const GetFolderPath::operator()(folder_id _id) const
452 char folder_path[MAX_PATH];
463 LASSERT(false, /**/);
465 HRESULT const result = (folder_path_func_)(0, id, 0,
468 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
472 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
477 string const full_ext = "." + ext;
479 DWORD bufSize = MAX_PATH + 100;
480 TCHAR buf[MAX_PATH + 100];
481 // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
482 char const * action = (mode == VIEW) ? "open" : "edit";
483 return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
484 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
488 bool autoOpenFile(string const & filename, auto_open_mode const mode)
490 // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
491 char const * action = (mode == VIEW) ? "open" : "edit";
492 return reinterpret_cast<int>(ShellExecute(NULL, action,
493 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
497 string real_path(string const & path)
499 // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
500 QString const qpath = get_long_path(toqstr(path));
501 HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ,
502 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
504 if (hpath == INVALID_HANDLE_VALUE) {
505 // The file cannot be accessed.
509 // Get the file size.
511 DWORD size_lo = GetFileSize(hpath, &size_hi);
513 if (size_lo == 0 && size_hi == 0) {
514 // A zero-length file cannot be mapped.
519 // Create a file mapping object.
520 HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL);
527 // Create a file mapping to get the file name.
528 void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1);
536 TCHAR realpath[MAX_PATH + 1];
538 if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) {
539 UnmapViewOfFile(pmem);
545 // Translate device name to UNC prefix or drive letters.
546 TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\");
547 UINT namelen = _tcslen(tmpbuf);
548 if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) {
550 _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen);
551 strncpy(realpath, tmpbuf, MAX_PATH);
552 realpath[MAX_PATH] = '\0';
553 } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) {
554 // Check whether device name corresponds to some local drive.
555 TCHAR name[MAX_PATH];
556 TCHAR drive[3] = TEXT(" :");
560 // Copy the drive letter to the template string
562 // Look up each device name
563 if (QueryDosDevice(drive, name, MAX_PATH)) {
564 namelen = _tcslen(name);
565 if (namelen < MAX_PATH) {
566 found = _tcsnicmp(realpath, name, namelen) == 0;
568 // Repl. device spec with drive
569 TCHAR tempfile[MAX_PATH];
578 realpath[MAX_PATH] = '\0';
582 // Advance p to the next NULL character.
584 } while (!found && *p);
586 UnmapViewOfFile(pmem);
589 string const retpath = subst(string(realpath), '\\', '/');
590 return FileName::fromFilesystemEncoding(retpath).absFilename();
594 } // namespace support