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