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 * ====================================================== */
21 #include "lyx_gui_misc.h"
23 #include "support/path.h"
24 #include "support/filetools.h"
25 #include "bufferlist.h"
27 #include "support/FileInfo.h"
28 #include "lastfiles.h"
30 #include "lyxserver.h"
37 extern void LoadLyXFile(string const &);
41 string system_tempdir;
42 string user_lyxdir; // Default $HOME/.lyx
44 // Should this be kept global? Asger says Yes.
47 LastFiles * lastfiles;
49 // This is the global bufferlist object
50 BufferList bufferlist;
52 LyXServer * lyxserver = 0;
53 // this should be static, but I need it in buffer.C
54 bool finished = false; // flag, that we are quitting the program
56 // convenient to have it here.
57 kb_keymap * toplevel_keymap;
60 LyX::LyX(int * argc, char * argv[])
62 // Prevent crash with --help
66 // Here we need to parse the command line. At least
67 // we need to parse for "-dbg" and "-help"
68 bool gui = easyParse(argc, argv);
70 // Global bindings (this must be done as early as possible.) (Lgb)
71 toplevel_keymap = new kb_keymap;
73 // Fill the toplevel_keymap with some defaults
74 for (LyXRC::Bindings::const_iterator cit = lyxrc.bindings.begin();
75 cit != lyxrc.bindings.end(); ++cit) {
76 toplevel_keymap->bind((*cit).first.c_str(), (*cit).second);
79 // Make the GUI object, and let it take care of the
80 // command line arguments that concerns it.
81 lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
82 lyxGUI = new LyXGUI(this, argc, argv, gui);
83 lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
85 // Initialization of LyX (reads lyxrc and more)
86 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
87 init(argc, argv, gui);
88 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
92 // Load the files specified in the command line.
93 // Now the GUI and LyX have taken care of their arguments, so
94 // the only thing left on the command line should be
97 lyxerr[Debug::INFO] << "Opening document..." << endl;
99 lyxerr[Debug::INFO] << "Opening documents..." << endl;
101 Buffer * last_loaded = 0;
103 for (int argi = (*argc) - 1; argi >= 1; --argi) {
104 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
111 string splash = i18nLibFileSearch("examples", "splash.lyx");
112 lyxerr.debug() << "Opening splash document "
113 << splash << "..." << endl;
114 Buffer * loadb = bufferlist.loadLyXFile(splash);
120 if (last_loaded != 0) {
121 lyxerr.debug() << "Yes we loaded some files." << endl;
123 lyxGUI->regBuf(last_loaded);
126 // Execute batch commands if available
127 if (!batch_command.empty()) {
128 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
130 // no buffer loaded, create one
132 last_loaded = bufferlist.newFile("tmpfile", string());
134 // try to dispatch to last loaded buffer first
135 bool dispatched = last_loaded->Dispatch(batch_command);
137 // if this was successful, return.
138 // Maybe we could do something more clever than aborting...
140 lyxerr << "We are done!" << endl;
144 // otherwise, let the GUI handle the batch command
145 lyxGUI->regBuf(last_loaded);
146 lyxGUI->getLyXView()->getLyXFunc()->Dispatch(batch_command);
151 // Let the ball begin...
156 // A destructor is always necessary (asierra-970604)
164 extern "C" void error_handler(int err_sig);
166 void LyX::init(int */*argc*/, char **argv, bool gui)
168 // Install the signal handlers
169 signal(SIGHUP, error_handler);
170 signal(SIGFPE, error_handler);
171 signal(SIGSEGV, error_handler);
172 signal(SIGINT, error_handler);
173 signal(SIGTERM, error_handler);
176 // Determine path of binary
180 string binpath = subst(argv[0], '\\', '/');
181 string binname = OnlyFilename(argv[0]);
182 // Sorry for system specific code. (SMiyata)
183 if (suffixIs(binname, ".exe"))
184 binname.erase(binname.length()-4, string::npos);
186 binpath = ExpandPath(binpath); // This expands ./ and ~/
188 if (!AbsolutePath(binpath)) {
189 string binsearchpath = GetEnvPath("PATH");
190 // This will make "src/lyx" work always :-)
191 binsearchpath += ";.";
192 binpath = FileOpenSearch(binsearchpath, argv[0]);
195 fullbinpath = binpath;
196 binpath = MakeAbsPath(OnlyPath(binpath));
198 // In case we are running in place and compiled with shared libraries
199 if (suffixIs(binpath, "/.libs/"))
200 binpath.erase(binpath.length()-6, string::npos);
202 if (binpath.empty()) {
203 lyxerr << _("Warning: could not determine path of binary.")
205 << _("If you have problems, try starting LyX with an absolute path.")
208 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
211 // Determine system directory.
214 // Directories are searched in this order:
215 // 1) -sysdir command line parameter
216 // 2) LYX_DIR_11x environment variable
217 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
218 // 4) <path of binary>/../share/<name of binary>/
219 // 4a) repeat 4 after following the Symlink if <path of
220 // binary> is a symbolic link.
221 // 5) hardcoded lyx_dir
222 // The directory is checked for the presence of the file
223 // "chkconfig.ltx", and if that is present, the directory
224 // is accepted as the system directory.
225 // If no chkconfig.ltx file is found, a warning is given,
226 // and the hardcoded lyx_dir is used.
228 // If we had a command line switch, system_lyxdir is already set
230 if (!system_lyxdir.empty())
231 searchpath= MakeAbsPath(system_lyxdir) + ';';
233 // LYX_DIR_11x environment variable
234 string lyxdir = GetEnvPath("LYX_DIR_11x");
236 if (!lyxdir.empty()) {
237 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
238 searchpath += lyxdir + ';';
241 // <path of binary>/TOP_SRCDIR/lib
242 build_lyxdir = MakeAbsPath("../lib", binpath);
243 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
244 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
246 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
247 "place... yes" << endl;
250 << "Checking whether LyX is run in place... no"
252 build_lyxdir.erase();
257 // Path of binary/../share/name of binary/
258 searchpath += NormalizePath(AddPath(binpath, "../share/") +
259 OnlyFilename(binname)) + ';';
262 FileInfo file(fullbinpath, true);
263 FollowLink = file.isLink();
266 if (LyXReadLink(fullbinpath, Link)) {
268 binpath = MakeAbsPath(OnlyPath(fullbinpath));
274 } while (FollowLink);
277 searchpath += LYX_DIR;
279 // If debugging, show complete search path
280 lyxerr[Debug::INIT] << "System directory search path: "
281 << searchpath << endl;
283 string const filename = "chkconfig.ltx";
284 string temp = FileOpenSearch(searchpath, filename, string());
285 system_lyxdir = OnlyPath(temp);
287 // Reduce "path/../path" stuff out of system directory
288 system_lyxdir = NormalizePath(system_lyxdir);
290 bool path_shown = false;
292 // Warn if environment variable is set, but unusable
293 if (!lyxdir.empty()) {
294 if (system_lyxdir != NormalizePath(lyxdir)) {
295 lyxerr <<_("LYX_DIR_11x environment variable no good.")
297 << _("System directory set to: ")
298 << system_lyxdir << endl;
303 // Warn the user if we couldn't find "chkconfig.ltx"
304 if (system_lyxdir == "./") {
305 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
306 <<_("Try the '-sysdir' command line parameter or")
307 <<_("set the environment variable LYX_DIR_11x to the "
308 "LyX system directory")
309 << _("containing the file `chkconfig.ltx'.") << endl;
311 lyxerr << _("Using built-in default ")
312 << LYX_DIR << _(" but expect problems.")
315 lyxerr << _("Expect problems.") << endl;
316 system_lyxdir = LYX_DIR;
320 // Report the system directory if debugging is on
322 lyxerr[Debug::INIT] << "System directory: '"
323 << system_lyxdir << '\'' << endl;
326 // Determine user lyx-dir
329 user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
330 lyxerr[Debug::INIT] << "User LyX directory: '"
331 << user_lyxdir << '\'' << endl;
333 // Check that user LyX directory is ok.
337 // Load the layouts first
340 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
344 // Shine up lyxrc defaults
347 // Default template path: system_dir/templates
348 if (lyxrc.template_path.empty()){
349 lyxrc.template_path = AddPath(system_lyxdir, "templates");
352 // Default lastfiles file: $HOME/.lyx/lastfiles
353 if (lyxrc.lastfiles.empty()){
354 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
357 // Disable gui when either lyxrc or easyparse says so
359 lyxrc.use_gui = false;
361 // Calculate screen dpi as average of x-DPI and y-DPI:
363 lyxrc.dpi = getScreenDPI();
364 lyxerr[Debug::INFO] << "DPI setting detected to be "
365 << lyxrc.dpi + 0.5 << endl;
367 lyxrc.dpi = 1; // I hope this is safe
371 // Read configuration files
374 ReadRcFile("lyxrc.defaults");
377 // Ensure that we have really read a bind file, so that LyX is
379 if (!lyxrc.hasBindFile)
380 lyxrc.ReadBindFile();
382 if (lyxerr.debugging(Debug::LYXRC)) {
386 // Create temp directory
387 system_tempdir = CreateLyXTmpDir(lyxrc.tempdir_path);
388 if (lyxerr.debugging(Debug::INIT)) {
389 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
392 // load the lastfiles mini-database
393 lyxerr[Debug::INIT] << "Reading lastfiles `"
394 << lyxrc.lastfiles << "'..." << endl;
395 lastfiles = new LastFiles(lyxrc.lastfiles,
396 lyxrc.check_lastfiles,
397 lyxrc.num_lastfiles);
399 // start up the lyxserver. (is this a bit early?) (Lgb)
400 // 0.12 this will be way to early, we need the GUI to be initialized
401 // first, so move it for now.
402 // lyxserver = new LyXServer;
406 // This one is not allowed to use anything on the main form, since that
407 // one does not exist yet. (Asger)
408 void LyX::queryUserLyXDir()
410 // Does user directory exist?
411 FileInfo fileInfo(user_lyxdir);
412 if (fileInfo.isOK() && fileInfo.isDir()) {
420 if (!AskQuestion(_("You don't have a personal LyX directory."),
421 _("It is needed to keep your own configuration."),
422 _("Should I try to set it up for you (recommended)?"))) {
423 lyxerr << _("Running without personal LyX directory.") << endl;
424 // No, let's use $HOME instead.
425 user_lyxdir = GetEnvPath("HOME");
429 // Tell the user what is going on
430 lyxerr << _("LyX: Creating directory ") << user_lyxdir
431 << _(" and running configure...") << endl;
433 // Create directory structure
434 if (!createDirectory(user_lyxdir, 0755)) {
435 // Failed, let's use $HOME instead.
436 user_lyxdir = GetEnvPath("HOME");
437 lyxerr << _("Failed. Will use ") << user_lyxdir
438 << _(" instead.") << endl;
442 // Run configure in user lyx directory
444 system(AddName(system_lyxdir, "configure").c_str());
445 lyxerr << "LyX: " << _("Done!") << endl;
449 // Read the rc file `name'
450 void LyX::ReadRcFile(string const & name)
452 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
454 string lyxrc_path = LibFileSearch(string(), name);
455 if (!lyxrc_path.empty()){
456 lyxerr[Debug::INIT] << "Found " << name
457 << " in " << lyxrc_path << endl;
458 if (lyxrc.read(lyxrc_path) < 0) {
459 WriteAlert(_("LyX Warning!"),
460 _("Error while reading ")+lyxrc_path+".",
461 _("Using built-in defaults."));
464 lyxerr[Debug::INIT] << "Could not find " << name << endl;
468 // Set debugging level and report result to user
469 void setDebuggingLevel(string const & dbgLevel)
471 lyxerr << _("Setting debug level to ") << dbgLevel << endl;
472 lyxerr.level(Debug::value(dbgLevel));
473 Debug::showLevel(lyxerr, lyxerr.level());
477 // Give command line help
478 void commandLineHelp()
480 lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
482 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
483 "Command line switches (case sensitive):\n"
484 "\t-help summarize LyX usage\n"
485 "\t-sysdir x try to set system directory to x\n"
486 "\t-width x set the width of the main window\n"
487 "\t-height y set the height of the main window\n"
488 "\t-xpos x set the x position of the main window\n"
489 "\t-ypos y set the y position of the main window\n"
490 "\t-dbg feature[,feature]...\n"
491 " select the features to debug.\n"
492 " Type `lyx -dbg' to see the list of features\n"
493 "Check the LyX man page for more options.") << endl;
497 bool LyX::easyParse(int * argc, char * argv[])
500 for(int i = 1; i < *argc; ++i) {
501 string arg = argv[i];
503 // Check for -dbg int
506 setDebuggingLevel(argv[i + 1]);
508 // Now, remove these two arguments by shifting
509 // the following two places down.
511 for (int j = i; j < (*argc); ++j)
512 argv[j] = argv[j + 2];
513 --i; // After shift, check this number again.
515 lyxerr << _("List of supported debug flags:")
517 Debug::showTags(lyxerr);
521 // Check for "-sysdir"
522 else if (arg == "-sysdir") {
524 system_lyxdir = argv[i + 1];
526 // Now, remove these two arguments by shifting
527 // the following two places down.
529 for (int j= i; j < (*argc); ++j)
530 argv[j] = argv[j + 2];
531 --i; // After shift, check this number again.
533 lyxerr << _("Missing directory for -sysdir switch!")
535 // Check for --help or -help
536 } else if (arg == "--help" || arg == "-help") {
540 // Check for "-nw": No XWindows as for emacs this should
541 // give a LyX that could be used in a terminal window.
542 //else if (arg == "-nw") {
546 // Check for "-x": Execute commands
547 else if (arg == "-x" || arg == "--execute") {
549 batch_command = string(argv[i + 1]);
551 // Now, remove these two arguments by shifting
552 // the following two places down.
554 for (int j = i; j < (*argc); ++j)
555 argv[j] = argv[j + 2];
556 --i; // After shift, check this number again.
560 lyxerr << _("Missing command string after -x switch!") << endl;
562 // Argh. Setting gui to false segfaults..
566 else if (arg == "-e" || arg == "--export") {
568 string type(argv[i+1]);
571 for (int j = i; j < (*argc); ++j)
572 argv[j] = argv[j + 2];
573 --i; // After shift, check this number again.
577 else if (type == "ps")
579 else if (type == "text" || type == "txt")
582 if (type == "latex" || type == "postscript"
583 || type == "ascii" || type == "html")
584 batch_command = "buffer-export " + type;
586 lyxerr << _("Unknown file type '")
587 << type << _("' after ")
588 << arg << _(" switch!") << endl;
590 lyxerr << _("Missing file type [eg latex, "
592 << arg << _(" switch!") << endl;
595 else if (arg == "--import") {
597 string type(argv[i+1]);
598 string file(argv[i+2]);
601 for (int j = i; j < (*argc); ++j)
602 argv[j] = argv[j + 3];
603 --i; // After shift, check this number again.
605 batch_command = "buffer-import " + type + " " + file;
606 lyxerr << "batch_command: "
607 << batch_command << endl;
610 lyxerr << _("Missing type [eg latex, "
612 << arg << _(" switch!") << endl;
621 void error_handler(int err_sig)
625 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
631 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
634 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
636 "Sorry, you have found a bug in LyX."
637 " If possible, please read 'Known bugs'\n"
638 "under the Help menu and then send us "
639 "a full bug report. Thanks!" << endl;
646 // Deinstall the signal handlers
647 signal(SIGHUP, SIG_DFL);
648 signal(SIGINT, SIG_DFL);
649 signal(SIGFPE, SIG_DFL);
650 signal(SIGSEGV, SIG_DFL);
651 signal(SIGTERM, SIG_DFL);
653 bufferlist.emergencyWriteAll();
655 lyxerr << "Bye." << endl;
656 if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))