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