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"
16 #include "support/debug.h"
17 #include "support/environment.h"
18 #include "support/ExceptionMessage.h"
19 #include "support/filetools.h"
20 #include "support/gettext.h"
21 #include "support/lassert.h"
22 #include "support/lstrings.h"
23 #include "support/os.h"
25 #if defined (USE_WINDOWS_PACKAGING)
26 # include "support/os_win32.h"
32 #if !defined (USE_WINDOWS_PACKAGING) && \
33 !defined (USE_MACOSX_PACKAGING) && \
34 !defined (USE_POSIX_PACKAGING)
35 #error USE_FOO_PACKAGING must be defined for FOO = WINDOWS, MACOSX or POSIX.
38 #if defined (USE_MACOSX_PACKAGING)
39 # include <CoreServices/CoreServices.h> // FSFindFolder, FSRefMakePath
50 bool initialised_ = false;
55 void init_package(string const & command_line_arg0,
56 string const & command_line_system_support_dir,
57 string const & command_line_user_support_dir,
58 exe_build_dir_to_top_build_dir top_build_dir_location)
60 package_ = Package(command_line_arg0,
61 command_line_system_support_dir,
62 command_line_user_support_dir,
63 top_build_dir_location);
68 Package const & package()
70 LASSERT(initialised_, /**/);
77 FileName const abs_path_from_binary_name(string const & exe);
79 void buildDirs(FileName const & abs_binary,
80 exe_build_dir_to_top_build_dir top_build_dir_location,
81 FileName &, FileName &);
83 FileName const get_document_dir(FileName const & home_dir);
85 FileName const get_locale_dir(FileName const & system_support_dir);
87 FileName const get_system_support_dir(FileName const & abs_binary,
88 string const & command_line_system_support_dir);
90 FileName const get_default_user_support_dir(FileName const & home_dir);
92 bool userSupportDir(FileName const & default_user_support_dir,
93 string const & command_line_user_support_dir, FileName & result);
95 string const & with_version_suffix();
97 string const fix_dir_name(string const & name);
102 Package::Package(string const & command_line_arg0,
103 string const & command_line_system_support_dir,
104 string const & command_line_user_support_dir,
105 exe_build_dir_to_top_build_dir top_build_dir_location)
106 : explicit_user_support_dir_(false)
108 // Specification of temp_dir_ may be reset by LyXRC,
109 // but the default is fixed for a given OS.
110 system_temp_dir_ = FileName::tempPath();
111 temp_dir_ = system_temp_dir_;
112 document_dir_ = get_document_dir(get_home_dir());
114 FileName const abs_binary = abs_path_from_binary_name(command_line_arg0);
115 binary_dir_ = FileName(onlyPath(abs_binary.absFileName()));
117 // the LyX package directory
118 lyx_dir_ = FileName(addPath(binary_dir_.absFileName(), "../"));
119 lyx_dir_ = FileName(lyx_dir_.realPath());
121 // Is LyX being run in-place from the build tree?
122 buildDirs(abs_binary, top_build_dir_location,
123 build_support_dir_, system_support_dir_);
125 if (build_support_dir_.empty())
126 system_support_dir_ =
127 get_system_support_dir(abs_binary,
128 command_line_system_support_dir);
130 // The LyX executable is one level above binary_dir_ if we are running
131 // tex2lyx in place. Otherwise it is in binary_dir_.
133 if (build_support_dir_.empty() ||
134 top_build_dir_location == top_build_dir_is_one_level_up)
135 abs_lyx_dir = binary_dir_.absFileName();
137 FileName fn(addPath(binary_dir_.absFileName(), "../"));
138 abs_lyx_dir = fn.realPath();
140 // The LyX executable may have a package suffix if we are not running
142 if (build_support_dir_.empty())
143 lyx_binary_ = FileName(addName(abs_lyx_dir,
144 "lyx" + string(PROGRAM_SUFFIX)));
146 lyx_binary_ = FileName(addName(abs_lyx_dir, "lyx"));
148 locale_dir_ = get_locale_dir(system_support_dir_);
150 FileName const default_user_support_dir =
151 get_default_user_support_dir(get_home_dir());
153 explicit_user_support_dir_ = userSupportDir(default_user_support_dir,
154 command_line_user_support_dir, user_support_dir_);
156 FileName const configure_script(addName(system_support().absFileName(), "configure.py"));
157 configure_command_ = os::python() + ' ' +
158 quoteName(configure_script.toFilesystemEncoding(), quote_python) +
159 with_version_suffix();
161 LYXERR(Debug::INIT, "<package>\n"
162 << "\tbinary_dir " << binary_dir().absFileName() << '\n'
163 << "\tsystem_support " << system_support().absFileName() << '\n'
164 << "\tbuild_support " << build_support().absFileName() << '\n'
165 << "\tuser_support " << user_support().absFileName() << '\n'
166 << "\tlocale_dir " << locale_dir().absFileName() << '\n'
167 << "\tdocument_dir " << document_dir().absFileName() << '\n'
168 << "\ttemp_dir " << temp_dir().absFileName() << '\n'
169 << "\thome_dir " << get_home_dir().absFileName() << '\n'
174 void Package::set_temp_dir(FileName const & temp_dir) const
176 if (temp_dir.empty())
177 temp_dir_ = system_temp_dir_;
179 temp_dir_ = temp_dir;
182 // The specification of home_dir_ is fixed for a given OS.
183 // A typical example on Windows: "C:/Documents and Settings/USERNAME"
184 // and on a Posix-like machine: "/home/USERNAME".
185 FileName const & Package::get_home_dir()
187 #if defined (USE_WINDOWS_PACKAGING)
188 static FileName const home_dir(getEnv("USERPROFILE"));
190 static FileName const home_dir(getEnv("HOME"));
198 // These next functions contain the stuff that is substituted at
199 // configuration-time.
200 FileName const hardcoded_localedir()
203 // The build system needs to make sure that this is in utf8 encoding.
204 return FileName(LYX_ABS_INSTALLED_LOCALEDIR);
208 FileName const hardcoded_system_support_dir()
211 // The build system needs to make sure that this is in utf8 encoding.
212 return FileName(LYX_ABS_INSTALLED_DATADIR);
216 string const & with_version_suffix()
218 static string const program_suffix = PROGRAM_SUFFIX;
219 static string const with_version_suffix =
220 " --with-version-suffix=" PROGRAM_SUFFIX;
221 return program_suffix.empty() ? program_suffix : with_version_suffix;
227 FileName const & Package::top_srcdir()
230 // The build system needs to make sure that this is in utf8 encoding.
231 static FileName const dir(LYX_ABS_TOP_SRCDIR);
238 bool check_command_line_dir(string const & dir,
240 string const & command_line_switch);
242 FileName const extract_env_var_dir(string const & env_var);
244 bool check_env_var_dir(FileName const & dir,
245 string const & env_var);
247 bool check_env_var_dir(FileName const & dir,
249 string const & env_var);
251 string const relative_locale_dir();
253 string const relative_system_support_dir();
257 * Convert \p name to internal path and strip a trailing slash, since it
258 * comes from user input (commandline or environment).
259 * \p name is encoded in utf8.
261 string const fix_dir_name(string const & name)
263 return rtrim(os::internal_path(name), "/");
267 FileName buildSupportDir(string const & binary_dir,
268 exe_build_dir_to_top_build_dir top_build_dir_location)
271 switch (top_build_dir_location) {
272 case top_build_dir_is_one_level_up:
273 indirection = "../lib";
275 case top_build_dir_is_two_levels_up:
276 indirection = "../../lib";
279 return FileName(addPath(binary_dir, indirection));
283 void buildDirs(FileName const & abs_binary,
284 exe_build_dir_to_top_build_dir top_build_dir_location,
285 FileName & build_support_dir, FileName & system_support_dir)
287 string const check_text = "Checking whether LyX is run in place...";
289 // We're looking for "Makefile" in a directory
291 // We're also looking for "chkconfig.ltx" in a directory
293 // If both are found, then we're running LyX in-place.
295 // Note that the name of the lyx binary may be a symbolic link.
296 // If that is the case, then we follow the links too.
297 FileName binary = abs_binary;
299 // Try and find "lyxrc.defaults".
300 string binary_dir = onlyPath(binary.absFileName());
301 build_support_dir = buildSupportDir(binary_dir, top_build_dir_location);
302 if (!fileSearch(build_support_dir.absFileName(), "Makefile").empty()) {
303 // Try and find "chkconfig.ltx".
305 FileName(addPath(Package::top_srcdir().absFileName(), "lib"));
307 if (!fileSearch(system_support_dir.absFileName(), "chkconfig.ltx").empty()) {
308 LYXERR(Debug::INIT, check_text << " yes");
313 // Check whether binary is a symbolic link.
314 // If so, resolve it and repeat the exercise.
315 if (!binary.isSymLink())
319 if (readLink(binary, link)) {
322 // Unable to resolve the link.
327 LYXERR(Debug::INIT, check_text << " no");
328 system_support_dir = FileName();
329 build_support_dir = FileName();
333 // Specification of document_dir_ may be reset by LyXRC,
334 // but the default is fixed for a given OS.
335 FileName const get_document_dir(FileName const & home_dir)
337 #if defined (USE_WINDOWS_PACKAGING)
338 (void)home_dir; // Silence warning about unused variable.
339 os::GetFolderPath win32_folder_path;
340 return FileName(win32_folder_path(os::GetFolderPath::PERSONAL));
348 // Several sources are probed to ascertain the locale directory.
349 // The only requirement is that the result is indeed a directory.
350 FileName const get_locale_dir(FileName const & system_support_dir)
352 // 1. Use the "LYX_LOCALEDIR" environment variable.
353 FileName const path_env = extract_env_var_dir("LYX_LOCALEDIR");
354 if (!path_env.empty() && check_env_var_dir(path_env, "LYX_LOCALEDIR"))
357 // 2. Search for system_support_dir / <relative locale dir>
358 // The <relative locale dir> is OS-dependent. (On Unix, it will
360 FileName path(addPath(system_support_dir.absFileName(),
361 relative_locale_dir()));
363 if (path.exists() && path.isDirectory())
366 // 3. Fall back to the hard-coded LOCALEDIR.
367 path = hardcoded_localedir();
368 if (path.exists() && path.isDirectory())
375 // Extracts the absolute path from the foo of "-sysdir foo" or "-userdir foo"
376 FileName const abs_path_from_command_line(string const & command_line)
378 if (command_line.empty())
381 string const str_path = fix_dir_name(command_line);
382 return makeAbsPath(str_path);
386 // Does the grunt work for abs_path_from_binary_name()
387 FileName const get_binary_path(string const & exe)
389 #if defined (USE_WINDOWS_PACKAGING)
390 // The executable may have been invoked either with or
391 // without the .exe extension.
392 // Ensure that it is present.
393 string const as_internal_path = os::internal_path(exe);
394 string const exe_path = suffixIs(as_internal_path, ".exe") ?
395 as_internal_path : as_internal_path + ".exe";
397 string const exe_path = os::internal_path(exe);
399 if (FileName::isAbsolute(exe_path))
400 return FileName(exe_path);
402 // Two possibilities present themselves.
403 // 1. The binary is relative to the CWD.
404 FileName const abs_exe_path = makeAbsPath(exe_path);
405 if (abs_exe_path.exists())
408 // 2. exe must be the name of the binary only and it
409 // can be found on the PATH.
410 string const exe_name = onlyFileName(exe_path);
411 if (exe_name != exe_path)
414 vector<string> const path = getEnvPath("PATH");
415 vector<string>::const_iterator it = path.begin();
416 vector<string>::const_iterator const end = path.end();
417 for (; it != end; ++it) {
418 // This will do nothing if *it is already absolute.
419 string const exe_dir = makeAbsPath(*it).absFileName();
421 FileName const exe_path(addName(exe_dir, exe_name));
422 if (exe_path.exists())
426 // Didn't find anything.
431 // Extracts the absolute path to the binary name received as argv[0].
432 FileName const abs_path_from_binary_name(string const & exe)
434 FileName const abs_binary = get_binary_path(exe);
435 if (abs_binary.empty()) {
437 throw ExceptionMessage(ErrorException,
438 _("LyX binary not found"),
439 bformat(_("Unable to determine the path to the LyX binary from the command line %1$s"),
446 // A plethora of directories is searched to ascertain the system
447 // lyxdir which is defined as the first directory to contain
450 get_system_support_dir(FileName const & abs_binary,
451 string const & command_line_system_support_dir)
453 string const chkconfig_ltx = "chkconfig.ltx";
455 // searched_dirs is used for diagnostic purposes only in the case
456 // that "chkconfig.ltx" is not found.
457 list<FileName> searched_dirs;
459 // 1. Use the -sysdir command line parameter.
460 FileName path = abs_path_from_command_line(command_line_system_support_dir);
462 searched_dirs.push_back(path);
463 if (check_command_line_dir(path.absFileName(), chkconfig_ltx, "-sysdir"))
467 // 2. Use the "LYX_DIR_${major}${minor}x" environment variable.
468 path = extract_env_var_dir(LYX_DIR_VER);
470 searched_dirs.push_back(path);
471 if (check_env_var_dir(path, chkconfig_ltx, LYX_DIR_VER))
475 // 3. Search relative to the lyx binary.
476 // We're looking for "chkconfig.ltx" in a directory
477 // OnlyPath(abs_binary) / <relative dir> / PACKAGE /
478 // PACKAGE is hardcoded in config.h. Eg "lyx" or "lyx-1.3.6cvs".
479 // <relative dir> is OS-dependent; on Unix, it will be "../share/".
480 string const relative_lyxdir = relative_system_support_dir();
482 // One subtlety to be aware of. The name of the lyx binary may be
483 // a symbolic link. If that is the case, then we follow the links too.
484 FileName binary = abs_binary;
486 // Try and find "chkconfig.ltx".
487 string const binary_dir = onlyPath(binary.absFileName());
489 FileName const lyxdir(addPath(binary_dir, relative_lyxdir));
490 searched_dirs.push_back(lyxdir);
492 if (!fileSearch(lyxdir.absFileName(), chkconfig_ltx).empty()) {
493 // Success! "chkconfig.ltx" has been found.
497 // Check whether binary is a symbolic link.
498 // If so, resolve it and repeat the exercise.
499 if (!binary.isSymLink())
503 if (readLink(binary, link)) {
506 // Unable to resolve the link.
511 // 4. Repeat the exercise on the directory itself.
512 FileName binary_dir(onlyPath(abs_binary.absFileName()));
514 // This time test whether the directory is a symbolic link
515 // *before* looking for "chkconfig.ltx".
516 // (We've looked relative to the original already.)
517 if (!binary.isSymLink())
521 if (readLink(binary_dir, link)) {
524 // Unable to resolve the link.
528 // Try and find "chkconfig.ltx".
529 FileName const lyxdir(addPath(binary_dir.absFileName(),
531 searched_dirs.push_back(lyxdir);
533 if (!fileSearch(lyxdir.absFileName(), chkconfig_ltx).empty()) {
534 // Success! "chkconfig.ltx" has been found.
539 // 5. In desparation, try the hard-coded system support dir.
540 path = hardcoded_system_support_dir();
541 if (!fileSearch(path.absFileName(), chkconfig_ltx).empty())
544 // Everything has failed :-(
545 // So inform the user and exit.
546 string searched_dirs_str;
547 typedef list<FileName>::const_iterator iterator;
548 iterator const begin = searched_dirs.begin();
549 iterator const end = searched_dirs.end();
550 for (iterator it = begin; it != end; ++it) {
552 searched_dirs_str += "\n\t";
553 searched_dirs_str += it->absFileName();
557 throw ExceptionMessage(ErrorException, _("No system directory"),
558 bformat(_("Unable to determine the system directory "
561 "Use the '-sysdir' command line parameter or "
562 "set the environment variable\n%2$s "
563 "to the LyX system directory containing the "
564 "file `chkconfig.ltx'."),
565 from_utf8(searched_dirs_str), from_ascii(LYX_DIR_VER)));
567 // Keep the compiler happy.
572 // Returns the absolute path to the user lyxdir, together with a flag
573 // indicating whether this directory was specified explicitly (as -userdir
574 // or through an environment variable) or whether it was deduced.
575 bool userSupportDir(FileName const & default_user_support_dir,
576 string const & command_line_user_support_dir, FileName & result)
578 // 1. Use the -userdir command line parameter.
579 result = abs_path_from_command_line(command_line_user_support_dir);
583 // 2. Use the LYX_USERDIR_${major}${minor}x environment variable.
584 result = extract_env_var_dir(LYX_USERDIR_VER);
588 // 3. Use the OS-dependent default_user_support_dir
589 result = default_user_support_dir;
594 // $HOME/.lyx on POSIX but on Win32 it will be something like
595 // "C:/Documents and Settings/USERNAME/Application Data/LyX"
596 FileName const get_default_user_support_dir(FileName const & home_dir)
598 #if defined (USE_WINDOWS_PACKAGING)
599 (void)home_dir; // Silence warning about unused variable.
601 os::GetFolderPath win32_folder_path;
602 return FileName(addPath(win32_folder_path(os::GetFolderPath::APPDATA), PACKAGE));
604 #elif defined (USE_MACOSX_PACKAGING)
605 (void)home_dir; // Silence warning about unused variable.
608 OSErr const error_code =
609 FSFindFolder(kUserDomain, kApplicationSupportFolderType,
610 kDontCreateFolder, &fsref);
614 // FSRefMakePath returns the result in utf8
615 char store[PATH_MAX + 1];
616 OSStatus const status_code =
617 FSRefMakePath(&fsref,
618 reinterpret_cast<UInt8*>(store), PATH_MAX);
619 if (status_code != 0)
622 return FileName(addPath(reinterpret_cast<char const *>(store), PACKAGE));
624 #else // USE_POSIX_PACKAGING
625 return FileName(addPath(home_dir.absFileName(), string(".") + PACKAGE));
630 // Check that directory @c dir contains @c file.
631 // Else emit an error message about an invalid @c command_line_switch.
632 bool check_command_line_dir(string const & dir,
634 string const & command_line_switch)
636 FileName const abs_path = fileSearch(dir, file);
637 if (abs_path.empty()) {
639 throw ExceptionMessage(ErrorException, _("File not found"), bformat(
640 _("Invalid %1$s switch.\nDirectory %2$s does not contain %3$s."),
641 from_utf8(command_line_switch), from_utf8(dir),
645 return !abs_path.empty();
649 // The environment variable @c env_var expands to a (single) file path.
650 FileName const extract_env_var_dir(string const & env_var)
652 string const dir = fix_dir_name(getEnv(env_var));
653 return dir.empty() ? FileName() : makeAbsPath(dir);
657 // Check that directory @c dir contains @c file.
658 // Else emit a warning about an invalid @c env_var.
659 bool check_env_var_dir(FileName const & dir,
661 string const & env_var)
663 FileName const abs_path = fileSearch(dir.absFileName(), file);
664 if (abs_path.empty()) {
666 throw ExceptionMessage(WarningException, _("File not found"), bformat(
667 _("Invalid %1$s environment variable.\n"
668 "Directory %2$s does not contain %3$s."),
669 from_utf8(env_var), from_utf8(dir.absFileName()),
673 return !abs_path.empty();
677 // Check that directory @c dir is indeed a directory.
678 // Else emit a warning about an invalid @c env_var.
679 bool check_env_var_dir(FileName const & dir,
680 string const & env_var)
682 bool const success = dir.exists() && dir.isDirectory();
685 // Put this string on a single line so that the gettext
686 // search mechanism in po/Makefile.in.in will register
687 // Package.cpp.in as a file containing strings that need
690 docstring const fmt =
691 _("Invalid %1$s environment variable.\n%2$s is not a directory.");
693 throw ExceptionMessage(WarningException, _("Directory not found"), bformat(
694 fmt, from_utf8(env_var), from_utf8(dir.absFileName())));
701 // The locale directory relative to the LyX system directory.
702 string const relative_locale_dir()
704 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
712 // The system lyxdir is relative to the directory containing the LyX binary.
713 string const relative_system_support_dir()
717 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
718 result = "../Resources/";
720 result = addPath("../share/", PACKAGE);
728 } // namespace support