]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
Now that exceptions are allowed, handle gracefully the case where a Buffer temp direc...
[lyx.git] / src / support / os_win32.cpp
1 /**
2  * \file os_win32.cpp
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
20 #include "support/debug.h"
21 #include "support/FileName.h"
22 #include "support/gettext.h"
23 #include "support/filetools.h"
24 #include "support/lstrings.h"
25 #include "support/ExceptionMessage.h"
26
27 #include <boost/assert.hpp>
28
29 #include <cstdlib>
30 #include <vector>
31
32 /* The GetLongPathName macro may be defined on the compiling machine,
33  * but we must use a bit of trickery if the resulting executable is
34  * to run on a Win95 machine.
35  * Fortunately, Microsoft provide the trickery. All we need is the
36  * NewAPIs.h header file, available for download from Microsoft as
37  * part of the Platform SDK.
38  */
39 #if defined (HAVE_NEWAPIS_H)
40 // This should be defined already to keep Boost.Filesystem happy.
41 # if !defined (WANT_GETFILEATTRIBUTESEX_WRAPPER)
42 #   error Expected WANT_GETFILEATTRIBUTESEX_WRAPPER to be defined!
43 # endif
44 # define WANT_GETLONGPATHNAME_WRAPPER 1
45 # define COMPILE_NEWAPIS_STUBS
46 # include <NewAPIs.h>
47 # undef COMPILE_NEWAPIS_STUBS
48 # undef WANT_GETLONGPATHNAME_WRAPPER
49 #endif
50
51 #include <io.h>
52 #include <direct.h> // _getdrive
53 #include <shlobj.h>  // SHGetFolderPath
54 #include <windef.h>
55 #include <shellapi.h>
56 #include <shlwapi.h>
57
58 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
59 #if defined(__MINGW32__)  || defined(__CYGWIN__) || defined(__CYGWIN32__)
60 # include <w32api.h>
61 # if __W32API_MAJOR_VERSION < 3 || \
62      __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION  < 2
63 #  define SHGFP_TYPE_CURRENT 0
64 # endif
65 #endif
66
67 using namespace std;
68
69 namespace lyx {
70 namespace support {
71 namespace os {
72
73 namespace {
74
75 bool windows_style_tex_paths_ = true;
76
77 string cygdrive = "/cygdrive";
78
79 } // namespace anon
80
81 void init(int /* argc */, char * argv[])
82 {
83         /* Note from Angus, 17 Jan 2005:
84          *
85          * The code below is taken verbatim from Ruurd's original patch
86          * porting LyX to Win32.
87          *
88          * Windows allows us to define LyX either as a console-based app
89          * or as a GUI-based app. Ruurd decided to define LyX as a
90          * console-based app with a "main" function rather than a "WinMain"
91          * function as the point of entry to the program, but to
92          * immediately close the console window that Windows helpfully
93          * opens for us. Doing so allows the user to see all of LyX's
94          * debug output simply by running LyX from a DOS or MSYS-shell
95          * prompt.
96          *
97          * The alternative approach is to define LyX as a genuine
98          * GUI-based app, with a "WinMain" function as the entry point to the
99          * executable rather than a "main" function, so:
100          *
101          * #if defined (_WIN32)
102          * # define WIN32_LEAN_AND_MEAN
103          * # include <stdlib.h>  // for __argc, __argv
104          * # include <windows.h> // for WinMain
105          * #endif
106          *
107          * // This will require the "-mwindows" flag when linking with
108          * // gcc under MinGW.
109          * // For MSVC, use "/subsystem:windows".
110          * #if defined (_WIN32)
111          * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
112          * {
113          *     return mymain(__argc, __argv);
114          * }
115          * #endif
116          *
117          * where "mymain" is just a renamed "main".
118          *
119          * However, doing so means that the lyxerr messages would mysteriously
120          * disappear. They could be resurrected with something like:
121          *
122          * #ifdef WIN32
123          *  AllocConsole();
124          *  freopen("conin$","r",stdin);
125          *  freopen("conout$","w",stdout);
126          *  freopen("conout$","w",stderr);
127          * #endif
128          *
129          * This code could be invoked (say) the first time that lyxerr
130          * is called. However, Ruurd has tried this route and found that some
131          * shell scripts failed, for mysterious reasons...
132          *
133          * I've chosen for now, therefore, to simply add Ruurd's original
134          * code as-is. A wrapper program hidecmd.c has been added to
135          * development/Win32 which hides the console window of lyx when
136          * lyx is invoked as a parameter of hidecmd.exe.
137          */
138
139         // If cygwin is detected, query the cygdrive prefix
140         HKEY regKey;
141         char buf[MAX_PATH];
142         DWORD bufSize = sizeof(buf);
143         LONG retVal;
144
145         retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
146                         "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
147                         0, KEY_QUERY_VALUE, &regKey);
148         if (retVal != ERROR_SUCCESS) {
149                 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
150                                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
151                                 0, KEY_QUERY_VALUE, &regKey);
152         }
153         if (retVal == ERROR_SUCCESS) {
154                 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
155                                 (LPBYTE) buf, &bufSize);
156                 RegCloseKey(regKey);
157                 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
158                         cygdrive = buf;
159         }
160 }
161
162
163 string current_root()
164 {
165         // _getdrive returns the current drive (1=A, 2=B, and so on).
166         char const drive = ::_getdrive() + 'A' - 1;
167         return string(1, drive) + ":/";
168 }
169
170
171 docstring::size_type common_path(docstring const & p1, docstring const & p2)
172 {
173         size_t i = 0;
174         size_t const p1_len = p1.length();
175         size_t const p2_len = p2.length();
176         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
177                 ++i;
178         if ((i < p1_len && i < p2_len)
179             || (i < p1_len && p1[i] != '/' && i == p2_len)
180             || (i < p2_len && p2[i] != '/' && i == p1_len))
181         {
182                 if (i)
183                         --i;     // here was the last match
184                 while (i && p1[i] != '/')
185                         --i;
186         }
187         return i;
188 }
189
190
191 string external_path(string const & p)
192 {
193         string const dos_path = subst(p, "/", "\\");
194
195         LYXERR(Debug::LATEX, "<Win32 path correction> ["
196                 << p << "]->>[" << dos_path << ']');
197         return dos_path;
198 }
199
200
201 static string const get_long_path(string const & short_path)
202 {
203         // GetLongPathName needs the path in file system encoding.
204         // We can use to_local8bit, since file system encoding and the
205         // local 8 bit encoding are identical on windows.
206         vector<char> long_path(MAX_PATH);
207         DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
208                                        &long_path[0], long_path.size());
209
210         if (result > long_path.size()) {
211                 long_path.resize(result);
212                 result = GetLongPathName(short_path.c_str(),
213                                          &long_path[0], long_path.size());
214                 BOOST_ASSERT(result <= long_path.size());
215         }
216
217         return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
218 }
219
220
221 string internal_path(string const & p)
222 {
223         return subst(get_long_path(p), "\\", "/");
224 }
225
226
227 string external_path_list(string const & p)
228 {
229         return subst(p, '/', '\\');
230 }
231
232
233 string internal_path_list(string const & p)
234 {
235         return subst(p, '\\', '/');
236 }
237
238
239 string latex_path(string const & p)
240 {
241         // We may need a posix style path or a windows style path (depending
242         // on windows_style_tex_paths_), but we use always forward slashes,
243         // since it gets written into a .tex file.
244
245         FileName path(p);
246         if (!windows_style_tex_paths_ && path.isAbsolute()) {
247                 string const drive = p.substr(0, 2);
248                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
249                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
250                 LYXERR(Debug::LATEX, "<Path correction for LaTeX> ["
251                         << p << "]->>[" << cygpath << ']');
252                 return cygpath;
253         }
254         return subst(p, '\\', '/');
255 }
256
257
258 // returns a string suitable to be passed to popen when
259 // reading a pipe
260 char const * popen_read_mode()
261 {
262         return "r";
263 }
264
265
266 string const & nulldev()
267 {
268         static string const nulldev_ = "nul";
269         return nulldev_;
270 }
271
272
273 shell_type shell()
274 {
275         return CMD_EXE;
276 }
277
278
279 char path_separator()
280 {
281         return ';';
282 }
283
284
285 void windows_style_tex_paths(bool use_windows_paths)
286 {
287         windows_style_tex_paths_ = use_windows_paths;
288 }
289
290
291 GetFolderPath::GetFolderPath()
292         : folder_module_(0),
293           folder_path_func_(0)
294 {
295         folder_module_ = LoadLibrary("shfolder.dll");
296         if (!folder_module_) {
297                 throw ExceptionMessage(ErrorException, _("System file not found"),
298                         _("Unable to load shfolder.dll\nPlease install."));
299         }
300
301         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
302         if (folder_path_func_ == 0) {
303                 throw ExceptionMessage(ErrorException, _("System function not found"),
304                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
305                           "Don't know how to proceed. Sorry."));
306         }
307 }
308
309
310 GetFolderPath::~GetFolderPath()
311 {
312         if (folder_module_)
313                 FreeLibrary(folder_module_);
314 }
315
316
317 // Given a folder ID, returns the folder name (in unix-style format).
318 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
319 string const GetFolderPath::operator()(folder_id _id) const
320 {
321         char folder_path[MAX_PATH];
322
323         int id = 0;
324         switch (_id) {
325         case PERSONAL:
326                 id = CSIDL_PERSONAL;
327                 break;
328         case APPDATA:
329                 id = CSIDL_APPDATA;
330                 break;
331         default:
332                 BOOST_ASSERT(false);
333         }
334         HRESULT const result = (folder_path_func_)(0, id, 0,
335                                                    SHGFP_TYPE_CURRENT,
336                                                    folder_path);
337         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
338 }
339
340
341 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
342 {
343         if (ext.empty())
344                 return false;
345
346         string const full_ext = "." + ext;
347
348         DWORD bufSize = MAX_PATH + 100;
349         TCHAR buf[MAX_PATH + 100];
350         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
351         //                 /platform/shell/reference/shlwapi/registry/assocquerystring.asp
352         char const * action = (mode == VIEW) ? "open" : "edit";
353         return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
354                 full_ext.c_str(), action, buf, &bufSize);
355 }
356
357
358 bool autoOpenFile(string const & filename, auto_open_mode const mode)
359 {
360         // reference: http://msdn.microsoft.com/library/default.asp
361         // ?url=/library/en-us/shellcc/platform/shell/reference/functions/
362         // shellexecute.asp
363         char const * action = (mode == VIEW) ? "open" : "edit";
364         return reinterpret_cast<int>(ShellExecute(NULL, action,
365                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
366 }
367
368 } // namespace os
369 } // namespace support
370 } // namespace lyx