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"
27 #include "support/lassert.h"
32 /* The GetLongPathName macro may be defined on the compiling machine,
33 * but we must use a bit of trickery if the resulting executable is
34 * to run on a Win95 machine.
35 * Fortunately, Microsoft provide the trickery. All we need is the
36 * NewAPIs.h header file, available for download from Microsoft as
37 * part of the Platform SDK.
39 #if defined (HAVE_NEWAPIS_H)
40 // This should be defined already to keep Boost.Filesystem happy.
41 # if !defined (WANT_GETFILEATTRIBUTESEX_WRAPPER)
42 # error Expected WANT_GETFILEATTRIBUTESEX_WRAPPER to be defined!
44 # define WANT_GETLONGPATHNAME_WRAPPER 1
45 # define COMPILE_NEWAPIS_STUBS
47 # undef COMPILE_NEWAPIS_STUBS
48 # undef WANT_GETLONGPATHNAME_WRAPPER
52 #include <direct.h> // _getdrive
53 #include <shlobj.h> // SHGetFolderPath
58 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
59 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
61 # if __W32API_MAJOR_VERSION < 3 || \
62 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
63 # define SHGFP_TYPE_CURRENT 0
67 #if !defined(ASSOCF_INIT_IGNOREUNKNOWN) && !defined(__MINGW32__)
68 #define ASSOCF_INIT_IGNOREUNKNOWN 0
79 bool windows_style_tex_paths_ = true;
81 string cygdrive = "/cygdrive";
85 void init(int /* argc */, char * argv[])
87 /* Note from Angus, 17 Jan 2005:
89 * The code below is taken verbatim from Ruurd's original patch
90 * porting LyX to Win32.
92 * Windows allows us to define LyX either as a console-based app
93 * or as a GUI-based app. Ruurd decided to define LyX as a
94 * console-based app with a "main" function rather than a "WinMain"
95 * function as the point of entry to the program, but to
96 * immediately close the console window that Windows helpfully
97 * opens for us. Doing so allows the user to see all of LyX's
98 * debug output simply by running LyX from a DOS or MSYS-shell
101 * The alternative approach is to define LyX as a genuine
102 * GUI-based app, with a "WinMain" function as the entry point to the
103 * executable rather than a "main" function, so:
105 * #if defined (_WIN32)
106 * # define WIN32_LEAN_AND_MEAN
107 * # include <stdlib.h> // for __argc, __argv
108 * # include <windows.h> // for WinMain
111 * // This will require the "-mwindows" flag when linking with
112 * // gcc under MinGW.
113 * // For MSVC, use "/subsystem:windows".
114 * #if defined (_WIN32)
115 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
117 * return mymain(__argc, __argv);
121 * where "mymain" is just a renamed "main".
123 * However, doing so means that the lyxerr messages would mysteriously
124 * disappear. They could be resurrected with something like:
128 * freopen("conin$","r",stdin);
129 * freopen("conout$","w",stdout);
130 * freopen("conout$","w",stderr);
133 * This code could be invoked (say) the first time that lyxerr
134 * is called. However, Ruurd has tried this route and found that some
135 * shell scripts failed, for mysterious reasons...
137 * I've chosen for now, therefore, to simply add Ruurd's original
138 * code as-is. A wrapper program hidecmd.c has been added to
139 * development/Win32 which hides the console window of lyx when
140 * lyx is invoked as a parameter of hidecmd.exe.
143 // If cygwin is detected, query the cygdrive prefix
146 DWORD bufSize = sizeof(buf);
149 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
150 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
151 0, KEY_QUERY_VALUE, ®Key);
152 if (retVal != ERROR_SUCCESS) {
153 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
154 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
155 0, KEY_QUERY_VALUE, ®Key);
157 if (retVal == ERROR_SUCCESS) {
158 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
159 (LPBYTE) buf, &bufSize);
161 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
162 cygdrive = rtrim(string(buf), "/");
167 string current_root()
169 // _getdrive returns the current drive (1=A, 2=B, and so on).
170 char const drive = ::_getdrive() + 'A' - 1;
171 return string(1, drive) + ":/";
175 bool isFilesystemCaseSensitive()
181 docstring::size_type common_path(docstring const & p1, docstring const & p2)
184 size_t const p1_len = p1.length();
185 size_t const p2_len = p2.length();
186 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
188 if ((i < p1_len && i < p2_len)
189 || (i < p1_len && p1[i] != '/' && i == p2_len)
190 || (i < p2_len && p2[i] != '/' && i == p1_len))
193 --i; // here was the last match
194 while (i && p1[i] != '/')
201 string external_path(string const & p)
203 string const dos_path = subst(p, "/", "\\");
205 LYXERR(Debug::LATEX, "<Win32 path correction> ["
206 << p << "]->>[" << dos_path << ']');
211 static string const get_long_path(string const & short_path)
213 // GetLongPathName needs the path in file system encoding.
214 // We can use to_local8bit, since file system encoding and the
215 // local 8 bit encoding are identical on windows.
216 vector<char> long_path(MAX_PATH);
217 DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
218 &long_path[0], long_path.size());
220 if (result > long_path.size()) {
221 long_path.resize(result);
222 result = GetLongPathName(short_path.c_str(),
223 &long_path[0], long_path.size());
224 LASSERT(result <= long_path.size(), /**/);
227 return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
231 string internal_path(string const & p)
233 return subst(get_long_path(p), "\\", "/");
237 string external_path_list(string const & p)
239 return subst(p, '/', '\\');
243 string internal_path_list(string const & p)
245 return subst(p, '\\', '/');
249 string latex_path(string const & p)
251 // We may need a posix style path or a windows style path (depending
252 // on windows_style_tex_paths_), but we use always forward slashes,
253 // since it gets written into a .tex file.
256 if (!windows_style_tex_paths_ && path.isAbsolute()) {
257 string const drive = p.substr(0, 2);
258 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
259 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
260 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
261 << p << "]->>[" << cygpath << ']');
264 return subst(p, '\\', '/');
268 bool is_valid_strftime(string const & p)
270 string::size_type pos = p.find_first_of('%');
271 while (pos != string::npos) {
272 if (pos + 1 == string::npos)
274 if (!containsOnly(p.substr(pos + 1, 1),
275 "aAbBcdfHIjmMpSUwWxXyYzZ%"))
277 if (pos + 2 == string::npos)
279 pos = p.find_first_of('%', pos + 2);
285 // returns a string suitable to be passed to popen when
287 char const * popen_read_mode()
293 string const & nulldev()
295 static string const nulldev_ = "nul";
306 char path_separator()
312 void windows_style_tex_paths(bool use_windows_paths)
314 windows_style_tex_paths_ = use_windows_paths;
318 GetFolderPath::GetFolderPath()
322 folder_module_ = LoadLibrary("shfolder.dll");
323 if (!folder_module_) {
324 throw ExceptionMessage(ErrorException, _("System file not found"),
325 _("Unable to load shfolder.dll\nPlease install."));
328 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
329 if (folder_path_func_ == 0) {
330 throw ExceptionMessage(ErrorException, _("System function not found"),
331 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
332 "Don't know how to proceed. Sorry."));
337 GetFolderPath::~GetFolderPath()
340 FreeLibrary(folder_module_);
344 // Given a folder ID, returns the folder name (in unix-style format).
345 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
346 string const GetFolderPath::operator()(folder_id _id) const
348 char folder_path[MAX_PATH];
359 LASSERT(false, /**/);
361 HRESULT const result = (folder_path_func_)(0, id, 0,
364 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
368 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
373 string const full_ext = "." + ext;
375 DWORD bufSize = MAX_PATH + 100;
376 TCHAR buf[MAX_PATH + 100];
377 // reference: http://msdn.microsoft.com/en-us/library/bb773471.aspx
378 char const * action = (mode == VIEW) ? "open" : "edit";
379 return S_OK == AssocQueryString(ASSOCF_INIT_IGNOREUNKNOWN,
380 ASSOCSTR_EXECUTABLE, full_ext.c_str(), action, buf, &bufSize);
384 bool autoOpenFile(string const & filename, auto_open_mode const mode)
386 // reference: http://msdn.microsoft.com/en-us/library/bb762153.aspx
387 char const * action = (mode == VIEW) ? "open" : "edit";
388 return reinterpret_cast<int>(ShellExecute(NULL, action,
389 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
393 bool isSameFile(string const & fileone, string const & filetwo)
395 HANDLE h1 = CreateFile(fileone.c_str(), 0,
396 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
397 HANDLE h2 = CreateFile(filetwo.c_str(), 0,
398 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
400 if (h1 == INVALID_HANDLE_VALUE || h2 == INVALID_HANDLE_VALUE) {
401 // One or both files cannot be accessed.
402 if (h1 != INVALID_HANDLE_VALUE)
404 if (h2 != INVALID_HANDLE_VALUE)
409 BY_HANDLE_FILE_INFORMATION info1;
410 BY_HANDLE_FILE_INFORMATION info2;
411 bool samefile = false;
412 if (GetFileInformationByHandle(h1, &info1) != 0
413 && GetFileInformationByHandle(h2, &info2) != 0) {
414 // Serial number of the volumes containing the files.
415 ULONG st1_dev = info1.dwVolumeSerialNumber;
416 ULONG st2_dev = info2.dwVolumeSerialNumber;
417 // Unique identifiers associated to the files on the volumes.
418 ULONGLONG highbits = info1.nFileIndexHigh & 0x0000FFFF;
419 ULONGLONG st1_ino = (highbits << sizeof(ULONG)) | info1.nFileIndexLow;
420 highbits = info2.nFileIndexHigh & 0x0000FFFF;
421 ULONGLONG st2_ino = (highbits << sizeof(ULONG)) | info2.nFileIndexLow;
422 samefile = st1_ino == st2_ino && st1_dev == st2_dev;
430 } // namespace support