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