]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.C
* src/support/package.C.in (relative_locale_dir): fix for Windows and OSX.
[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
22 #include "debug.h"
23
24 #include <boost/assert.hpp>
25
26 #include <cstdlib>
27 #include <vector>
28
29 #include <string>
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
54 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
55 #if defined(__MINGW32__)  || defined(__CYGWIN__) || defined(__CYGWIN32__)
56 # include <w32api.h>
57 # if __W32API_MAJOR_VERSION < 3 || \
58      __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION  < 2
59 #  define SHGFP_TYPE_CURRENT 0
60 # endif
61 #endif
62
63 using std::endl;
64 using std::string;
65
66 using lyx::support::runCommand;
67 using lyx::support::split;
68
69
70 namespace lyx {
71 namespace support {
72 namespace os {
73
74 namespace {
75
76 bool cygwin_path_fix_ = false;
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.
136          */
137         // Close the console when run (probably)
138         // not run from command prompt
139         char WindowTitle[1024];
140         if (GetConsoleTitle(WindowTitle, sizeof(WindowTitle)) == 0) {
141                 // Could not get the title, so we just leave things as they are
142                 return;
143         }
144
145         if ((strcmp(WindowTitle, argv[0]) == 0) ||
146                 (strcmp(WindowTitle, "LyX") == 0)) {
147                 // format a "unique" newWindowTitle
148                 wsprintf(WindowTitle, "%d/%d",
149                         GetTickCount(),
150                         GetCurrentProcessId());
151                 // change current window title
152                 SetConsoleTitle(WindowTitle);
153                 // ensure window title has been updated
154                 Sleep(40);
155                 // look for newWindowTitle
156                 HWND const hwndFound = FindWindow(NULL, WindowTitle);
157                 // If found, hide it
158                 if (hwndFound != NULL)
159                         ShowWindow( hwndFound, SW_HIDE);
160         }
161
162         // If cygwin is detected, query the cygdrive prefix
163         cmd_ret const c = runCommand("sh -c uname");
164         if (c.first != -1 && prefixIs(c.second, "CYGWIN")) {
165                 cmd_ret const p = runCommand("mount --show-cygdrive-prefix");
166                 // The output of the mount command is as follows:
167                 // Prefix              Type         Flags
168                 // /cygdrive           system       binmode
169                 // So, we use the inner split to pass the second line to the
170                 // outer split which sets cygdrive with its contents until
171                 // the first blank, discarding the unneeded return value.
172                 if (p.first != -1 && prefixIs(p.second, "Prefix"))
173                         (void) split(split(p.second, '\n'), cygdrive, ' ');
174         }
175 }
176
177
178 string current_root()
179 {
180         // _getdrive returns the current drive (1=A, 2=B, and so on).
181         char const drive = ::_getdrive() + 'A' - 1;
182         return string(1, drive) + ":/";
183 }
184
185
186 string::size_type common_path(string const & p1, string const & p2)
187 {
188         string::size_type i = 0;
189         string::size_type       p1_len = p1.length();
190         string::size_type       p2_len = p2.length();
191         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
192                 ++i;
193         if ((i < p1_len && i < p2_len)
194             || (i < p1_len && p1[i] != '/' && i == p2_len)
195             || (i < p2_len && p2[i] != '/' && i == p1_len))
196         {
197                 if (i)
198                         --i;     // here was the last match
199                 while (i && p1[i] != '/')
200                         --i;
201         }
202         return i;
203 }
204
205
206 string external_path(string const & p)
207 {
208         string const dos_path = subst(p, "/", "\\");
209
210         lyxerr[Debug::LATEX]
211                 << "<Win32 path correction> ["
212                 << p << "]->>["
213                 << dos_path << ']' << endl;
214         return dos_path;
215 }
216
217
218 namespace {
219
220 string const get_long_path(string const & short_path)
221 {
222         std::vector<char> long_path(MAX_PATH);
223         DWORD result = GetLongPathName(short_path.c_str(),
224                                        &long_path[0], long_path.size());
225
226         if (result > long_path.size()) {
227                 long_path.resize(result);
228                 result = GetLongPathName(short_path.c_str(),
229                                          &long_path[0], long_path.size());
230                 BOOST_ASSERT(result <= long_path.size());
231         }
232
233         return (result == 0) ? short_path : &long_path[0];
234 }
235
236 } // namespace anon
237
238
239 string internal_path(string const & p)
240 {
241         return subst(get_long_path(p), "\\", "/");
242 }
243
244
245 string external_path_list(string const & p)
246 {
247         return subst(p, '/', '\\');
248 }
249
250
251 string internal_path_list(string const & p)
252 {
253         return subst(p, '\\', '/');
254 }
255
256
257 string latex_path(string const & p)
258 {
259         // We may need a posix style path or a windows style path (depending
260         // on cygwin_path_fix_), but we use always forward slashes, since it
261         // gets written into a .tex file.
262
263         if (cygwin_path_fix_ && is_absolute_path(p)) {
264                 string const drive = p.substr(0, 2);
265                 string const cygprefix = cygdrive + "/" + drive.substr(0, 1);
266                 string const cygpath = subst(subst(p, '\\', '/'), drive, cygprefix);
267                 lyxerr[Debug::LATEX]
268                         << "<Cygwin path correction> ["
269                         << p << "]->>["
270                         << cygpath << ']' << endl;
271                 return cygpath;
272         }
273         return subst(p, '\\', '/');
274 }
275
276
277 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
278 // Therefore an absolute path could be either a pathname starting
279 // with a slash (Unix) or a pathname starting with a drive letter
280 // followed by a colon. Because a colon is not valid in pathes in Unix
281 // and at another location in Win32 testing just for the existance
282 // of the colon in the 2nd position seems to be enough!
283 bool is_absolute_path(string const & p)
284 {
285         if (p.empty())
286                 return false;
287
288         bool isDosPath = (p.length() > 1 && p[1] == ':');
289         bool isUnixPath = (p[0] == '/');
290
291         return isDosPath || isUnixPath;
292 }
293
294
295 // returns a string suitable to be passed to popen when
296 // reading a pipe
297 char const * popen_read_mode()
298 {
299         return "r";
300 }
301
302
303 string const & nulldev()
304 {
305         static string const nulldev_ = "nul";
306         return nulldev_;
307 }
308
309
310 shell_type shell()
311 {
312         return CMD_EXE;
313 }
314
315
316 char path_separator()
317 {
318         return ';';
319 }
320
321
322 void cygwin_path_fix(bool use_cygwin_paths)
323 {
324         cygwin_path_fix_ = !use_cygwin_paths;
325 }
326
327
328 namespace {
329
330 void bail_out()
331 {
332 #ifndef CXX_GLOBAL_CSTD
333         using std::exit;
334 #endif
335         exit(1);
336 }
337
338 } // namespace anon
339
340
341 GetFolderPath::GetFolderPath()
342         : folder_module_(0),
343           folder_path_func_(0)
344 {
345         folder_module_ = LoadLibrary("shfolder.dll");
346         if (!folder_module_) {
347                 lyxerr << "Unable to load shfolder.dll\nPlease install."
348                        << std::endl;
349                 bail_out();
350         }
351
352         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
353         if (folder_path_func_ == 0) {
354                 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
355                           "Don't know how to proceed. Sorry."
356                        << std::endl;
357                 bail_out();
358         }
359 }
360
361
362 GetFolderPath::~GetFolderPath()
363 {
364         if (folder_module_)
365                 FreeLibrary(folder_module_);
366 }
367
368
369 // Given a folder ID, returns the folder name (in unix-style format).
370 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
371 string const GetFolderPath::operator()(folder_id _id) const
372 {
373         char folder_path[MAX_PATH];
374
375         int id = 0;
376         switch (_id) {
377         case PERSONAL:
378                 id = CSIDL_PERSONAL;
379                 break;
380         case APPDATA:
381                 id = CSIDL_APPDATA;
382                 break;
383         default:
384                 BOOST_ASSERT(false);
385         }
386         HRESULT const result = (folder_path_func_)(0, id, 0,
387                                                    SHGFP_TYPE_CURRENT,
388                                                    folder_path);
389         return (result == 0) ? os::internal_path(folder_path) : string();
390 }
391
392 } // namespace os
393 } // namespace support
394 } // namespace lyx