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"
39 # include "MenuBackend.h"
41 #include "ToolbarDefaults.h"
44 // only to get access to NEW_EXPORT
50 extern void LoadLyXFile(string const &);
51 extern void QuitLyX();
55 string system_tempdir;
56 string user_lyxdir; // Default $HOME/.lyx
58 // Should this be kept global? Asger says Yes.
61 LastFiles * lastfiles;
63 // This is the global bufferlist object
64 BufferList bufferlist;
66 LyXServer * lyxserver = 0;
67 // this should be static, but I need it in buffer.C
68 bool finished = false; // flag, that we are quitting the program
70 // convenient to have it here.
71 kb_keymap * toplevel_keymap;
74 LyX::LyX(int * argc, char * argv[])
76 // Prevent crash with --help
80 // Here we need to parse the command line. At least
81 // we need to parse for "-dbg" and "-help"
82 bool gui = easyParse(argc, argv);
84 // Global bindings (this must be done as early as possible.) (Lgb)
85 toplevel_keymap = new kb_keymap;
86 defaultKeyBindings(toplevel_keymap);
88 // Make the GUI object, and let it take care of the
89 // command line arguments that concerns it.
90 lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
91 lyxGUI = new LyXGUI(this, argc, argv, gui);
92 lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
94 // Now the GUI and LyX have taken care of their arguments, so
95 // the only thing left on the command line should be
96 // filenames. Let's check anyway.
97 for (int argi = 1; argi < *argc ; ++argi) {
98 if (argv[argi][0] == '-') {
99 lyxerr << _("Wrong command line option `")
101 << _("'. Exiting.") << endl;
106 // Initialization of LyX (reads lyxrc and more)
107 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
108 init(argc, argv, gui);
109 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
113 // Load the files specified in the command line.
115 lyxerr[Debug::INFO] << "Opening document..." << endl;
116 else if ((*argc) > 2)
117 lyxerr[Debug::INFO] << "Opening documents..." << endl;
119 Buffer * last_loaded = 0;
121 for (int argi = (*argc) - 1; argi >= 1; --argi) {
122 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
129 string splash = i18nLibFileSearch("examples", "splash.lyx");
130 lyxerr[Debug::INIT] << "Opening splash document "
131 << splash << "..." << endl;
132 Buffer * loadb = bufferlist.loadLyXFile(splash);
138 if (last_loaded != 0) {
139 lyxerr[Debug::INIT] << "Yes we loaded some files." << endl;
141 lyxGUI->regBuf(last_loaded);
144 // Execute batch commands if available
145 if (!batch_command.empty()) {
146 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
148 // no buffer loaded, create one
150 last_loaded = bufferlist.newFile("tmpfile", string());
152 // try to dispatch to last loaded buffer first
153 bool dispatched = last_loaded->Dispatch(batch_command);
155 // if this was successful, return.
156 // Maybe we could do something more clever than aborting...
158 lyxerr << "We are done!" << endl;
163 // otherwise, let the GUI handle the batch command
164 lyxGUI->regBuf(last_loaded);
165 lyxGUI->getLyXView()->getLyXFunc()->Dispatch(batch_command);
170 // Let the ball begin...
175 // A destructor is always necessary (asierra-970604)
183 extern "C" void error_handler(int err_sig);
185 void LyX::init(int */*argc*/, char **argv, bool gui)
187 // Install the signal handlers
188 signal(SIGHUP, error_handler);
189 signal(SIGFPE, error_handler);
190 signal(SIGSEGV, error_handler);
191 signal(SIGINT, error_handler);
192 signal(SIGTERM, error_handler);
195 // Determine path of binary
199 string binpath = subst(argv[0], '\\', '/');
200 string binname = OnlyFilename(argv[0]);
201 // Sorry for system specific code. (SMiyata)
202 if (suffixIs(binname, ".exe"))
203 binname.erase(binname.length()-4, string::npos);
205 binpath = ExpandPath(binpath); // This expands ./ and ~/
207 if (!AbsolutePath(binpath)) {
208 string binsearchpath = GetEnvPath("PATH");
209 // This will make "src/lyx" work always :-)
210 binsearchpath += ";.";
211 binpath = FileOpenSearch(binsearchpath, argv[0]);
214 fullbinpath = binpath;
215 binpath = MakeAbsPath(OnlyPath(binpath));
217 // In case we are running in place and compiled with shared libraries
218 if (suffixIs(binpath, "/.libs/"))
219 binpath.erase(binpath.length()-6, string::npos);
221 if (binpath.empty()) {
222 lyxerr << _("Warning: could not determine path of binary.")
224 << _("If you have problems, try starting LyX with an absolute path.")
227 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
230 // Determine system directory.
233 // Directories are searched in this order:
234 // 1) -sysdir command line parameter
235 // 2) LYX_DIR_11x environment variable
236 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
237 // 4) <path of binary>/../share/<name of binary>/
238 // 4a) repeat 4 after following the Symlink if <path of
239 // binary> is a symbolic link.
240 // 5) hardcoded lyx_dir
241 // The directory is checked for the presence of the file
242 // "chkconfig.ltx", and if that is present, the directory
243 // is accepted as the system directory.
244 // If no chkconfig.ltx file is found, a warning is given,
245 // and the hardcoded lyx_dir is used.
247 // If we had a command line switch, system_lyxdir is already set
249 if (!system_lyxdir.empty())
250 searchpath= MakeAbsPath(system_lyxdir) + ';';
252 // LYX_DIR_11x environment variable
253 string lyxdir = GetEnvPath("LYX_DIR_11x");
255 if (!lyxdir.empty()) {
256 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
257 searchpath += lyxdir + ';';
260 // <path of binary>/TOP_SRCDIR/lib
261 build_lyxdir = MakeAbsPath("../lib", binpath);
262 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
263 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
265 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
266 "place... yes" << endl;
269 << "Checking whether LyX is run in place... no"
271 build_lyxdir.erase();
276 // Path of binary/../share/name of binary/
277 searchpath += NormalizePath(AddPath(binpath, "../share/") +
278 OnlyFilename(binname)) + ';';
281 FileInfo file(fullbinpath, true);
282 FollowLink = file.isLink();
285 if (LyXReadLink(fullbinpath, Link)) {
287 binpath = MakeAbsPath(OnlyPath(fullbinpath));
293 } while (FollowLink);
296 searchpath += LYX_DIR;
298 // If debugging, show complete search path
299 lyxerr[Debug::INIT] << "System directory search path: "
300 << searchpath << endl;
302 string const filename = "chkconfig.ltx";
303 string temp = FileOpenSearch(searchpath, filename, string());
304 system_lyxdir = OnlyPath(temp);
306 // Reduce "path/../path" stuff out of system directory
307 system_lyxdir = NormalizePath(system_lyxdir);
309 bool path_shown = false;
311 // Warn if environment variable is set, but unusable
312 if (!lyxdir.empty()) {
313 if (system_lyxdir != NormalizePath(lyxdir)) {
314 lyxerr <<_("LYX_DIR_11x environment variable no good.")
316 << _("System directory set to: ")
317 << system_lyxdir << endl;
322 // Warn the user if we couldn't find "chkconfig.ltx"
323 if (system_lyxdir == "./") {
324 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
325 <<_("Try the '-sysdir' command line parameter or")
326 <<_("set the environment variable LYX_DIR_11x to the "
327 "LyX system directory")
328 << _("containing the file `chkconfig.ltx'.") << endl;
330 lyxerr << _("Using built-in default ")
331 << LYX_DIR << _(" but expect problems.")
334 lyxerr << _("Expect problems.") << endl;
335 system_lyxdir = LYX_DIR;
339 // Report the system directory if debugging is on
341 lyxerr[Debug::INIT] << "System directory: '"
342 << system_lyxdir << '\'' << endl;
345 // Determine user lyx-dir
348 // Directories are searched in this order:
349 // 1) -userdir command line parameter
350 // 2) LYX_USERDIR_11x environment variable
351 // 3) $HOME/.<name of binary>
353 // If we had a command line switch, user_lyxdir is already set
354 bool explicit_userdir = true;
355 if (user_lyxdir.empty()) {
357 // LYX_USERDIR_11x environment variable
358 user_lyxdir = GetEnvPath("LYX_USERDIR_11x");
361 if (user_lyxdir.empty())
362 user_lyxdir = AddPath(GetEnvPath("HOME"),
363 string(".") + PACKAGE);
364 explicit_userdir = false;
367 lyxerr[Debug::INIT] << "User LyX directory: '"
368 << user_lyxdir << '\'' << endl;
370 // Check that user LyX directory is ok.
371 queryUserLyXDir(explicit_userdir);
374 // Load the layouts first
377 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
381 // Shine up lyxrc defaults
384 // Default template path: system_dir/templates
385 if (lyxrc.template_path.empty()){
386 lyxrc.template_path = AddPath(system_lyxdir, "templates");
389 // Default lastfiles file: $HOME/.lyx/lastfiles
390 if (lyxrc.lastfiles.empty()){
391 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
394 // Disable gui when either lyxrc or easyparse says so
396 lyxrc.use_gui = false;
398 // Calculate screen dpi as average of x-DPI and y-DPI:
400 lyxrc.dpi = getScreenDPI();
401 lyxerr[Debug::INIT] << "DPI setting detected to be "
402 << lyxrc.dpi + 0.5 << endl;
404 lyxrc.dpi = 1; // I hope this is safe
408 // Read configuration files
411 ReadRcFile("lyxrc.defaults");
412 // system_lyxrc = lyxrc;
413 // If there is a preferences file we read that instead
414 // of the old lyxrc file.
415 if (!ReadRcFile("preferences"))
418 // Ensure that we have really read a bind file, so that LyX is
420 if (!lyxrc.hasBindFile)
421 lyxrc.ReadBindFile();
424 ReadUIFile(lyxrc.ui_file);
426 // Bind the X dead keys to the corresponding LyX functions if
428 if (lyxrc.override_x_deadkeys)
429 deadKeyBindings(toplevel_keymap);
431 if (lyxerr.debugging(Debug::LYXRC)) {
435 // Create temp directory
436 system_tempdir = CreateLyXTmpDir(lyxrc.tempdir_path);
437 if (lyxerr.debugging(Debug::INIT)) {
438 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
441 // load the lastfiles mini-database
442 lyxerr[Debug::INIT] << "Reading lastfiles `"
443 << lyxrc.lastfiles << "'..." << endl;
444 lastfiles = new LastFiles(lyxrc.lastfiles,
445 lyxrc.check_lastfiles,
446 lyxrc.num_lastfiles);
448 // start up the lyxserver. (is this a bit early?) (Lgb)
449 // 0.12 this will be way to early, we need the GUI to be initialized
450 // first, so move it for now.
451 // lyxserver = new LyXServer;
454 // These are the default bindings known to LyX
455 void LyX::defaultKeyBindings(kb_keymap * kbmap)
457 kbmap->bind("Right", LFUN_RIGHT);
458 kbmap->bind("Left", LFUN_LEFT);
459 kbmap->bind("Up", LFUN_UP);
460 kbmap->bind("Down", LFUN_DOWN);
462 kbmap->bind("Tab", LFUN_TAB);
464 kbmap->bind("Home", LFUN_HOME);
465 kbmap->bind("End", LFUN_END);
466 kbmap->bind("Prior", LFUN_PRIOR);
467 kbmap->bind("Next", LFUN_NEXT);
469 kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
470 kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
472 kbmap->bind("Delete", LFUN_DELETE);
473 kbmap->bind("BackSpace", LFUN_BACKSPACE);
475 // kbmap->bindings to enable the use of the numeric keypad
477 kbmap->bind("KP_0", LFUN_SELFINSERT);
478 kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
479 kbmap->bind("KP_Enter", LFUN_SELFINSERT);
480 kbmap->bind("KP_1", LFUN_SELFINSERT);
481 kbmap->bind("KP_2", LFUN_SELFINSERT);
482 kbmap->bind("KP_3", LFUN_SELFINSERT);
483 kbmap->bind("KP_4", LFUN_SELFINSERT);
484 kbmap->bind("KP_5", LFUN_SELFINSERT);
485 kbmap->bind("KP_6", LFUN_SELFINSERT);
486 kbmap->bind("KP_Add", LFUN_SELFINSERT);
487 kbmap->bind("KP_7", LFUN_SELFINSERT);
488 kbmap->bind("KP_8", LFUN_SELFINSERT);
489 kbmap->bind("KP_9", LFUN_SELFINSERT);
490 kbmap->bind("KP_Divide", LFUN_SELFINSERT);
491 kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
492 kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
494 /* Most self-insert keys are handled in the 'default:' section of
495 * WorkAreaKeyPress - so we don't have to define them all.
496 * However keys explicit decleared as self-insert are
497 * handled seperatly (LFUN_SELFINSERT.) Lgb. */
499 kbmap->bind("C-Tab", LFUN_TABINSERT); // ale970515
500 kbmap->bind("S-Tab", LFUN_SHIFT_TAB); // jug20000522
503 // LyX can optionally take over the handling of deadkeys
504 void LyX::deadKeyBindings(kb_keymap * kbmap)
506 // bindKeyings for transparent handling of deadkeys
507 // The keysyms are gotten from XFree86 X11R6
508 kbmap->bind("~C-~S-~M-dead_acute", LFUN_ACUTE);
509 kbmap->bind("~C-~S-~M-dead_breve", LFUN_BREVE);
510 kbmap->bind("~C-~S-~M-dead_caron", LFUN_CARON);
511 kbmap->bind("~C-~S-~M-dead_cedilla", LFUN_CEDILLA);
512 kbmap->bind("~C-~S-~M-dead_abovering", LFUN_CIRCLE);
513 kbmap->bind("~C-~S-~M-dead_circumflex", LFUN_CIRCUMFLEX);
514 kbmap->bind("~C-~S-~M-dead_abovedot", LFUN_DOT);
515 kbmap->bind("~C-~S-~M-dead_grave", LFUN_GRAVE);
516 kbmap->bind("~C-~S-~M-dead_doubleacute", LFUN_HUNG_UMLAUT);
517 kbmap->bind("~C-~S-~M-dead_macron", LFUN_MACRON);
518 // nothing with this name
519 // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
520 kbmap->bind("~C-~S-~M-dead_tilde", LFUN_TILDE);
521 kbmap->bind("~C-~S-~M-dead_diaeresis", LFUN_UMLAUT);
522 // nothing with this name either...
523 //kbmap->bind("~C-~S-~M-dead_underbar", LFUN_UNDERBAR);
524 kbmap->bind("~C-~S-~M-dead_belowdot", LFUN_UNDERDOT);
525 kbmap->bind("~C-~S-~M-dead_tie", LFUN_TIE);
526 kbmap->bind("~C-~S-~M-dead_ogonek", LFUN_OGONEK);
531 // This one is not allowed to use anything on the main form, since that
532 // one does not exist yet. (Asger)
533 void LyX::queryUserLyXDir(bool explicit_userdir)
535 // Does user directory exist?
536 FileInfo fileInfo(user_lyxdir);
537 if (fileInfo.isOK() && fileInfo.isDir()) {
545 // Different wording if the user specifically requested a directory
546 if (!AskQuestion( explicit_userdir
547 ? _("You have specified an invalid LyX directory.")
548 : _("You don't have a personal LyX directory.") ,
550 _("It is needed to keep your own configuration."),
551 _("Should I try to set it up for you (recommended)?"))) {
552 lyxerr << _("Running without personal LyX directory.") << endl;
553 // No, let's use $HOME instead.
554 user_lyxdir = GetEnvPath("HOME");
558 // Tell the user what is going on
559 lyxerr << _("LyX: Creating directory ") << user_lyxdir
560 << _(" and running configure...") << endl;
562 // Create directory structure
563 if (!createDirectory(user_lyxdir, 0755)) {
564 // Failed, let's use $HOME instead.
565 user_lyxdir = GetEnvPath("HOME");
566 lyxerr << _("Failed. Will use ") << user_lyxdir
567 << _(" instead.") << endl;
571 // Run configure in user lyx directory
573 system(AddName(system_lyxdir, "configure").c_str());
574 lyxerr << "LyX: " << _("Done!") << endl;
578 // Read the rc file `name'
579 bool LyX::ReadRcFile(string const & name)
581 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
583 string lyxrc_path = LibFileSearch(string(), name);
584 if (!lyxrc_path.empty()){
585 lyxerr[Debug::INIT] << "Found " << name
586 << " in " << lyxrc_path << endl;
587 if (lyxrc.read(lyxrc_path) < 0) {
588 WriteAlert(_("LyX Warning!"),
589 _("Error while reading ")+lyxrc_path+".",
590 _("Using built-in defaults."));
595 lyxerr[Debug::INIT] << "Could not find " << name << endl;
600 // Read the ui file `name'
601 void LyX::ReadUIFile(string const & name)
609 struct keyword_item uitags[ui_last-1] = {
610 { "menuset", ui_menuset },
611 { "toolbar", ui_toolbar }
614 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
616 string ui_path = LibFileSearch("ui", name, "ui");
618 if (ui_path.empty()) {
619 lyxerr[Debug::INIT] << "Could not find " << name << endl;
623 lyxerr[Debug::INIT] << "Found " << name
624 << " in " << ui_path << endl;
625 LyXLex lex(uitags, ui_last - 1);
626 lex.setFile(ui_path);
628 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
632 if (lyxerr.debugging(Debug::PARSER))
633 lex.printTable(lyxerr);
639 menubackend.read(lex);
642 // Skip any menu definition and fall over to toolbar.
643 // This is a hack, but it is supposed to go away...
646 if (!lex.IsOK()) return;
648 while (lex.lex() != ui_toolbar);
652 toolbardefaults.read(lex);
656 lex.printError("LyX::ReadUFile: "
657 "Unknown menu tag: `$$Token'");
664 // Set debugging level and report result to user
665 void setDebuggingLevel(string const & dbgLevel)
667 lyxerr << _("Setting debug level to ") << dbgLevel << endl;
668 lyxerr.level(Debug::value(dbgLevel));
669 Debug::showLevel(lyxerr, lyxerr.level());
673 // Give command line help
674 void commandLineHelp()
676 lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
678 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
679 "Command line switches (case sensitive):\n"
680 "\t-help summarize LyX usage\n"
681 "\t-userdir dir try to set user directory to dir\n"
682 "\t-sysdir dir try to set system directory to dir\n"
683 "\t-geometry WxH+X+Y set geometry of the main window\n"
684 "\t-dbg feature[,feature]...\n"
685 " select the features to debug.\n"
686 " Type `lyx -dbg' to see the list of features\n"
687 "Check the LyX man page for more options.") << endl;
690 bool LyX::easyParse(int * argc, char * argv[])
693 int removeargs = 0; // used when options are read
694 for(int i = 1; i < *argc; ++i) {
695 string arg = argv[i];
697 // Check for -dbg int
700 setDebuggingLevel(argv[i + 1]);
703 lyxerr << _("List of supported debug flags:")
705 Debug::showTags(lyxerr);
709 // Check for "-sysdir"
710 else if (arg == "-sysdir") {
712 system_lyxdir = argv[i + 1];
715 lyxerr << _("Missing directory for -sysdir switch!")
720 // Check for "-userdir"
721 else if (arg == "-userdir") {
723 user_lyxdir = argv[i + 1];
726 lyxerr << _("Missing directory for -userdir switch!")
731 // Check for --help or -help
732 else if (arg == "--help" || arg == "-help") {
736 // Check for "-nw": No XWindows as for emacs this should
737 // give a LyX that could be used in a terminal window.
738 //else if (arg == "-nw") {
742 // Check for "-x": Execute commands
743 else if (arg == "-x" || arg == "--execute") {
745 batch_command = string(argv[i + 1]);
749 lyxerr << _("Missing command string after -x switch!") << endl;
751 // Argh. Setting gui to false segfaults..
755 else if (arg == "-e" || arg == "--export") {
757 string type(argv[i+1]);
760 batch_command = "buffer-export " + type;
764 else if (type == "ps")
766 else if (type == "text" || type == "txt")
769 if (type == "latex" || type == "postscript"
770 || type == "linuxdoc" || type == "docbook"
771 || type == "ascii" || type == "html")
772 batch_command = "buffer-export " + type;
774 lyxerr << _("Unknown file type '")
775 << type << _("' after ")
776 << arg << _(" switch!") << endl;
779 lyxerr << _("Missing file type [eg latex, "
781 << arg << _(" switch!") << endl;
783 else if (arg == "--import") {
785 string type(argv[i+1]);
786 string file(argv[i+2]);
789 batch_command = "buffer-import " + type + " " + file;
790 lyxerr << "batch_command: "
791 << batch_command << endl;
794 lyxerr << _("Missing type [eg latex, "
796 << arg << _(" switch!") << endl;
799 if (removeargs > 0) {
800 // Now, remove used arguments by shifting
801 // the following ones removeargs places down.
802 (*argc) -= removeargs;
803 for (int j = i; j < (*argc); ++j)
804 argv[j] = argv[j + removeargs];
805 --i; // After shift, check this number again.
816 void error_handler(int err_sig)
820 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
826 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
829 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
831 "Sorry, you have found a bug in LyX."
832 " If possible, please read 'Known bugs'\n"
833 "under the Help menu and then send us "
834 "a full bug report. Thanks!" << endl;
841 // Deinstall the signal handlers
842 signal(SIGHUP, SIG_DFL);
843 signal(SIGINT, SIG_DFL);
844 signal(SIGFPE, SIG_DFL);
845 signal(SIGSEGV, SIG_DFL);
846 signal(SIGTERM, SIG_DFL);
848 bufferlist.emergencyWriteAll();
850 lyxerr << "Bye." << endl;
851 if(err_sig!= SIGHUP &&
852 (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))