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