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