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