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