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
74 bool windows_style_tex_paths_ = true;
76 string cygdrive = "/cygdrive";
80 void init(int /* argc */, char * argv[])
82 /* Note from Angus, 17 Jan 2005:
84 * The code below is taken verbatim from Ruurd's original patch
85 * porting LyX to Win32.
87 * Windows allows us to define LyX either as a console-based app
88 * or as a GUI-based app. Ruurd decided to define LyX as a
89 * console-based app with a "main" function rather than a "WinMain"
90 * function as the point of entry to the program, but to
91 * immediately close the console window that Windows helpfully
92 * opens for us. Doing so allows the user to see all of LyX's
93 * debug output simply by running LyX from a DOS or MSYS-shell
96 * The alternative approach is to define LyX as a genuine
97 * GUI-based app, with a "WinMain" function as the entry point to the
98 * executable rather than a "main" function, so:
100 * #if defined (_WIN32)
101 * # define WIN32_LEAN_AND_MEAN
102 * # include <stdlib.h> // for __argc, __argv
103 * # include <windows.h> // for WinMain
106 * // This will require the "-mwindows" flag when linking with
107 * // gcc under MinGW.
108 * // For MSVC, use "/subsystem:windows".
109 * #if defined (_WIN32)
110 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
112 * return mymain(__argc, __argv);
116 * where "mymain" is just a renamed "main".
118 * However, doing so means that the lyxerr messages would mysteriously
119 * disappear. They could be resurrected with something like:
123 * freopen("conin$","r",stdin);
124 * freopen("conout$","w",stdout);
125 * freopen("conout$","w",stderr);
128 * This code could be invoked (say) the first time that lyxerr
129 * is called. However, Ruurd has tried this route and found that some
130 * shell scripts failed, for mysterious reasons...
132 * I've chosen for now, therefore, to simply add Ruurd's original
133 * code as-is. A wrapper program hidecmd.c has been added to
134 * development/Win32 which hides the console window of lyx when
135 * lyx is invoked as a parameter of hidecmd.exe.
138 // If cygwin is detected, query the cygdrive prefix
141 DWORD bufSize = sizeof(buf);
144 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
145 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
146 0, KEY_QUERY_VALUE, ®Key);
147 if (retVal != ERROR_SUCCESS) {
148 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
149 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
150 0, KEY_QUERY_VALUE, ®Key);
152 if (retVal == ERROR_SUCCESS) {
153 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
154 (LPBYTE) buf, &bufSize);
156 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
162 string current_root()
164 // _getdrive returns the current drive (1=A, 2=B, and so on).
165 char const drive = ::_getdrive() + 'A' - 1;
166 return string(1, drive) + ":/";
170 docstring::size_type common_path(docstring const & p1, docstring const & p2)
173 size_t const p1_len = p1.length();
174 size_t const p2_len = p2.length();
175 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
177 if ((i < p1_len && i < p2_len)
178 || (i < p1_len && p1[i] != '/' && i == p2_len)
179 || (i < p2_len && p2[i] != '/' && i == p1_len))
182 --i; // here was the last match
183 while (i && p1[i] != '/')
190 string external_path(string const & p)
192 string const dos_path = subst(p, "/", "\\");
194 LYXERR(Debug::LATEX, "<Win32 path correction> ["
195 << p << "]->>[" << dos_path << ']');
200 static string const get_long_path(string const & short_path)
202 // GetLongPathName needs the path in file system encoding.
203 // We can use to_local8bit, since file system encoding and the
204 // local 8 bit encoding are identical on windows.
205 std::vector<char> long_path(MAX_PATH);
206 DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
207 &long_path[0], long_path.size());
209 if (result > long_path.size()) {
210 long_path.resize(result);
211 result = GetLongPathName(short_path.c_str(),
212 &long_path[0], long_path.size());
213 BOOST_ASSERT(result <= long_path.size());
216 return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
220 string internal_path(string const & p)
222 return subst(get_long_path(p), "\\", "/");
226 string external_path_list(string const & p)
228 return subst(p, '/', '\\');
232 string internal_path_list(string const & p)
234 return subst(p, '\\', '/');
238 string latex_path(string const & p)
240 // We may need a posix style path or a windows style path (depending
241 // on windows_style_tex_paths_), but we use always forward slashes,
242 // since it gets written into a .tex file.
244 if (!windows_style_tex_paths_ && is_absolute_path(p)) {
245 string const drive = p.substr(0, 2);
246 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
247 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
248 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
249 << p << "]->>[" << cygpath << ']');
252 return subst(p, '\\', '/');
256 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
257 // Therefore an absolute path could be either a pathname starting
258 // with a slash (Unix) or a pathname starting with a drive letter
259 // followed by a colon. Because a colon is not valid in pathes in Unix
260 // and at another location in Win32 testing just for the existance
261 // of the colon in the 2nd position seems to be enough!
262 bool is_absolute_path(string const & p)
267 bool isDosPath = (p.length() > 1 && p[1] == ':');
268 bool isUnixPath = (p[0] == '/');
270 return isDosPath || isUnixPath;
274 // returns a string suitable to be passed to popen when
276 char const * popen_read_mode()
282 string const & nulldev()
284 static string const nulldev_ = "nul";
295 char path_separator()
301 void windows_style_tex_paths(bool use_windows_paths)
303 windows_style_tex_paths_ = use_windows_paths;
307 GetFolderPath::GetFolderPath()
311 folder_module_ = LoadLibrary("shfolder.dll");
312 if (!folder_module_) {
313 throw ExceptionMessage(ErrorException, _("System file not found"),
314 _("Unable to load shfolder.dll\nPlease install."));
317 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
318 if (folder_path_func_ == 0) {
319 throw ExceptionMessage(ErrorException, _("System function not found"),
320 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
321 "Don't know how to proceed. Sorry."));
326 GetFolderPath::~GetFolderPath()
329 FreeLibrary(folder_module_);
333 // Given a folder ID, returns the folder name (in unix-style format).
334 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
335 string const GetFolderPath::operator()(folder_id _id) const
337 char folder_path[MAX_PATH];
350 HRESULT const result = (folder_path_func_)(0, id, 0,
353 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
357 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
362 string const full_ext = "." + ext;
364 DWORD bufSize = MAX_PATH + 100;
365 TCHAR buf[MAX_PATH + 100];
366 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
367 // /platform/shell/reference/shlwapi/registry/assocquerystring.asp
368 char const * action = (mode == VIEW) ? "open" : "edit";
369 return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
370 full_ext.c_str(), action, buf, &bufSize);
374 bool autoOpenFile(string const & filename, auto_open_mode const mode)
376 // reference: http://msdn.microsoft.com/library/default.asp
377 // ?url=/library/en-us/shellcc/platform/shell/reference/functions/
379 char const * action = (mode == VIEW) ? "open" : "edit";
380 return reinterpret_cast<int>(ShellExecute(NULL, action,
381 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
385 } // namespace support