]> git.lyx.org Git - lyx.git/blob - development/Win32/package.C
- Adjust to Lars boost::filesystem stuff
[lyx.git] / development / Win32 / package.C
1 // -*- C++ -*-
2 /**
3  * \file package.C
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Angus Leeming
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  * Warning! This file is autogenerated from package.C.in.
12  * All changes to this file will be lost.
13  */
14
15 #include <config.h>
16
17 #include "support/package.h"
18
19 #include "debug.h"
20 #include "gettext.h"
21
22 #include "support/filetools.h"
23 #include "support/lstrings.h"
24 #include "support/os.h"
25
26 #include <boost/assert.hpp>
27 #include <boost/tuple/tuple.hpp>
28 #include <boost/filesystem/operations.hpp>
29
30 #include <list>
31 #include <utility>
32
33 #if !defined (USE_WINDOWS_PACKAGING) && \
34     !defined (USE_MACOSX_PACKAGING) && \
35     !defined (USE_POSIX_PACKAGING)
36 #error USE_FOO_PACKAGING must be defined for FOO = WINDOWS, MACOSX or POSIX.
37 #endif
38
39 #if defined (USE_WINDOWS_PACKAGING)
40 # include <windows.h>
41 # include <shlobj.h>  // SHGetFolderPath
42
43   // Needed for MinGW:
44 # ifndef SHGFP_TYPE_CURRENT
45 #  define SHGFP_TYPE_CURRENT 0
46 # endif
47
48 #elif defined (USE_MACOSX_PACKAGING)
49 # include <CoreServices/CoreServices.h> // FSFindFolder, FSRefMakePath
50 #endif
51
52 using std::string;
53
54 namespace fs = boost::filesystem;
55
56
57 namespace lyx {
58 namespace support {
59
60 namespace {
61
62 Package package_;
63 bool initialised_ = false;
64
65 } // namespace anon
66
67
68 void init_package(string const & command_line_arg0,
69                   string const & command_line_system_support_dir,
70                   string const & command_line_user_support_dir)
71 {
72         // Can do so only once.
73         if (initialised_)
74                 return;
75
76         package_ = Package(command_line_arg0,
77                            command_line_system_support_dir,
78                            command_line_user_support_dir);
79         initialised_ = true;
80 }
81
82
83 Package const & package()
84 {
85         // Commented out because package().locale_dir() can be called
86         // from the message translation code in messages.C before
87         // init_package() is called. Lars is on the case...
88         // BOOST_ASSERT(initialised_);
89         return package_;
90 }
91
92
93 namespace {
94
95 string const abs_path_from_binary_name(string const & exe);
96
97 std::pair<string, string> const get_build_dirs(string const & abs_binary);
98
99 string const get_document_dir(string const & home_dir);
100
101 string const get_home_dir();
102
103 string const get_locale_dir(string const & system_support_dir);
104
105 string const get_system_support_dir(string const & abs_binary,
106                                     string const & command_line_system_support_dir);
107
108 string const get_temp_dir();
109
110 string const get_default_user_support_dir(string const & home_dir);
111
112 std::pair<string, bool> const
113 get_user_support_dir(string const & default_user_support_dir,
114                      string const & command_line_user_support_dir);
115
116 } // namespace anon
117
118
119 Package::Package(string const & command_line_arg0,
120                  string const & command_line_system_support_dir,
121                  string const & command_line_user_support_dir)
122         : explicit_user_support_dir_(false)
123 {
124         home_dir_ = get_home_dir();
125         temp_dir_ = get_temp_dir();
126         document_dir_ = get_document_dir(home_dir_);
127
128         string const abs_binary = abs_path_from_binary_name(command_line_arg0);
129         binary_dir_ = OnlyPath(abs_binary);
130
131         // Is LyX being run in-place from the build tree?
132         boost::tie(build_support_dir_, system_support_dir_) =
133                 get_build_dirs(abs_binary);
134
135         if (build_support_dir_.empty())
136                 system_support_dir_ =
137                         get_system_support_dir(abs_binary,
138                                                command_line_system_support_dir);
139
140         locale_dir_ = get_locale_dir(system_support_dir_);
141
142         string const default_user_support_dir =
143                 get_default_user_support_dir(home_dir_);
144         boost::tie(user_support_dir_, explicit_user_support_dir_) =
145                 get_user_support_dir(default_user_support_dir,
146                                      command_line_user_support_dir);
147
148         lyxerr[Debug::INIT]
149                 << "<package>\n"
150                 << "\tbinary_dir " << binary_dir() << '\n'
151                 << "\tsystem_support " << system_support() << '\n'
152                 << "\tbuild_support " << build_support() << '\n'
153                 << "\tuser_support " << user_support() << '\n'
154                 << "\tlocale_dir " << locale_dir() << '\n'
155                 << "\tdocument_dir " << document_dir() << '\n'
156                 << "\ttemp_dir " << temp_dir() << '\n'
157                 << "\thome_dir " << home_dir() << '\n'
158                 << "</package>\n" << std::endl;
159 }
160
161
162 namespace {
163
164 // These next three functions contain the stuff that is substituted at
165 // configuration-time.
166 string const top_srcdir()
167 {
168         static string const dir("c:\\lyx\\lyx-devel");
169         return dir;
170 }
171
172
173 string const hardcoded_localedir()
174 {
175         return string("c:\\lyx\\lyx-devel\\lib\\locale");
176 }
177
178
179 string const hardcoded_system_support_dir()
180 {
181         return string("c:\\lyx\\lyx-devel\\lib");
182 }
183
184 } // namespace anon
185
186
187 string const & Package::top_srcdir() const
188 {
189         static string const dir("c:\\lyx\\lyx-devel");
190         return dir;
191 }
192
193
194 namespace {
195
196 bool check_command_line_dir(string const & dir,
197                             string const & file,
198                             string const & command_line_switch);
199
200 string const extract_env_var_dir(string const & env_var);
201
202 bool check_env_var_dir(string const & dir,
203                        string const & env_var);
204
205 bool check_env_var_dir(string const & dir,
206                        string const & file,
207                        string const & env_var);
208
209 string const relative_locale_dir();
210
211 string const relative_system_support_dir();
212
213
214 #if defined (USE_WINDOWS_PACKAGING)
215 // Given a folder ID, returns the folder name (in unix-style format).
216 // Eg CSIDL_PERSONAL -> "C:/Documents and Settings/USERNAME/My Documents"
217 string const win32_folder_path(int folder_id)
218 {
219         char folder_path[MAX_PATH + 1];
220         if (SUCCEEDED(SHGetFolderPath(0, folder_id, 0,
221                                       SHGFP_TYPE_CURRENT, folder_path)))
222                 return os::internal_path(folder_path);
223         return string();
224 }
225 #endif
226
227
228 std::pair<string, string> const get_build_dirs(string const & abs_binary)
229 {
230         string const check_text = "Checking whether LyX is run in place...";
231
232         // We're looking for "lyxrc.defaults" in a directory
233         //   binary_dir/../lib
234         // We're also looking for "chkconfig.ltx" in a directory
235         //   binary_dir/top_srcdir()/lib
236         // If both are found, then we're running LyX in-place.
237
238         // Note that the name of the lyx binary may be a symbolic link.
239         // If that is the case, then we follow the links too.
240         string binary = abs_binary;
241         while (true) {
242                 // Try and find "lyxrc.defaults".
243                 string const binary_dir = OnlyPath(binary);
244                 string const build_support_dir =
245                         NormalizePath(AddPath(binary_dir, "../lib"));
246
247                 if (!FileSearch(build_support_dir, "lyxrc.defaults").empty()) {
248                         // Try and find "chkconfig.ltx".
249                         string const system_support_dir =
250                                 MakeAbsPath(AddPath(top_srcdir(), "lib"),
251                                             AddPath(binary_dir, "support"));
252
253                         if (!FileSearch(system_support_dir, "chkconfig.ltx").empty()) {
254                                 lyxerr[Debug::INIT] << check_text << " yes"
255                                                     << std::endl;
256                                 return std::make_pair(build_support_dir, system_support_dir);
257                         }
258                 }
259
260                 break;
261         }
262
263         lyxerr[Debug::INIT] << check_text << " no" << std::endl;
264         return std::make_pair(string(), string());
265 }
266
267
268 // Specification of document_dir_ may be reset by LyXRC,
269 // but the default is fixed for a given OS.
270 string const get_document_dir(string const & home_dir)
271 {
272 #if defined (USE_WINDOWS_PACKAGING)
273         (void)home_dir; // Silence warning about unused variable.
274         return win32_folder_path(CSIDL_PERSONAL);
275 #else // Posix-like.
276         return home_dir;
277 #endif
278 }
279
280
281 // The specification of home_dir_ is fixed for a given OS.
282 // A typical example on Windows: "C:/Documents and Settings/USERNAME"
283 // and on a Posix-like machine: "/home/USERNAME".
284 string const get_home_dir()
285 {
286 #if defined (USE_WINDOWS_PACKAGING)
287         string const home_dir = GetEnv("USERPROFILE");
288 #else // Posix-like.
289         string const home_dir = GetEnv("HOME");
290 #endif
291
292         return os::internal_path(home_dir);
293 }
294
295
296 // Several sources are probed to ascertain the locale directory.
297 // The only requirement is that the result is indeed a directory.
298 string const get_locale_dir(string const & system_support_dir)
299 {
300         // 1. Use the "LYX_LOCALEDIR" environment variable.
301         string path = extract_env_var_dir("LYX_LOCALEDIR");
302         if (!path.empty() && check_env_var_dir(path, "LYX_LOCALEDIR"))
303                 return path;
304
305         // 2. Search for system_support_dir / <relative locale dir>
306         // The <relative locale dir> is OS-dependent. (On Unix, it will
307         // be "../locale/".)
308         path = NormalizePath(AddPath(system_support_dir, relative_locale_dir()));
309
310         if (fs::is_directory(path))
311                 return path;
312
313         // 3. Fall back to the hard-coded LOCALEDIR.
314         path = hardcoded_localedir();
315         if (fs::is_directory(path))
316                 return path;
317
318         return string();
319 }
320
321
322 // Specification of temp_dir_ may be reset by LyXRC,
323 // but the default is fixed for a given OS.
324 string const get_temp_dir()
325 {
326 #if defined (USE_WINDOWS_PACKAGING)
327         // Typical example: C:/TEMP/.
328         char path[MAX_PATH + 1];
329         GetTempPath(MAX_PATH, path);
330         return os::internal_path(path);
331 #else // Posix-like.
332         return "/tmp";
333 #endif
334 }
335
336
337 // If we use a 'lazy' lyxerr in the hope of setting the locale before
338 // printing any messages, then we should ensure that it is flushed first.
339 void bail_out()
340 {
341 #ifndef CXX_GLOBAL_CSTD
342         using std::exit;
343 #endif
344         exit(1);
345 }
346
347
348 // Extracts the absolute path from the foo of "-sysdir foo" or "-userdir foo"
349 string const abs_path_from_command_line(string const & command_line)
350 {
351         if (command_line.empty())
352                 return string();
353
354         string const path = os::internal_path(command_line);
355         return os::is_absolute_path(path) ? path : MakeAbsPath(path);
356 }
357
358
359 // Does the grunt work for abs_path_from_binary_name()
360 string const get_binary_path(string const & exe)
361 {
362         string const exe_path = os::internal_path(exe);
363         if (os::is_absolute_path(exe_path))
364                 return exe_path;
365
366         // Two possibilities present themselves.
367         // 1. The binary is relative to the CWD.
368         string const abs_exe_path = MakeAbsPath(exe_path);
369         if (fs::exists(abs_exe_path))
370                 return abs_exe_path;
371
372         // 2. exe must be the name of the binary only and it
373         // can be found on the PATH.
374         string const exe_name = OnlyFilename(exe_path);
375         if (exe_name != exe_path)
376                 return string();
377
378         std::vector<string> const path = getEnvPath("PATH");
379         std::vector<string>::const_iterator it = path.begin();
380         std::vector<string>::const_iterator const end = path.end();
381         for (; it != end; ++it) {
382                 // This will do nothing if *it is already absolute.
383                 string const exe_dir = MakeAbsPath(*it);
384
385                 string const exe_path = AddName(exe_dir, exe_name);
386                 if (fs::exists(exe_path))
387                         return exe_path;
388         }
389
390         // Didn't find anything.
391         return string();
392 }
393
394
395 // Extracts the absolute path to the binary name received as argv[0].
396 string const abs_path_from_binary_name(string const & exe)
397 {
398         string const abs_binary = get_binary_path(exe);
399         if (abs_binary.empty()) {
400                 lyxerr << bformat(_("Unable to determine the path to the "
401                                     "LyX binary from the command line %1$s"),
402                                   exe)
403                        << std::endl;
404                 bail_out();
405         }
406         return abs_binary;
407 }
408
409
410 // A plethora of directories is searched to ascertain the system
411 // lyxdir which is defined as the first directory to contain
412 // "chkconfig.ltx".
413 string const
414 get_system_support_dir(string const & abs_binary,
415                   string const & command_line_system_support_dir)
416 {
417         string const chkconfig_ltx = "chkconfig.ltx";
418
419         // searched_dirs is used for diagnostic purposes only in the case
420         // that "chkconfig.ltx" is not found.
421         std::list<string> searched_dirs;
422
423         // 1. Use the -sysdir command line parameter.
424         string path = abs_path_from_command_line(command_line_system_support_dir);
425         if (!path.empty()) {
426                 searched_dirs.push_back(path);
427                 if (check_command_line_dir(path, chkconfig_ltx, "-sysdir"))
428                         return path;
429         }
430
431         // 2. Use the "LYX_DIR_13x" environment variable.
432         path = extract_env_var_dir("LYX_DIR_13x");
433         if (!path.empty()) {
434                 searched_dirs.push_back(path);
435                 if (check_env_var_dir(path, chkconfig_ltx, "LYX_DIR_13x"))
436                         return path;
437         }
438
439         // 3. Search relative to the lyx binary.
440         // We're looking for "chkconfig.ltx" in a directory
441         //   OnlyPath(abs_binary) / <relative dir> / PACKAGE /
442         // PACKAGE is hardcoded in config.h. Eg "lyx" or "lyx-1.3.6cvs".
443         // <relative dir> is OS-dependent; on Unix, it will be "../share/".
444         string const relative_lyxdir = relative_system_support_dir();
445
446         // One subtlety to be aware of. The name of the lyx binary may be
447         // a symbolic link. If that is the case, then we follow the links too.
448         string binary = abs_binary;
449         while (true) {
450                 // Try and find "chkconfig.ltx".
451                 string const binary_dir = OnlyPath(binary);
452
453                 string const lyxdir =
454                         NormalizePath(AddPath(binary_dir, relative_lyxdir));
455                 searched_dirs.push_back(lyxdir);
456
457                 if (!FileSearch(lyxdir, chkconfig_ltx).empty()) {
458                         // Success! "chkconfig.ltx" has been found.
459                         return lyxdir;
460                 }
461
462                 break;
463         }
464
465         // 5. In desparation, try the hard-coded system support dir.
466         path = hardcoded_system_support_dir();
467         if (!FileSearch(path, chkconfig_ltx).empty())
468                 return path;
469
470         // Everything has failed :-(
471         // So inform the user and exit.
472         string searched_dirs_str;
473         typedef std::list<string>::const_iterator iterator;
474         iterator const begin = searched_dirs.begin();
475         iterator const end = searched_dirs.end();
476         for (iterator it = begin; it != end; ++it) {
477                 if (it != begin)
478                         searched_dirs_str += "\n\t";
479                 searched_dirs_str += *it;
480         }
481
482         lyxerr << bformat(_("Unable to determine the system directory "
483                             "having searched\n"
484                             "\t%1$s\n"
485                             "Try the '-sysdir' command line parameter or "
486                             "set the environment variable LYX_DIR_13x to "
487                             "the LyX system directory containing the file "
488                             "`chkconfig.ltx'."),
489                           searched_dirs_str)
490                << std::endl;
491
492         bail_out();
493         // Keep the compiler happy.
494         return string();
495 }
496
497
498 // Returns the absolute path to the user lyxdir, together with a flag
499 // indicating whether this directory was specified explicitly (as -userdir
500 // or through an environment variable) or whether it was deduced.
501 std::pair<string, bool> const
502 get_user_support_dir(string const & default_user_support_dir,
503                      string const & command_line_user_support_dir)
504 {
505         bool explicit_userdir = true;
506
507         // 1. Use the -userdir command line parameter.
508         string path =
509                 abs_path_from_command_line(command_line_user_support_dir);
510         if (!path.empty())
511                 return std::make_pair(path, explicit_userdir);
512
513         // 2. Use the LYX_USERDIR_13x environment variable.
514         path = extract_env_var_dir("LYX_USERDIR_13x");
515         if (!path.empty())
516                 return std::make_pair(path, explicit_userdir);
517
518         // 3. Use the OS-dependent default_user_support_dir
519         explicit_userdir = false;
520         return std::make_pair(default_user_support_dir, explicit_userdir);
521 }
522
523
524 // $HOME/.lyx on all platforms but Win32 where it will be something like
525 // "C:/Documents and Settings/USERNAME/Application Data/lyx"
526 string const get_default_user_support_dir(string const & home_dir)
527 {
528 #if defined (USE_WINDOWS_PACKAGING)
529         (void)home_dir; // Silence warning about unused variable.
530
531         return AddPath(win32_folder_path(CSIDL_APPDATA), PACKAGE);
532
533 #elif defined (USE_MACOSX_PACKAGING)
534         (void)home_dir; // Silence warning about unused variable.
535
536         FSRef fsref;
537         OSErr const error_code =
538                 FSFindFolder(kUserDomain, kApplicationSupportFolderType,
539                              kDontCreateFolder, &fsref);
540         if (error_code != 0)
541                 return string();
542
543         char store[PATH_MAX + 1];
544         OSStatus const status_code =
545                 FSRefMakePath(&fsref,
546                               reinterpret_cast<UInt8*>(store), PATH_MAX);
547         if (status_code != 0)
548                 return string();
549
550         return AddPath(reinterpret_cast<char const *>(store), PACKAGE);
551
552 #else // USE_POSIX_PACKAGING
553         return AddPath(home_dir, string(".") + PACKAGE);
554 #endif
555 }
556
557
558 // Check that directory @c dir contains @c file.
559 // Else emit a warning about an invalid @c command_line_switch.
560 bool check_command_line_dir(string const & dir,
561                             string const & file,
562                             string const & command_line_switch)
563 {
564         string const abs_path = FileSearch(dir, file);
565         if (abs_path.empty()) {
566                 lyxerr << bformat(_("Invalid %1$s switch.\n"
567                                     "Directory %2$s does not contain %3$s."),
568                                   command_line_switch, dir, file)
569                        << std::endl;
570         }
571
572         return !abs_path.empty();
573 }
574
575
576 // The environment variable @c env_var expands to a (single) file path.
577 string const extract_env_var_dir(string const & env_var)
578 {
579         string const dir = os::internal_path(GetEnv(env_var));
580         return dir.empty() ? dir : MakeAbsPath(dir);
581 }
582
583
584 // Check that directory @c dir contains @c file.
585 // Else emit a warning about an invalid @c env_var.
586 bool check_env_var_dir(string const & dir,
587                        string const & file,
588                        string const & env_var)
589 {
590         string const abs_path = FileSearch(dir, file);
591         if (abs_path.empty()) {
592                 lyxerr << bformat(_("Invalid %1$s environment variable.\n"
593                                     "Directory %2$s does not contain %3$s."),
594                                   env_var, dir, file)
595                        << std::endl;
596         }
597
598         return !abs_path.empty();
599 }
600
601
602 // Check that directory @c dir is indeed a directory.
603 // Else emit a warning about an invalid @c env_var.
604 bool check_env_var_dir(string const & dir,
605                        string const & env_var)
606 {
607         bool const success = fs::is_directory(dir);
608
609         if (!success) {
610                 // Put this string on a single line so that the gettext
611                 // search mechanism in po/Makefile.in.in will register
612                 // package.C.in as a file containing strings that need
613                 // translation.
614                 string const fmt =
615                 _("Invalid %1$s environment variable.\n%2$s is not a directory.");
616                 
617                 lyxerr << bformat(fmt, env_var, dir)
618                        << std::endl;
619         }
620
621         return success;
622 }
623
624
625 // The locale directory relative to the LyX system directory.
626 string const relative_locale_dir()
627 {
628         return "../locale/";
629 }
630
631
632 // The system lyxdir is relative to the directory containing the LyX binary.
633 string const relative_system_support_dir()
634 {
635         string result;
636
637 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
638         result = AddPath("../Resources/", PACKAGE);
639 #else // Posix-like.
640         result = AddPath("../share/", PACKAGE);
641 #endif
642
643         return result;
644 }
645
646 } // namespace anon
647
648 } // namespace support
649 } // namespace lyx