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