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