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"
19 #include "support/debug.h"
20 #include "support/gettext.h"
21 #include "support/filetools.h"
22 #include "support/lstrings.h"
23 #include "support/ExceptionMessage.h"
25 #include <boost/assert.hpp>
30 /* The GetLongPathName macro may be defined on the compiling machine,
31 * but we must use a bit of trickery if the resulting executable is
32 * to run on a Win95 machine.
33 * Fortunately, Microsoft provide the trickery. All we need is the
34 * NewAPIs.h header file, available for download from Microsoft as
35 * part of the Platform SDK.
37 #if defined (HAVE_NEWAPIS_H)
38 // This should be defined already to keep Boost.Filesystem happy.
39 # if !defined (WANT_GETFILEATTRIBUTESEX_WRAPPER)
40 # error Expected WANT_GETFILEATTRIBUTESEX_WRAPPER to be defined!
42 # define WANT_GETLONGPATHNAME_WRAPPER 1
43 # define COMPILE_NEWAPIS_STUBS
45 # undef COMPILE_NEWAPIS_STUBS
46 # undef WANT_GETLONGPATHNAME_WRAPPER
50 #include <direct.h> // _getdrive
51 #include <shlobj.h> // SHGetFolderPath
56 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
57 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
59 # if __W32API_MAJOR_VERSION < 3 || \
60 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
61 # define SHGFP_TYPE_CURRENT 0
73 bool windows_style_tex_paths_ = true;
75 string cygdrive = "/cygdrive";
79 void init(int /* argc */, char * argv[])
81 /* Note from Angus, 17 Jan 2005:
83 * The code below is taken verbatim from Ruurd's original patch
84 * porting LyX to Win32.
86 * Windows allows us to define LyX either as a console-based app
87 * or as a GUI-based app. Ruurd decided to define LyX as a
88 * console-based app with a "main" function rather than a "WinMain"
89 * function as the point of entry to the program, but to
90 * immediately close the console window that Windows helpfully
91 * opens for us. Doing so allows the user to see all of LyX's
92 * debug output simply by running LyX from a DOS or MSYS-shell
95 * The alternative approach is to define LyX as a genuine
96 * GUI-based app, with a "WinMain" function as the entry point to the
97 * executable rather than a "main" function, so:
99 * #if defined (_WIN32)
100 * # define WIN32_LEAN_AND_MEAN
101 * # include <stdlib.h> // for __argc, __argv
102 * # include <windows.h> // for WinMain
105 * // This will require the "-mwindows" flag when linking with
106 * // gcc under MinGW.
107 * // For MSVC, use "/subsystem:windows".
108 * #if defined (_WIN32)
109 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
111 * return mymain(__argc, __argv);
115 * where "mymain" is just a renamed "main".
117 * However, doing so means that the lyxerr messages would mysteriously
118 * disappear. They could be resurrected with something like:
122 * freopen("conin$","r",stdin);
123 * freopen("conout$","w",stdout);
124 * freopen("conout$","w",stderr);
127 * This code could be invoked (say) the first time that lyxerr
128 * is called. However, Ruurd has tried this route and found that some
129 * shell scripts failed, for mysterious reasons...
131 * I've chosen for now, therefore, to simply add Ruurd's original
132 * code as-is. A wrapper program hidecmd.c has been added to
133 * development/Win32 which hides the console window of lyx when
134 * lyx is invoked as a parameter of hidecmd.exe.
137 // If cygwin is detected, query the cygdrive prefix
140 DWORD bufSize = sizeof(buf);
143 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
144 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
145 0, KEY_QUERY_VALUE, ®Key);
146 if (retVal != ERROR_SUCCESS) {
147 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
148 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
149 0, KEY_QUERY_VALUE, ®Key);
151 if (retVal == ERROR_SUCCESS) {
152 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
153 (LPBYTE) buf, &bufSize);
155 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
161 string current_root()
163 // _getdrive returns the current drive (1=A, 2=B, and so on).
164 char const drive = ::_getdrive() + 'A' - 1;
165 return string(1, drive) + ":/";
169 docstring::size_type common_path(docstring const & p1, docstring const & p2)
172 size_t const p1_len = p1.length();
173 size_t const p2_len = p2.length();
174 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
176 if ((i < p1_len && i < p2_len)
177 || (i < p1_len && p1[i] != '/' && i == p2_len)
178 || (i < p2_len && p2[i] != '/' && i == p1_len))
181 --i; // here was the last match
182 while (i && p1[i] != '/')
189 string external_path(string const & p)
191 string const dos_path = subst(p, "/", "\\");
193 LYXERR(Debug::LATEX, "<Win32 path correction> ["
194 << p << "]->>[" << dos_path << ']');
199 static string const get_long_path(string const & short_path)
201 // GetLongPathName needs the path in file system encoding.
202 // We can use to_local8bit, since file system encoding and the
203 // local 8 bit encoding are identical on windows.
204 vector<char> long_path(MAX_PATH);
205 DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
206 &long_path[0], long_path.size());
208 if (result > long_path.size()) {
209 long_path.resize(result);
210 result = GetLongPathName(short_path.c_str(),
211 &long_path[0], long_path.size());
212 BOOST_ASSERT(result <= long_path.size());
215 return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
219 string internal_path(string const & p)
221 return subst(get_long_path(p), "\\", "/");
225 string external_path_list(string const & p)
227 return subst(p, '/', '\\');
231 string internal_path_list(string const & p)
233 return subst(p, '\\', '/');
237 string latex_path(string const & p)
239 // We may need a posix style path or a windows style path (depending
240 // on windows_style_tex_paths_), but we use always forward slashes,
241 // since it gets written into a .tex file.
243 if (!windows_style_tex_paths_ && is_absolute_path(p)) {
244 string const drive = p.substr(0, 2);
245 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
246 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
247 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
248 << p << "]->>[" << cygpath << ']');
251 return subst(p, '\\', '/');
255 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
256 // Therefore an absolute path could be either a pathname starting
257 // with a slash (Unix) or a pathname starting with a drive letter
258 // followed by a colon. Because a colon is not valid in pathes in Unix
259 // and at another location in Win32 testing just for the existance
260 // of the colon in the 2nd position seems to be enough!
261 bool is_absolute_path(string const & p)
266 bool isDosPath = (p.length() > 1 && p[1] == ':');
267 bool isUnixPath = (p[0] == '/');
269 return isDosPath || isUnixPath;
273 // returns a string suitable to be passed to popen when
275 char const * popen_read_mode()
281 string const & nulldev()
283 static string const nulldev_ = "nul";
294 char path_separator()
300 void windows_style_tex_paths(bool use_windows_paths)
302 windows_style_tex_paths_ = use_windows_paths;
306 GetFolderPath::GetFolderPath()
310 folder_module_ = LoadLibrary("shfolder.dll");
311 if (!folder_module_) {
312 throw ExceptionMessage(ErrorException, _("System file not found"),
313 _("Unable to load shfolder.dll\nPlease install."));
316 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
317 if (folder_path_func_ == 0) {
318 throw ExceptionMessage(ErrorException, _("System function not found"),
319 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
320 "Don't know how to proceed. Sorry."));
325 GetFolderPath::~GetFolderPath()
328 FreeLibrary(folder_module_);
332 // Given a folder ID, returns the folder name (in unix-style format).
333 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
334 string const GetFolderPath::operator()(folder_id _id) const
336 char folder_path[MAX_PATH];
349 HRESULT const result = (folder_path_func_)(0, id, 0,
352 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
356 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
361 string const full_ext = "." + ext;
363 DWORD bufSize = MAX_PATH + 100;
364 TCHAR buf[MAX_PATH + 100];
365 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
366 // /platform/shell/reference/shlwapi/registry/assocquerystring.asp
367 char const * action = (mode == VIEW) ? "open" : "edit";
368 return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
369 full_ext.c_str(), action, buf, &bufSize);
373 bool autoOpenFile(string const & filename, auto_open_mode const mode)
375 // reference: http://msdn.microsoft.com/library/default.asp
376 // ?url=/library/en-us/shellcc/platform/shell/reference/functions/
378 char const * action = (mode == VIEW) ? "open" : "edit";
379 return reinterpret_cast<int>(ShellExecute(NULL, action,
380 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
384 } // namespace support