]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.cpp
Register math fonts with Qt 4.2 or higher. Using Qt 4.1, the old
[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/lstrings.h"
20 #include "support/filetools.h"
21 #include "support/ExceptionMessage.h"
22
23 #include "debug.h"
24 #include "gettext.h"
25
26 #include <boost/assert.hpp>
27
28 #include <cstdlib>
29 #include <vector>
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. A wrapper program hidecmd.c has been added to
139          * development/Win32 which hides the console window of lyx when
140          * lyx is invoked as a parameter of hidecmd.exe.
141          */
142
143         // If cygwin is detected, query the cygdrive prefix
144         HKEY regKey;
145         char buf[MAX_PATH];
146         DWORD bufSize = sizeof(buf);
147         LONG retVal;
148
149         retVal = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
150                         "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
151                         0, KEY_QUERY_VALUE, &regKey);
152         if (retVal != ERROR_SUCCESS) {
153                 retVal = RegOpenKeyEx(HKEY_CURRENT_USER,
154                                 "Software\\Cygnus Solutions\\Cygwin\\mounts v2",
155                                 0, KEY_QUERY_VALUE, &regKey);
156         }
157         if (retVal == ERROR_SUCCESS) {
158                 retVal = RegQueryValueEx(regKey, "cygdrive prefix", NULL, NULL,
159                                 (LPBYTE) buf, &bufSize);
160                 RegCloseKey(regKey);
161                 if ((retVal == ERROR_SUCCESS) && (bufSize <= MAX_PATH))
162                         cygdrive = buf;
163         }
164 }
165
166
167 string current_root()
168 {
169         // _getdrive returns the current drive (1=A, 2=B, and so on).
170         char const drive = ::_getdrive() + 'A' - 1;
171         return string(1, drive) + ":/";
172 }
173
174
175 docstring::size_type common_path(docstring const & p1, docstring const & p2)
176 {
177         docstring::size_type i = 0;
178         docstring::size_type const p1_len = p1.length();
179         docstring::size_type const p2_len = p2.length();
180         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
181                 ++i;
182         if ((i < p1_len && i < p2_len)
183             || (i < p1_len && p1[i] != '/' && i == p2_len)
184             || (i < p2_len && p2[i] != '/' && i == p1_len))
185         {
186                 if (i)
187                         --i;     // here was the last match
188                 while (i && p1[i] != '/')
189                         --i;
190         }
191         return i;
192 }
193
194
195 string external_path(string const & p)
196 {
197         string const dos_path = subst(p, "/", "\\");
198
199         LYXERR(Debug::LATEX)
200                 << "<Win32 path correction> ["
201                 << p << "]->>["
202                 << dos_path << ']' << endl;
203         return dos_path;
204 }
205
206
207 namespace {
208
209 string const get_long_path(string const & short_path)
210 {
211         // GetLongPathName needs the path in file system encoding.
212         // We can use to_local8bit, since file system encoding and the
213         // local 8 bit encoding are identical on windows.
214         std::vector<char> long_path(MAX_PATH);
215         DWORD result = GetLongPathName(to_local8bit(from_utf8(short_path)).c_str(),
216                                        &long_path[0], long_path.size());
217
218         if (result > long_path.size()) {
219                 long_path.resize(result);
220                 result = GetLongPathName(short_path.c_str(),
221                                          &long_path[0], long_path.size());
222                 BOOST_ASSERT(result <= long_path.size());
223         }
224
225         return (result == 0) ? short_path : to_utf8(from_filesystem8bit(&long_path[0]));
226 }
227
228 } // namespace anon
229
230
231 string internal_path(string const & p)
232 {
233         return subst(get_long_path(p), "\\", "/");
234 }
235
236
237 string external_path_list(string const & p)
238 {
239         return subst(p, '/', '\\');
240 }
241
242
243 string internal_path_list(string const & p)
244 {
245         return subst(p, '\\', '/');
246 }
247
248
249 string latex_path(string const & p)
250 {
251         // We may need a posix style path or a windows style path (depending
252         // on windows_style_tex_paths_), but we use always forward slashes,
253         // since it gets written into a .tex file.
254
255         if (!windows_style_tex_paths_ && is_absolute_path(p)) {
256                 string const drive = p.substr(0, 2);
257                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
258                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
259                 LYXERR(Debug::LATEX)
260                         << "<Path correction for LaTeX> ["
261                         << p << "]->>["
262                         << cygpath << ']' << endl;
263                 return cygpath;
264         }
265         return subst(p, '\\', '/');
266 }
267
268
269 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
270 // Therefore an absolute path could be either a pathname starting
271 // with a slash (Unix) or a pathname starting with a drive letter
272 // followed by a colon. Because a colon is not valid in pathes in Unix
273 // and at another location in Win32 testing just for the existance
274 // of the colon in the 2nd position seems to be enough!
275 bool is_absolute_path(string const & p)
276 {
277         if (p.empty())
278                 return false;
279
280         bool isDosPath = (p.length() > 1 && p[1] == ':');
281         bool isUnixPath = (p[0] == '/');
282
283         return isDosPath || isUnixPath;
284 }
285
286
287 // returns a string suitable to be passed to popen when
288 // reading a pipe
289 char const * popen_read_mode()
290 {
291         return "r";
292 }
293
294
295 string const & nulldev()
296 {
297         static string const nulldev_ = "nul";
298         return nulldev_;
299 }
300
301
302 shell_type shell()
303 {
304         return CMD_EXE;
305 }
306
307
308 char path_separator()
309 {
310         return ';';
311 }
312
313
314 void windows_style_tex_paths(bool use_windows_paths)
315 {
316         windows_style_tex_paths_ = use_windows_paths;
317 }
318
319
320 GetFolderPath::GetFolderPath()
321         : folder_module_(0),
322           folder_path_func_(0)
323 {
324         folder_module_ = LoadLibrary("shfolder.dll");
325         if (!folder_module_) {
326                 throw ExceptionMessage(ErrorException, _("System file not found"),
327                         _("Unable to load shfolder.dll\nPlease install."));
328         }
329
330         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
331         if (folder_path_func_ == 0) {
332                 throw ExceptionMessage(ErrorException, _("System function not found"),
333                         _("Unable to find SHGetFolderPathA in shfolder.dll\n"
334                           "Don't know how to proceed. Sorry."));
335         }
336 }
337
338
339 GetFolderPath::~GetFolderPath()
340 {
341         if (folder_module_)
342                 FreeLibrary(folder_module_);
343 }
344
345
346 // Given a folder ID, returns the folder name (in unix-style format).
347 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
348 string const GetFolderPath::operator()(folder_id _id) const
349 {
350         char folder_path[MAX_PATH];
351
352         int id = 0;
353         switch (_id) {
354         case PERSONAL:
355                 id = CSIDL_PERSONAL;
356                 break;
357         case APPDATA:
358                 id = CSIDL_APPDATA;
359                 break;
360         default:
361                 BOOST_ASSERT(false);
362         }
363         HRESULT const result = (folder_path_func_)(0, id, 0,
364                                                    SHGFP_TYPE_CURRENT,
365                                                    folder_path);
366         return (result == 0) ? os::internal_path(to_utf8(from_filesystem8bit(folder_path))) : string();
367 }
368
369
370 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
371 {
372         if (ext.empty())
373                 return false;
374
375         string const full_ext = "." + ext;
376
377         DWORD bufSize = MAX_PATH + 100;
378         TCHAR buf[MAX_PATH + 100];
379         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
380         //                 /platform/shell/reference/shlwapi/registry/assocquerystring.asp
381         char const * action = (mode == VIEW) ? "open" : "edit";
382         return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
383                 full_ext.c_str(), action, buf, &bufSize);
384 }
385
386
387 bool autoOpenFile(string const & filename, auto_open_mode const mode)
388 {
389         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
390         //                 /platform/shell/reference/functions/shellexecute.asp
391         char const * action = (mode == VIEW) ? "open" : "edit";
392         return reinterpret_cast<int>(ShellExecute(NULL, action,
393                 to_local8bit(from_utf8(filename)).c_str(), NULL, NULL, 1)) > 32;
394 }
395
396 } // namespace os
397 } // namespace support
398 } // namespace lyx