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"
42 // only to get access to NEW_EXPORT
48 extern void LoadLyXFile(string const &);
49 extern void QuitLyX();
53 string system_tempdir;
54 string user_lyxdir; // Default $HOME/.lyx
56 // Should this be kept global? Asger says Yes.
59 LastFiles * lastfiles;
61 // This is the global bufferlist object
62 BufferList bufferlist;
64 LyXServer * lyxserver = 0;
65 // this should be static, but I need it in buffer.C
66 bool finished = false; // flag, that we are quitting the program
68 // convenient to have it here.
69 kb_keymap * toplevel_keymap;
72 LyX::LyX(int * argc, char * argv[])
74 // Prevent crash with --help
78 // Here we need to parse the command line. At least
79 // we need to parse for "-dbg" and "-help"
80 bool gui = easyParse(argc, argv);
82 // Global bindings (this must be done as early as possible.) (Lgb)
83 toplevel_keymap = new kb_keymap;
84 defaultKeyBindings(toplevel_keymap);
86 // Make the GUI object, and let it take care of the
87 // command line arguments that concerns it.
88 lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
89 lyxGUI = new LyXGUI(this, argc, argv, gui);
90 lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
92 // Now the GUI and LyX have taken care of their arguments, so
93 // the only thing left on the command line should be
94 // filenames. Let's check anyway.
95 for (int argi = 1; argi < *argc ; ++argi) {
96 if (argv[argi][0] == '-') {
97 lyxerr << _("Wrong command line option `")
99 << _("'. Exiting.") << endl;
104 // Initialization of LyX (reads lyxrc and more)
105 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
106 init(argc, argv, gui);
107 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
111 // Load the files specified in the command line.
113 lyxerr[Debug::INFO] << "Opening document..." << endl;
114 else if ((*argc) > 2)
115 lyxerr[Debug::INFO] << "Opening documents..." << endl;
117 Buffer * last_loaded = 0;
119 for (int argi = (*argc) - 1; argi >= 1; --argi) {
120 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
127 string splash = i18nLibFileSearch("examples", "splash.lyx");
128 lyxerr[Debug::INIT] << "Opening splash document "
129 << splash << "..." << endl;
130 Buffer * loadb = bufferlist.loadLyXFile(splash);
136 if (last_loaded != 0) {
137 lyxerr[Debug::INIT] << "Yes we loaded some files." << endl;
139 lyxGUI->regBuf(last_loaded);
142 // Execute batch commands if available
143 if (!batch_command.empty()) {
144 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
146 // no buffer loaded, create one
148 last_loaded = bufferlist.newFile("tmpfile", string());
150 // try to dispatch to last loaded buffer first
151 bool dispatched = last_loaded->Dispatch(batch_command);
153 // if this was successful, return.
154 // Maybe we could do something more clever than aborting...
156 lyxerr << "We are done!" << endl;
161 // otherwise, let the GUI handle the batch command
162 lyxGUI->regBuf(last_loaded);
163 lyxGUI->getLyXView()->getLyXFunc()->Dispatch(batch_command);
168 // Let the ball begin...
173 // A destructor is always necessary (asierra-970604)
181 extern "C" void error_handler(int err_sig);
183 void LyX::init(int */*argc*/, char **argv, bool gui)
185 // Install the signal handlers
186 signal(SIGHUP, error_handler);
187 signal(SIGFPE, error_handler);
188 signal(SIGSEGV, error_handler);
189 signal(SIGINT, error_handler);
190 signal(SIGTERM, error_handler);
193 // Determine path of binary
197 string binpath = subst(argv[0], '\\', '/');
198 string binname = OnlyFilename(argv[0]);
199 // Sorry for system specific code. (SMiyata)
200 if (suffixIs(binname, ".exe"))
201 binname.erase(binname.length()-4, string::npos);
203 binpath = ExpandPath(binpath); // This expands ./ and ~/
205 if (!AbsolutePath(binpath)) {
206 string binsearchpath = GetEnvPath("PATH");
207 // This will make "src/lyx" work always :-)
208 binsearchpath += ";.";
209 binpath = FileOpenSearch(binsearchpath, argv[0]);
212 fullbinpath = binpath;
213 binpath = MakeAbsPath(OnlyPath(binpath));
215 // In case we are running in place and compiled with shared libraries
216 if (suffixIs(binpath, "/.libs/"))
217 binpath.erase(binpath.length()-6, string::npos);
219 if (binpath.empty()) {
220 lyxerr << _("Warning: could not determine path of binary.")
222 << _("If you have problems, try starting LyX with an absolute path.")
225 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
228 // Determine system directory.
231 // Directories are searched in this order:
232 // 1) -sysdir command line parameter
233 // 2) LYX_DIR_11x environment variable
234 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
235 // 4) <path of binary>/../share/<name of binary>/
236 // 4a) repeat 4 after following the Symlink if <path of
237 // binary> is a symbolic link.
238 // 5) hardcoded lyx_dir
239 // The directory is checked for the presence of the file
240 // "chkconfig.ltx", and if that is present, the directory
241 // is accepted as the system directory.
242 // If no chkconfig.ltx file is found, a warning is given,
243 // and the hardcoded lyx_dir is used.
245 // If we had a command line switch, system_lyxdir is already set
247 if (!system_lyxdir.empty())
248 searchpath= MakeAbsPath(system_lyxdir) + ';';
250 // LYX_DIR_11x environment variable
251 string lyxdir = GetEnvPath("LYX_DIR_11x");
253 if (!lyxdir.empty()) {
254 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
255 searchpath += lyxdir + ';';
258 // <path of binary>/TOP_SRCDIR/lib
259 build_lyxdir = MakeAbsPath("../lib", binpath);
260 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
261 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
263 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
264 "place... yes" << endl;
267 << "Checking whether LyX is run in place... no"
269 build_lyxdir.erase();
274 // Path of binary/../share/name of binary/
275 searchpath += NormalizePath(AddPath(binpath, "../share/") +
276 OnlyFilename(binname)) + ';';
279 FileInfo file(fullbinpath, true);
280 FollowLink = file.isLink();
283 if (LyXReadLink(fullbinpath, Link)) {
285 binpath = MakeAbsPath(OnlyPath(fullbinpath));
291 } while (FollowLink);
294 searchpath += LYX_DIR;
296 // If debugging, show complete search path
297 lyxerr[Debug::INIT] << "System directory search path: "
298 << searchpath << endl;
300 string const filename = "chkconfig.ltx";
301 string temp = FileOpenSearch(searchpath, filename, string());
302 system_lyxdir = OnlyPath(temp);
304 // Reduce "path/../path" stuff out of system directory
305 system_lyxdir = NormalizePath(system_lyxdir);
307 bool path_shown = false;
309 // Warn if environment variable is set, but unusable
310 if (!lyxdir.empty()) {
311 if (system_lyxdir != NormalizePath(lyxdir)) {
312 lyxerr <<_("LYX_DIR_11x environment variable no good.")
314 << _("System directory set to: ")
315 << system_lyxdir << endl;
320 // Warn the user if we couldn't find "chkconfig.ltx"
321 if (system_lyxdir == "./") {
322 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
323 <<_("Try the '-sysdir' command line parameter or")
324 <<_("set the environment variable LYX_DIR_11x to the "
325 "LyX system directory")
326 << _("containing the file `chkconfig.ltx'.") << endl;
328 lyxerr << _("Using built-in default ")
329 << LYX_DIR << _(" but expect problems.")
332 lyxerr << _("Expect problems.") << endl;
333 system_lyxdir = LYX_DIR;
337 // Report the system directory if debugging is on
339 lyxerr[Debug::INIT] << "System directory: '"
340 << system_lyxdir << '\'' << endl;
343 // Determine user lyx-dir
346 // Directories are searched in this order:
347 // 1) -userdir command line parameter
348 // 2) LYX_USERDIR_11x environment variable
349 // 3) $HOME/.<name of binary>
351 // If we had a command line switch, user_lyxdir is already set
352 bool explicit_userdir = true;
353 if (user_lyxdir.empty()) {
355 // LYX_USERDIR_11x environment variable
356 user_lyxdir = GetEnvPath("LYX_USERDIR_11x");
359 if (user_lyxdir.empty())
360 user_lyxdir = AddPath(GetEnvPath("HOME"),
361 string(".") + PACKAGE);
362 explicit_userdir = false;
365 lyxerr[Debug::INIT] << "User LyX directory: '"
366 << user_lyxdir << '\'' << endl;
368 // Check that user LyX directory is ok.
369 queryUserLyXDir(explicit_userdir);
372 // Load the layouts first
375 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
379 // Shine up lyxrc defaults
382 // Default template path: system_dir/templates
383 if (lyxrc.template_path.empty()){
384 lyxrc.template_path = AddPath(system_lyxdir, "templates");
387 // Default lastfiles file: $HOME/.lyx/lastfiles
388 if (lyxrc.lastfiles.empty()){
389 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
392 // Disable gui when either lyxrc or easyparse says so
394 lyxrc.use_gui = false;
396 // Calculate screen dpi as average of x-DPI and y-DPI:
398 lyxrc.dpi = getScreenDPI();
399 lyxerr[Debug::INIT] << "DPI setting detected to be "
400 << lyxrc.dpi + 0.5 << endl;
402 lyxrc.dpi = 1; // I hope this is safe
406 // Read configuration files
409 ReadRcFile("lyxrc.defaults");
410 // system_lyxrc = lyxrc;
411 // If there is a preferences file we read that instead
412 // of the old lyxrc file.
413 if (!ReadRcFile("preferences"))
416 // Ensure that we have really read a bind file, so that LyX is
418 if (!lyxrc.hasBindFile)
419 lyxrc.ReadBindFile();
422 ReadUIFile(lyxrc.ui_file);
424 // Bind the X dead keys to the corresponding LyX functions if
426 if (lyxrc.override_x_deadkeys)
427 deadKeyBindings(toplevel_keymap);
429 if (lyxerr.debugging(Debug::LYXRC)) {
433 // Create temp directory
434 system_tempdir = CreateLyXTmpDir(lyxrc.tempdir_path);
435 if (lyxerr.debugging(Debug::INIT)) {
436 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
439 // load the lastfiles mini-database
440 lyxerr[Debug::INIT] << "Reading lastfiles `"
441 << lyxrc.lastfiles << "'..." << endl;
442 lastfiles = new LastFiles(lyxrc.lastfiles,
443 lyxrc.check_lastfiles,
444 lyxrc.num_lastfiles);
446 // start up the lyxserver. (is this a bit early?) (Lgb)
447 // 0.12 this will be way to early, we need the GUI to be initialized
448 // first, so move it for now.
449 // lyxserver = new LyXServer;
452 // These are the default bindings known to LyX
453 void LyX::defaultKeyBindings(kb_keymap * kbmap)
455 kbmap->bind("Right", LFUN_RIGHT);
456 kbmap->bind("Left", LFUN_LEFT);
457 kbmap->bind("Up", LFUN_UP);
458 kbmap->bind("Down", LFUN_DOWN);
460 kbmap->bind("Tab", LFUN_TAB);
462 kbmap->bind("Home", LFUN_HOME);
463 kbmap->bind("End", LFUN_END);
464 kbmap->bind("Prior", LFUN_PRIOR);
465 kbmap->bind("Next", LFUN_NEXT);
467 kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
468 kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
470 kbmap->bind("Delete", LFUN_DELETE);
471 kbmap->bind("BackSpace", LFUN_BACKSPACE);
473 // kbmap->bindings to enable the use of the numeric keypad
475 kbmap->bind("KP_0", LFUN_SELFINSERT);
476 kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
477 kbmap->bind("KP_Enter", LFUN_SELFINSERT);
478 kbmap->bind("KP_1", LFUN_SELFINSERT);
479 kbmap->bind("KP_2", LFUN_SELFINSERT);
480 kbmap->bind("KP_3", LFUN_SELFINSERT);
481 kbmap->bind("KP_4", LFUN_SELFINSERT);
482 kbmap->bind("KP_5", LFUN_SELFINSERT);
483 kbmap->bind("KP_6", LFUN_SELFINSERT);
484 kbmap->bind("KP_Add", LFUN_SELFINSERT);
485 kbmap->bind("KP_7", LFUN_SELFINSERT);
486 kbmap->bind("KP_8", LFUN_SELFINSERT);
487 kbmap->bind("KP_9", LFUN_SELFINSERT);
488 kbmap->bind("KP_Divide", LFUN_SELFINSERT);
489 kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
490 kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
492 /* Most self-insert keys are handled in the 'default:' section of
493 * WorkAreaKeyPress - so we don't have to define them all.
494 * However keys explicit decleared as self-insert are
495 * handled seperatly (LFUN_SELFINSERT.) Lgb. */
497 kbmap->bind("C-Tab", LFUN_TABINSERT); // ale970515
498 kbmap->bind("S-Tab", LFUN_SHIFT_TAB); // jug20000522
501 // LyX can optionally take over the handling of deadkeys
502 void LyX::deadKeyBindings(kb_keymap * kbmap)
504 // bindKeyings for transparent handling of deadkeys
505 // The keysyms are gotten from XFree86 X11R6
506 kbmap->bind("~C-~S-~M-dead_acute", LFUN_ACUTE);
507 kbmap->bind("~C-~S-~M-dead_breve", LFUN_BREVE);
508 kbmap->bind("~C-~S-~M-dead_caron", LFUN_CARON);
509 kbmap->bind("~C-~S-~M-dead_cedilla", LFUN_CEDILLA);
510 kbmap->bind("~C-~S-~M-dead_abovering", LFUN_CIRCLE);
511 kbmap->bind("~C-~S-~M-dead_circumflex", LFUN_CIRCUMFLEX);
512 kbmap->bind("~C-~S-~M-dead_abovedot", LFUN_DOT);
513 kbmap->bind("~C-~S-~M-dead_grave", LFUN_GRAVE);
514 kbmap->bind("~C-~S-~M-dead_doubleacute", LFUN_HUNG_UMLAUT);
515 kbmap->bind("~C-~S-~M-dead_macron", LFUN_MACRON);
516 // nothing with this name
517 // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
518 kbmap->bind("~C-~S-~M-dead_tilde", LFUN_TILDE);
519 kbmap->bind("~C-~S-~M-dead_diaeresis", LFUN_UMLAUT);
520 // nothing with this name either...
521 //kbmap->bind("~C-~S-~M-dead_underbar", LFUN_UNDERBAR);
522 kbmap->bind("~C-~S-~M-dead_belowdot", LFUN_UNDERDOT);
523 kbmap->bind("~C-~S-~M-dead_tie", LFUN_TIE);
524 kbmap->bind("~C-~S-~M-dead_ogonek", LFUN_OGONEK);
529 // This one is not allowed to use anything on the main form, since that
530 // one does not exist yet. (Asger)
531 void LyX::queryUserLyXDir(bool explicit_userdir)
533 // Does user directory exist?
534 FileInfo fileInfo(user_lyxdir);
535 if (fileInfo.isOK() && fileInfo.isDir()) {
543 // Different wording if the user specifically requested a directory
544 if (!AskQuestion( explicit_userdir
545 ? _("You have specified an invalid LyX directory.")
546 : _("You don't have a personal LyX directory.") ,
548 _("It is needed to keep your own configuration."),
549 _("Should I try to set it up for you (recommended)?"))) {
550 lyxerr << _("Running without personal LyX directory.") << endl;
551 // No, let's use $HOME instead.
552 user_lyxdir = GetEnvPath("HOME");
556 // Tell the user what is going on
557 lyxerr << _("LyX: Creating directory ") << user_lyxdir
558 << _(" and running configure...") << endl;
560 // Create directory structure
561 if (!createDirectory(user_lyxdir, 0755)) {
562 // Failed, let's use $HOME instead.
563 user_lyxdir = GetEnvPath("HOME");
564 lyxerr << _("Failed. Will use ") << user_lyxdir
565 << _(" instead.") << endl;
569 // Run configure in user lyx directory
571 system(AddName(system_lyxdir, "configure").c_str());
572 lyxerr << "LyX: " << _("Done!") << endl;
576 // Read the rc file `name'
577 bool LyX::ReadRcFile(string const & name)
579 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
581 string lyxrc_path = LibFileSearch(string(), name);
582 if (!lyxrc_path.empty()){
583 lyxerr[Debug::INIT] << "Found " << name
584 << " in " << lyxrc_path << endl;
585 if (lyxrc.read(lyxrc_path) < 0) {
586 WriteAlert(_("LyX Warning!"),
587 _("Error while reading ")+lyxrc_path+".",
588 _("Using built-in defaults."));
593 lyxerr[Debug::INIT] << "Could not find " << name << endl;
598 // Read the ui file `name'
599 void LyX::ReadUIFile(string const & name)
607 struct keyword_item uitags[ui_last-1] = {
608 { "menuset", ui_menuset },
609 { "toolbar", ui_toolbar }
612 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
614 string ui_path = LibFileSearch("ui", name, "ui");
616 if (ui_path.empty()) {
617 lyxerr[Debug::INIT] << "Could not find " << name << endl;
621 lyxerr[Debug::INIT] << "Found " << name
622 << " in " << ui_path << endl;
623 LyXLex lex(uitags, ui_last - 1);
624 lex.setFile(ui_path);
626 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
630 if (lyxerr.debugging(Debug::PARSER))
631 lex.printTable(lyxerr);
636 menubackend.read(lex);
640 toolbardefaults.read(lex);
644 lex.printError("LyX::ReadUFile: "
645 "Unknown menu tag: `$$Token'");
652 // Set debugging level and report result to user
653 void setDebuggingLevel(string const & dbgLevel)
655 lyxerr << _("Setting debug level to ") << dbgLevel << endl;
656 lyxerr.level(Debug::value(dbgLevel));
657 Debug::showLevel(lyxerr, lyxerr.level());
661 // Give command line help
662 void commandLineHelp()
664 lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
666 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
667 "Command line switches (case sensitive):\n"
668 "\t-help summarize LyX usage\n"
669 "\t-userdir dir try to set user directory to dir\n"
670 "\t-sysdir dir try to set system directory to dir\n"
671 "\t-geometry WxH+X+Y set geometry of the main window\n"
672 "\t-dbg feature[,feature]...\n"
673 " select the features to debug.\n"
674 " Type `lyx -dbg' to see the list of features\n"
675 "Check the LyX man page for more options.") << endl;
678 bool LyX::easyParse(int * argc, char * argv[])
681 int removeargs = 0; // used when options are read
682 for(int i = 1; i < *argc; ++i) {
683 string arg = argv[i];
685 // Check for -dbg int
688 setDebuggingLevel(argv[i + 1]);
691 lyxerr << _("List of supported debug flags:")
693 Debug::showTags(lyxerr);
697 // Check for "-sysdir"
698 else if (arg == "-sysdir") {
700 system_lyxdir = argv[i + 1];
703 lyxerr << _("Missing directory for -sysdir switch!")
708 // Check for "-userdir"
709 else if (arg == "-userdir") {
711 user_lyxdir = argv[i + 1];
714 lyxerr << _("Missing directory for -userdir switch!")
719 // Check for --help or -help
720 else if (arg == "--help" || arg == "-help") {
724 // Check for "-nw": No XWindows as for emacs this should
725 // give a LyX that could be used in a terminal window.
726 //else if (arg == "-nw") {
730 // Check for "-x": Execute commands
731 else if (arg == "-x" || arg == "--execute") {
733 batch_command = string(argv[i + 1]);
737 lyxerr << _("Missing command string after -x switch!") << endl;
739 // Argh. Setting gui to false segfaults..
743 else if (arg == "-e" || arg == "--export") {
745 string type(argv[i+1]);
748 batch_command = "buffer-export " + type;
752 else if (type == "ps")
754 else if (type == "text" || type == "txt")
757 if (type == "latex" || type == "postscript"
758 || type == "linuxdoc" || type == "docbook"
759 || type == "ascii" || type == "html")
760 batch_command = "buffer-export " + type;
762 lyxerr << _("Unknown file type '")
763 << type << _("' after ")
764 << arg << _(" switch!") << endl;
767 lyxerr << _("Missing file type [eg latex, "
769 << arg << _(" switch!") << endl;
771 else if (arg == "--import") {
773 string type(argv[i+1]);
774 string file(argv[i+2]);
777 batch_command = "buffer-import " + type + " " + file;
778 lyxerr << "batch_command: "
779 << batch_command << endl;
782 lyxerr << _("Missing type [eg latex, "
784 << arg << _(" switch!") << endl;
787 if (removeargs > 0) {
788 // Now, remove used arguments by shifting
789 // the following ones removeargs places down.
790 (*argc) -= removeargs;
791 for (int j = i; j < (*argc); ++j)
792 argv[j] = argv[j + removeargs];
793 --i; // After shift, check this number again.
804 void error_handler(int err_sig)
808 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
814 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
817 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
819 "Sorry, you have found a bug in LyX."
820 " If possible, please read 'Known bugs'\n"
821 "under the Help menu and then send us "
822 "a full bug report. Thanks!" << endl;
829 // Deinstall the signal handlers
830 signal(SIGHUP, SIG_DFL);
831 signal(SIGINT, SIG_DFL);
832 signal(SIGFPE, SIG_DFL);
833 signal(SIGSEGV, SIG_DFL);
834 signal(SIGTERM, SIG_DFL);
836 bufferlist.emergencyWriteAll();
838 lyxerr << "Bye." << endl;
839 if(err_sig!= SIGHUP &&
840 (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))