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/ExceptionMessage.h"
22 #include "support/Package.h"
23 #include "support/Path.h"
28 #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 // API definition for manually calling font functions on Windows 2000 and later
78 typedef int (WINAPI *FONTAPI)(LPCSTR, DWORD, PVOID);
79 #define FR_PRIVATE 0x10
81 // Names of TrueType fonts to load
82 string const win_fonts_truetype[] = {"cmex10", "cmmi10", "cmr10", "cmsy10",
83 "eufm10", "msam10", "msbm10", "wasy10", "esint10"};
84 const int num_fonts_truetype = sizeof(win_fonts_truetype) / sizeof(*win_fonts_truetype);
93 bool windows_style_tex_paths_ = true;
95 string cygdrive = "/cygdrive";
99 void init(int /* argc */, char * argv[])
101 /* Note from Angus, 17 Jan 2005:
103 * The code below is taken verbatim from Ruurd's original patch
104 * porting LyX to Win32.
106 * Windows allows us to define LyX either as a console-based app
107 * or as a GUI-based app. Ruurd decided to define LyX as a
108 * console-based app with a "main" function rather than a "WinMain"
109 * function as the point of entry to the program, but to
110 * immediately close the console window that Windows helpfully
111 * opens for us. Doing so allows the user to see all of LyX's
112 * debug output simply by running LyX from a DOS or MSYS-shell
115 * The alternative approach is to define LyX as a genuine
116 * GUI-based app, with a "WinMain" function as the entry point to the
117 * executable rather than a "main" function, so:
119 * #if defined (_WIN32)
120 * # define WIN32_LEAN_AND_MEAN
121 * # include <stdlib.h> // for __argc, __argv
122 * # include <windows.h> // for WinMain
125 * // This will require the "-mwindows" flag when linking with
126 * // gcc under MinGW.
127 * // For MSVC, use "/subsystem:windows".
128 * #if defined (_WIN32)
129 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
131 * return mymain(__argc, __argv);
135 * where "mymain" is just a renamed "main".
137 * However, doing so means that the lyxerr messages would mysteriously
138 * disappear. They could be resurrected with something like:
142 * freopen("conin$","r",stdin);
143 * freopen("conout$","w",stdout);
144 * freopen("conout$","w",stderr);
147 * This code could be invoked (say) the first time that lyxerr
148 * is called. However, Ruurd has tried this route and found that some
149 * shell scripts failed, for mysterious reasons...
151 * I've chosen for now, therefore, to simply add Ruurd's original
152 * code as-is. A wrapper program hidecmd.c has been added to
153 * development/Win32 which hides the console window of lyx when
154 * lyx is invoked as a parameter of hidecmd.exe.
157 // If cygwin is detected, query the cygdrive prefix
160 DWORD bufSize = sizeof(buf);
163 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
164 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
165 0, KEY_QUERY_VALUE, ®Key);
166 if (retVal != ERROR_SUCCESS) {
167 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
168 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
169 0, KEY_QUERY_VALUE, ®Key);
171 if (retVal == ERROR_SUCCESS) {
172 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
173 (LPBYTE) buf, &bufSize);
175 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
181 string current_root()
183 // _getdrive returns the current drive (1=A, 2=B, and so on).
184 char const drive = ::_getdrive() + 'A' - 1;
185 return string(1, drive) + ":/";
189 docstring::size_type common_path(docstring const & p1, docstring const & p2)
191 docstring::size_type i = 0;
192 docstring::size_type const p1_len = p1.length();
193 docstring::size_type const p2_len = p2.length();
194 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
196 if ((i < p1_len && i < p2_len)
197 || (i < p1_len && p1[i] != '/' && i == p2_len)
198 || (i < p2_len && p2[i] != '/' && i == p1_len))
201 --i; // here was the last match
202 while (i && p1[i] != '/')
209 string external_path(string const & p)
211 string const dos_path = subst(p, "/", "\\");
214 << "<Win32 path correction> ["
216 << dos_path << ']' << endl;
223 string const get_long_path(string const & short_path)
225 // GetLongPathName needs the path in file system encoding.
226 // We can use to_local8bit, since file system encoding and the
227 // local 8 bit encoding are identical on windows.
228 std::vector<char> long_path(MAX_PATH);
229 DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
230 &long_path[0], long_path.size());
232 if (result > long_path.size()) {
233 long_path.resize(result);
234 result = GetLongPathName(short_path.c_str(),
235 &long_path[0], long_path.size());
236 BOOST_ASSERT(result <= long_path.size());
239 return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
245 string internal_path(string const & p)
247 return subst(get_long_path(p), "\\", "/");
251 string external_path_list(string const & p)
253 return subst(p, '/', '\\');
257 string internal_path_list(string const & p)
259 return subst(p, '\\', '/');
263 string latex_path(string const & p)
265 // We may need a posix style path or a windows style path (depending
266 // on windows_style_tex_paths_), but we use always forward slashes,
267 // since it gets written into a .tex file.
269 if (!windows_style_tex_paths_ && is_absolute_path(p)) {
270 string const drive = p.substr(0, 2);
271 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
272 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
274 << "<Path correction for LaTeX> ["
276 << cygpath << ']' << endl;
279 return subst(p, '\\', '/');
283 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
284 // Therefore an absolute path could be either a pathname starting
285 // with a slash (Unix) or a pathname starting with a drive letter
286 // followed by a colon. Because a colon is not valid in pathes in Unix
287 // and at another location in Win32 testing just for the existance
288 // of the colon in the 2nd position seems to be enough!
289 bool is_absolute_path(string const & p)
294 bool isDosPath = (p.length() > 1 && p[1] == ':');
295 bool isUnixPath = (p[0] == '/');
297 return isDosPath || isUnixPath;
301 // returns a string suitable to be passed to popen when
303 char const * popen_read_mode()
309 string const & nulldev()
311 static string const nulldev_ = "nul";
322 char path_separator()
328 void windows_style_tex_paths(bool use_windows_paths)
330 windows_style_tex_paths_ = use_windows_paths;
334 GetFolderPath::GetFolderPath()
338 folder_module_ = LoadLibrary("shfolder.dll");
339 if (!folder_module_) {
340 throw ExceptionMessage(ErrorException, _("System file not found"),
341 _("Unable to load shfolder.dll\nPlease install."));
344 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
345 if (folder_path_func_ == 0) {
346 throw ExceptionMessage(ErrorException, _("System function not found"),
347 _("Unable to find SHGetFolderPathA in shfolder.dll\n"
348 "Don't know how to proceed. Sorry."));
353 GetFolderPath::~GetFolderPath()
356 FreeLibrary(folder_module_);
360 // Given a folder ID, returns the folder name (in unix-style format).
361 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
362 string const GetFolderPath::operator()(folder_id _id) const
364 char folder_path[MAX_PATH];
377 HRESULT const result = (folder_path_func_)(0, id, 0,
380 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
384 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
389 string const full_ext = "." + ext;
391 DWORD bufSize = MAX_PATH + 100;
392 TCHAR buf[MAX_PATH + 100];
393 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
394 // /platform/shell/reference/shlwapi/registry/assocquerystring.asp
395 char const * action = (mode == VIEW) ? "open" : "edit";
396 return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
397 full_ext.c_str(), action, buf, &bufSize);
401 bool autoOpenFile(string const & filename, auto_open_mode const mode)
403 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
404 // /platform/shell/reference/functions/shellexecute.asp
405 char const * action = (mode == VIEW) ? "open" : "edit";
406 return reinterpret_cast<int>(ShellExecute(NULL, action,
407 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
411 void addFontResources()
413 // Windows only: Add BaKoMa TrueType font resources
414 string const fonts_dir = addPath(package().system_support().absFilename(), "fonts");
416 HMODULE hDLL = LoadLibrary("gdi32");
417 FONTAPI pAddFontResourceEx = (FONTAPI) GetProcAddress(hDLL, "AddFontResourceExA");
419 for (int i = 0 ; i < num_fonts_truetype ; ++i) {
420 string const font_current =
421 addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
422 if (pAddFontResourceEx) {
423 // Windows 2000 and later: Use AddFontResourceEx for private font
424 pAddFontResourceEx(to_local8bit(from_utf8(external_path(font_current))).c_str(), FR_PRIVATE, 0);
426 // Older Windows versions: Use AddFontResource
427 AddFontResource(to_local8bit(from_utf8(external_path(font_current))).c_str());
435 void restoreFontResources()
437 // Windows only: Remove BaKoMa TrueType font resources
438 string const fonts_dir = addPath(package().system_support().absFilename(), "fonts");
440 HMODULE hDLL = LoadLibrary("gdi32");
441 FONTAPI pRemoveFontResourceEx = (FONTAPI) GetProcAddress(hDLL, "RemoveFontResourceExA");
443 for(int i = 0 ; i < num_fonts_truetype ; ++i) {
444 string const font_current =
445 addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
446 if (pRemoveFontResourceEx) {
447 // Windows 2000 and later: Use RemoveFontResourceEx for private font
448 pRemoveFontResourceEx(to_local8bit(from_utf8(external_path(font_current))).c_str(), FR_PRIVATE, 0);
450 // Older Windows versions: Use RemoveFontResource
451 RemoveFontResource(to_local8bit(from_utf8(external_path(font_current))).c_str());
459 } // namespace support