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