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