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