1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * ====================================================== */
17 #pragma implementation
25 #include "lyx_gui_misc.h"
27 #include "support/path.h"
28 #include "support/filetools.h"
29 #include "bufferlist.h"
31 #include "support/FileInfo.h"
32 #include "lastfiles.h"
34 #include "lyxserver.h"
38 #include "MenuBackend.h"
39 #include "ToolbarDefaults.h"
44 extern void LoadLyXFile(string const &);
45 extern void QuitLyX();
49 string system_tempdir;
50 string user_lyxdir; // Default $HOME/.lyx
52 // Should this be kept global? Asger says Yes.
55 LastFiles * lastfiles;
57 // This is the global bufferlist object
58 BufferList bufferlist;
60 LyXServer * lyxserver = 0;
61 // this should be static, but I need it in buffer.C
62 bool finished = false; // flag, that we are quitting the program
64 // convenient to have it here.
65 kb_keymap * toplevel_keymap;
68 LyX::LyX(int * argc, char * argv[])
70 // Prevent crash with --help
74 // Here we need to parse the command line. At least
75 // we need to parse for "-dbg" and "-help"
76 bool gui = easyParse(argc, argv);
78 // Global bindings (this must be done as early as possible.) (Lgb)
79 toplevel_keymap = new kb_keymap;
80 defaultKeyBindings(toplevel_keymap);
82 // Make the GUI object, and let it take care of the
83 // command line arguments that concerns it.
84 lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
85 lyxGUI = new LyXGUI(this, argc, argv, gui);
86 lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
88 // Now the GUI and LyX have taken care of their arguments, so
89 // the only thing left on the command line should be
90 // filenames. Let's check anyway.
91 for (int argi = 1; argi < *argc ; ++argi) {
92 if (argv[argi][0] == '-') {
93 lyxerr << _("Wrong command line option `")
95 << _("'. Exiting.") << endl;
100 // Initialization of LyX (reads lyxrc and more)
101 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
102 init(argc, argv, gui);
103 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
107 // Load the files specified in the command line.
109 lyxerr[Debug::INFO] << "Opening document..." << endl;
110 else if ((*argc) > 2)
111 lyxerr[Debug::INFO] << "Opening documents..." << endl;
113 Buffer * last_loaded = 0;
115 for (int argi = (*argc) - 1; argi >= 1; --argi) {
116 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
123 string splash = i18nLibFileSearch("examples", "splash.lyx");
124 lyxerr[Debug::INIT] << "Opening splash document "
125 << splash << "..." << endl;
126 Buffer * loadb = bufferlist.loadLyXFile(splash);
132 if (last_loaded != 0) {
133 lyxerr[Debug::INIT] << "Yes we loaded some files." << endl;
135 lyxGUI->regBuf(last_loaded);
138 // Execute batch commands if available
139 if (!batch_command.empty()) {
140 lyxerr << "About to handle -x '"
141 << batch_command << "'" << endl;
143 // no buffer loaded, create one
145 last_loaded = bufferlist.newFile("tmpfile", string());
147 // try to dispatch to last loaded buffer first
148 bool dispatched = last_loaded->Dispatch(batch_command);
150 // if this was successful, return.
151 // Maybe we could do something more clever than aborting...
153 lyxerr << "We are done!" << endl;
158 // otherwise, let the GUI handle the batch command
159 lyxGUI->regBuf(last_loaded);
160 lyxGUI->getLyXView()->getLyXFunc()->Dispatch(batch_command);
165 // Let the ball begin...
170 // A destructor is always necessary (asierra-970604)
178 extern "C" void error_handler(int err_sig);
180 void LyX::init(int */*argc*/, char **argv, bool gui)
182 // Install the signal handlers
183 signal(SIGHUP, error_handler);
184 signal(SIGFPE, error_handler);
185 signal(SIGSEGV, error_handler);
186 signal(SIGINT, error_handler);
187 signal(SIGTERM, error_handler);
190 // Determine path of binary
194 string binpath = subst(argv[0], '\\', '/');
195 string binname = OnlyFilename(argv[0]);
196 // Sorry for system specific code. (SMiyata)
197 if (suffixIs(binname, ".exe"))
198 binname.erase(binname.length()-4, string::npos);
200 binpath = ExpandPath(binpath); // This expands ./ and ~/
202 if (!AbsolutePath(binpath)) {
203 string binsearchpath = GetEnvPath("PATH");
204 // This will make "src/lyx" work always :-)
205 binsearchpath += ";.";
206 binpath = FileOpenSearch(binsearchpath, argv[0]);
209 fullbinpath = binpath;
210 binpath = MakeAbsPath(OnlyPath(binpath));
212 // In case we are running in place and compiled with shared libraries
213 if (suffixIs(binpath, "/.libs/"))
214 binpath.erase(binpath.length()-6, string::npos);
216 if (binpath.empty()) {
217 lyxerr << _("Warning: could not determine path of binary.")
219 << _("If you have problems, try starting LyX with an absolute path.")
222 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
225 // Determine system directory.
228 // Directories are searched in this order:
229 // 1) -sysdir command line parameter
230 // 2) LYX_DIR_11x environment variable
231 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
232 // 4) <path of binary>/../share/<name of binary>/
233 // 4a) repeat 4 after following the Symlink if <path of
234 // binary> is a symbolic link.
235 // 5) hardcoded lyx_dir
236 // The directory is checked for the presence of the file
237 // "chkconfig.ltx", and if that is present, the directory
238 // is accepted as the system directory.
239 // If no chkconfig.ltx file is found, a warning is given,
240 // and the hardcoded lyx_dir is used.
242 // If we had a command line switch, system_lyxdir is already set
244 if (!system_lyxdir.empty())
245 searchpath= MakeAbsPath(system_lyxdir) + ';';
247 // LYX_DIR_11x environment variable
248 string lyxdir = GetEnvPath("LYX_DIR_11x");
250 if (!lyxdir.empty()) {
251 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
252 searchpath += lyxdir + ';';
255 // <path of binary>/TOP_SRCDIR/lib
256 build_lyxdir = MakeAbsPath("../lib", binpath);
257 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
258 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
260 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
261 "place... yes" << endl;
264 << "Checking whether LyX is run in place... no"
266 build_lyxdir.erase();
271 // Path of binary/../share/name of binary/
272 searchpath += NormalizePath(AddPath(binpath, "../share/") +
273 OnlyFilename(binname)) + ';';
276 FileInfo file(fullbinpath, true);
277 FollowLink = file.isLink();
280 if (LyXReadLink(fullbinpath, Link)) {
282 binpath = MakeAbsPath(OnlyPath(fullbinpath));
288 } while (FollowLink);
291 searchpath += LYX_DIR;
293 // If debugging, show complete search path
294 lyxerr[Debug::INIT] << "System directory search path: "
295 << searchpath << endl;
297 string const filename = "chkconfig.ltx";
298 string temp = FileOpenSearch(searchpath, filename, string());
299 system_lyxdir = OnlyPath(temp);
301 // Reduce "path/../path" stuff out of system directory
302 system_lyxdir = NormalizePath(system_lyxdir);
304 bool path_shown = false;
306 // Warn if environment variable is set, but unusable
307 if (!lyxdir.empty()) {
308 if (system_lyxdir != NormalizePath(lyxdir)) {
309 lyxerr <<_("LYX_DIR_11x environment variable no good.")
311 << _("System directory set to: ")
312 << system_lyxdir << endl;
317 // Warn the user if we couldn't find "chkconfig.ltx"
318 if (system_lyxdir == "./") {
319 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
320 <<_("Try the '-sysdir' command line parameter or")
321 <<_("set the environment variable LYX_DIR_11x to the "
322 "LyX system directory")
323 << _("containing the file `chkconfig.ltx'.") << endl;
325 lyxerr << _("Using built-in default ")
326 << LYX_DIR << _(" but expect problems.")
329 lyxerr << _("Expect problems.") << endl;
330 system_lyxdir = LYX_DIR;
334 // Report the system directory if debugging is on
336 lyxerr[Debug::INIT] << "System directory: '"
337 << system_lyxdir << '\'' << endl;
340 // Determine user lyx-dir
343 // Directories are searched in this order:
344 // 1) -userdir command line parameter
345 // 2) LYX_USERDIR_11x environment variable
346 // 3) $HOME/.<name of binary>
348 // If we had a command line switch, user_lyxdir is already set
349 bool explicit_userdir = true;
350 if (user_lyxdir.empty()) {
352 // LYX_USERDIR_11x environment variable
353 user_lyxdir = GetEnvPath("LYX_USERDIR_11x");
356 if (user_lyxdir.empty())
357 user_lyxdir = AddPath(GetEnvPath("HOME"),
358 string(".") + PACKAGE);
359 explicit_userdir = false;
362 lyxerr[Debug::INIT] << "User LyX directory: '"
363 << user_lyxdir << '\'' << endl;
365 // Check that user LyX directory is ok.
366 queryUserLyXDir(explicit_userdir);
369 // Load the layouts first
372 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
376 // Shine up lyxrc defaults
379 // Default template path: system_dir/templates
380 if (lyxrc.template_path.empty()){
381 lyxrc.template_path = AddPath(system_lyxdir, "templates");
384 // Default lastfiles file: $HOME/.lyx/lastfiles
385 if (lyxrc.lastfiles.empty()){
386 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
389 // Disable gui when either lyxrc or easyparse says so
391 lyxrc.use_gui = false;
393 // Calculate screen dpi as average of x-DPI and y-DPI:
395 lyxrc.dpi = getScreenDPI();
396 lyxerr[Debug::INIT] << "DPI setting detected to be "
397 << lyxrc.dpi + 0.5 << endl;
399 lyxrc.dpi = 1; // I hope this is safe
403 // Read configuration files
406 ReadRcFile("lyxrc.defaults");
407 // system_lyxrc = lyxrc;
408 // If there is a preferences file we read that instead
409 // of the old lyxrc file.
410 if (!ReadRcFile("preferences"))
413 // Ensure that we have really read a bind file, so that LyX is
415 if (!lyxrc.hasBindFile)
416 lyxrc.ReadBindFile();
419 ReadUIFile(lyxrc.ui_file);
421 // Bind the X dead keys to the corresponding LyX functions if
423 if (lyxrc.override_x_deadkeys)
424 deadKeyBindings(toplevel_keymap);
426 if (lyxerr.debugging(Debug::LYXRC)) {
430 // Create temp directory
431 system_tempdir = CreateLyXTmpDir(lyxrc.tempdir_path);
432 if (lyxerr.debugging(Debug::INIT)) {
433 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
436 // load the lastfiles mini-database
437 lyxerr[Debug::INIT] << "Reading lastfiles `"
438 << lyxrc.lastfiles << "'..." << endl;
439 lastfiles = new LastFiles(lyxrc.lastfiles,
440 lyxrc.check_lastfiles,
441 lyxrc.num_lastfiles);
443 // start up the lyxserver. (is this a bit early?) (Lgb)
444 // 0.12 this will be way to early, we need the GUI to be initialized
445 // first, so move it for now.
446 // lyxserver = new LyXServer;
449 // These are the default bindings known to LyX
450 void LyX::defaultKeyBindings(kb_keymap * kbmap)
452 kbmap->bind("Right", LFUN_RIGHT);
453 kbmap->bind("Left", LFUN_LEFT);
454 kbmap->bind("Up", LFUN_UP);
455 kbmap->bind("Down", LFUN_DOWN);
457 kbmap->bind("Tab", LFUN_TAB);
459 kbmap->bind("Home", LFUN_HOME);
460 kbmap->bind("End", LFUN_END);
461 kbmap->bind("Prior", LFUN_PRIOR);
462 kbmap->bind("Next", LFUN_NEXT);
464 kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
465 kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
467 kbmap->bind("Delete", LFUN_DELETE);
468 kbmap->bind("BackSpace", LFUN_BACKSPACE);
470 // kbmap->bindings to enable the use of the numeric keypad
472 kbmap->bind("KP_0", LFUN_SELFINSERT);
473 kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
474 kbmap->bind("KP_Enter", LFUN_SELFINSERT);
475 kbmap->bind("KP_1", LFUN_SELFINSERT);
476 kbmap->bind("KP_2", LFUN_SELFINSERT);
477 kbmap->bind("KP_3", LFUN_SELFINSERT);
478 kbmap->bind("KP_4", LFUN_SELFINSERT);
479 kbmap->bind("KP_5", LFUN_SELFINSERT);
480 kbmap->bind("KP_6", LFUN_SELFINSERT);
481 kbmap->bind("KP_Add", LFUN_SELFINSERT);
482 kbmap->bind("KP_7", LFUN_SELFINSERT);
483 kbmap->bind("KP_8", LFUN_SELFINSERT);
484 kbmap->bind("KP_9", LFUN_SELFINSERT);
485 kbmap->bind("KP_Divide", LFUN_SELFINSERT);
486 kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
487 kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
489 /* Most self-insert keys are handled in the 'default:' section of
490 * WorkAreaKeyPress - so we don't have to define them all.
491 * However keys explicit decleared as self-insert are
492 * handled seperatly (LFUN_SELFINSERT.) Lgb. */
494 kbmap->bind("C-Tab", LFUN_TABINSERT); // ale970515
495 kbmap->bind("S-Tab", LFUN_SHIFT_TAB); // jug20000522
498 // LyX can optionally take over the handling of deadkeys
499 void LyX::deadKeyBindings(kb_keymap * kbmap)
501 // bindKeyings for transparent handling of deadkeys
502 // The keysyms are gotten from XFree86 X11R6
503 kbmap->bind("~C-~S-~M-dead_acute", LFUN_ACUTE);
504 kbmap->bind("~C-~S-~M-dead_breve", LFUN_BREVE);
505 kbmap->bind("~C-~S-~M-dead_caron", LFUN_CARON);
506 kbmap->bind("~C-~S-~M-dead_cedilla", LFUN_CEDILLA);
507 kbmap->bind("~C-~S-~M-dead_abovering", LFUN_CIRCLE);
508 kbmap->bind("~C-~S-~M-dead_circumflex", LFUN_CIRCUMFLEX);
509 kbmap->bind("~C-~S-~M-dead_abovedot", LFUN_DOT);
510 kbmap->bind("~C-~S-~M-dead_grave", LFUN_GRAVE);
511 kbmap->bind("~C-~S-~M-dead_doubleacute", LFUN_HUNG_UMLAUT);
512 kbmap->bind("~C-~S-~M-dead_macron", LFUN_MACRON);
513 // nothing with this name
514 // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
515 kbmap->bind("~C-~S-~M-dead_tilde", LFUN_TILDE);
516 kbmap->bind("~C-~S-~M-dead_diaeresis", LFUN_UMLAUT);
517 // nothing with this name either...
518 //kbmap->bind("~C-~S-~M-dead_underbar", LFUN_UNDERBAR);
519 kbmap->bind("~C-~S-~M-dead_belowdot", LFUN_UNDERDOT);
520 kbmap->bind("~C-~S-~M-dead_tie", LFUN_TIE);
521 kbmap->bind("~C-~S-~M-dead_ogonek", LFUN_OGONEK);
526 // This one is not allowed to use anything on the main form, since that
527 // one does not exist yet. (Asger)
528 void LyX::queryUserLyXDir(bool explicit_userdir)
530 // Does user directory exist?
531 FileInfo fileInfo(user_lyxdir);
532 if (fileInfo.isOK() && fileInfo.isDir()) {
540 // Different wording if the user specifically requested a directory
541 if (!AskQuestion( explicit_userdir
542 ? _("You have specified an invalid LyX directory.")
543 : _("You don't have a personal LyX directory.") ,
545 _("It is needed to keep your own configuration."),
546 _("Should I try to set it up for you (recommended)?"))) {
547 lyxerr << _("Running without personal LyX directory.") << endl;
548 // No, let's use $HOME instead.
549 user_lyxdir = GetEnvPath("HOME");
553 // Tell the user what is going on
554 lyxerr << _("LyX: Creating directory ") << user_lyxdir
555 << _(" and running configure...") << endl;
557 // Create directory structure
558 if (!createDirectory(user_lyxdir, 0755)) {
559 // Failed, let's use $HOME instead.
560 user_lyxdir = GetEnvPath("HOME");
561 lyxerr << _("Failed. Will use ") << user_lyxdir
562 << _(" instead.") << endl;
566 // Run configure in user lyx directory
568 ::system(AddName(system_lyxdir, "configure").c_str());
569 lyxerr << "LyX: " << _("Done!") << endl;
573 // Read the rc file `name'
574 bool LyX::ReadRcFile(string const & name)
576 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
578 string lyxrc_path = LibFileSearch(string(), name);
579 if (!lyxrc_path.empty()){
580 lyxerr[Debug::INIT] << "Found " << name
581 << " in " << lyxrc_path << endl;
582 if (lyxrc.read(lyxrc_path) < 0) {
583 WriteAlert(_("LyX Warning!"),
584 _("Error while reading ")+lyxrc_path+".",
585 _("Using built-in defaults."));
590 lyxerr[Debug::INIT] << "Could not find " << name << endl;
595 // Read the ui file `name'
596 void LyX::ReadUIFile(string const & name)
604 struct keyword_item uitags[ui_last-1] = {
605 { "menuset", ui_menuset },
606 { "toolbar", ui_toolbar }
609 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
611 string ui_path = LibFileSearch("ui", name, "ui");
613 if (ui_path.empty()) {
614 lyxerr[Debug::INIT] << "Could not find " << name << endl;
618 lyxerr[Debug::INIT] << "Found " << name
619 << " in " << ui_path << endl;
620 LyXLex lex(uitags, ui_last - 1);
621 lex.setFile(ui_path);
623 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
627 if (lyxerr.debugging(Debug::PARSER))
628 lex.printTable(lyxerr);
633 menubackend.read(lex);
637 toolbardefaults.read(lex);
641 lex.printError("LyX::ReadUFile: "
642 "Unknown menu tag: `$$Token'");
649 // Set debugging level and report result to user
650 void setDebuggingLevel(string const & dbgLevel)
652 lyxerr << _("Setting debug level to ") << dbgLevel << endl;
653 lyxerr.level(Debug::value(dbgLevel));
654 Debug::showLevel(lyxerr, lyxerr.level());
658 // Give command line help
659 void commandLineHelp()
661 lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
663 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
664 "Command line switches (case sensitive):\n"
665 "\t-help summarize LyX usage\n"
666 "\t-userdir dir try to set user directory to dir\n"
667 "\t-sysdir dir try to set system directory to dir\n"
668 "\t-geometry WxH+X+Y set geometry of the main window\n"
669 "\t-dbg feature[,feature]...\n"
670 " select the features to debug.\n"
671 " Type `lyx -dbg' to see the list of features\n"
672 "Check the LyX man page for more options.") << endl;
675 bool LyX::easyParse(int * argc, char * argv[])
678 int removeargs = 0; // used when options are read
679 for(int i = 1; i < *argc; ++i) {
680 string arg = argv[i];
682 // Check for -dbg int
685 setDebuggingLevel(argv[i + 1]);
688 lyxerr << _("List of supported debug flags:")
690 Debug::showTags(lyxerr);
694 // Check for "-sysdir"
695 else if (arg == "-sysdir") {
697 system_lyxdir = argv[i + 1];
700 lyxerr << _("Missing directory for -sysdir switch!")
705 // Check for "-userdir"
706 else if (arg == "-userdir") {
708 user_lyxdir = argv[i + 1];
711 lyxerr << _("Missing directory for -userdir switch!")
716 // Check for --help or -help
717 else if (arg == "--help" || arg == "-help") {
721 // Check for "-nw": No XWindows as for emacs this should
722 // give a LyX that could be used in a terminal window.
723 //else if (arg == "-nw") {
727 // Check for "-x": Execute commands
728 else if (arg == "-x" || arg == "--execute") {
730 batch_command = string(argv[i + 1]);
734 lyxerr << _("Missing command string after -x switch!") << endl;
736 // Argh. Setting gui to false segfaults..
740 else if (arg == "-e" || arg == "--export") {
742 string type(argv[i+1]);
744 batch_command = "buffer-export " + type;
747 lyxerr << _("Missing file type [eg latex, "
749 << arg << _(" switch!") << endl;
751 else if (arg == "--import") {
753 string type(argv[i+1]);
754 string file(argv[i+2]);
757 batch_command = "buffer-import " + type + " " + file;
758 lyxerr << "batch_command: "
759 << batch_command << endl;
762 lyxerr << _("Missing type [eg latex, "
764 << arg << _(" switch!") << endl;
767 if (removeargs > 0) {
768 // Now, remove used arguments by shifting
769 // the following ones removeargs places down.
770 (*argc) -= removeargs;
771 for (int j = i; j < (*argc); ++j)
772 argv[j] = argv[j + removeargs];
773 --i; // After shift, check this number again.
784 void error_handler(int err_sig)
788 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
794 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
797 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
799 "Sorry, you have found a bug in LyX."
800 " If possible, please read 'Known bugs'\n"
801 "under the Help menu and then send us "
802 "a full bug report. Thanks!" << endl;
809 // Deinstall the signal handlers
810 signal(SIGHUP, SIG_DFL);
811 signal(SIGINT, SIG_DFL);
812 signal(SIGFPE, SIG_DFL);
813 signal(SIGSEGV, SIG_DFL);
814 signal(SIGTERM, SIG_DFL);
816 bufferlist.emergencyWriteAll();
818 lyxerr << "Bye." << endl;
819 if(err_sig!= SIGHUP &&
820 (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))