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