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