]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.C
Stop using 'sh uname' etc for cygdrive, from Enrico Forestieri <forenr@tlc.unipr.it>
[lyx.git] / src / support / os_win32.C
1 /**
2  * \file os_win32.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Ruurd A. Reitsma
7  * \author Claus Hentschel
8  * \author Angus Leeming
9  *
10  * Full author contact details are available in file CREDITS.
11  *
12  * Various OS specific functions
13  */
14
15 #include <config.h>
16
17 #include "support/os.h"
18 #include "support/os_win32.h"
19 #include "support/lstrings.h"
20 #include "support/filetools.h"
21
22 #include "debug.h"
23
24 #include <boost/assert.hpp>
25
26 #include <cstdlib>
27 #include <vector>
28
29 #include <string>
30
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.
37  */
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!
42 # endif
43 # define WANT_GETLONGPATHNAME_WRAPPER 1
44 # define COMPILE_NEWAPIS_STUBS
45 # include <NewAPIs.h>
46 # undef COMPILE_NEWAPIS_STUBS
47 # undef WANT_GETLONGPATHNAME_WRAPPER
48 #endif
49
50 #include <io.h>
51 #include <direct.h> // _getdrive
52 #include <shlobj.h>  // SHGetFolderPath
53 #include <windef.h>
54 #include <shellapi.h>   
55 #include <shlwapi.h>
56
57 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
58 #if defined(__MINGW32__)  || defined(__CYGWIN__) || defined(__CYGWIN32__)
59 # include <w32api.h>
60 # if __W32API_MAJOR_VERSION < 3 || \
61      __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION  < 2
62 #  define SHGFP_TYPE_CURRENT 0
63 # endif
64 #endif
65
66 using std::endl;
67 using std::string;
68
69 using lyx::support::runCommand;
70 using lyx::support::split;
71
72
73 namespace lyx {
74 namespace support {
75 namespace os {
76
77 namespace {
78
79 bool windows_style_tex_paths_ = true;
80
81 string cygdrive = "/cygdrive";
82
83 } // namespace anon
84
85 void init(int /* argc */, char * argv[])
86 {
87         /* Note from Angus, 17 Jan 2005:
88          *
89          * The code below is taken verbatim from Ruurd's original patch
90          * porting LyX to Win32.
91          *
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
99          * prompt.
100          *
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:
104          *
105          * #if defined (_WIN32)
106          * # define WIN32_LEAN_AND_MEAN
107          * # include <stdlib.h>  // for __argc, __argv
108          * # include <windows.h> // for WinMain
109          * #endif
110          *
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)
116          * {
117          *     return mymain(__argc, __argv);
118          * }
119          * #endif
120          *
121          * where "mymain" is just a renamed "main".
122          *
123          * However, doing so means that the lyxerr messages would mysteriously
124          * disappear. They could be resurrected with something like:
125          *
126          * #ifdef WIN32
127          *  AllocConsole();
128          *  freopen("conin$","r",stdin);
129          *  freopen("conout$","w",stdout);
130          *  freopen("conout$","w",stderr);
131          * #endif
132          *
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...
136          *
137          * I've chosen for now, therefore, to simply add Ruurd's original
138          * code as-is.
139          */
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
145                 return;
146         }
147
148         if ((strcmp(WindowTitle, argv[0]) == 0) ||
149                 (strcmp(WindowTitle, "LyX") == 0)) {
150                 // format a "unique" newWindowTitle
151                 wsprintf(WindowTitle, "%d/%d",
152                         GetTickCount(),
153                         GetCurrentProcessId());
154                 // change current window title
155                 SetConsoleTitle(WindowTitle);
156                 // ensure window title has been updated
157                 Sleep(40);
158                 // look for newWindowTitle
159                 HWND const hwndFound = FindWindow(NULL, WindowTitle);
160                 // If found, hide it
161                 if (hwndFound != NULL)
162                         ShowWindow( hwndFound, SW_HIDE);
163         }
164
165         // If cygwin is detected, query the cygdrive prefix
166         HKEY regKey;
167         char buf[MAX_PATH];
168         DWORD bufSize = sizeof(buf);
169         LONG retVal;
170
171         retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
172                         "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
173                         0, KEY_QUERY_VALUE, &regKey);
174         if (retVal != ERROR_SUCCESS) {
175                 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
176                                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
177                                 0, KEY_QUERY_VALUE, &regKey);
178         }
179         if (retVal == ERROR_SUCCESS) {
180                 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
181                                 (LPBYTE) buf, &bufSize);
182                 RegCloseKey(regKey);
183                 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
184                         cygdrive = buf;
185         }
186 }
187
188
189 string current_root()
190 {
191         // _getdrive returns the current drive (1=A, 2=B, and so on).
192         char const drive = ::_getdrive() + 'A' - 1;
193         return string(1, drive) + ":/";
194 }
195
196
197 string::size_type common_path(string const & p1, string const & p2)
198 {
199         string::size_type i = 0;
200         string::size_type       p1_len = p1.length();
201         string::size_type       p2_len = p2.length();
202         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
203                 ++i;
204         if ((i < p1_len && i < p2_len)
205             || (i < p1_len && p1[i] != '/' && i == p2_len)
206             || (i < p2_len && p2[i] != '/' && i == p1_len))
207         {
208                 if (i)
209                         --i;     // here was the last match
210                 while (i && p1[i] != '/')
211                         --i;
212         }
213         return i;
214 }
215
216
217 string external_path(string const & p)
218 {
219         string const dos_path = subst(p, "/", "\\");
220
221         lyxerr[Debug::LATEX]
222                 << "<Win32 path correction> ["
223                 << p << "]->>["
224                 << dos_path << ']' << endl;
225         return dos_path;
226 }
227
228
229 namespace {
230
231 string const get_long_path(string const & short_path)
232 {
233         std::vector<char> long_path(MAX_PATH);
234         DWORD result = GetLongPathName(short_path.c_str(),
235                                        &long_path[0], long_path.size());
236
237         if (result > long_path.size()) {
238                 long_path.resize(result);
239                 result = GetLongPathName(short_path.c_str(),
240                                          &long_path[0], long_path.size());
241                 BOOST_ASSERT(result <= long_path.size());
242         }
243
244         return (result == 0) ? short_path : &long_path[0];
245 }
246
247 } // namespace anon
248
249
250 string internal_path(string const & p)
251 {
252         return subst(get_long_path(p), "\\", "/");
253 }
254
255
256 string external_path_list(string const & p)
257 {
258         return subst(p, '/', '\\');
259 }
260
261
262 string internal_path_list(string const & p)
263 {
264         return subst(p, '\\', '/');
265 }
266
267
268 string latex_path(string const & p)
269 {
270         // We may need a posix style path or a windows style path (depending
271         // on windows_style_tex_paths_), but we use always forward slashes,
272         // since it gets written into a .tex file.
273
274         if (!windows_style_tex_paths_ && is_absolute_path(p)) {
275                 string const drive = p.substr(0, 2);
276                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
277                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
278                 lyxerr[Debug::LATEX]
279                         << "<Path correction for LaTeX> ["
280                         << p << "]->>["
281                         << cygpath << ']' << endl;
282                 return cygpath;
283         }
284         return subst(p, '\\', '/');
285 }
286
287
288 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
289 // Therefore an absolute path could be either a pathname starting
290 // with a slash (Unix) or a pathname starting with a drive letter
291 // followed by a colon. Because a colon is not valid in pathes in Unix
292 // and at another location in Win32 testing just for the existance
293 // of the colon in the 2nd position seems to be enough!
294 bool is_absolute_path(string const & p)
295 {
296         if (p.empty())
297                 return false;
298
299         bool isDosPath = (p.length() > 1 && p[1] == ':');
300         bool isUnixPath = (p[0] == '/');
301
302         return isDosPath || isUnixPath;
303 }
304
305
306 // returns a string suitable to be passed to popen when
307 // reading a pipe
308 char const * popen_read_mode()
309 {
310         return "r";
311 }
312
313
314 string const & nulldev()
315 {
316         static string const nulldev_ = "nul";
317         return nulldev_;
318 }
319
320
321 shell_type shell()
322 {
323         return CMD_EXE;
324 }
325
326
327 char path_separator()
328 {
329         return ';';
330 }
331
332
333 void windows_style_tex_paths(bool use_windows_paths)
334 {
335         windows_style_tex_paths_ = use_windows_paths;
336 }
337
338
339 namespace {
340
341 void bail_out()
342 {
343 #ifndef CXX_GLOBAL_CSTD
344         using std::exit;
345 #endif
346         exit(1);
347 }
348
349 } // namespace anon
350
351
352 GetFolderPath::GetFolderPath()
353         : folder_module_(0),
354           folder_path_func_(0)
355 {
356         folder_module_ = LoadLibrary("shfolder.dll");
357         if (!folder_module_) {
358                 lyxerr << "Unable to load shfolder.dll\nPlease install."
359                        << std::endl;
360                 bail_out();
361         }
362
363         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
364         if (folder_path_func_ == 0) {
365                 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
366                           "Don't know how to proceed. Sorry."
367                        << std::endl;
368                 bail_out();
369         }
370 }
371
372
373 GetFolderPath::~GetFolderPath()
374 {
375         if (folder_module_)
376                 FreeLibrary(folder_module_);
377 }
378
379
380 // Given a folder ID, returns the folder name (in unix-style format).
381 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
382 string const GetFolderPath::operator()(folder_id _id) const
383 {
384         char folder_path[MAX_PATH];
385
386         int id = 0;
387         switch (_id) {
388         case PERSONAL:
389                 id = CSIDL_PERSONAL;
390                 break;
391         case APPDATA:
392                 id = CSIDL_APPDATA;
393                 break;
394         default:
395                 BOOST_ASSERT(false);
396         }
397         HRESULT const result = (folder_path_func_)(0, id, 0,
398                                                    SHGFP_TYPE_CURRENT,
399                                                    folder_path);
400         return (result == 0) ? os::internal_path(folder_path) : string();
401 }
402
403
404 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
405 {
406         if (ext.empty())
407                 return false;
408
409         string const full_ext = "." + ext;
410
411         DWORD bufSize = MAX_PATH + 100;
412         TCHAR buf[MAX_PATH + 100];
413         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
414         //                 /platform/shell/reference/shlwapi/registry/assocquerystring.asp
415         char const * action = (mode == VIEW) ? "open" : "edit";
416         return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
417                 full_ext.c_str(), action, buf, &bufSize);
418 }
419
420
421 bool autoOpenFile(string const & filename, auto_open_mode const mode)
422 {
423         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
424         //                 /platform/shell/reference/functions/shellexecute.asp
425         char const * action = (mode == VIEW) ? "open" : "edit";
426         return reinterpret_cast<int>(ShellExecute(NULL, action,
427                 filename.c_str(), NULL, NULL, 1)) > 32;
428 }
429
430
431 } // namespace os
432 } // namespace support
433 } // namespace lyx