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/lstrings.h"
20 #include "support/filetools.h"
21 #include "support/package.h"
22 #include "support/path.h"
26 #include <boost/assert.hpp>
33 /* The GetLongPathName macro may be defined on the compiling machine,
34 * but we must use a bit of trickery if the resulting executable is
35 * to run on a Win95 machine.
36 * Fortunately, Microsoft provide the trickery. All we need is the
37 * NewAPIs.h header file, available for download from Microsoft as
38 * part of the Platform SDK.
40 #if defined (HAVE_NEWAPIS_H)
41 // This should be defined already to keep Boost.Filesystem happy.
42 # if !defined (WANT_GETFILEATTRIBUTESEX_WRAPPER)
43 # error Expected WANT_GETFILEATTRIBUTESEX_WRAPPER to be defined!
45 # define WANT_GETLONGPATHNAME_WRAPPER 1
46 # define COMPILE_NEWAPIS_STUBS
48 # undef COMPILE_NEWAPIS_STUBS
49 # undef WANT_GETLONGPATHNAME_WRAPPER
53 #include <direct.h> // _getdrive
54 #include <shlobj.h> // SHGetFolderPath
59 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
60 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
62 # if __W32API_MAJOR_VERSION < 3 || \
63 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
64 # define SHGFP_TYPE_CURRENT 0
71 using lyx::support::runCommand;
72 using lyx::support::split;
73 using lyx::support::addName;
74 using lyx::support::addPath;
75 using lyx::support::package;
77 string const win_fonts_truetype[] = {"cmex10", "cmmi10", "cmr10", "cmsy10",
78 "eufm10", "msam10", "msbm10", "wasy10", "esint10"};
79 const int num_fonts_truetype = sizeof(win_fonts_truetype) / sizeof(*win_fonts_truetype);
88 bool windows_style_tex_paths_ = true;
90 string cygdrive = "/cygdrive";
94 void init(int /* argc */, char * argv[])
96 /* Note from Angus, 17 Jan 2005:
98 * The code below is taken verbatim from Ruurd's original patch
99 * porting LyX to Win32.
101 * Windows allows us to define LyX either as a console-based app
102 * or as a GUI-based app. Ruurd decided to define LyX as a
103 * console-based app with a "main" function rather than a "WinMain"
104 * function as the point of entry to the program, but to
105 * immediately close the console window that Windows helpfully
106 * opens for us. Doing so allows the user to see all of LyX's
107 * debug output simply by running LyX from a DOS or MSYS-shell
110 * The alternative approach is to define LyX as a genuine
111 * GUI-based app, with a "WinMain" function as the entry point to the
112 * executable rather than a "main" function, so:
114 * #if defined (_WIN32)
115 * # define WIN32_LEAN_AND_MEAN
116 * # include <stdlib.h> // for __argc, __argv
117 * # include <windows.h> // for WinMain
120 * // This will require the "-mwindows" flag when linking with
121 * // gcc under MinGW.
122 * // For MSVC, use "/subsystem:windows".
123 * #if defined (_WIN32)
124 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
126 * return mymain(__argc, __argv);
130 * where "mymain" is just a renamed "main".
132 * However, doing so means that the lyxerr messages would mysteriously
133 * disappear. They could be resurrected with something like:
137 * freopen("conin$","r",stdin);
138 * freopen("conout$","w",stdout);
139 * freopen("conout$","w",stderr);
142 * This code could be invoked (say) the first time that lyxerr
143 * is called. However, Ruurd has tried this route and found that some
144 * shell scripts failed, for mysterious reasons...
146 * I've chosen for now, therefore, to simply add Ruurd's original
147 * code as-is. A wrapper program hidecmd.c has been added to
148 * development/Win32 which hides the console window of lyx when
149 * lyx is invoked as a parameter of hidecmd.exe.
152 // If cygwin is detected, query the cygdrive prefix
155 DWORD bufSize = sizeof(buf);
158 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
159 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
160 0, KEY_QUERY_VALUE, ®Key);
161 if (retVal != ERROR_SUCCESS) {
162 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
163 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
164 0, KEY_QUERY_VALUE, ®Key);
166 if (retVal == ERROR_SUCCESS) {
167 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
168 (LPBYTE) buf, &bufSize);
170 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
176 string current_root()
178 // _getdrive returns the current drive (1=A, 2=B, and so on).
179 char const drive = ::_getdrive() + 'A' - 1;
180 return string(1, drive) + ":/";
184 string::size_type common_path(string const & p1, string const & p2)
186 string::size_type i = 0;
187 string::size_type p1_len = p1.length();
188 string::size_type p2_len = p2.length();
189 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
191 if ((i < p1_len && i < p2_len)
192 || (i < p1_len && p1[i] != '/' && i == p2_len)
193 || (i < p2_len && p2[i] != '/' && i == p1_len))
196 --i; // here was the last match
197 while (i && p1[i] != '/')
204 string external_path(string const & p)
206 string const dos_path = subst(p, "/", "\\");
209 << "<Win32 path correction> ["
211 << dos_path << ']' << endl;
218 string const get_long_path(string const & short_path)
220 std::vector<char> long_path(MAX_PATH);
221 DWORD result = GetLongPathName(short_path.c_str(),
222 &long_path[0], long_path.size());
224 if (result > long_path.size()) {
225 long_path.resize(result);
226 result = GetLongPathName(short_path.c_str(),
227 &long_path[0], long_path.size());
228 BOOST_ASSERT(result <= long_path.size());
231 return (result == 0) ? short_path : &long_path[0];
237 string internal_path(string const & p)
239 return subst(get_long_path(p), "\\", "/");
243 string external_path_list(string const & p)
245 return subst(p, '/', '\\');
249 string internal_path_list(string const & p)
251 return subst(p, '\\', '/');
255 string latex_path(string const & p)
257 // We may need a posix style path or a windows style path (depending
258 // on windows_style_tex_paths_), but we use always forward slashes,
259 // since it gets written into a .tex file.
261 if (!windows_style_tex_paths_ && is_absolute_path(p)) {
262 string const drive = p.substr(0, 2);
263 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
264 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
266 << "<Path correction for LaTeX> ["
268 << cygpath << ']' << endl;
271 return subst(p, '\\', '/');
275 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
276 // Therefore an absolute path could be either a pathname starting
277 // with a slash (Unix) or a pathname starting with a drive letter
278 // followed by a colon. Because a colon is not valid in pathes in Unix
279 // and at another location in Win32 testing just for the existance
280 // of the colon in the 2nd position seems to be enough!
281 bool is_absolute_path(string const & p)
286 bool isDosPath = (p.length() > 1 && p[1] == ':');
287 bool isUnixPath = (p[0] == '/');
289 return isDosPath || isUnixPath;
293 // returns a string suitable to be passed to popen when
295 char const * popen_read_mode()
301 string const & nulldev()
303 static string const nulldev_ = "nul";
314 char path_separator()
320 void windows_style_tex_paths(bool use_windows_paths)
322 windows_style_tex_paths_ = use_windows_paths;
330 #ifndef CXX_GLOBAL_CSTD
339 GetFolderPath::GetFolderPath()
343 folder_module_ = LoadLibrary("shfolder.dll");
344 if (!folder_module_) {
345 lyxerr << "Unable to load shfolder.dll\nPlease install."
350 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
351 if (folder_path_func_ == 0) {
352 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
353 "Don't know how to proceed. Sorry."
360 GetFolderPath::~GetFolderPath()
363 FreeLibrary(folder_module_);
367 // Given a folder ID, returns the folder name (in unix-style format).
368 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
369 string const GetFolderPath::operator()(folder_id _id) const
371 char folder_path[MAX_PATH];
384 HRESULT const result = (folder_path_func_)(0, id, 0,
387 return (result == 0) ? os::internal_path(folder_path) : string();
391 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
396 string const full_ext = "." + ext;
398 DWORD bufSize = MAX_PATH + 100;
399 TCHAR buf[MAX_PATH + 100];
400 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
401 // /platform/shell/reference/shlwapi/registry/assocquerystring.asp
402 char const * action = (mode == VIEW) ? "open" : "edit";
403 return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
404 full_ext.c_str(), action, buf, &bufSize);
408 bool autoOpenFile(string const & filename, auto_open_mode const mode)
410 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
411 // /platform/shell/reference/functions/shellexecute.asp
412 char const * action = (mode == VIEW) ? "open" : "edit";
413 return reinterpret_cast<int>(ShellExecute(NULL, action,
414 filename.c_str(), NULL, NULL, 1)) > 32;
418 void addFontResources()
420 // Windows only: Add BaKoMa TrueType font resources
421 string const fonts_dir = addPath(package().system_support(), "fonts");
423 for (int i = 0 ; i < num_fonts_truetype ; ++i) {
424 string const font_current =
425 addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
426 AddFontResource(external_path(font_current).c_str());
431 void restoreFontResources()
433 // Windows only: Remove BaKoMa TrueType font resources
434 string const fonts_dir = addPath(package().system_support(), "fonts");
436 for(int i = 0 ; i < num_fonts_truetype ; ++i) {
437 string const font_current =
438 addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
439 RemoveFontResource(external_path(font_current).c_str());
444 } // namespace support