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