]> git.lyx.org Git - lyx.git/blob - src/support/os_win32.C
Fix latex_path on cygwin:
[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
21 #include "debug.h"
22
23 #include <boost/assert.hpp>
24
25 #include <cstdlib>
26 #include <vector>
27
28 #include <string>
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
53 // Must define SHGFP_TYPE_CURRENT for older versions of MinGW.
54 #if defined(__MINGW32__)  || defined(__CYGWIN__) || defined(__CYGWIN32__)
55 # include <w32api.h>
56 # if __W32API_MAJOR_VERSION < 3 || \
57      __W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION  < 2
58 #  define SHGFP_TYPE_CURRENT 0
59 # endif
60 #endif
61
62 using std::endl;
63 using std::string;
64
65
66 namespace lyx {
67 namespace support {
68 namespace os {
69
70 void init(int /* argc */, char * argv[])
71 {
72         /* Note from Angus, 17 Jan 2005:
73          *
74          * The code below is taken verbatim from Ruurd's original patch
75          * porting LyX to Win32.
76          *
77          * Windows allows us to define LyX either as a console-based app
78          * or as a GUI-based app. Ruurd decided to define LyX as a
79          * console-based app with a "main" function rather than a "WinMain"
80          * function as the point of entry to the program, but to
81          * immediately close the console window that Windows helpfully
82          * opens for us. Doing so allows the user to see all of LyX's
83          * debug output simply by running LyX from a DOS or MSYS-shell
84          * prompt.
85          *
86          * The alternative approach is to define LyX as a genuine
87          * GUI-based app, with a "WinMain" function as the entry point to the
88          * executable rather than a "main" function, so:
89          *
90          * #if defined (_WIN32)
91          * # define WIN32_LEAN_AND_MEAN
92          * # include <stdlib.h>  // for __argc, __argv
93          * # include <windows.h> // for WinMain
94          * #endif
95          *
96          * // This will require the "-mwindows" flag when linking with
97          * // gcc under MinGW.
98          * // For MSVC, use "/subsystem:windows".
99          * #if defined (_WIN32)
100          * int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
101          * {
102          *     return mymain(__argc, __argv);
103          * }
104          * #endif
105          *
106          * where "mymain" is just a renamed "main".
107          *
108          * However, doing so means that the lyxerr messages would mysteriously
109          * disappear. They could be resurrected with something like:
110          *
111          * #ifdef WIN32
112          *  AllocConsole();
113          *  freopen("conin$","r",stdin);
114          *  freopen("conout$","w",stdout);
115          *  freopen("conout$","w",stderr);
116          * #endif
117          *
118          * This code could be invoked (say) the first time that lyxerr
119          * is called. However, Ruurd has tried this route and found that some
120          * shell scripts failed, for mysterious reasons...
121          *
122          * I've chosen for now, therefore, to simply add Ruurd's original
123          * code as-is.
124          */
125         // Close the console when run (probably)
126         // not run from command prompt
127         char WindowTitle[1024];
128         if (GetConsoleTitle(WindowTitle, sizeof(WindowTitle)) == 0) {
129                 // Could not get the title, so we just leave things as they are
130                 return;
131         }
132
133         if ((strcmp(WindowTitle, argv[0]) == 0) ||
134                 (strcmp(WindowTitle, "LyX") == 0)) {
135                 // format a "unique" newWindowTitle
136                 wsprintf(WindowTitle, "%d/%d",
137                         GetTickCount(),
138                         GetCurrentProcessId());
139                 // change current window title
140                 SetConsoleTitle(WindowTitle);
141                 // ensure window title has been updated
142                 Sleep(40);
143                 // look for newWindowTitle
144                 HWND const hwndFound = FindWindow(NULL, WindowTitle);
145                 // If found, hide it
146                 if (hwndFound != NULL)
147                         ShowWindow( hwndFound, SW_HIDE);
148         }
149 }
150
151
152 string current_root()
153 {
154         // _getdrive returns the current drive (1=A, 2=B, and so on).
155         char const drive = ::_getdrive() + 'A' - 1;
156         return string(1, drive) + ":/";
157 }
158
159
160 string::size_type common_path(string const & p1, string const & p2)
161 {
162         string::size_type i = 0;
163         string::size_type       p1_len = p1.length();
164         string::size_type       p2_len = p2.length();
165         while (i < p1_len && i < p2_len && uppercase(p1[i]) == uppercase(p2[i]))
166                 ++i;
167         if ((i < p1_len && i < p2_len)
168             || (i < p1_len && p1[i] != '/' && i == p2_len)
169             || (i < p2_len && p2[i] != '/' && i == p1_len))
170         {
171                 if (i)
172                         --i;     // here was the last match
173                 while (i && p1[i] != '/')
174                         --i;
175         }
176         return i;
177 }
178
179
180 string external_path(string const & p)
181 {
182         string const dos_path = subst(p, "/", "\\");
183
184         lyxerr[Debug::LATEX]
185                 << "<Win32 path correction> ["
186                 << p << "]->>["
187                 << dos_path << ']' << endl;
188         return dos_path;
189 }
190
191
192 namespace {
193
194 string const get_long_path(string const & short_path)
195 {
196         std::vector<char> long_path(MAX_PATH);
197         DWORD result = GetLongPathName(short_path.c_str(),
198                                        &long_path[0], long_path.size());
199
200         if (result > long_path.size()) {
201                 long_path.resize(result);
202                 result = GetLongPathName(short_path.c_str(),
203                                          &long_path[0], long_path.size());
204                 BOOST_ASSERT(result <= long_path.size());
205         }
206
207         return (result == 0) ? short_path : &long_path[0];
208 }
209
210 } // namespace anon
211
212
213 string internal_path(string const & p)
214 {
215         return subst(get_long_path(p), "\\", "/");
216 }
217
218
219 string latex_path(string const & p)
220 {
221         return p;
222 }
223
224
225 // (Claus H.) On Win32 both Unix and Win32/DOS pathnames are used.
226 // Therefore an absolute path could be either a pathname starting
227 // with a slash (Unix) or a pathname starting with a drive letter
228 // followed by a colon. Because a colon is not valid in pathes in Unix
229 // and at another location in Win32 testing just for the existance
230 // of the colon in the 2nd position seems to be enough!
231 bool is_absolute_path(string const & p)
232 {
233         if (p.empty())
234                 return false;
235
236         bool isDosPath = (p.length() > 1 && p[1] == ':');
237         bool isUnixPath = (p[0] == '/');
238
239         return isDosPath || isUnixPath;
240 }
241
242
243 // returns a string suitable to be passed to popen when
244 // reading a pipe
245 char const * popen_read_mode()
246 {
247         return "r";
248 }
249
250
251 string const & nulldev()
252 {
253         static string const nulldev_ = "nul";
254         return nulldev_;
255 }
256
257
258 shell_type shell()
259 {
260         return CMD_EXE;
261 }
262
263
264 char path_separator()
265 {
266         return ';';
267 }
268
269
270 void cygwin_path_fix(bool)
271 {}
272
273
274 namespace {
275
276 void bail_out()
277 {
278 #ifndef CXX_GLOBAL_CSTD
279         using std::exit;
280 #endif
281         exit(1);
282 }
283
284 } // namespace anon
285
286
287 GetFolderPath::GetFolderPath()
288         : folder_module_(0),
289           folder_path_func_(0)
290 {
291         folder_module_ = LoadLibrary("shfolder.dll");
292         if (!folder_module_) {
293                 lyxerr << "Unable to load shfolder.dll\nPlease install."
294                        << std::endl;
295                 bail_out();
296         }
297
298         folder_path_func_ = reinterpret_cast<function_pointer>(::GetProcAddress(folder_module_, "SHGetFolderPathA"));
299         if (folder_path_func_ == 0) {
300                 lyxerr << "Unable to find SHGetFolderPathA in shfolder.dll\n"
301                           "Don't know how to proceed. Sorry."
302                        << std::endl;
303                 bail_out();
304         }
305 }
306
307
308 GetFolderPath::~GetFolderPath()
309 {
310         if (folder_module_)
311                 FreeLibrary(folder_module_);
312 }
313
314
315 // Given a folder ID, returns the folder name (in unix-style format).
316 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
317 string const GetFolderPath::operator()(folder_id _id) const
318 {
319         char folder_path[MAX_PATH];
320
321         int id = 0;
322         switch (_id) {
323         case PERSONAL:
324                 id = CSIDL_PERSONAL;
325                 break;
326         case APPDATA:
327                 id = CSIDL_APPDATA;
328                 break;
329         default:
330                 BOOST_ASSERT(false);
331         }
332         HRESULT const result = (folder_path_func_)(0, id, 0,
333                                                    SHGFP_TYPE_CURRENT,
334                                                    folder_path);
335         return (result == 0) ? os::internal_path(folder_path) : string();
336 }
337
338 } // namespace os
339 } // namespace support
340 } // namespace lyx