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