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