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