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