]> git.lyx.org Git - lyx.git/blob - development/Win32/package.C
reflect change in master package.C.in
[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         // The executable may have been invoked either with or
418         // without the .exe extension.
419         // Ensure that it is present.
420         string const as_internal_path = os::internal_path(exe);
421         string const exe_path = suffixIs(as_internal_path, ".exe") ?
422                 as_internal_path : as_internal_path + ".exe";
423         if (os::is_absolute_path(exe_path))
424                 return exe_path;
425
426         // Two possibilities present themselves.
427         // 1. The binary is relative to the CWD.
428         string const abs_exe_path = MakeAbsPath(exe_path);
429         if (fs::exists(abs_exe_path))
430                 return abs_exe_path;
431
432         // 2. exe must be the name of the binary only and it
433         // can be found on the PATH.
434         string const exe_name = OnlyFilename(exe_path);
435         if (exe_name != exe_path)
436                 return string();
437
438         std::vector<string> const path = getEnvPath("PATH");
439         std::vector<string>::const_iterator it = path.begin();
440         std::vector<string>::const_iterator const end = path.end();
441         for (; it != end; ++it) {
442                 // This will do nothing if *it is already absolute.
443                 string const exe_dir = MakeAbsPath(*it);
444
445                 string const exe_path = AddName(exe_dir, exe_name);
446                 if (fs::exists(exe_path))
447                         return exe_path;
448         }
449
450         // Didn't find anything.
451         return string();
452 }
453
454
455 // Extracts the absolute path to the binary name received as argv[0].
456 string const abs_path_from_binary_name(string const & exe)
457 {
458         string const abs_binary = get_binary_path(exe);
459         if (abs_binary.empty()) {
460                 lyxerr << bformat(_("Unable to determine the path to the "
461                                     "LyX binary from the command line %1$s"),
462                                   exe)
463                        << std::endl;
464                 bail_out();
465         }
466         return abs_binary;
467 }
468
469
470 // A plethora of directories is searched to ascertain the system
471 // lyxdir which is defined as the first directory to contain
472 // "chkconfig.ltx".
473 string const
474 get_system_support_dir(string const & abs_binary,
475                   string const & command_line_system_support_dir)
476 {
477         string const chkconfig_ltx = "chkconfig.ltx";
478
479         // searched_dirs is used for diagnostic purposes only in the case
480         // that "chkconfig.ltx" is not found.
481         std::list<string> searched_dirs;
482
483         // 1. Use the -sysdir command line parameter.
484         string path = abs_path_from_command_line(command_line_system_support_dir);
485         if (!path.empty()) {
486                 searched_dirs.push_back(path);
487                 if (check_command_line_dir(path, chkconfig_ltx, "-sysdir"))
488                         return path;
489         }
490
491         // 2. Use the "LYX_DIR_13x" environment variable.
492         path = extract_env_var_dir("LYX_DIR_13x");
493         if (!path.empty()) {
494                 searched_dirs.push_back(path);
495                 if (check_env_var_dir(path, chkconfig_ltx, "LYX_DIR_13x"))
496                         return path;
497         }
498
499         // 3. Search relative to the lyx binary.
500         // We're looking for "chkconfig.ltx" in a directory
501         //   OnlyPath(abs_binary) / <relative dir> / PACKAGE /
502         // PACKAGE is hardcoded in config.h. Eg "lyx" or "lyx-1.3.6cvs".
503         // <relative dir> is OS-dependent; on Unix, it will be "../share/".
504         string const relative_lyxdir = relative_system_support_dir();
505
506         // One subtlety to be aware of. The name of the lyx binary may be
507         // a symbolic link. If that is the case, then we follow the links too.
508         string binary = abs_binary;
509         while (true) {
510                 // Try and find "chkconfig.ltx".
511                 string const binary_dir = OnlyPath(binary);
512
513                 string const lyxdir =
514                         NormalizePath(AddPath(binary_dir, relative_lyxdir));
515                 searched_dirs.push_back(lyxdir);
516
517                 if (!FileSearch(lyxdir, chkconfig_ltx).empty()) {
518                         // Success! "chkconfig.ltx" has been found.
519                         return lyxdir;
520                 }
521
522                 // Check whether binary is a symbolic link.
523                 // If so, resolve it and repeat the exercise.
524                 if (!fs::symbolic_link_exists(binary))
525                         break;
526
527                 string link;
528                 if (LyXReadLink(binary, link, true)) {
529                         binary = link;
530                 } else {
531                         // Unable to resolve the link.
532                         break;
533                 }
534         }
535
536         // 4. Repeat the exercise on the directory itself.
537         string binary_dir = OnlyPath(abs_binary);
538         while (true) {
539                 // This time test whether the directory is a symbolic link
540                 // *before* looking for "chkconfig.ltx".
541                 // (We've looked relative to the original already.)
542                 if (!fs::symbolic_link_exists(binary))
543                         break;
544
545                 string link;
546                 if (LyXReadLink(binary_dir, link, true)) {
547                         binary_dir = link;
548                 } else {
549                         // Unable to resolve the link.
550                         break;
551                 }
552
553                 // Try and find "chkconfig.ltx".
554                 string const lyxdir =
555                         NormalizePath(AddPath(binary_dir, relative_lyxdir));
556                 searched_dirs.push_back(lyxdir);
557
558                 if (!FileSearch(lyxdir, chkconfig_ltx).empty()) {
559                         // Success! "chkconfig.ltx" has been found.
560                         return lyxdir;
561                 }
562         }
563
564         // 5. In desparation, try the hard-coded system support dir.
565         path = hardcoded_system_support_dir();
566         if (!FileSearch(path, chkconfig_ltx).empty())
567                 return path;
568
569         // Everything has failed :-(
570         // So inform the user and exit.
571         string searched_dirs_str;
572         typedef std::list<string>::const_iterator iterator;
573         iterator const begin = searched_dirs.begin();
574         iterator const end = searched_dirs.end();
575         for (iterator it = begin; it != end; ++it) {
576                 if (it != begin)
577                         searched_dirs_str += "\n\t";
578                 searched_dirs_str += *it;
579         }
580
581         lyxerr << bformat(_("Unable to determine the system directory "
582                             "having searched\n"
583                             "\t%1$s\n"
584                             "Try the '-sysdir' command line parameter or "
585                             "set the environment variable LYX_DIR_13x to "
586                             "the LyX system directory containing the file "
587                             "`chkconfig.ltx'."),
588                           searched_dirs_str)
589                << std::endl;
590
591         bail_out();
592         // Keep the compiler happy.
593         return string();
594 }
595
596
597 // Returns the absolute path to the user lyxdir, together with a flag
598 // indicating whether this directory was specified explicitly (as -userdir
599 // or through an environment variable) or whether it was deduced.
600 std::pair<string, bool> const
601 get_user_support_dir(string const & default_user_support_dir,
602                      string const & command_line_user_support_dir)
603 {
604         bool explicit_userdir = true;
605
606         // 1. Use the -userdir command line parameter.
607         string path =
608                 abs_path_from_command_line(command_line_user_support_dir);
609         if (!path.empty())
610                 return std::make_pair(path, explicit_userdir);
611
612         // 2. Use the LYX_USERDIR_13x environment variable.
613         path = extract_env_var_dir("LYX_USERDIR_13x");
614         if (!path.empty())
615                 return std::make_pair(path, explicit_userdir);
616
617         // 3. Use the OS-dependent default_user_support_dir
618         explicit_userdir = false;
619         return std::make_pair(default_user_support_dir, explicit_userdir);
620 }
621
622
623 // $HOME/.lyx on all platforms but Win32 where it will be something like
624 // "C:/Documents and Settings/USERNAME/Application Data/lyx"
625 string const get_default_user_support_dir(string const & home_dir)
626 {
627 #if defined (USE_WINDOWS_PACKAGING)
628         (void)home_dir; // Silence warning about unused variable.
629
630         return AddPath(win32_folder_path(CSIDL_APPDATA), PACKAGE);
631
632 #elif defined (USE_MACOSX_PACKAGING)
633         (void)home_dir; // Silence warning about unused variable.
634
635         FSRef fsref;
636         OSErr const error_code =
637                 FSFindFolder(kUserDomain, kApplicationSupportFolderType,
638                              kDontCreateFolder, &fsref);
639         if (error_code != 0)
640                 return string();
641
642         char store[PATH_MAX + 1];
643         OSStatus const status_code =
644                 FSRefMakePath(&fsref,
645                               reinterpret_cast<UInt8*>(store), PATH_MAX);
646         if (status_code != 0)
647                 return string();
648
649         return AddPath(reinterpret_cast<char const *>(store), PACKAGE);
650
651 #else // USE_POSIX_PACKAGING
652         return AddPath(home_dir, string(".") + PACKAGE);
653 #endif
654 }
655
656
657 // Check that directory @c dir contains @c file.
658 // Else emit a warning about an invalid @c command_line_switch.
659 bool check_command_line_dir(string const & dir,
660                             string const & file,
661                             string const & command_line_switch)
662 {
663         string const abs_path = FileSearch(dir, file);
664         if (abs_path.empty()) {
665                 lyxerr << bformat(_("Invalid %1$s switch.\n"
666                                     "Directory %2$s does not contain %3$s."),
667                                   command_line_switch, dir, file)
668                        << std::endl;
669         }
670
671         return !abs_path.empty();
672 }
673
674
675 // The environment variable @c env_var expands to a (single) file path.
676 string const extract_env_var_dir(string const & env_var)
677 {
678         string const dir = os::internal_path(getEnv(env_var));
679         return dir.empty() ? dir : MakeAbsPath(dir);
680 }
681
682
683 // Check that directory @c dir contains @c file.
684 // Else emit a warning about an invalid @c env_var.
685 bool check_env_var_dir(string const & dir,
686                        string const & file,
687                        string const & env_var)
688 {
689         string const abs_path = FileSearch(dir, file);
690         if (abs_path.empty()) {
691                 lyxerr << bformat(_("Invalid %1$s environment variable.\n"
692                                     "Directory %2$s does not contain %3$s."),
693                                   env_var, dir, file)
694                        << std::endl;
695         }
696
697         return !abs_path.empty();
698 }
699
700
701 // Check that directory @c dir is indeed a directory.
702 // Else emit a warning about an invalid @c env_var.
703 bool check_env_var_dir(string const & dir,
704                        string const & env_var)
705 {
706         bool const success = (fs::exists(dir) && fs::is_directory(dir));
707
708         if (!success) {
709                 // Put this string on a single line so that the gettext
710                 // search mechanism in po/Makefile.in.in will register
711                 // package.C.in as a file containing strings that need
712                 // translation.
713                 string const fmt =
714                 _("Invalid %1$s environment variable.\n%2$s is not a directory.");
715
716                 lyxerr << bformat(fmt, env_var, dir)
717                        << std::endl;
718         }
719
720         return success;
721 }
722
723
724 // The locale directory relative to the LyX system directory.
725 string const relative_locale_dir()
726 {
727         return "../locale/";
728 }
729
730
731 // The system lyxdir is relative to the directory containing the LyX binary.
732 string const relative_system_support_dir()
733 {
734         string result;
735
736 #if defined (USE_WINDOWS_PACKAGING) || defined (USE_MACOSX_PACKAGING)
737         result = AddPath("../Resources/", PACKAGE);
738 #else // Posix-like.
739         result = AddPath("../share/", PACKAGE);
740 #endif
741
742         return result;
743 }
744
745 } // namespace anon
746
747 } // namespace support
748 } // namespace lyx