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"
24 #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;
79 bool cygwin_path_fix_ = false;
81 string cygdrive = "/cygdrive";
85 void init(int /* argc */, char * argv[])
87 /* Note from Angus, 17 Jan 2005:
89 * The code below is taken verbatim from Ruurd's original patch
90 * porting LyX to Win32.
92 * Windows allows us to define LyX either as a console-based app
93 * or as a GUI-based app. Ruurd decided to define LyX as a
94 * console-based app with a "main" function rather than a "WinMain"
95 * function as the point of entry to the program, but to
96 * immediately close the console window that Windows helpfully
97 * opens for us. Doing so allows the user to see all of LyX's
98 * debug output simply by running LyX from a DOS or MSYS-shell
101 * The alternative approach is to define LyX as a genuine
102 * GUI-based app, with a "WinMain" function as the entry point to the
103 * executable rather than a "main" function, so:
105 * #if defined (_WIN32)
106 * # define WIN32_LEAN_AND_MEAN
107 * # include <stdlib.h> // for __argc, __argv
108 * # include <windows.h> // for WinMain
111 * // This will require the "-mwindows" flag when linking with
112 * // gcc under MinGW.
113 * // For MSVC, use "/subsystem:windows".
114 * #if defined (_WIN32)
115 * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
117 * return mymain(__argc, __argv);
121 * where "mymain" is just a renamed "main".
123 * However, doing so means that the lyxerr messages would mysteriously
124 * disappear. They could be resurrected with something like:
128 * freopen("conin$","r",stdin);
129 * freopen("conout$","w",stdout);
130 * freopen("conout$","w",stderr);
133 * This code could be invoked (say) the first time that lyxerr
134 * is called. However, Ruurd has tried this route and found that some
135 * shell scripts failed, for mysterious reasons...
137 * I've chosen for now, therefore, to simply add Ruurd's original
140 // Close the console when run (probably)
141 // not run from command prompt
142 char WindowTitle[1024];
143 if (GetConsoleTitle(WindowTitle, sizeof(WindowTitle)) == 0) {
144 // Could not get the title, so we just leave things as they are
148 if ((strcmp(WindowTitle, argv[0]) == 0) ||
149 (strcmp(WindowTitle, "LyX") == 0)) {
150 // format a "unique" newWindowTitle
151 wsprintf(WindowTitle, "%d/%d",
153 GetCurrentProcessId());
154 // change current window title
155 SetConsoleTitle(WindowTitle);
156 // ensure window title has been updated
158 // look for newWindowTitle
159 HWND const hwndFound = FindWindow(NULL, WindowTitle);
161 if (hwndFound != NULL)
162 ShowWindow( hwndFound, SW_HIDE);
165 // If cygwin is detected, query the cygdrive prefix
166 cmd_ret const c = runCommand("sh -c uname");
167 if (c.first != -1 && prefixIs(c.second, "CYGWIN")) {
168 cmd_ret const p = runCommand("mount --show-cygdrive-prefix");
169 // The output of the mount command is as follows:
171 // /cygdrive system binmode
172 // So, we use the inner split to pass the second line to the
173 // outer split which sets cygdrive with its contents until
174 // the first blank, discarding the unneeded return value.
175 if (p.first != -1 && prefixIs(p.second, "Prefix"))
176 (void) split(split(p.second, '\n'), cygdrive, ' ');
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 string::size_type common_path(string const & p1, string const & p2)
191 string::size_type i = 0;
192 string::size_type p1_len = p1.length();
193 string::size_type 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 std::vector<char> long_path(MAX_PATH);
226 DWORD result = GetLongPathName(short_path.c_str(),
227 &long_path[0], long_path.size());
229 if (result > long_path.size()) {
230 long_path.resize(result);
231 result = GetLongPathName(short_path.c_str(),
232 &long_path[0], long_path.size());
233 BOOST_ASSERT(result <= long_path.size());
236 return (result == 0) ? short_path : &long_path[0];
242 string internal_path(string const & p)
244 return subst(get_long_path(p), "\\", "/");
248 string external_path_list(string const & p)
250 return subst(p, '/', '\\');
254 string internal_path_list(string const & p)
256 return subst(p, '\\', '/');
260 string latex_path(string const & p)
262 // We may need a posix style path or a windows style path (depending
263 // on cygwin_path_fix_), but we use always forward slashes, since it
264 // gets written into a .tex file.
266 if (cygwin_path_fix_ && is_absolute_path(p)) {
267 string const drive = p.substr(0, 2);
268 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
269 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
271 << "<Cygwin path correction> ["
273 << cygpath << ']' << endl;
276 return subst(p, '\\', '/');
280 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
281 // Therefore an absolute path could be either a pathname starting
282 // with a slash (Unix) or a pathname starting with a drive letter
283 // followed by a colon. Because a colon is not valid in pathes in Unix
284 // and at another location in Win32 testing just for the existance
285 // of the colon in the 2nd position seems to be enough!
286 bool is_absolute_path(string const & p)
291 bool isDosPath = (p.length() > 1 && p[1] == ':');
292 bool isUnixPath = (p[0] == '/');
294 return isDosPath || isUnixPath;
298 // returns a string suitable to be passed to popen when
300 char const * popen_read_mode()
306 string const & nulldev()
308 static string const nulldev_ = "nul";
319 char path_separator()
325 void cygwin_path_fix(bool use_cygwin_paths)
327 cygwin_path_fix_ = !use_cygwin_paths;
335 #ifndef CXX_GLOBAL_CSTD
344 GetFolderPath::GetFolderPath()
348 folder_module_ = LoadLibrary("shfolder.dll");
349 if (!folder_module_) {
350 lyxerr << "Unable to load shfolder.dll\nPlease install."
355 folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
356 if (folder_path_func_ == 0) {
357 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
358 "Don't know how to proceed. Sorry."
365 GetFolderPath::~GetFolderPath()
368 FreeLibrary(folder_module_);
372 // Given a folder ID, returns the folder name (in unix-style format).
373 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
374 string const GetFolderPath::operator()(folder_id _id) const
376 char folder_path[MAX_PATH];
389 HRESULT const result = (folder_path_func_)(0, id, 0,
392 return (result == 0) ? os::internal_path(folder_path) : string();
396 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
401 string const full_ext = "." + ext;
403 DWORD bufSize = MAX_PATH + 100;
404 TCHAR buf[MAX_PATH + 100];
405 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
406 // /platform/shell/reference/shlwapi/registry/assocquerystring.asp
407 char const * action = (mode == VIEW) ? "open" : "edit";
408 return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
409 full_ext.c_str(), action, buf, &bufSize);
413 bool autoOpenFile(string const & filename, auto_open_mode const mode)
415 // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
416 // /platform/shell/reference/functions/shellexecute.asp
417 char const * action = (mode == VIEW) ? "open" : "edit";
418 return reinterpret_cast<int>(ShellExecute(NULL, action,
419 filename.c_str(), NULL, NULL, 1)) > 32;
424 } // namespace support