]> git.lyx.org Git - lyx.git/blob - src/LyX.cpp
b033e40bd8f05d6fb10dc60c443d10f2a9b365d3
[lyx.git] / src / LyX.cpp
1 /**
2  * \file LyX.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16 #include <version.h>
17
18 #include "LyX.h"
19
20 #include "AppleSpellChecker.h"
21 #include "AspellChecker.h"
22 #include "Buffer.h"
23 #include "BufferList.h"
24 #include "CmdDef.h"
25 #include "ColorSet.h"
26 #include "ConverterCache.h"
27 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "EnchantChecker.h"
30 #include "Encoding.h"
31 #include "ErrorList.h"
32 #include "Format.h"
33 #include "FuncStatus.h"
34 #include "HunspellChecker.h"
35 #include "KeyMap.h"
36 #include "Language.h"
37 #include "LayoutFile.h"
38 #include "Lexer.h"
39 #include "LyX.h"
40 #include "LyXAction.h"
41 #include "LyXRC.h"
42 #include "ModuleList.h"
43 #include "Mover.h"
44 #include "Server.h"
45 #include "ServerSocket.h"
46 #include "Session.h"
47
48 #include "frontends/alert.h"
49 #include "frontends/Application.h"
50
51 #include "graphics/Previews.h"
52
53 #include "support/lassert.h"
54 #include "support/debug.h"
55 #include "support/environment.h"
56 #include "support/ExceptionMessage.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60 #include "support/Messages.h"
61 #include "support/os.h"
62 #include "support/Package.h"
63 #include "support/Path.h"
64 #include "support/Systemcall.h"
65
66 #include "support/bind.h"
67 #include <boost/scoped_ptr.hpp>
68
69 #include <algorithm>
70 #include <iostream>
71 #include <csignal>
72 #include <map>
73 #include <stdlib.h>
74 #include <string>
75 #include <vector>
76
77 using namespace std;
78 using namespace lyx::support;
79
80 namespace lyx {
81
82 namespace Alert = frontend::Alert;
83 namespace os = support::os;
84
85
86
87 // Are we using the GUI at all?  We default to true and this is changed
88 // to false when the export feature is used.
89
90 bool use_gui = true;
91
92
93 // We default to open documents in an already running instance, provided that
94 // the lyxpipe has been setup. This can be overridden either on the command
95 // line or through preference settings.
96
97 RunMode run_mode = PREFERRED;
98
99
100 // Tell what files can be silently overwritten during batch export.
101 // Possible values are: NO_FILES, MAIN_FILE, ALL_FILES, UNSPECIFIED.
102 // Unless specified on command line (through the -f switch) or through the
103 // environment variable LYX_FORCE_OVERWRITE, the default will be MAIN_FILE.
104
105 OverwriteFiles force_overwrite = UNSPECIFIED;
106
107
108 namespace {
109
110 // Filled with the command line arguments "foo" of "-sysdir foo" or
111 // "-userdir foo".
112 string cl_system_support;
113 string cl_user_support;
114
115 string geometryArg;
116
117 LyX * singleton_ = 0;
118
119 void showFileError(string const & error)
120 {
121         Alert::warning(_("Could not read configuration file"),
122                        bformat(_("Error while reading the configuration file\n%1$s.\n"
123                            "Please check your installation."), from_utf8(error)));
124 }
125
126
127 void reconfigureUserLyXDir()
128 {
129         string const configure_command = package().configure_command();
130
131         lyxerr << to_utf8(_("LyX: reconfiguring user directory")) << endl;
132         PathChanger p(package().user_support());
133         Systemcall one;
134         one.startscript(Systemcall::Wait, configure_command);
135         lyxerr << "LyX: " << to_utf8(_("Done!")) << endl;
136 }
137
138 } // namespace anon
139
140 /// The main application class private implementation.
141 struct LyX::Impl
142 {
143         Impl() : spell_checker_(0), apple_spell_checker_(0), aspell_checker_(0), enchant_checker_(0), hunspell_checker_(0)
144         {
145                 // Set the default User Interface language as soon as possible.
146                 // The language used will be derived from the environment
147                 // variables.
148                 messages_["GUI"] = Messages();
149         }
150
151         ~Impl()
152         {
153                 delete apple_spell_checker_;
154                 delete aspell_checker_;
155                 delete enchant_checker_;
156                 delete hunspell_checker_;
157         }
158
159         ///
160         BufferList buffer_list_;
161         ///
162         KeyMap toplevel_keymap_;
163         ///
164         CmdDef toplevel_cmddef_;
165         ///
166         boost::scoped_ptr<Server> lyx_server_;
167         ///
168         boost::scoped_ptr<ServerSocket> lyx_socket_;
169         ///
170         boost::scoped_ptr<frontend::Application> application_;
171         /// lyx session, containing lastfiles, lastfilepos, and lastopened
172         boost::scoped_ptr<Session> session_;
173
174         /// Files to load at start.
175         vector<string> files_to_load_;
176
177         /// The messages translators.
178         map<string, Messages> messages_;
179
180         /// The file converters.
181         Converters converters_;
182
183         // The system converters copy after reading lyxrc.defaults.
184         Converters system_converters_;
185
186         ///
187         Movers movers_;
188         ///
189         Movers system_movers_;
190
191         /// has this user started lyx for the first time?
192         bool first_start;
193         /// the parsed command line batch command if any
194         vector<string> batch_commands;
195
196         ///
197         graphics::Previews preview_;
198         ///
199         SpellChecker * spell_checker_;
200         ///
201         SpellChecker * apple_spell_checker_;
202         ///
203         SpellChecker * aspell_checker_;
204         ///
205         SpellChecker * enchant_checker_;
206         ///
207         SpellChecker * hunspell_checker_;
208 };
209
210 ///
211 frontend::Application * theApp()
212 {
213         if (singleton_)
214                 return singleton_->pimpl_->application_.get();
215         else
216                 return 0;
217 }
218
219
220 LyX::~LyX()
221 {
222         delete pimpl_;
223         singleton_ = 0;
224 }
225
226
227 void lyx_exit(int exit_code)
228 {
229         if (exit_code)
230                 // Something wrong happened so better save everything, just in
231                 // case.
232                 emergencyCleanup();
233
234 #ifndef NDEBUG
235         // Properly crash in debug mode in order to get a useful backtrace.
236         abort();
237 #endif
238
239         // In release mode, try to exit gracefully.
240         if (theApp())
241                 theApp()->exit(exit_code);
242         else
243                 exit(exit_code);
244 }
245
246
247 LyX::LyX()
248         : first_start(false)
249 {
250         singleton_ = this;
251         pimpl_ = new Impl;
252 }
253
254
255 Messages & LyX::messages(string const & language)
256 {
257         map<string, Messages>::iterator it = pimpl_->messages_.find(language);
258
259         if (it != pimpl_->messages_.end())
260                 return it->second;
261
262         pair<map<string, Messages>::iterator, bool> result =
263                         pimpl_->messages_.insert(make_pair(language, Messages(language)));
264
265         LASSERT(result.second, /**/);
266         return result.first->second;
267 }
268
269
270 void setRcGuiLanguage()
271 {
272         LASSERT(singleton_, /**/);
273         if (lyxrc.gui_language == "auto")
274                 return;
275         Language const * language = languages.getLanguage(lyxrc.gui_language);
276         if (language) {
277                 LYXERR(Debug::LOCALE, "Setting LANGUAGE to " << language->code());
278                 if (!setEnv("LANGUAGE", language->code()))
279                         LYXERR(Debug::LOCALE, "\t... failed!");
280         }
281         LYXERR(Debug::LOCALE, "Setting LC_ALL to en_US");
282         if (!setEnv("LC_ALL", "en_US"))
283                 LYXERR(Debug::LOCALE, "\t... failed!");
284         Messages::init();
285         singleton_->pimpl_->messages_["GUI"] = Messages();
286 }
287
288
289 int LyX::exec(int & argc, char * argv[])
290 {
291         // Minimal setting of locale before parsing command line
292         try {
293                 init_package(os::utf8_argv(0), string(), string(),
294                         top_build_dir_is_one_level_up);
295         } catch (ExceptionMessage const & message) {
296                 LYXERR(Debug::LOCALE, message.title_ + ", " + message.details_);
297 #ifdef _WIN32
298                 // no console and no Qt here so use a simple message box
299                 MessageBoxA(0, to_ascii(message.details_).c_str(), to_ascii(message.title_).c_str(), 0);
300                 return 1;
301 #endif
302         }
303         locale_init();
304
305         // Here we need to parse the command line. At least
306         // we need to parse for "-dbg" and "-help"
307         easyParse(argc, argv);
308
309         try {
310                 init_package(os::utf8_argv(0),
311                         cl_system_support, cl_user_support,
312                         top_build_dir_is_one_level_up);
313         } catch (ExceptionMessage const & message) {
314                 if (message.type_ == ErrorException) {
315                         Alert::error(message.title_, message.details_);
316                         lyx_exit(1);
317                 } else if (message.type_ == WarningException) {
318                         Alert::warning(message.title_, message.details_);
319                 }
320         }
321
322         // Reinit the messages machinery in case package() knows
323         // something interesting about the locale directory.
324         Messages::init();
325
326         if (!use_gui) {
327                 // FIXME: create a ConsoleApplication
328                 int exit_status = init(argc, argv);
329                 if (exit_status) {
330                         prepareExit();
331                         return exit_status;
332                 }
333
334                 // this is correct, since return values are inverted.
335                 exit_status = !loadFiles();
336
337                 if (pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
338                         prepareExit();
339                         return exit_status;
340                 }
341
342                 BufferList::iterator begin = pimpl_->buffer_list_.begin();
343
344                 bool final_success = false;
345                 for (BufferList::iterator I = begin; I != pimpl_->buffer_list_.end(); ++I) {
346                         Buffer * buf = *I;
347                         if (buf != buf->masterBuffer())
348                                 continue;
349                         vector<string>::const_iterator bcit  = pimpl_->batch_commands.begin();
350                         vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
351                         DispatchResult dr;
352                         for (; bcit != bcend; bcit++) {
353                                 LYXERR(Debug::ACTION, "Buffer::dispatch: cmd: " << *bcit);
354                                 buf->dispatch(*bcit, dr);
355                                 final_success |= !dr.error();
356                         }
357                 }
358                 prepareExit();
359                 return !final_success;
360         }
361
362         // Let the frontend parse and remove all arguments that it knows
363         pimpl_->application_.reset(createApplication(argc, argv));
364
365         // Reestablish our defaults, as Qt overwrites them
366         // after createApplication()
367         locale_init();
368
369         // Parse and remove all known arguments in the LyX singleton
370         // Give an error for all remaining ones.
371         int exit_status = init(argc, argv);
372         if (exit_status) {
373                 // Kill the application object before exiting.
374                 pimpl_->application_.reset();
375                 use_gui = false;
376                 prepareExit();
377                 return exit_status;
378         }
379
380         // If not otherwise specified by a command line option or
381         // by preferences, we default to reuse a running instance.
382         if (run_mode == PREFERRED)
383                 run_mode = USE_REMOTE;
384
385         // FIXME
386         /* Create a CoreApplication class that will provide the main event loop
387         * and the socket callback registering. With Qt4, only QtCore
388         * library would be needed.
389         * When this is done, a server_mode could be created and the following two
390         * line would be moved out from here.
391         * However, note that the first of the two lines below triggers the
392         * "single instance" behavior, which should occur right at this point.
393         */
394         // Note: socket callback must be registered after init(argc, argv)
395         // such that package().temp_dir() is properly initialized.
396         pimpl_->lyx_server_.reset(new Server(lyxrc.lyxpipes));
397         pimpl_->lyx_socket_.reset(new ServerSocket(
398                         FileName(package().temp_dir().absFileName() + "/lyxsocket")));
399
400         // Start the real execution loop.
401         if (!theServer().deferredLoadingToOtherInstance())
402                 exit_status = pimpl_->application_->exec();
403         else if (!pimpl_->files_to_load_.empty()) {
404                 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
405                 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
406                 lyxerr << _("The following files could not be loaded:") << endl;
407                 for (; it != end; ++it)
408                         lyxerr << *it << endl;
409         }
410
411         prepareExit();
412
413         return exit_status;
414 }
415
416
417 void LyX::prepareExit()
418 {
419         // Clear the clipboard and selection stack:
420         cap::clearCutStack();
421         cap::clearSelection();
422
423         // Write the index file of the converter cache
424         ConverterCache::get().writeIndex();
425
426         // close buffers first
427         pimpl_->buffer_list_.closeAll();
428
429         // register session changes and shutdown server and socket
430         if (use_gui) {
431                 if (pimpl_->session_)
432                         pimpl_->session_->writeFile();
433                 pimpl_->session_.reset();
434                 pimpl_->lyx_server_.reset();
435                 pimpl_->lyx_socket_.reset();
436         }
437
438         // do any other cleanup procedures now
439         if (package().temp_dir() != package().system_temp_dir()) {
440                 string const abs_tmpdir = package().temp_dir().absFileName();
441                 if (!contains(package().temp_dir().absFileName(), "lyx_tmpdir")) {
442                         docstring const msg =
443                                 bformat(_("%1$s does not appear like a LyX created temporary directory."),
444                                 from_utf8(abs_tmpdir));
445                         Alert::warning(_("Cannot remove temporary directory"), msg);
446                 } else {
447                         LYXERR(Debug::INFO, "Deleting tmp dir "
448                                 << package().temp_dir().absFileName());
449                         if (!package().temp_dir().destroyDirectory()) {
450                                 docstring const msg =
451                                         bformat(_("Unable to remove the temporary directory %1$s"),
452                                         from_utf8(package().temp_dir().absFileName()));
453                                 Alert::warning(_("Unable to remove temporary directory"), msg);
454                         }
455                 }
456         }
457
458         // Kill the application object before exiting. This avoids crashes
459         // when exiting on Linux.
460         if (pimpl_->application_)
461                 pimpl_->application_.reset();
462 }
463
464
465 void LyX::earlyExit(int status)
466 {
467         LASSERT(pimpl_->application_.get(), /**/);
468         // LyX::pimpl_::application_ is not initialised at this
469         // point so it's safe to just exit after some cleanup.
470         prepareExit();
471         exit(status);
472 }
473
474
475 int LyX::init(int & argc, char * argv[])
476 {
477         // check for any spurious extra arguments
478         // other than documents
479         for (int argi = 1; argi < argc ; ++argi) {
480                 if (argv[argi][0] == '-') {
481                         lyxerr << to_utf8(
482                                 bformat(_("Wrong command line option `%1$s'. Exiting."),
483                                 from_utf8(os::utf8_argv(argi)))) << endl;
484                         return EXIT_FAILURE;
485                 }
486         }
487
488         // Initialization of LyX (reads lyxrc and more)
489         LYXERR(Debug::INIT, "Initializing LyX::init...");
490         bool success = init();
491         LYXERR(Debug::INIT, "Initializing LyX::init...done");
492         if (!success)
493                 return EXIT_FAILURE;
494
495         // Remaining arguments are assumed to be files to load.
496         for (int argi = 1; argi < argc; ++argi)
497                 pimpl_->files_to_load_.push_back(os::utf8_argv(argi));
498
499         if (first_start) {
500                 pimpl_->files_to_load_.push_back(
501                         i18nLibFileSearch("examples", "splash.lyx").absFileName());
502         }
503
504         return EXIT_SUCCESS;
505 }
506
507
508 bool LyX::loadFiles()
509 {
510         LASSERT(!use_gui, /**/);
511         bool success = true;
512         vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
513         vector<string>::const_iterator end = pimpl_->files_to_load_.end();
514
515         for (; it != end; ++it) {
516                 // get absolute path of file and add ".lyx" to
517                 // the filename if necessary
518                 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
519                         may_not_exist);
520
521                 if (fname.empty())
522                         continue;
523
524                 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFileName(), false);
525                 if (buf->loadLyXFile() == Buffer::ReadSuccess) {
526                         ErrorList const & el = buf->errorList("Parse");
527                         if (!el.empty())
528                                 for_each(el.begin(), el.end(),
529                                 bind(&LyX::printError, this, _1));
530                 }
531                 else {
532                         pimpl_->buffer_list_.release(buf);
533                         success = false;
534                 }
535         }
536         return success;
537 }
538
539
540 void execBatchCommands()
541 {
542         LASSERT(singleton_, /**/);
543         singleton_->execCommands();
544 }
545
546
547 void LyX::execCommands()
548 {
549         // The advantage of doing this here is that the event loop
550         // is already started. So any need for interaction will be
551         // aknowledged.
552
553         // if reconfiguration is needed.
554         if (LayoutFileList::get().empty()) {
555                 switch (Alert::prompt(
556                         _("No textclass is found"),
557                         _("LyX will only have minimal functionality because no textclasses "
558                                 "have been found. You can either try to reconfigure LyX normally, "
559                                 "try to reconfigure without checking your LaTeX installation, or continue."),
560                         0, 2,
561                         _("&Reconfigure"),
562                         _("&Without LaTeX"),
563                         _("&Continue")))
564                 {
565                 case 0:
566                         // regular reconfigure
567                         lyx::dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
568                         break;
569                 case 1:
570                         // reconfigure --without-latex-config
571                         lyx::dispatch(FuncRequest(LFUN_RECONFIGURE,
572                                 " --without-latex-config"));
573                         break;
574                 default:
575                         break;
576                 }
577         }
578
579         // create the first main window
580         lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
581
582         if (!pimpl_->files_to_load_.empty()) {
583                 // if some files were specified at command-line we assume that the
584                 // user wants to edit *these* files and not to restore the session.
585                 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
586                         lyx::dispatch(
587                                 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
588                 }
589                 // clear this list to save a few bytes of RAM
590                 pimpl_->files_to_load_.clear();
591         } else
592                 pimpl_->application_->restoreGuiSession();
593
594         // Execute batch commands if available
595         if (pimpl_->batch_commands.empty())
596                 return;
597
598         vector<string>::const_iterator bcit  = pimpl_->batch_commands.begin();
599         vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
600         for (; bcit != bcend; bcit++) {
601                 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
602                 lyx::dispatch(lyxaction.lookupFunc(*bcit));
603         }
604 }
605
606
607 /*
608 Signals and Windows
609 ===================
610 The SIGHUP signal does not exist on Windows and does not need to be handled.
611
612 Windows handles SIGFPE and SIGSEGV signals as expected.
613
614 Ctrl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
615 cause a new thread to be spawned. This may well result in unexpected
616 behaviour by the single-threaded LyX.
617
618 SIGTERM signals will come only from another process actually sending
619 that signal using 'raise' in Windows' POSIX compatability layer. It will
620 not come from the general "terminate process" methods that everyone
621 actually uses (and which can't be trapped). Killing an app 'politely' on
622 Windows involves first sending a WM_CLOSE message, something that is
623 caught already by the Qt frontend.
624
625 For more information see:
626
627 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
628 ...signals are mostly useless on Windows for a variety of reasons that are
629 Windows specific...
630
631 'UNIX Application Migration Guide, Chapter 9'
632 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
633
634 'How To Terminate an Application "Cleanly" in Win32'
635 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
636 */
637 extern "C" {
638
639 static void error_handler(int err_sig)
640 {
641         // Throw away any signals other than the first one received.
642         static sig_atomic_t handling_error = false;
643         if (handling_error)
644                 return;
645         handling_error = true;
646
647         // We have received a signal indicating a fatal error, so
648         // try and save the data ASAP.
649         emergencyCleanup();
650
651         // These lyxerr calls may or may not work:
652
653         // Signals are asynchronous, so the main program may be in a very
654         // fragile state when a signal is processed and thus while a signal
655         // handler function executes.
656         // In general, therefore, we should avoid performing any
657         // I/O operations or calling most library and system functions from
658         // signal handlers.
659
660         // This shouldn't matter here, however, as we've already invoked
661         // emergencyCleanup.
662         docstring msg;
663         switch (err_sig) {
664 #ifdef SIGHUP
665         case SIGHUP:
666                 msg = _("SIGHUP signal caught!\nBye.");
667                 break;
668 #endif
669         case SIGFPE:
670                 msg = _("SIGFPE signal caught!\nBye.");
671                 break;
672         case SIGSEGV:
673                 msg = _("SIGSEGV signal caught!\n"
674                           "Sorry, you have found a bug in LyX, "
675                           "hope you have not lost any data.\n"
676                           "Please read the bug-reporting instructions "
677                           "in 'Help->Introduction' and send us a bug report, "
678                           "if necessary. Thanks!\nBye.");
679                 break;
680         case SIGINT:
681         case SIGTERM:
682                 // no comments
683                 break;
684         }
685
686         if (!msg.empty()) {
687                 lyxerr << "\nlyx: " << msg << endl;
688                 // try to make a GUI message
689                 Alert::error(_("LyX crashed!"), msg);
690         }
691
692         // Deinstall the signal handlers
693 #ifdef SIGHUP
694         signal(SIGHUP, SIG_DFL);
695 #endif
696         signal(SIGINT, SIG_DFL);
697         signal(SIGFPE, SIG_DFL);
698         signal(SIGSEGV, SIG_DFL);
699         signal(SIGTERM, SIG_DFL);
700
701 #ifdef SIGHUP
702         if (err_sig == SIGSEGV ||
703                 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty())) {
704 #else
705         if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty()) {
706 #endif
707 #ifdef _MSC_VER
708                 // with abort() it crashes again.
709                 exit(err_sig);
710 #else
711                 abort();
712 #endif
713         }
714
715         exit(0);
716 }
717
718 }
719
720
721 void LyX::printError(ErrorItem const & ei)
722 {
723         docstring tmp = _("LyX: ") + ei.error + char_type(':')
724                 + ei.description;
725         cerr << to_utf8(tmp) << endl;
726 }
727
728
729 bool LyX::init()
730 {
731 #ifdef SIGHUP
732         signal(SIGHUP, error_handler);
733 #endif
734         signal(SIGFPE, error_handler);
735         signal(SIGSEGV, error_handler);
736         signal(SIGINT, error_handler);
737         signal(SIGTERM, error_handler);
738         // SIGPIPE can be safely ignored.
739
740         lyxrc.tempdir_path = package().temp_dir().absFileName();
741         lyxrc.document_path = package().document_dir().absFileName();
742
743         if (lyxrc.example_path.empty()) {
744                 lyxrc.example_path = addPath(package().system_support().absFileName(),
745                                               "examples");
746         }
747         if (lyxrc.template_path.empty()) {
748                 lyxrc.template_path = addPath(package().system_support().absFileName(),
749                                               "templates");
750         }
751
752         // init LyXDir environment variable
753         string const lyx_dir = package().lyx_dir().absFileName();
754         LYXERR(Debug::INIT, "Setting LyXDir... to \"" << lyx_dir << "\"");
755         if (!setEnv("LyXDir", lyx_dir))
756                 LYXERR(Debug::INIT, "\t... failed!");
757
758         //
759         // Read configuration files
760         //
761
762         // This one may have been distributed along with LyX.
763         if (!readRcFile("lyxrc.dist"))
764                 return false;
765
766         // Set the language defined by the distributor.
767         setRcGuiLanguage();
768
769         // Set the PATH correctly.
770 #if !defined (USE_POSIX_PACKAGING)
771         // Add the directory containing the LyX executable to the path
772         // so that LyX can find things like tex2lyx.
773         if (package().build_support().empty())
774                 prependEnvPath("PATH", package().binary_dir().absFileName());
775 #endif
776         if (!lyxrc.path_prefix.empty())
777                 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
778
779         // Check that user LyX directory is ok.
780         if (queryUserLyXDir(package().explicit_user_support()))
781                 reconfigureUserLyXDir();
782
783         if (!use_gui) {
784                 // No need for a splash when there is no GUI
785                 first_start = false;
786                 // Default is to overwrite the main file during export, unless
787                 // the -f switch was specified or LYX_FORCE_OVERWRITE was set
788                 if (force_overwrite == UNSPECIFIED) {
789                         string const what = getEnv("LYX_FORCE_OVERWRITE");
790                         if (what == "all")
791                                 force_overwrite = ALL_FILES;
792                         else if (what == "none")
793                                 force_overwrite = NO_FILES;
794                         else
795                                 force_overwrite = MAIN_FILE;
796                 }
797         }
798
799         // This one is generated in user_support directory by lib/configure.py.
800         if (!readRcFile("lyxrc.defaults"))
801                 return false;
802
803         // Query the OS to know what formats are viewed natively
804         formats.setAutoOpen();
805
806         // Read lyxrc.dist again to be able to override viewer auto-detection.
807         readRcFile("lyxrc.dist");
808
809         // Set again the language defined by the distributor.
810         setRcGuiLanguage();
811
812         system_lyxrc = lyxrc;
813         system_formats = formats;
814         pimpl_->system_converters_ = pimpl_->converters_;
815         pimpl_->system_movers_ = pimpl_->movers_;
816         system_lcolor = lcolor;
817
818         // This one is edited through the preferences dialog.
819         if (!readRcFile("preferences", true))
820                 return false;
821
822         if (!readEncodingsFile("encodings", "unicodesymbols"))
823                 return false;
824         if (!readLanguagesFile("languages"))
825                 return false;
826
827         // Set the language defined by the user.
828         setRcGuiLanguage();
829
830         LYXERR(Debug::INIT, "Reading layouts...");
831         // Load the layouts
832         LayoutFileList::get().read();
833         //...and the modules
834         theModuleList.read();
835
836         // read keymap and ui files in batch mode as well
837         // because InsetInfo needs to know these to produce
838         // the correct output
839
840         // Set up command definitions
841         pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
842
843         // FIXME
844         // Set up bindings
845         pimpl_->toplevel_keymap_.read("site");
846         pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
847         // load user bind file user.bind
848         pimpl_->toplevel_keymap_.read("user", 0, KeyMap::MissingOK);
849
850         if (lyxerr.debugging(Debug::LYXRC))
851                 lyxrc.print();
852
853         os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
854         if (!lyxrc.path_prefix.empty())
855                 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
856
857         FileName const document_path(lyxrc.document_path);
858         if (document_path.exists() && document_path.isDirectory())
859                 package().document_dir() = document_path;
860
861         package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
862         if (package().temp_dir().empty()) {
863                 Alert::error(_("Could not create temporary directory"),
864                              bformat(_("Could not create a temporary directory in\n"
865                                                        "\"%1$s\"\n"
866                                                            "Make sure that this path exists and is writable and try again."),
867                                      from_utf8(lyxrc.tempdir_path)));
868                 // createLyXTmpDir() tries sufficiently hard to create a
869                 // usable temp dir, so the probability to come here is
870                 // close to zero. We therefore don't try to overcome this
871                 // problem with e.g. asking the user for a new path and
872                 // trying again but simply exit.
873                 return false;
874         }
875
876         LYXERR(Debug::INIT, "LyX tmp dir: `"
877                             << package().temp_dir().absFileName() << '\'');
878
879         LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
880         pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
881
882         // This must happen after package initialization and after lyxrc is
883         // read, therefore it can't be done by a static object.
884         ConverterCache::init();
885
886         return true;
887 }
888
889
890 void emergencyCleanup()
891 {
892         // what to do about tmpfiles is non-obvious. we would
893         // like to delete any we find, but our lyxdir might
894         // contain documents etc. which might be helpful on
895         // a crash
896
897         singleton_->pimpl_->buffer_list_.emergencyWriteAll();
898         if (use_gui) {
899                 if (singleton_->pimpl_->lyx_server_)
900                         singleton_->pimpl_->lyx_server_->emergencyCleanup();
901                 singleton_->pimpl_->lyx_server_.reset();
902                 singleton_->pimpl_->lyx_socket_.reset();
903         }
904 }
905
906
907 // return true if file does not exist or is older than configure.py.
908 static bool needsUpdate(string const & file)
909 {
910         // We cannot initialize configure_script directly because the package
911         // is not initialized yet when  static objects are constructed.
912         static FileName configure_script;
913         static bool firstrun = true;
914         if (firstrun) {
915                 configure_script =
916                         FileName(addName(package().system_support().absFileName(),
917                                 "configure.py"));
918                 firstrun = false;
919         }
920
921         FileName absfile =
922                 FileName(addName(package().user_support().absFileName(), file));
923         return !absfile.exists()
924                 || configure_script.lastModified() > absfile.lastModified();
925 }
926
927
928 bool LyX::queryUserLyXDir(bool explicit_userdir)
929 {
930         // Does user directory exist?
931         FileName const sup = package().user_support();
932         if (sup.exists() && sup.isDirectory()) {
933                 first_start = false;
934
935                 return needsUpdate("lyxrc.defaults")
936                         || needsUpdate("lyxmodules.lst")
937                         || needsUpdate("textclass.lst")
938                         || needsUpdate("packages.lst");
939         }
940
941         first_start = !explicit_userdir;
942
943         // If the user specified explicitly a directory, ask whether
944         // to create it. If the user says "no", then exit.
945         if (explicit_userdir &&
946             Alert::prompt(
947                     _("Missing user LyX directory"),
948                     bformat(_("You have specified a non-existent user "
949                                            "LyX directory, %1$s.\n"
950                                            "It is needed to keep your own configuration."),
951                             from_utf8(package().user_support().absFileName())),
952                     1, 0,
953                     _("&Create directory"),
954                     _("&Exit LyX"))) {
955                 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
956                 earlyExit(EXIT_FAILURE);
957         }
958
959         lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
960                           from_utf8(sup.absFileName()))) << endl;
961
962         if (!sup.createDirectory(0755)) {
963                 // Failed, so let's exit.
964                 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
965                        << endl;
966                 earlyExit(EXIT_FAILURE);
967         }
968
969         return true;
970 }
971
972
973 bool LyX::readRcFile(string const & name, bool check_format)
974 {
975         LYXERR(Debug::INIT, "About to read " << name << "... ");
976
977         FileName const lyxrc_path = libFileSearch(string(), name);
978         if (lyxrc_path.empty()) {
979                 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
980                 // FIXME
981                 // This was the previous logic, but can it be right??
982                 return true;
983         }
984         LYXERR(Debug::INIT, "Found in " << lyxrc_path);
985         bool const success = lyxrc.read(lyxrc_path, check_format);
986         if (!success)
987                 showFileError(name);
988         return success;
989 }
990
991 // Read the languages file `name'
992 bool LyX::readLanguagesFile(string const & name)
993 {
994         LYXERR(Debug::INIT, "About to read " << name << "...");
995
996         FileName const lang_path = libFileSearch(string(), name);
997         if (lang_path.empty()) {
998                 showFileError(name);
999                 return false;
1000         }
1001         languages.read(lang_path);
1002         return true;
1003 }
1004
1005
1006 // Read the encodings file `name'
1007 bool LyX::readEncodingsFile(string const & enc_name,
1008                             string const & symbols_name)
1009 {
1010         LYXERR(Debug::INIT, "About to read " << enc_name << " and "
1011                             << symbols_name << "...");
1012
1013         FileName const symbols_path = libFileSearch(string(), symbols_name);
1014         if (symbols_path.empty()) {
1015                 showFileError(symbols_name);
1016                 return false;
1017         }
1018
1019         FileName const enc_path = libFileSearch(string(), enc_name);
1020         if (enc_path.empty()) {
1021                 showFileError(enc_name);
1022                 return false;
1023         }
1024         encodings.read(enc_path, symbols_path);
1025         return true;
1026 }
1027
1028
1029 namespace {
1030
1031 /// return the the number of arguments consumed
1032 typedef boost::function<int(string const &, string const &, string &)> cmd_helper;
1033
1034 int parse_dbg(string const & arg, string const &, string &)
1035 {
1036         if (arg.empty()) {
1037                 lyxerr << to_utf8(_("List of supported debug flags:")) << endl;
1038                 Debug::showTags(lyxerr);
1039                 exit(0);
1040         }
1041         lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1042
1043         lyxerr.setLevel(Debug::value(arg));
1044         Debug::showLevel(lyxerr, lyxerr.level());
1045         return 1;
1046 }
1047
1048
1049 int parse_help(string const &, string const &, string &)
1050 {
1051         lyxerr <<
1052                 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1053                   "Command line switches (case sensitive):\n"
1054                   "\t-help              summarize LyX usage\n"
1055                   "\t-userdir dir       set user directory to dir\n"
1056                   "\t-sysdir dir        set system directory to dir\n"
1057                   "\t-geometry WxH+X+Y  set geometry of the main window\n"
1058                   "\t-dbg feature[,feature]...\n"
1059                   "                  select the features to debug.\n"
1060                   "                  Type `lyx -dbg' to see the list of features\n"
1061                   "\t-x [--execute] command\n"
1062                   "                  where command is a lyx command.\n"
1063                   "\t-e [--export] fmt\n"
1064                   "                  where fmt is the export format of choice.\n"
1065                   "                  Look on Tools->Preferences->File formats->Format\n"
1066                   "                  to get an idea which parameters should be passed.\n"
1067                   "                  Note that the order of -e and -x switches matters.\n"
1068                   "\t-i [--import] fmt file.xxx\n"
1069                   "                  where fmt is the import format of choice\n"
1070                   "                  and file.xxx is the file to be imported.\n"
1071                   "\t-f [--force-overwrite] what\n"
1072                   "                  where what is either `all', `main' or `none',\n"
1073                   "                  specifying whether all files, main file only, or no files,\n"
1074                   "                  respectively, are to be overwritten during a batch export.\n"
1075                   "                  Anything else is equivalent to `all', but is not consumed.\n"
1076                   "\t-n [--no-remote]\n"
1077                   "                  open documents in a new instance\n"
1078                   "\t-r [--remote]\n"
1079                   "                  open documents in an already running instance\n"
1080                   "                  (a working lyxpipe is needed)\n"
1081                   "\t-batch    execute commands without launching GUI and exit.\n"
1082                   "\t-version  summarize version and build info\n"
1083                                "Check the LyX man page for more details.")) << endl;
1084         exit(0);
1085         return 0;
1086 }
1087
1088
1089 int parse_version(string const &, string const &, string &)
1090 {
1091         lyxerr << "LyX " << lyx_version
1092                << " (" << lyx_release_date << ")" << endl;
1093         lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
1094
1095         lyxerr << lyx_version_info << endl;
1096         exit(0);
1097         return 0;
1098 }
1099
1100
1101 int parse_sysdir(string const & arg, string const &, string &)
1102 {
1103         if (arg.empty()) {
1104                 Alert::error(_("No system directory"),
1105                         _("Missing directory for -sysdir switch"));
1106                 exit(1);
1107         }
1108         cl_system_support = arg;
1109         return 1;
1110 }
1111
1112
1113 int parse_userdir(string const & arg, string const &, string &)
1114 {
1115         if (arg.empty()) {
1116                 Alert::error(_("No user directory"),
1117                         _("Missing directory for -userdir switch"));
1118                 exit(1);
1119         }
1120         cl_user_support = arg;
1121         return 1;
1122 }
1123
1124
1125 int parse_execute(string const & arg, string const &, string & batch)
1126 {
1127         if (arg.empty()) {
1128                 Alert::error(_("Incomplete command"),
1129                         _("Missing command string after --execute switch"));
1130                 exit(1);
1131         }
1132         batch = arg;
1133         return 1;
1134 }
1135
1136
1137 int parse_export(string const & type, string const &, string & batch)
1138 {
1139         if (type.empty()) {
1140                 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1141                                          "--export switch")) << endl;
1142                 exit(1);
1143         }
1144         batch = "buffer-export " + type;
1145         use_gui = false;
1146         return 1;
1147 }
1148
1149
1150 int parse_import(string const & type, string const & file, string & batch)
1151 {
1152         if (type.empty()) {
1153                 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1154                                          "--import switch")) << endl;
1155                 exit(1);
1156         }
1157         if (file.empty()) {
1158                 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1159                 exit(1);
1160         }
1161
1162         batch = "buffer-import " + type + ' ' + file;
1163         return 2;
1164 }
1165
1166
1167 int parse_geometry(string const & arg1, string const &, string &)
1168 {
1169         geometryArg = arg1;
1170         // don't remove "-geometry", it will be pruned out later in the
1171         // frontend if need be.
1172         return -1;
1173 }
1174
1175
1176 int parse_batch(string const &, string const &, string &)
1177 {
1178         use_gui = false;
1179         return 0;
1180 }
1181
1182
1183 int parse_noremote(string const &, string const &, string &)
1184 {
1185         run_mode = NEW_INSTANCE;
1186         return 0;
1187 }
1188
1189
1190 int parse_remote(string const &, string const &, string &)
1191 {
1192         run_mode = USE_REMOTE;
1193         return 0;
1194 }
1195
1196
1197 int parse_force(string const & arg, string const &, string &)
1198 {
1199         if (arg == "all") {
1200                 force_overwrite = ALL_FILES;
1201                 return 1;
1202         } else if (arg == "main") {
1203                 force_overwrite = MAIN_FILE;
1204                 return 1;
1205         } else if (arg == "none") {
1206                 force_overwrite = NO_FILES;
1207                 return 1;
1208         }
1209         force_overwrite = ALL_FILES;
1210         return 0;
1211 }
1212
1213
1214 } // namespace anon
1215
1216
1217 void LyX::easyParse(int & argc, char * argv[])
1218 {
1219         map<string, cmd_helper> cmdmap;
1220
1221         cmdmap["-dbg"] = parse_dbg;
1222         cmdmap["-help"] = parse_help;
1223         cmdmap["--help"] = parse_help;
1224         cmdmap["-version"] = parse_version;
1225         cmdmap["--version"] = parse_version;
1226         cmdmap["-sysdir"] = parse_sysdir;
1227         cmdmap["-userdir"] = parse_userdir;
1228         cmdmap["-x"] = parse_execute;
1229         cmdmap["--execute"] = parse_execute;
1230         cmdmap["-e"] = parse_export;
1231         cmdmap["--export"] = parse_export;
1232         cmdmap["-i"] = parse_import;
1233         cmdmap["--import"] = parse_import;
1234         cmdmap["-geometry"] = parse_geometry;
1235         cmdmap["-batch"] = parse_batch;
1236         cmdmap["-f"] = parse_force;
1237         cmdmap["--force-overwrite"] = parse_force;
1238         cmdmap["-n"] = parse_noremote;
1239         cmdmap["--no-remote"] = parse_noremote;
1240         cmdmap["-r"] = parse_remote;
1241         cmdmap["--remote"] = parse_remote;
1242
1243         for (int i = 1; i < argc; ++i) {
1244                 map<string, cmd_helper>::const_iterator it
1245                         = cmdmap.find(argv[i]);
1246
1247                 // don't complain if not found - may be parsed later
1248                 if (it == cmdmap.end())
1249                         continue;
1250
1251                 string const arg =
1252                         (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
1253                 string const arg2 =
1254                         (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
1255
1256                 string batch;
1257                 int const remove = 1 + it->second(arg, arg2, batch);
1258                 if (!batch.empty())
1259                         pimpl_->batch_commands.push_back(batch);
1260
1261                 // Now, remove used arguments by shifting
1262                 // the following ones remove places down.
1263                 if (remove > 0) {
1264                         os::remove_internal_args(i, remove);
1265                         argc -= remove;
1266                         for (int j = i; j < argc; ++j)
1267                                 argv[j] = argv[j + remove];
1268                         --i;
1269                 }
1270         }
1271 }
1272
1273
1274 FuncStatus getStatus(FuncRequest const & action)
1275 {
1276         LASSERT(theApp(), /**/);
1277         return theApp()->getStatus(action);
1278 }
1279
1280
1281 void dispatch(FuncRequest const & action)
1282 {
1283         LASSERT(theApp(), /**/);
1284         return theApp()->dispatch(action);
1285 }
1286
1287
1288 void dispatch(FuncRequest const & action, DispatchResult & dr)
1289 {
1290         LASSERT(theApp(), /**/);
1291         return theApp()->dispatch(action, dr);
1292 }
1293
1294
1295 vector<string> & theFilesToLoad()
1296 {
1297         LASSERT(singleton_, /**/);
1298         return singleton_->pimpl_->files_to_load_;
1299 }
1300
1301
1302 BufferList & theBufferList()
1303 {
1304         LASSERT(singleton_, /**/);
1305         return singleton_->pimpl_->buffer_list_;
1306 }
1307
1308
1309 Server & theServer()
1310 {
1311         // FIXME: this should not be use_gui dependent
1312         LASSERT(use_gui, /**/);
1313         LASSERT(singleton_, /**/);
1314         return *singleton_->pimpl_->lyx_server_.get();
1315 }
1316
1317
1318 ServerSocket & theServerSocket()
1319 {
1320         // FIXME: this should not be use_gui dependent
1321         LASSERT(use_gui, /**/);
1322         LASSERT(singleton_, /**/);
1323         return *singleton_->pimpl_->lyx_socket_.get();
1324 }
1325
1326
1327 KeyMap & theTopLevelKeymap()
1328 {
1329         LASSERT(singleton_, /**/);
1330         return singleton_->pimpl_->toplevel_keymap_;
1331 }
1332
1333
1334 Converters & theConverters()
1335 {
1336         LASSERT(singleton_, /**/);
1337         return  singleton_->pimpl_->converters_;
1338 }
1339
1340
1341 Converters & theSystemConverters()
1342 {
1343         LASSERT(singleton_, /**/);
1344         return  singleton_->pimpl_->system_converters_;
1345 }
1346
1347
1348 Movers & theMovers()
1349 {
1350         LASSERT(singleton_, /**/);
1351         return singleton_->pimpl_->movers_;
1352 }
1353
1354
1355 Mover const & getMover(string  const & fmt)
1356 {
1357         LASSERT(singleton_, /**/);
1358         return singleton_->pimpl_->movers_(fmt);
1359 }
1360
1361
1362 void setMover(string const & fmt, string const & command)
1363 {
1364         LASSERT(singleton_, /**/);
1365         singleton_->pimpl_->movers_.set(fmt, command);
1366 }
1367
1368
1369 Movers & theSystemMovers()
1370 {
1371         LASSERT(singleton_, /**/);
1372         return singleton_->pimpl_->system_movers_;
1373 }
1374
1375
1376 Messages const & getMessages(string const & language)
1377 {
1378         LASSERT(singleton_, /**/);
1379         return singleton_->messages(language);
1380 }
1381
1382
1383 Messages const & getGuiMessages()
1384 {
1385         LASSERT(singleton_, /**/);
1386         return singleton_->pimpl_->messages_["GUI"];
1387 }
1388
1389
1390 graphics::Previews & thePreviews()
1391 {
1392         LASSERT(singleton_, /**/);
1393         return singleton_->pimpl_->preview_;
1394 }
1395
1396
1397 Session & theSession()
1398 {
1399         LASSERT(singleton_, /**/);
1400         return *singleton_->pimpl_->session_.get();
1401 }
1402
1403
1404 CmdDef & theTopLevelCmdDef()
1405 {
1406         LASSERT(singleton_, /**/);
1407         return singleton_->pimpl_->toplevel_cmddef_;
1408 }
1409
1410
1411 SpellChecker * theSpellChecker()
1412 {
1413         if (!singleton_->pimpl_->spell_checker_)
1414                 setSpellChecker();
1415         return singleton_->pimpl_->spell_checker_;
1416 }
1417
1418
1419 void setSpellChecker()
1420 {
1421         SpellChecker::ChangeNumber speller_change_number =singleton_->pimpl_->spell_checker_ ?
1422                 singleton_->pimpl_->spell_checker_->changeNumber() : 0;
1423
1424         if (lyxrc.spellchecker == "native") {
1425 #if defined(USE_MACOSX_PACKAGING)
1426                 if (!singleton_->pimpl_->apple_spell_checker_)
1427                         singleton_->pimpl_->apple_spell_checker_ = new AppleSpellChecker();
1428                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->apple_spell_checker_;
1429 #else
1430                 singleton_->pimpl_->spell_checker_ = 0;
1431 #endif
1432         } else if (lyxrc.spellchecker == "aspell") {
1433 #if defined(USE_ASPELL)
1434                 if (!singleton_->pimpl_->aspell_checker_)
1435                         singleton_->pimpl_->aspell_checker_ = new AspellChecker();
1436                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->aspell_checker_;
1437 #else
1438                 singleton_->pimpl_->spell_checker_ = 0;
1439 #endif
1440         } else if (lyxrc.spellchecker == "enchant") {
1441 #if defined(USE_ENCHANT)
1442                 if (!singleton_->pimpl_->enchant_checker_)
1443                         singleton_->pimpl_->enchant_checker_ = new EnchantChecker();
1444                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->enchant_checker_;
1445 #else
1446                 singleton_->pimpl_->spell_checker_ = 0;
1447 #endif
1448         } else if (lyxrc.spellchecker == "hunspell") {
1449 #if defined(USE_HUNSPELL)
1450                 if (!singleton_->pimpl_->hunspell_checker_)
1451                         singleton_->pimpl_->hunspell_checker_ = new HunspellChecker();
1452                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->hunspell_checker_;
1453 #else
1454                 singleton_->pimpl_->spell_checker_ = 0;
1455 #endif
1456         } else {
1457                 singleton_->pimpl_->spell_checker_ = 0;
1458         }
1459         if (singleton_->pimpl_->spell_checker_) {
1460                 singleton_->pimpl_->spell_checker_->changeNumber(speller_change_number);
1461                 singleton_->pimpl_->spell_checker_->advanceChangeNumber();
1462         }
1463 }
1464
1465 } // namespace lyx