4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "support/Package.h"
19 #include "support/environment.h"
20 #include "support/filetools.h"
21 #include "support/lstrings.h"
22 #include "support/ExceptionMessage.h"
23 #include "support/os.h"
25 #if defined (USE_WINDOWS_PACKAGING)
26 # include "support/os_win32.h"
29 #include <boost/filesystem/operations.hpp>
30 #include <boost/tuple/tuple.hpp>
35 #if !defined (USE_WINDOWS_PACKAGING) && \
36 !defined (USE_MACOSX_PACKAGING) && \
37 !defined (USE_POSIX_PACKAGING)
38 #error USE_FOO_PACKAGING must be defined for FOO = WINDOWS, MACOSX or POSIX.
41 #if defined (USE_MACOSX_PACKAGING)
42 # include <CoreServices/CoreServices.h> // FSFindFolder, FSRefMakePath
47 namespace fs = boost::filesystem;
55 bool initialised_ = false;
60 void init_package(string const & command_line_arg0,
61 string const & command_line_system_support_dir,
62 string const & command_line_user_support_dir,
63 exe_build_dir_to_top_build_dir top_build_dir_location)
65 // Can do so only once.
69 package_ = Package(command_line_arg0,
70 command_line_system_support_dir,
71 command_line_user_support_dir,
72 top_build_dir_location);
77 Package const & package()
79 // Commented out because package().locale_dir() can be called
80 // from the message translation code in Messages.cpp before
81 // init_package() is called. Lars is on the case...
82 // BOOST_ASSERT(initialised_);
89 FileName const abs_path_from_binary_name(string const & exe);
91 std::pair<FileName, FileName> const
92 get_build_dirs(FileName const & abs_binary,
93 exe_build_dir_to_top_build_dir top_build_dir_location);
95 FileName const get_document_dir(FileName const & home_dir);
97 FileName const get_home_dir();
99 FileName const get_locale_dir(FileName const & system_support_dir);
101 FileName const get_system_support_dir(FileName const & abs_binary,
102 string const & command_line_system_support_dir);
104 FileName const get_temp_dir();
106 FileName const get_default_user_support_dir(FileName const & home_dir);
108 std::pair<FileName, bool> const
109 get_user_support_dir(FileName const & default_user_support_dir,
110 string const & command_line_user_support_dir);
113 string const & with_version_suffix();
118 Package::Package(string const & command_line_arg0,
119 string const & command_line_system_support_dir,
120 string const & command_line_user_support_dir,
121 exe_build_dir_to_top_build_dir top_build_dir_location)
122 : explicit_user_support_dir_(false)
124 home_dir_ = get_home_dir();
125 system_temp_dir_ = get_temp_dir();
126 temp_dir_ = system_temp_dir_;
127 document_dir_ = get_document_dir(home_dir_);
129 FileName const abs_binary = abs_path_from_binary_name(command_line_arg0);
130 string const bdir = onlyPath(abs_binary.absFilename());
131 // We may be using libtools
132 if (suffixIs(bdir, ".libs/"))
133 binary_dir_ = FileName(addPath(bdir, "../"));
135 binary_dir_ = FileName(bdir);
137 // Is LyX being run in-place from the build tree?
138 boost::tie(build_support_dir_, system_support_dir_) =
139 get_build_dirs(abs_binary, top_build_dir_location);
141 if (build_support_dir_.empty())
142 system_support_dir_ =
143 get_system_support_dir(abs_binary,
144 command_line_system_support_dir);
146 locale_dir_ = get_locale_dir(system_support_dir_);
148 FileName const default_user_support_dir =
149 get_default_user_support_dir(home_dir_);
150 boost::tie(user_support_dir_, explicit_user_support_dir_) =
151 get_user_support_dir(default_user_support_dir,
152 command_line_user_support_dir);
154 FileName const configure_script(addName(system_support().absFilename(), "configure.py"));
155 configure_command_ = os::python() + ' ' +
156 quoteName(configure_script.toFilesystemEncoding()) +
157 with_version_suffix();
161 << "\tbinary_dir " << binary_dir().absFilename() << '\n'
162 << "\tsystem_support " << system_support().absFilename() << '\n'
163 << "\tbuild_support " << build_support().absFilename() << '\n'
164 << "\tuser_support " << user_support().absFilename() << '\n'
165 << "\tlocale_dir " << locale_dir().absFilename() << '\n'
166 << "\tdocument_dir " << document_dir().absFilename() << '\n'
167 << "\ttemp_dir " << temp_dir().absFilename() << '\n'
168 << "\thome_dir " << home_dir().absFilename() << '\n'
169 << "</package>\n" << std::endl;
175 // These next functions contain the stuff that is substituted at
176 // configuration-time.
177 FileName const hardcoded_localedir()
180 // The build system needs to make sure that this is in utf8 encoding.
181 return FileName(LYX_ABS_INSTALLED_LOCALEDIR);
185 FileName const hardcoded_system_support_dir()
188 // The build system needs to make sure that this is in utf8 encoding.
189 return FileName(LYX_ABS_INSTALLED_DATADIR);
193 string const & with_version_suffix()
195 static string const program_suffix = PROGRAM_SUFFIX;
196 static string const with_version_suffix =
197 " --with-version-suffix=" PROGRAM_SUFFIX;
198 return program_suffix.empty() ? program_suffix : with_version_suffix;
204 FileName const & Package::top_srcdir()
207 // The build system needs to make sure that this is in utf8 encoding.
208 static FileName const dir(LYX_ABS_TOP_SRCDIR);
215 bool check_command_line_dir(string const & dir,
217 string const & command_line_switch);
219 FileName const extract_env_var_dir(string const & env_var);
221 bool check_env_var_dir(FileName const & dir,
222 string const & env_var);
224 bool check_env_var_dir(FileName const & dir,
226 string const & env_var);
228 string const relative_locale_dir();
230 string const relative_system_support_dir();
234 * Convert \p name to internal path and strip a trailing slash, since it
235 * comes from user input (commandline or environment).
236 * \p name is encoded in utf8.
238 string const fix_dir_name(string const & name)
240 return rtrim(os::internal_path(name), "/");
245 get_build_support_dir(string const & binary_dir,
246 exe_build_dir_to_top_build_dir top_build_dir_location)
249 switch (top_build_dir_location) {
250 case top_build_dir_is_one_level_up:
251 indirection = "../lib";
253 case top_build_dir_is_two_levels_up:
254 indirection = "../../lib";
257 return FileName(normalizePath(addPath(binary_dir, indirection)));
261 std::pair<FileName, FileName> const
262 get_build_dirs(FileName const & abs_binary,
263 exe_build_dir_to_top_build_dir top_build_dir_location)
265 string const check_text = "Checking whether LyX is run in place...";
267 // We're looking for "Makefile" in a directory
269 // We're also looking for "chkconfig.ltx" in a directory
271 // If both are found, then we're running LyX in-place.
273 // Note that the name of the lyx binary may be a symbolic link.
274 // If that is the case, then we follow the links too.
275 FileName binary = abs_binary;
277 // Try and find "lyxrc.defaults".
278 string binary_dir = onlyPath(binary.absFilename());
279 // We may be using libtools with static linking.
280 if (suffixIs(binary_dir, ".libs/"))
281 binary_dir = addPath(binary_dir, "../");
282 FileName const build_support_dir =
283 get_build_support_dir(binary_dir, top_build_dir_location);
284 if (!fileSearch(build_support_dir.absFilename(), "Makefile").empty()) {
285 // Try and find "chkconfig.ltx".
286 string const system_support_dir =
287 addPath(Package::top_srcdir().absFilename(), "lib");
289 if (!fileSearch(system_support_dir, "chkconfig.ltx").empty()) {
290 lyxerr[Debug::INIT] << check_text << " yes"
292 return std::make_pair(build_support_dir, system_support_dir);
296 // Check whether binary is a symbolic link.
297 // If so, resolve it and repeat the exercise.
298 if (!fs::symbolic_link_exists(binary.toFilesystemEncoding()))
302 if (readLink(binary, link)) {
305 // Unable to resolve the link.
310 lyxerr[Debug::INIT] << check_text << " no" << std::endl;
311 return std::make_pair(FileName(), FileName());
315 // Specification of document_dir_ may be reset by LyXRC,
316 // but the default is fixed for a given OS.
317 FileName const get_document_dir(FileName const & home_dir)
319 #if defined (USE_WINDOWS_PACKAGING)
320 (void)home_dir; // Silence warning about unused variable.
321 os::GetFolderPath win32_folder_path;
322 return FileName(win32_folder_path(os::GetFolderPath::PERSONAL));
329 // The specification of home_dir_ is fixed for a given OS.
330 // A typical example on Windows: "C:/Documents and Settings/USERNAME"
331 // and on a Posix-like machine: "/home/USERNAME".
332 FileName const get_home_dir()
334 #if defined (USE_WINDOWS_PACKAGING)
335 string const home_dir = getEnv("USERPROFILE");
337 string const home_dir = getEnv("HOME");
340 return FileName(fix_dir_name(home_dir));
344 // Several sources are probed to ascertain the locale directory.
345 // The only requirement is that the result is indeed a directory.
346 FileName const get_locale_dir(FileName const & system_support_dir)
348 // 1. Use the "LYX_LOCALEDIR" environment variable.
349 FileName const path_env = extract_env_var_dir("LYX_LOCALEDIR");
350 if (!path_env.empty() && check_env_var_dir(path_env, "LYX_LOCALEDIR"))
353 // 2. Search for system_support_dir / <relative locale dir>
354 // The <relative locale dir> is OS-dependent. (On Unix, it will
356 FileName path(normalizePath(addPath(system_support_dir.absFilename(),
357 relative_locale_dir())));
359 if (fs::exists(path.toFilesystemEncoding()) &&
360 fs::is_directory(path.toFilesystemEncoding()))
363 // 3. Fall back to the hard-coded LOCALEDIR.
364 path = hardcoded_localedir();
365 if (fs::exists(path.toFilesystemEncoding()) &&
366 fs::is_directory(path.toFilesystemEncoding()))
373 // Specification of temp_dir_ may be reset by LyXRC,
374 // but the default is fixed for a given OS.
375 FileName const get_temp_dir()
377 #if defined (USE_WINDOWS_PACKAGING)
378 // Typical example: C:/TEMP/.
380 GetTempPath(MAX_PATH, path);
381 return FileName(os::internal_path(to_utf8(from_local8bit(path))));
383 return FileName("/tmp");
388 // Extracts the absolute path from the foo of "-sysdir foo" or "-userdir foo"
389 FileName const abs_path_from_command_line(string const & command_line)
391 if (command_line.empty())
394 string const path = fix_dir_name(command_line);
395 return os::is_absolute_path(path) ? FileName(path) : makeAbsPath(path);
399 // Does the grunt work for abs_path_from_binary_name()
400 FileName const get_binary_path(string const & exe)
402 #if defined (USE_WINDOWS_PACKAGING)
403 // The executable may have been invoked either with or
404 // without the .exe extension.
405 // Ensure that it is present.
406 string const as_internal_path = os::internal_path(exe);
407 string const exe_path = suffixIs(as_internal_path, ".exe") ?
408 as_internal_path : as_internal_path + ".exe";
410 string const exe_path = os::internal_path(exe);
412 if (os::is_absolute_path(exe_path))
413 return FileName(exe_path);
415 // Two possibilities present themselves.
416 // 1. The binary is relative to the CWD.
417 FileName const abs_exe_path = makeAbsPath(exe_path);
418 if (fs::exists(abs_exe_path.toFilesystemEncoding()))
421 // 2. exe must be the name of the binary only and it
422 // can be found on the PATH.
423 string const exe_name = onlyFilename(exe_path);
424 if (exe_name != exe_path)
427 std::vector<string> const path = getEnvPath("PATH");
428 std::vector<string>::const_iterator it = path.begin();
429 std::vector<string>::const_iterator const end = path.end();
430 for (; it != end; ++it) {
431 // This will do nothing if *it is already absolute.
432 string const exe_dir = makeAbsPath(*it).absFilename();
434 FileName const exe_path(addName(exe_dir, exe_name));
435 if (fs::exists(exe_path.toFilesystemEncoding()))
439 // Didn't find anything.
444 // Extracts the absolute path to the binary name received as argv[0].
445 FileName const abs_path_from_binary_name(string const & exe)
447 FileName const abs_binary = get_binary_path(exe);
448 if (abs_binary.empty()) {
450 throw ExceptionMessage(ErrorException,
451 _("LyX binary not found"),
452 bformat(_("Unable to determine the path to the LyX binary from the command line %1$s"),
459 // A plethora of directories is searched to ascertain the system
460 // lyxdir which is defined as the first directory to contain
463 get_system_support_dir(FileName const & abs_binary,
464 string const & command_line_system_support_dir)
466 string const chkconfig_ltx = "chkconfig.ltx";
468 // searched_dirs is used for diagnostic purposes only in the case
469 // that "chkconfig.ltx" is not found.
470 std::list<FileName> searched_dirs;
472 // 1. Use the -sysdir command line parameter.
473 FileName path = abs_path_from_command_line(command_line_system_support_dir);
475 searched_dirs.push_back(path);
476 if (check_command_line_dir(path.absFilename(), chkconfig_ltx, "-sysdir"))
480 // 2. Use the "LYX_DIR_15x" environment variable.
481 path = extract_env_var_dir("LYX_DIR_15x");
483 searched_dirs.push_back(path);
484 if (check_env_var_dir(path, chkconfig_ltx, "LYX_DIR_15x"))
488 // 3. Search relative to the lyx binary.
489 // We're looking for "chkconfig.ltx" in a directory
490 // OnlyPath(abs_binary) / <relative dir> / PACKAGE /
491 // PACKAGE is hardcoded in config.h. Eg "lyx" or "lyx-1.3.6cvs".
492 // <relative dir> is OS-dependent; on Unix, it will be "../share/".
493 string const relative_lyxdir = relative_system_support_dir();
495 // One subtlety to be aware of. The name of the lyx binary may be
496 // a symbolic link. If that is the case, then we follow the links too.
497 FileName binary = abs_binary;
499 // Try and find "chkconfig.ltx".
500 string const binary_dir = onlyPath(binary.absFilename());
502 FileName const lyxdir(
503 normalizePath(addPath(binary_dir, relative_lyxdir)));
504 searched_dirs.push_back(lyxdir);
506 if (!fileSearch(lyxdir.absFilename(), chkconfig_ltx).empty()) {
507 // Success! "chkconfig.ltx" has been found.
511 // Check whether binary is a symbolic link.
512 // If so, resolve it and repeat the exercise.
513 if (!fs::symbolic_link_exists(binary.toFilesystemEncoding()))
517 if (readLink(binary, link)) {
520 // Unable to resolve the link.
525 // 4. Repeat the exercise on the directory itself.
526 FileName binary_dir(onlyPath(abs_binary.absFilename()));
528 // This time test whether the directory is a symbolic link
529 // *before* looking for "chkconfig.ltx".
530 // (We've looked relative to the original already.)
531 if (!fs::symbolic_link_exists(binary.toFilesystemEncoding()))
535 if (readLink(binary_dir, link)) {
538 // Unable to resolve the link.
542 // Try and find "chkconfig.ltx".
543 FileName const lyxdir(
544 normalizePath(addPath(binary_dir.absFilename(), relative_lyxdir)));
545 searched_dirs.push_back(lyxdir);
547 if (!fileSearch(lyxdir.absFilename(), chkconfig_ltx).empty()) {
548 // Success! "chkconfig.ltx" has been found.
553 // 5. In desparation, try the hard-coded system support dir.
554 path = hardcoded_system_support_dir();
555 if (!fileSearch(path.absFilename(), chkconfig_ltx).empty())
558 // Everything has failed :-(
559 // So inform the user and exit.
560 string searched_dirs_str;
561 typedef std::list<FileName>::const_iterator iterator;
562 iterator const begin = searched_dirs.begin();
563 iterator const end = searched_dirs.end();
564 for (iterator it = begin; it != end; ++it) {
566 searched_dirs_str += "\n\t";
567 searched_dirs_str += it->absFilename();
571 throw ExceptionMessage(ErrorException, _("No system directory"),
572 bformat(_("Unable to determine the system directory "
575 "Use the '-sysdir' command line parameter or "
576 "set the environment variable LYX_DIR_15x to "
577 "the LyX system directory containing the file "
579 from_utf8(searched_dirs_str)));
581 // Keep the compiler happy.
586 // Returns the absolute path to the user lyxdir, together with a flag
587 // indicating whether this directory was specified explicitly (as -userdir
588 // or through an environment variable) or whether it was deduced.
589 std::pair<FileName, bool> const
590 get_user_support_dir(FileName const & default_user_support_dir,
591 string const & command_line_user_support_dir)
593 bool explicit_userdir = true;
595 // 1. Use the -userdir command line parameter.
597 abs_path_from_command_line(command_line_user_support_dir);
599 return std::make_pair(path, explicit_userdir);
601 // 2. Use the LYX_USERDIR_15x environment variable.
602 path = extract_env_var_dir("LYX_USERDIR_15x");
604 return std::make_pair(path, explicit_userdir);
606 // 3. Use the OS-dependent default_user_support_dir
607 explicit_userdir = false;
608 return std::make_pair(default_user_support_dir, explicit_userdir);
612 // $HOME/.lyx on POSIX but on Win32 it will be something like
613 // "C:/Documents and Settings/USERNAME/Application Data/LyX"
614 FileName const get_default_user_support_dir(FileName const & home_dir)
616 #if defined (USE_WINDOWS_PACKAGING)
617 (void)home_dir; // Silence warning about unused variable.
619 os::GetFolderPath win32_folder_path;
620 return FileName(addPath(win32_folder_path(os::GetFolderPath::APPDATA), PACKAGE));
622 #elif defined (USE_MACOSX_PACKAGING)
623 (void)home_dir; // Silence warning about unused variable.
626 OSErr const error_code =
627 FSFindFolder(kUserDomain, kApplicationSupportFolderType,
628 kDontCreateFolder, &fsref);
632 // FSRefMakePath returns the result in utf8
633 char store[PATH_MAX + 1];
634 OSStatus const status_code =
635 FSRefMakePath(&fsref,
636 reinterpret_cast<UInt8*>(store), PATH_MAX);
637 if (status_code != 0)
640 return FileName(addPath(reinterpret_cast<char const *>(store), PACKAGE));
642 #else // USE_POSIX_PACKAGING
643 return FileName(addPath(home_dir.absFilename(), string(".") + PACKAGE));
648 // Check that directory @c dir contains @c file.
649 // Else emit a warning about an invalid @c command_line_switch.
650 bool check_command_line_dir(string const & dir,
652 string const & command_line_switch)
654 FileName const abs_path = fileSearch(dir, file);
655 if (abs_path.empty()) {
657 throw ExceptionMessage(WarningException, _("File not found"), bformat(
658 _("Invalid %1$s switch.\nDirectory %2$s does not contain %3$s."),
659 from_utf8(command_line_switch), from_utf8(dir),
663 return !abs_path.empty();
667 // The environment variable @c env_var expands to a (single) file path.
668 FileName const extract_env_var_dir(string const & env_var)
670 string const dir = fix_dir_name(getEnv(env_var));
671 return dir.empty() ? FileName() : makeAbsPath(dir);
675 // Check that directory @c dir contains @c file.
676 // Else emit a warning about an invalid @c env_var.
677 bool check_env_var_dir(FileName const & dir,
679 string const & env_var)
681 FileName const abs_path = fileSearch(dir.absFilename(), file);
682 if (abs_path.empty()) {
684 throw ExceptionMessage(WarningException, _("File not found"), bformat(
685 _("Invalid %1$s environment variable.\n"
686 "Directory %2$s does not contain %3$s."),
687 from_utf8(env_var), from_utf8(dir.absFilename()),
691 return !abs_path.empty();
695 // Check that directory @c dir is indeed a directory.
696 // Else emit a warning about an invalid @c env_var.
697 bool check_env_var_dir(FileName const & dir,
698 string const & env_var)
700 string const encoded(dir.toFilesystemEncoding());
701 bool const success = (fs::exists(encoded) && fs::is_directory(encoded));
704 // Put this string on a single line so that the gettext
705 // search mechanism in po/Makefile.in.in will register
706 // Package.cpp.in as a file containing strings that need
709 docstring const fmt =
710 _("Invalid %1$s environment variable.\n%2$s is not a directory.");
712 throw ExceptionMessage(WarningException, _("Directory not found"), bformat(
713 fmt, from_utf8(env_var), from_utf8(dir.absFilename())));
720 // The locale directory relative to the LyX system directory.
721 string const relative_locale_dir()
723 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
731 // The system lyxdir is relative to the directory containing the LyX binary.
732 string const relative_system_support_dir()
736 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
737 result = "../Resources/";
739 result = addPath("../share/", PACKAGE);
747 } // namespace support