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