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>
31 /* The GetLongPathName macro may be defined on the compiling machine,
32 * but we must use a bit of trickery if the resulting executable is
33 * to run on a Win95 machine.
34 * Fortunately, Microsoft provide the trickery. All we need is the
35 * NewAPIs.h header file, available for download from Microsoft as
36 * part of the Platform SDK.
38 #if defined (HAVE_NEWAPIS_H)
39 // This should be defined already to keep Boost.Filesystem happy.
40 # if !defined (WANT_GETFILEATTRIBUTESEX_WRAPPER)
41 # error Expected WANT_GETFILEATTRIBUTESEX_WRAPPER to be defined!
43 # define WANT_GETLONGPATHNAME_WRAPPER 1
44 # define COMPILE_NEWAPIS_STUBS
46 # undef COMPILE_NEWAPIS_STUBS
47 # undef WANT_GETLONGPATHNAME_WRAPPER
51 #include <direct.h> // _getdrive
52 #include <shlobj.h> // SHGetFolderPath
57 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
58 #if defined(__MINGW32__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
60 # if __W32API_MAJOR_VERSION < 3 || \
61 __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 2
62 # define SHGFP_TYPE_CURRENT 0
69 using lyx::support::runCommand;
70 using lyx::support::split;
71 using lyx::support::addName;
72 using lyx::support::addPath;
73 using lyx::support::package;
75 string const win_fonts_truetype[] = {"cmex10", "cmmi10", "cmr10", "cmsy10",
76 "eufm10", "msam10", "msbm10", "wasy10", "esint10"};
77 const int num_fonts_truetype = sizeof(win_fonts_truetype) / sizeof(*win_fonts_truetype);
86 bool windows_style_tex_paths_ = true;
88 string cygdrive = "/cygdrive";
92 void init(int /* argc */, char * argv[])
94 /* Note from Angus, 17 Jan 2005:
96 * The code below is taken verbatim from Ruurd's original patch
97 * porting LyX to Win32.
99 * Windows allows us to define LyX either as a console-based app
100 * or as a GUI-based app. Ruurd decided to define LyX as a
101 * console-based app with a "main" function rather than a "WinMain"
102 * function as the point of entry to the program, but to
103 * immediately close the console window that Windows helpfully
104 * opens for us. Doing so allows the user to see all of LyX's
105 * debug output simply by running LyX from a DOS or MSYS-shell
108 * The alternative approach is to define LyX as a genuine
109 * GUI-based app, with a "WinMain" function as the entry point to the
110 * executable rather than a "main" function, so:
112 * #if defined (_WIN32)
113 * # define WIN32_LEAN_AND_MEAN
114 * # include <stdlib.h> // for __argc, __argv
115 * # include <windows.h> // for WinMain
118 * // This will require the "-mwindows" flag when linking with
119 * // gcc under MinGW.
120 * // For MSVC, use "/subsystem:windows".
121 * #if defined (_WIN32)
122 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
124 * return mymain(__argc, __argv);
128 * where "mymain" is just a renamed "main".
130 * However, doing so means that the lyxerr messages would mysteriously
131 * disappear. They could be resurrected with something like:
135 * freopen("conin$","r",stdin);
136 * freopen("conout$","w",stdout);
137 * freopen("conout$","w",stderr);
140 * This code could be invoked (say) the first time that lyxerr
141 * is called. However, Ruurd has tried this route and found that some
142 * shell scripts failed, for mysterious reasons...
144 * I've chosen for now, therefore, to simply add Ruurd's original
145 * code as-is. A wrapper program hidecmd.c has been added to
146 * development/Win32 which hides the console window of lyx when
147 * lyx is invoked as a parameter of hidecmd.exe.
150 // If cygwin is detected, query the cygdrive prefix
153 DWORD bufSize = sizeof(buf);
156 retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
157 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
158 0, KEY_QUERY_VALUE, ®Key);
159 if (retVal != ERROR_SUCCESS) {
160 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
161 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
162 0, KEY_QUERY_VALUE, ®Key);
164 if (retVal == ERROR_SUCCESS) {
165 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
166 (LPBYTE) buf, &bufSize);
168 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
174 string current_root()
176 // _getdrive returns the current drive (1=A, 2=B, and so on).
177 char const drive = ::_getdrive() + 'A' - 1;
178 return string(1, drive) + ":/";
182 string::size_type common_path(string const & p1, string const & p2)
184 string::size_type i = 0;
185 string::size_type p1_len = p1.length();
186 string::size_type p2_len = p2.length();
187 while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
189 if ((i < p1_len && i < p2_len)
190 || (i < p1_len && p1[i] != '/' && i == p2_len)
191 || (i < p2_len && p2[i] != '/' && i == p1_len))
194 --i; // here was the last match
195 while (i && p1[i] != '/')
202 string external_path(string const & p)
204 string const dos_path = subst(p, "/", "\\");
207 << "<Win32 path correction> ["
209 << dos_path << ']' << endl;
216 string const get_long_path(string const & short_path)
218 // GetLongPathName needs the path in file system encoding.
219 // We can use to_local8bit, since file system encoding and the
220 // local 8 bit encoding are identical on windows.
221 std::vector<char> long_path(MAX_PATH);
222 DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
223 &long_path[0], long_path.size());
225 if (result > long_path.size()) {
226 long_path.resize(result);
227 result = GetLongPathName(short_path.c_str(),
228 &long_path[0], long_path.size());
229 BOOST_ASSERT(result <= long_path.size());
232 return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
238 string internal_path(string const & p)
240 return subst(get_long_path(p), "\\", "/");
244 string external_path_list(string const & p)
246 return subst(p, '/', '\\');
250 string internal_path_list(string const & p)
252 return subst(p, '\\', '/');
256 string latex_path(string const & p)
258 // We may need a posix style path or a windows style path (depending
259 // on windows_style_tex_paths_), but we use always forward slashes,
260 // since it gets written into a .tex file.
262 if (!windows_style_tex_paths_ && is_absolute_path(p)) {
263 string const drive = p.substr(0, 2);
264 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
265 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
267 << "<Path correction for LaTeX> ["
269 << cygpath << ']' << endl;
272 return subst(p, '\\', '/');
276 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
277 // Therefore an absolute path could be either a pathname starting
278 // with a slash (Unix) or a pathname starting with a drive letter
279 // followed by a colon. Because a colon is not valid in pathes in Unix
280 // and at another location in Win32 testing just for the existance
281 // of the colon in the 2nd position seems to be enough!
282 bool is_absolute_path(string const & p)
287 bool isDosPath = (p.length() > 1 && p[1] == ':');
288 bool isUnixPath = (p[0] == '/');
290 return isDosPath || isUnixPath;
294 // returns a string suitable to be passed to popen when
296 char const * popen_read_mode()
302 string const & nulldev()
304 static string const nulldev_ = "nul";
315 char path_separator()
321 void windows_style_tex_paths(bool use_windows_paths)
323 windows_style_tex_paths_ = use_windows_paths;
331 #ifndef CXX_GLOBAL_CSTD
340 GetFolderPath::GetFolderPath()
344 folder_module_ = LoadLibrary("shfolder.dll");
345 if (!folder_module_) {
346 lyxerr << "Unable to load shfolder.dll\nPlease install."
351 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
352 if (folder_path_func_ == 0) {
353 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
354 "Don't know how to proceed. Sorry."
361 GetFolderPath::~GetFolderPath()
364 FreeLibrary(folder_module_);
368 // Given a folder ID, returns the folder name (in unix-style format).
369 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
370 string const GetFolderPath::operator()(folder_id _id) const
372 char folder_path[MAX_PATH];
385 HRESULT const result = (folder_path_func_)(0, id, 0,
388 return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
392 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
397 string const full_ext = "." + ext;
399 DWORD bufSize = MAX_PATH + 100;
400 TCHAR buf[MAX_PATH + 100];
401 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
402 // /platform/shell/reference/shlwapi/registry/assocquerystring.asp
403 char const * action = (mode == VIEW) ? "open" : "edit";
404 return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
405 full_ext.c_str(), action, buf, &bufSize);
409 bool autoOpenFile(string const & filename, auto_open_mode const mode)
411 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
412 // /platform/shell/reference/functions/shellexecute.asp
413 char const * action = (mode == VIEW) ? "open" : "edit";
414 return reinterpret_cast<int>(ShellExecute(NULL, action,
415 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
419 void addFontResources()
421 // Windows only: Add BaKoMa TrueType font resources
422 string const fonts_dir = addPath(package().system_support(), "fonts");
424 for (int i = 0 ; i < num_fonts_truetype ; ++i) {
425 string const font_current =
426 addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
427 AddFontResource(to_local8bit(from_utf8(external_path(font_current))).c_str());
432 void restoreFontResources()
434 // Windows only: Remove BaKoMa TrueType font resources
435 string const fonts_dir = addPath(package().system_support(), "fonts");
437 for(int i = 0 ; i < num_fonts_truetype ; ++i) {
438 string const font_current =
439 addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
440 RemoveFontResource(to_local8bit(from_utf8(external_path(font_current))).c_str());
445 } // namespace support