]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.C
Convert internal_path() to unicode (partially). Fix bug 3114:
[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
26 #include <boost/assert.hpp>
27
28 #include <cstdlib>
29 #include <vector>
30
31 #include <string>
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 string::size_type common_path(string const & p1, string const & p2)
185 {
186         string::size_type i = 0;
187         string::size_type       p1_len = p1.length();
188         string::size_type       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         std::vector<char> long_path(MAX_PATH);
221         DWORD result = GetLongPathName(short_path.c_str(),
222                                        &long_path[0], long_path.size());
223
224         if (result > long_path.size()) {
225                 long_path.resize(result);
226                 result = GetLongPathName(short_path.c_str(),
227                                          &long_path[0], long_path.size());
228                 BOOST_ASSERT(result <= long_path.size());
229         }
230
231         return (result == 0) ? short_path : &long_path[0];
232 }
233
234 } // namespace anon
235
236
237 string internal_path(string const & p)
238 {
239         return subst(get_long_path(p), "\\", "/");
240 }
241
242
243 docstring internal_path(docstring const & p)
244 {
245         // FIXME UNICODE
246         return from_utf8(subst(get_long_path(to_utf8(p)), "\\", "/"));
247 }
248
249
250 string external_path_list(string const & p)
251 {
252         return subst(p, '/', '\\');
253 }
254
255
256 string internal_path_list(string const & p)
257 {
258         return subst(p, '\\', '/');
259 }
260
261
262 string latex_path(string const & p)
263 {
264         // We may need a posix style path or a windows style path (depending
265         // on windows_style_tex_paths_), but we use always forward slashes,
266         // since it gets written into a .tex file.
267
268         if (!windows_style_tex_paths_ && is_absolute_path(p)) {
269                 string const drive = p.substr(0, 2);
270                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
271                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
272                 lyxerr[Debug::LATEX]
273                         << "<Path correction for LaTeX> ["
274                         << p << "]->>["
275                         << cygpath << ']' << endl;
276                 return cygpath;
277         }
278         return subst(p, '\\', '/');
279 }
280
281
282 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
283 // Therefore an absolute path could be either a pathname starting
284 // with a slash (Unix) or a pathname starting with a drive letter
285 // followed by a colon. Because a colon is not valid in pathes in Unix
286 // and at another location in Win32 testing just for the existance
287 // of the colon in the 2nd position seems to be enough!
288 bool is_absolute_path(string const & p)
289 {
290         if (p.empty())
291                 return false;
292
293         bool isDosPath = (p.length() > 1 && p[1] == ':');
294         bool isUnixPath = (p[0] == '/');
295
296         return isDosPath || isUnixPath;
297 }
298
299
300 // returns a string suitable to be passed to popen when
301 // reading a pipe
302 char const * popen_read_mode()
303 {
304         return "r";
305 }
306
307
308 string const & nulldev()
309 {
310         static string const nulldev_ = "nul";
311         return nulldev_;
312 }
313
314
315 shell_type shell()
316 {
317         return CMD_EXE;
318 }
319
320
321 char path_separator()
322 {
323         return ';';
324 }
325
326
327 void windows_style_tex_paths(bool use_windows_paths)
328 {
329         windows_style_tex_paths_ = use_windows_paths;
330 }
331
332
333 namespace {
334
335 void bail_out()
336 {
337 #ifndef CXX_GLOBAL_CSTD
338         using std::exit;
339 #endif
340         exit(1);
341 }
342
343 } // namespace anon
344
345
346 GetFolderPath::GetFolderPath()
347         : folder_module_(0),
348           folder_path_func_(0)
349 {
350         folder_module_ = LoadLibrary("shfolder.dll");
351         if (!folder_module_) {
352                 lyxerr << "Unable to load shfolder.dll\nPlease install."
353                        << std::endl;
354                 bail_out();
355         }
356
357         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
358         if (folder_path_func_ == 0) {
359                 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
360                           "Don't know how to proceed. Sorry."
361                        << std::endl;
362                 bail_out();
363         }
364 }
365
366
367 GetFolderPath::~GetFolderPath()
368 {
369         if (folder_module_)
370                 FreeLibrary(folder_module_);
371 }
372
373
374 // Given a folder ID, returns the folder name (in unix-style format).
375 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
376 string const GetFolderPath::operator()(folder_id _id) const
377 {
378         char folder_path[MAX_PATH];
379
380         int id = 0;
381         switch (_id) {
382         case PERSONAL:
383                 id = CSIDL_PERSONAL;
384                 break;
385         case APPDATA:
386                 id = CSIDL_APPDATA;
387                 break;
388         default:
389                 BOOST_ASSERT(false);
390         }
391         HRESULT const result = (folder_path_func_)(0, id, 0,
392                                                    SHGFP_TYPE_CURRENT,
393                                                    folder_path);
394         return (result == 0) ? os::internal_path(folder_path) : string();
395 }
396
397
398 bool canAutoOpenFile(string const & ext, auto_open_mode const mode)
399 {
400         if (ext.empty())
401                 return false;
402
403         string const full_ext = "." + ext;
404
405         DWORD bufSize = MAX_PATH + 100;
406         TCHAR buf[MAX_PATH + 100];
407         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
408         //                 /platform/shell/reference/shlwapi/registry/assocquerystring.asp
409         char const * action = (mode == VIEW) ? "open" : "edit";
410         return S_OK == AssocQueryString(0, ASSOCSTR_EXECUTABLE,
411                 full_ext.c_str(), action, buf, &bufSize);
412 }
413
414
415 bool autoOpenFile(string const & filename, auto_open_mode const mode)
416 {
417         // reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc
418         //                 /platform/shell/reference/functions/shellexecute.asp
419         char const * action = (mode == VIEW) ? "open" : "edit";
420         return reinterpret_cast<int>(ShellExecute(NULL, action,
421                 filename.c_str(), NULL, NULL, 1)) > 32;
422 }
423
424
425 void addFontResources()
426 {
427         // Windows only: Add BaKoMa TrueType font resources
428         string const fonts_dir = addPath(package().system_support(), "fonts");
429         
430         for (int i = 0 ; i < num_fonts_truetype ; ++i) {
431                 string const font_current = 
432                         addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
433                 AddFontResource(external_path(font_current).c_str());
434         }
435 }
436
437
438 void restoreFontResources()
439 {
440         // Windows only: Remove BaKoMa TrueType font resources
441         string const fonts_dir = addPath(package().system_support(), "fonts");
442         
443         for(int i = 0 ; i < num_fonts_truetype ; ++i) {
444                 string const font_current = 
445                         addName(fonts_dir, win_fonts_truetype[i] + ".ttf");
446                 RemoveFontResource(external_path(font_current).c_str());
447         }
448 }
449
450 } // namespace os
451 } // namespace support
452 } // namespace lyx