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