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