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