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