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 (path.exists() && fs::is_directory(path.toFilesystemEncoding()))
362 // 3. Fall back to the hard-coded LOCALEDIR.
363 path = hardcoded_localedir();
364 if (path.exists() && fs::is_directory(path.toFilesystemEncoding()))
371 // Specification of temp_dir_ may be reset by LyXRC,
372 // but the default is fixed for a given OS.
373 FileName const get_temp_dir()
375 #if defined (USE_WINDOWS_PACKAGING)
376 // Typical example: C:/TEMP/.
378 GetTempPath(MAX_PATH, path);
379 return FileName(os::internal_path(to_utf8(from_local8bit(path))));
381 return FileName("/tmp");
386 // Extracts the absolute path from the foo of "-sysdir foo" or "-userdir foo"
387 FileName const abs_path_from_command_line(string const & command_line)
389 if (command_line.empty())
392 string const path = fix_dir_name(command_line);
393 return os::is_absolute_path(path) ? FileName(path) : makeAbsPath(path);
397 // Does the grunt work for abs_path_from_binary_name()
398 FileName const get_binary_path(string const & exe)
400 #if defined (USE_WINDOWS_PACKAGING)
401 // The executable may have been invoked either with or
402 // without the .exe extension.
403 // Ensure that it is present.
404 string const as_internal_path = os::internal_path(exe);
405 string const exe_path = suffixIs(as_internal_path, ".exe") ?
406 as_internal_path : as_internal_path + ".exe";
408 string const exe_path = os::internal_path(exe);
410 if (os::is_absolute_path(exe_path))
411 return FileName(exe_path);
413 // Two possibilities present themselves.
414 // 1. The binary is relative to the CWD.
415 FileName const abs_exe_path = makeAbsPath(exe_path);
416 if (abs_exe_path.exists())
419 // 2. exe must be the name of the binary only and it
420 // can be found on the PATH.
421 string const exe_name = onlyFilename(exe_path);
422 if (exe_name != exe_path)
425 std::vector<string> const path = getEnvPath("PATH");
426 std::vector<string>::const_iterator it = path.begin();
427 std::vector<string>::const_iterator const end = path.end();
428 for (; it != end; ++it) {
429 // This will do nothing if *it is already absolute.
430 string const exe_dir = makeAbsPath(*it).absFilename();
432 FileName const exe_path(addName(exe_dir, exe_name));
433 if (exe_path.exists())
437 // Didn't find anything.
442 // Extracts the absolute path to the binary name received as argv[0].
443 FileName const abs_path_from_binary_name(string const & exe)
445 FileName const abs_binary = get_binary_path(exe);
446 if (abs_binary.empty()) {
448 throw ExceptionMessage(ErrorException,
449 _("LyX binary not found"),
450 bformat(_("Unable to determine the path to the LyX binary from the command line %1$s"),
457 // A plethora of directories is searched to ascertain the system
458 // lyxdir which is defined as the first directory to contain
461 get_system_support_dir(FileName const & abs_binary,
462 string const & command_line_system_support_dir)
464 string const chkconfig_ltx = "chkconfig.ltx";
466 // searched_dirs is used for diagnostic purposes only in the case
467 // that "chkconfig.ltx" is not found.
468 std::list<FileName> searched_dirs;
470 // 1. Use the -sysdir command line parameter.
471 FileName path = abs_path_from_command_line(command_line_system_support_dir);
473 searched_dirs.push_back(path);
474 if (check_command_line_dir(path.absFilename(), chkconfig_ltx, "-sysdir"))
478 // 2. Use the "LYX_DIR_15x" environment variable.
479 path = extract_env_var_dir("LYX_DIR_15x");
481 searched_dirs.push_back(path);
482 if (check_env_var_dir(path, chkconfig_ltx, "LYX_DIR_15x"))
486 // 3. Search relative to the lyx binary.
487 // We're looking for "chkconfig.ltx" in a directory
488 // OnlyPath(abs_binary) / <relative dir> / PACKAGE /
489 // PACKAGE is hardcoded in config.h. Eg "lyx" or "lyx-1.3.6cvs".
490 // <relative dir> is OS-dependent; on Unix, it will be "../share/".
491 string const relative_lyxdir = relative_system_support_dir();
493 // One subtlety to be aware of. The name of the lyx binary may be
494 // a symbolic link. If that is the case, then we follow the links too.
495 FileName binary = abs_binary;
497 // Try and find "chkconfig.ltx".
498 string const binary_dir = onlyPath(binary.absFilename());
500 FileName const lyxdir(
501 normalizePath(addPath(binary_dir, relative_lyxdir)));
502 searched_dirs.push_back(lyxdir);
504 if (!fileSearch(lyxdir.absFilename(), chkconfig_ltx).empty()) {
505 // Success! "chkconfig.ltx" has been found.
509 // Check whether binary is a symbolic link.
510 // If so, resolve it and repeat the exercise.
511 if (!fs::symbolic_link_exists(binary.toFilesystemEncoding()))
515 if (readLink(binary, link)) {
518 // Unable to resolve the link.
523 // 4. Repeat the exercise on the directory itself.
524 FileName binary_dir(onlyPath(abs_binary.absFilename()));
526 // This time test whether the directory is a symbolic link
527 // *before* looking for "chkconfig.ltx".
528 // (We've looked relative to the original already.)
529 if (!fs::symbolic_link_exists(binary.toFilesystemEncoding()))
533 if (readLink(binary_dir, link)) {
536 // Unable to resolve the link.
540 // Try and find "chkconfig.ltx".
541 FileName const lyxdir(
542 normalizePath(addPath(binary_dir.absFilename(), relative_lyxdir)));
543 searched_dirs.push_back(lyxdir);
545 if (!fileSearch(lyxdir.absFilename(), chkconfig_ltx).empty()) {
546 // Success! "chkconfig.ltx" has been found.
551 // 5. In desparation, try the hard-coded system support dir.
552 path = hardcoded_system_support_dir();
553 if (!fileSearch(path.absFilename(), chkconfig_ltx).empty())
556 // Everything has failed :-(
557 // So inform the user and exit.
558 string searched_dirs_str;
559 typedef std::list<FileName>::const_iterator iterator;
560 iterator const begin = searched_dirs.begin();
561 iterator const end = searched_dirs.end();
562 for (iterator it = begin; it != end; ++it) {
564 searched_dirs_str += "\n\t";
565 searched_dirs_str += it->absFilename();
569 throw ExceptionMessage(ErrorException, _("No system directory"),
570 bformat(_("Unable to determine the system directory "
573 "Use the '-sysdir' command line parameter or "
574 "set the environment variable LYX_DIR_15x to "
575 "the LyX system directory containing the file "
577 from_utf8(searched_dirs_str)));
579 // Keep the compiler happy.
584 // Returns the absolute path to the user lyxdir, together with a flag
585 // indicating whether this directory was specified explicitly (as -userdir
586 // or through an environment variable) or whether it was deduced.
587 std::pair<FileName, bool> const
588 get_user_support_dir(FileName const & default_user_support_dir,
589 string const & command_line_user_support_dir)
591 bool explicit_userdir = true;
593 // 1. Use the -userdir command line parameter.
595 abs_path_from_command_line(command_line_user_support_dir);
597 return std::make_pair(path, explicit_userdir);
599 // 2. Use the LYX_USERDIR_15x environment variable.
600 path = extract_env_var_dir("LYX_USERDIR_15x");
602 return std::make_pair(path, explicit_userdir);
604 // 3. Use the OS-dependent default_user_support_dir
605 explicit_userdir = false;
606 return std::make_pair(default_user_support_dir, explicit_userdir);
610 // $HOME/.lyx on POSIX but on Win32 it will be something like
611 // "C:/Documents and Settings/USERNAME/Application Data/LyX"
612 FileName const get_default_user_support_dir(FileName const & home_dir)
614 #if defined (USE_WINDOWS_PACKAGING)
615 (void)home_dir; // Silence warning about unused variable.
617 os::GetFolderPath win32_folder_path;
618 return FileName(addPath(win32_folder_path(os::GetFolderPath::APPDATA), PACKAGE));
620 #elif defined (USE_MACOSX_PACKAGING)
621 (void)home_dir; // Silence warning about unused variable.
624 OSErr const error_code =
625 FSFindFolder(kUserDomain, kApplicationSupportFolderType,
626 kDontCreateFolder, &fsref);
630 // FSRefMakePath returns the result in utf8
631 char store[PATH_MAX + 1];
632 OSStatus const status_code =
633 FSRefMakePath(&fsref,
634 reinterpret_cast<UInt8*>(store), PATH_MAX);
635 if (status_code != 0)
638 return FileName(addPath(reinterpret_cast<char const *>(store), PACKAGE));
640 #else // USE_POSIX_PACKAGING
641 return FileName(addPath(home_dir.absFilename(), string(".") + PACKAGE));
646 // Check that directory @c dir contains @c file.
647 // Else emit a warning about an invalid @c command_line_switch.
648 bool check_command_line_dir(string const & dir,
650 string const & command_line_switch)
652 FileName const abs_path = fileSearch(dir, file);
653 if (abs_path.empty()) {
655 throw ExceptionMessage(WarningException, _("File not found"), bformat(
656 _("Invalid %1$s switch.\nDirectory %2$s does not contain %3$s."),
657 from_utf8(command_line_switch), from_utf8(dir),
661 return !abs_path.empty();
665 // The environment variable @c env_var expands to a (single) file path.
666 FileName const extract_env_var_dir(string const & env_var)
668 string const dir = fix_dir_name(getEnv(env_var));
669 return dir.empty() ? FileName() : makeAbsPath(dir);
673 // Check that directory @c dir contains @c file.
674 // Else emit a warning about an invalid @c env_var.
675 bool check_env_var_dir(FileName const & dir,
677 string const & env_var)
679 FileName const abs_path = fileSearch(dir.absFilename(), file);
680 if (abs_path.empty()) {
682 throw ExceptionMessage(WarningException, _("File not found"), bformat(
683 _("Invalid %1$s environment variable.\n"
684 "Directory %2$s does not contain %3$s."),
685 from_utf8(env_var), from_utf8(dir.absFilename()),
689 return !abs_path.empty();
693 // Check that directory @c dir is indeed a directory.
694 // Else emit a warning about an invalid @c env_var.
695 bool check_env_var_dir(FileName const & dir,
696 string const & env_var)
698 string const encoded = dir.toFilesystemEncoding();
699 bool const success = (dir.exists() && fs::is_directory(encoded));
702 // Put this string on a single line so that the gettext
703 // search mechanism in po/Makefile.in.in will register
704 // Package.cpp.in as a file containing strings that need
707 docstring const fmt =
708 _("Invalid %1$s environment variable.\n%2$s is not a directory.");
710 throw ExceptionMessage(WarningException, _("Directory not found"), bformat(
711 fmt, from_utf8(env_var), from_utf8(dir.absFilename())));
718 // The locale directory relative to the LyX system directory.
719 string const relative_locale_dir()
721 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
729 // The system lyxdir is relative to the directory containing the LyX binary.
730 string const relative_system_support_dir()
734 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
735 result = "../Resources/";
737 result = addPath("../share/", PACKAGE);
745 } // namespace support