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