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 bool packageInitialized()
74 Package const & package()
76 LASSERT(initialised_, /**/);
83 FileName const abs_path_from_binary_name(string const & exe);
85 void buildDirs(FileName const & abs_binary,
86 exe_build_dir_to_top_build_dir top_build_dir_location,
87 FileName &, FileName &);
89 FileName const get_document_dir(FileName const & home_dir);
91 FileName const get_locale_dir(FileName const & system_support_dir);
93 FileName const get_system_support_dir(FileName const & abs_binary,
94 string const & command_line_system_support_dir);
96 FileName const get_default_user_support_dir(FileName const & home_dir);
98 bool userSupportDir(FileName const & default_user_support_dir,
99 string const & command_line_user_support_dir, FileName & result);
101 string const & with_version_suffix();
103 string const fix_dir_name(string const & name);
108 Package::Package(string const & command_line_arg0,
109 string const & command_line_system_support_dir,
110 string const & command_line_user_support_dir,
111 exe_build_dir_to_top_build_dir top_build_dir_location)
112 : explicit_user_support_dir_(false)
114 // Specification of temp_dir_ may be reset by LyXRC,
115 // but the default is fixed for a given OS.
116 system_temp_dir_ = FileName::tempPath();
117 temp_dir_ = system_temp_dir_;
118 document_dir_ = get_document_dir(get_home_dir());
120 FileName const abs_binary = abs_path_from_binary_name(command_line_arg0);
121 binary_dir_ = FileName(onlyPath(abs_binary.absFileName()));
123 // the LyX package directory
124 lyx_dir_ = FileName(addPath(binary_dir_.absFileName(), "../"));
125 lyx_dir_ = FileName(lyx_dir_.realPath());
127 // Is LyX being run in-place from the build tree?
128 buildDirs(abs_binary, top_build_dir_location,
129 build_support_dir_, system_support_dir_);
131 if (build_support_dir_.empty())
132 system_support_dir_ =
133 get_system_support_dir(abs_binary,
134 command_line_system_support_dir);
136 // The LyX executable is one level above binary_dir_ if we are running
137 // tex2lyx in place. Otherwise it is in binary_dir_.
139 if (build_support_dir_.empty() ||
140 top_build_dir_location == top_build_dir_is_one_level_up)
141 abs_lyx_dir = binary_dir_.absFileName();
143 FileName fn(addPath(binary_dir_.absFileName(), "../"));
144 abs_lyx_dir = fn.realPath();
146 // The LyX executable may have a package suffix if we are not running
148 if (build_support_dir_.empty())
149 lyx_binary_ = FileName(addName(abs_lyx_dir,
150 "lyx" + string(PROGRAM_SUFFIX)));
152 lyx_binary_ = FileName(addName(abs_lyx_dir, "lyx"));
154 locale_dir_ = get_locale_dir(system_support_dir_);
156 FileName const default_user_support_dir =
157 get_default_user_support_dir(get_home_dir());
159 explicit_user_support_dir_ = userSupportDir(default_user_support_dir,
160 command_line_user_support_dir, user_support_dir_);
162 FileName const configure_script(addName(system_support().absFileName(), "configure.py"));
163 configure_command_ = os::python() + ' ' +
164 quoteName(configure_script.toFilesystemEncoding(), quote_python) +
165 with_version_suffix();
167 LYXERR(Debug::INIT, "<package>\n"
168 << "\tbinary_dir " << binary_dir().absFileName() << '\n'
169 << "\tsystem_support " << system_support().absFileName() << '\n'
170 << "\tbuild_support " << build_support().absFileName() << '\n'
171 << "\tuser_support " << user_support().absFileName() << '\n'
172 << "\tlocale_dir " << locale_dir().absFileName() << '\n'
173 << "\tdocument_dir " << document_dir().absFileName() << '\n'
174 << "\ttemp_dir " << temp_dir().absFileName() << '\n'
175 << "\thome_dir " << get_home_dir().absFileName() << '\n'
180 void Package::set_temp_dir(FileName const & temp_dir) const
182 if (temp_dir.empty())
183 temp_dir_ = system_temp_dir_;
185 temp_dir_ = temp_dir;
188 // The specification of home_dir_ is fixed for a given OS.
189 // A typical example on Windows: "C:/Documents and Settings/USERNAME"
190 // and on a Posix-like machine: "/home/USERNAME".
191 FileName const & Package::get_home_dir()
193 #if defined (USE_WINDOWS_PACKAGING)
194 static FileName const home_dir(getEnv("USERPROFILE"));
196 static FileName const home_dir(getEnv("HOME"));
204 // These next functions contain the stuff that is substituted at
205 // configuration-time.
206 FileName const hardcoded_localedir()
209 // The build system needs to make sure that this is in utf8 encoding.
210 return FileName(LYX_ABS_INSTALLED_LOCALEDIR);
214 FileName const hardcoded_system_support_dir()
217 // The build system needs to make sure that this is in utf8 encoding.
218 return FileName(LYX_ABS_INSTALLED_DATADIR);
222 string const & with_version_suffix()
224 static string const program_suffix = PROGRAM_SUFFIX;
225 static string const with_version_suffix =
226 " --with-version-suffix=" PROGRAM_SUFFIX;
227 return program_suffix.empty() ? program_suffix : with_version_suffix;
233 FileName const & Package::top_srcdir()
236 // The build system needs to make sure that this is in utf8 encoding.
237 static FileName const dir(LYX_ABS_TOP_SRCDIR);
244 bool check_command_line_dir(string const & dir,
246 string const & command_line_switch);
248 FileName const extract_env_var_dir(string const & env_var);
250 bool check_env_var_dir(FileName const & dir,
251 string const & env_var);
253 bool check_env_var_dir(FileName const & dir,
255 string const & env_var);
257 string const relative_locale_dir();
259 string const relative_system_support_dir();
263 * Convert \p name to internal path and strip a trailing slash, since it
264 * comes from user input (commandline or environment).
265 * \p name is encoded in utf8.
267 string const fix_dir_name(string const & name)
269 return rtrim(os::internal_path(name), "/");
273 FileName buildSupportDir(string const & binary_dir,
274 exe_build_dir_to_top_build_dir top_build_dir_location)
277 switch (top_build_dir_location) {
278 case top_build_dir_is_one_level_up:
279 indirection = "../lib";
281 case top_build_dir_is_two_levels_up:
282 indirection = "../../lib";
285 return FileName(addPath(binary_dir, indirection));
289 void buildDirs(FileName const & abs_binary,
290 exe_build_dir_to_top_build_dir top_build_dir_location,
291 FileName & build_support_dir, FileName & system_support_dir)
293 string const check_text = "Checking whether LyX is run in place...";
295 // We're looking for "Makefile" in a directory
297 // We're also looking for "chkconfig.ltx" in a directory
299 // If both are found, then we're running LyX in-place.
301 // Note that the name of the lyx binary may be a symbolic link.
302 // If that is the case, then we follow the links too.
303 FileName binary = abs_binary;
305 // Try and find "lyxrc.defaults".
306 string binary_dir = onlyPath(binary.absFileName());
307 build_support_dir = buildSupportDir(binary_dir, top_build_dir_location);
308 if (!fileSearch(build_support_dir.absFileName(), "Makefile").empty()) {
309 // Try and find "chkconfig.ltx".
311 FileName(addPath(Package::top_srcdir().absFileName(), "lib"));
313 if (!fileSearch(system_support_dir.absFileName(), "chkconfig.ltx").empty()) {
314 LYXERR(Debug::INIT, check_text << " yes");
319 // Check whether binary is a symbolic link.
320 // If so, resolve it and repeat the exercise.
321 if (!binary.isSymLink())
325 if (readLink(binary, link)) {
328 // Unable to resolve the link.
333 LYXERR(Debug::INIT, check_text << " no");
334 system_support_dir = FileName();
335 build_support_dir = FileName();
339 // Specification of document_dir_ may be reset by LyXRC,
340 // but the default is fixed for a given OS.
341 FileName const get_document_dir(FileName const & home_dir)
343 #if defined (USE_WINDOWS_PACKAGING)
344 (void)home_dir; // Silence warning about unused variable.
345 os::GetFolderPath win32_folder_path;
346 return FileName(win32_folder_path(os::GetFolderPath::PERSONAL));
354 // Several sources are probed to ascertain the locale directory.
355 // The only requirement is that the result is indeed a directory.
356 FileName const get_locale_dir(FileName const & system_support_dir)
358 // 1. Use the "LYX_LOCALEDIR" environment variable.
359 FileName const path_env = extract_env_var_dir("LYX_LOCALEDIR");
360 if (!path_env.empty() && check_env_var_dir(path_env, "LYX_LOCALEDIR"))
363 // 2. Search for system_support_dir / <relative locale dir>
364 // The <relative locale dir> is OS-dependent. (On Unix, it will
366 FileName path(addPath(system_support_dir.absFileName(),
367 relative_locale_dir()));
369 if (path.exists() && path.isDirectory())
372 // 3. Fall back to the hard-coded LOCALEDIR.
373 path = hardcoded_localedir();
374 if (path.exists() && path.isDirectory())
381 // Extracts the absolute path from the foo of "-sysdir foo" or "-userdir foo"
382 FileName const abs_path_from_command_line(string const & command_line)
384 if (command_line.empty())
387 string const str_path = fix_dir_name(command_line);
388 return makeAbsPath(str_path);
392 // Does the grunt work for abs_path_from_binary_name()
393 FileName const get_binary_path(string const & exe)
395 #if defined (USE_WINDOWS_PACKAGING)
396 // The executable may have been invoked either with or
397 // without the .exe extension.
398 // Ensure that it is present.
399 string const as_internal_path = os::internal_path(exe);
400 string const exe_path = suffixIs(as_internal_path, ".exe") ?
401 as_internal_path : as_internal_path + ".exe";
403 string const exe_path = os::internal_path(exe);
405 if (FileName::isAbsolute(exe_path))
406 return FileName(exe_path);
408 // Two possibilities present themselves.
409 // 1. The binary is relative to the CWD.
410 FileName const abs_exe_path = makeAbsPath(exe_path);
411 if (abs_exe_path.exists())
414 // 2. exe must be the name of the binary only and it
415 // can be found on the PATH.
416 string const exe_name = onlyFileName(exe_path);
417 if (exe_name != exe_path)
420 vector<string> const path = getEnvPath("PATH");
421 vector<string>::const_iterator it = path.begin();
422 vector<string>::const_iterator const end = path.end();
423 for (; it != end; ++it) {
424 // This will do nothing if *it is already absolute.
425 string const exe_dir = makeAbsPath(*it).absFileName();
427 FileName const exe_path(addName(exe_dir, exe_name));
428 if (exe_path.exists())
432 // Didn't find anything.
437 // Extracts the absolute path to the binary name received as argv[0].
438 FileName const abs_path_from_binary_name(string const & exe)
440 FileName const abs_binary = get_binary_path(exe);
441 if (abs_binary.empty()) {
443 throw ExceptionMessage(ErrorException,
444 _("LyX binary not found"),
445 bformat(_("Unable to determine the path to the LyX binary from the command line %1$s"),
452 // A plethora of directories is searched to ascertain the system
453 // lyxdir which is defined as the first directory to contain
456 get_system_support_dir(FileName const & abs_binary,
457 string const & command_line_system_support_dir)
459 string const chkconfig_ltx = "chkconfig.ltx";
461 // searched_dirs is used for diagnostic purposes only in the case
462 // that "chkconfig.ltx" is not found.
463 list<FileName> searched_dirs;
465 // 1. Use the -sysdir command line parameter.
466 FileName path = abs_path_from_command_line(command_line_system_support_dir);
468 searched_dirs.push_back(path);
469 if (check_command_line_dir(path.absFileName(), chkconfig_ltx, "-sysdir"))
473 // 2. Use the "LYX_DIR_${major}${minor}x" environment variable.
474 path = extract_env_var_dir(LYX_DIR_VER);
476 searched_dirs.push_back(path);
477 if (check_env_var_dir(path, chkconfig_ltx, LYX_DIR_VER))
481 // 3. Search relative to the lyx binary.
482 // We're looking for "chkconfig.ltx" in a directory
483 // OnlyPath(abs_binary) / <relative dir> / PACKAGE /
484 // PACKAGE is hardcoded in config.h. Eg "lyx" or "lyx-1.3.6cvs".
485 // <relative dir> is OS-dependent; on Unix, it will be "../share/".
486 string const relative_lyxdir = relative_system_support_dir();
488 // One subtlety to be aware of. The name of the lyx binary may be
489 // a symbolic link. If that is the case, then we follow the links too.
490 FileName binary = abs_binary;
492 // Try and find "chkconfig.ltx".
493 string const binary_dir = onlyPath(binary.absFileName());
495 FileName const lyxdir(addPath(binary_dir, relative_lyxdir));
496 searched_dirs.push_back(lyxdir);
498 if (!fileSearch(lyxdir.absFileName(), chkconfig_ltx).empty()) {
499 // Success! "chkconfig.ltx" has been found.
503 // Check whether binary is a symbolic link.
504 // If so, resolve it and repeat the exercise.
505 if (!binary.isSymLink())
509 if (readLink(binary, link)) {
512 // Unable to resolve the link.
517 // 4. Repeat the exercise on the directory itself.
518 FileName binary_dir(onlyPath(abs_binary.absFileName()));
520 // This time test whether the directory is a symbolic link
521 // *before* looking for "chkconfig.ltx".
522 // (We've looked relative to the original already.)
523 if (!binary.isSymLink())
527 if (readLink(binary_dir, link)) {
530 // Unable to resolve the link.
534 // Try and find "chkconfig.ltx".
535 FileName const lyxdir(addPath(binary_dir.absFileName(),
537 searched_dirs.push_back(lyxdir);
539 if (!fileSearch(lyxdir.absFileName(), chkconfig_ltx).empty()) {
540 // Success! "chkconfig.ltx" has been found.
545 // 5. In desparation, try the hard-coded system support dir.
546 path = hardcoded_system_support_dir();
547 if (!fileSearch(path.absFileName(), chkconfig_ltx).empty())
550 // Everything has failed :-(
551 // So inform the user and exit.
552 string searched_dirs_str;
553 typedef list<FileName>::const_iterator iterator;
554 iterator const begin = searched_dirs.begin();
555 iterator const end = searched_dirs.end();
556 for (iterator it = begin; it != end; ++it) {
558 searched_dirs_str += "\n\t";
559 searched_dirs_str += it->absFileName();
563 throw ExceptionMessage(ErrorException, _("No system directory"),
564 bformat(_("Unable to determine the system directory "
567 "Use the '-sysdir' command line parameter or "
568 "set the environment variable\n%2$s "
569 "to the LyX system directory containing the "
570 "file `chkconfig.ltx'."),
571 from_utf8(searched_dirs_str), from_ascii(LYX_DIR_VER)));
573 // Keep the compiler happy.
578 // Returns the absolute path to the user lyxdir, together with a flag
579 // indicating whether this directory was specified explicitly (as -userdir
580 // or through an environment variable) or whether it was deduced.
581 bool userSupportDir(FileName const & default_user_support_dir,
582 string const & command_line_user_support_dir, FileName & result)
584 // 1. Use the -userdir command line parameter.
585 result = abs_path_from_command_line(command_line_user_support_dir);
589 // 2. Use the LYX_USERDIR_${major}${minor}x environment variable.
590 result = extract_env_var_dir(LYX_USERDIR_VER);
594 // 3. Use the OS-dependent default_user_support_dir
595 result = default_user_support_dir;
600 // $HOME/.lyx on POSIX but on Win32 it will be something like
601 // "C:/Documents and Settings/USERNAME/Application Data/LyX"
602 FileName const get_default_user_support_dir(FileName const & home_dir)
604 #if defined (USE_WINDOWS_PACKAGING)
605 (void)home_dir; // Silence warning about unused variable.
607 os::GetFolderPath win32_folder_path;
608 return FileName(addPath(win32_folder_path(os::GetFolderPath::APPDATA), PACKAGE));
610 #elif defined (USE_MACOSX_PACKAGING)
611 (void)home_dir; // Silence warning about unused variable.
614 OSErr const error_code =
615 FSFindFolder(kUserDomain, kApplicationSupportFolderType,
616 kDontCreateFolder, &fsref);
620 // FSRefMakePath returns the result in utf8
621 char store[PATH_MAX + 1];
622 OSStatus const status_code =
623 FSRefMakePath(&fsref,
624 reinterpret_cast<UInt8*>(store), PATH_MAX);
625 if (status_code != 0)
628 return FileName(addPath(reinterpret_cast<char const *>(store), PACKAGE));
630 #else // USE_POSIX_PACKAGING
631 return FileName(addPath(home_dir.absFileName(), string(".") + PACKAGE));
636 // Check that directory @c dir contains @c file.
637 // Else emit an error message about an invalid @c command_line_switch.
638 bool check_command_line_dir(string const & dir,
640 string const & command_line_switch)
642 FileName const abs_path = fileSearch(dir, file);
643 if (abs_path.empty()) {
645 throw ExceptionMessage(ErrorException, _("File not found"), bformat(
646 _("Invalid %1$s switch.\nDirectory %2$s does not contain %3$s."),
647 from_utf8(command_line_switch), from_utf8(dir),
651 return !abs_path.empty();
655 // The environment variable @c env_var expands to a (single) file path.
656 FileName const extract_env_var_dir(string const & env_var)
658 string const dir = fix_dir_name(getEnv(env_var));
659 return dir.empty() ? FileName() : makeAbsPath(dir);
663 // Check that directory @c dir contains @c file.
664 // Else emit a warning about an invalid @c env_var.
665 bool check_env_var_dir(FileName const & dir,
667 string const & env_var)
669 FileName const abs_path = fileSearch(dir.absFileName(), file);
670 if (abs_path.empty()) {
672 throw ExceptionMessage(WarningException, _("File not found"), bformat(
673 _("Invalid %1$s environment variable.\n"
674 "Directory %2$s does not contain %3$s."),
675 from_utf8(env_var), from_utf8(dir.absFileName()),
679 return !abs_path.empty();
683 // Check that directory @c dir is indeed a directory.
684 // Else emit a warning about an invalid @c env_var.
685 bool check_env_var_dir(FileName const & dir,
686 string const & env_var)
688 bool const success = dir.exists() && dir.isDirectory();
691 // Put this string on a single line so that the gettext
692 // search mechanism in po/Makefile.in.in will register
693 // Package.cpp.in as a file containing strings that need
696 docstring const fmt =
697 _("Invalid %1$s environment variable.\n%2$s is not a directory.");
699 throw ExceptionMessage(WarningException, _("Directory not found"), bformat(
700 fmt, from_utf8(env_var), from_utf8(dir.absFileName())));
707 // The locale directory relative to the LyX system directory.
708 string const relative_locale_dir()
710 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
718 // The system lyxdir is relative to the directory containing the LyX binary.
719 string const relative_system_support_dir()
723 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
724 result = "../Resources/";
726 result = addPath("../share/", PACKAGE);
734 } // namespace support