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