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