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 * ====================================================== */
19 #include "lyx_gui_misc.h"
21 #include "support/path.h"
22 #include "support/filetools.h"
23 #include "bufferlist.h"
25 #include "support/FileInfo.h"
26 #include "lastfiles.h"
28 #include "lyxserver.h"
33 extern void LoadLyXFile(string const &);
37 string system_tempdir;
38 string user_lyxdir; // Default $HOME/.lyx
40 // Should this be kept global? Asger says Yes.
43 LastFiles * lastfiles;
45 // This is the global bufferlist object
46 BufferList bufferlist;
48 LyXServer * lyxserver = 0;
49 // this should be static, but I need it in buffer.C
50 bool finished = false; // flag, that we are quitting the program
52 // convenient to have it here.
53 kb_keymap * toplevel_keymap;
56 LyX::LyX(int * argc, char * argv[])
58 // Prevent crash with --help
62 // Here we need to parse the command line. At least
63 // we need to parse for "-dbg" and "-help"
64 bool gui = easyParse(argc, argv);
66 // Global bindings (this must be done as early as possible.) (Lgb)
67 toplevel_keymap = new kb_keymap;
68 // Fill the toplevel_keymap with some defaults
69 for (LyXRC::Bindings::const_iterator cit = lyxrc.bindings.begin();
70 cit != lyxrc.bindings.end(); ++cit) {
71 toplevel_keymap->bind((*cit).first.c_str(), (*cit).second);
74 // Make the GUI object, and let it take care of the
75 // command line arguments that concerns it.
76 lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
77 lyxGUI = new LyXGUI(this, argc, argv, gui);
78 lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
80 // Initialization of LyX (reads lyxrc and more)
81 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
82 init(argc, argv, gui);
83 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
87 // Load the files specified in the command line.
88 // Now the GUI and LyX have taken care of their arguments, so
89 // the only thing left on the command line should be
92 lyxerr[Debug::INFO] << "Opening document..." << endl;
94 lyxerr[Debug::INFO] << "Opening documents..." << endl;
96 Buffer * last_loaded = 0;
98 for (int argi = (*argc) - 1; argi >= 1; --argi) {
99 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
106 string splash = i18nLibFileSearch("examples", "splash.lyx");
107 lyxerr.debug() << "Opening splash document "
108 << splash << "..." << endl;
109 Buffer * loadb = bufferlist.loadLyXFile(splash);
115 if (last_loaded != 0) {
116 lyxerr.debug() << "Yes we loaded some files." << endl;
118 lyxGUI->regBuf(last_loaded);
121 // Execute batch commands if available
122 if (!batch_command.empty() && last_loaded) {
123 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
124 //Buffer buffer("Script Buffer");
125 //buffer.Dispatch(batch_command);
126 last_loaded->Dispatch(batch_command);
127 lyxerr << "We are done!" << endl;
128 return; // Maybe we could do something more clever than aborting..
131 // Let the ball begin...
136 // A destructor is always necessary (asierra-970604)
144 extern "C" void error_handler(int err_sig);
146 void LyX::init(int */*argc*/, char **argv, bool gui)
148 // Install the signal handlers
149 signal(SIGHUP, error_handler);
150 signal(SIGFPE, error_handler);
151 signal(SIGSEGV, error_handler);
152 signal(SIGINT, error_handler);
153 signal(SIGTERM, error_handler);
156 // Determine path of binary
160 string binpath = subst(argv[0], '\\', '/');
161 string binname = OnlyFilename(argv[0]);
162 // Sorry for system specific code. (SMiyata)
163 if (suffixIs(binname, ".exe"))
164 binname.erase(binname.length()-4, string::npos);
166 binpath = ExpandPath(binpath); // This expands ./ and ~/
168 if (!AbsolutePath(binpath)) {
169 string binsearchpath = GetEnvPath("PATH");
170 // This will make "src/lyx" work always :-)
171 binsearchpath += ";.";
172 binpath = FileOpenSearch(binsearchpath, argv[0]);
175 fullbinpath = binpath;
176 binpath = MakeAbsPath(OnlyPath(binpath));
178 // In case we are running in place and compiled with shared libraries
179 if (suffixIs(binpath, "/.libs/"))
180 binpath.erase(binpath.length()-6, string::npos);
182 if (binpath.empty()) {
183 lyxerr << _("Warning: could not determine path of binary.")
185 << _("If you have problems, try starting LyX with an absolute path.")
188 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
191 // Determine system directory.
194 // Directories are searched in this order:
195 // 1) -sysdir command line parameter
196 // 2) LYX_DIR_11x environment variable
197 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
198 // 4) <path of binary>/../share/<name of binary>/
199 // 4a) repeat 4 after following the Symlink if <path of
200 // binary> is a symbolic link.
201 // 5) hardcoded lyx_dir
202 // The directory is checked for the presence of the file
203 // "chkconfig.ltx", and if that is present, the directory
204 // is accepted as the system directory.
205 // If no chkconfig.ltx file is found, a warning is given,
206 // and the hardcoded lyx_dir is used.
208 // If we had a command line switch, system_lyxdir is already set
210 if (!system_lyxdir.empty())
211 searchpath= MakeAbsPath(system_lyxdir) + ';';
213 // LYX_DIR_11x environment variable
214 string lyxdir = GetEnvPath("LYX_DIR_11x");
216 if (!lyxdir.empty()) {
217 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
218 searchpath += lyxdir + ';';
221 // <path of binary>/TOP_SRCDIR/lib
222 build_lyxdir = MakeAbsPath("../lib", binpath);
223 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
224 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
226 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
227 "place... yes" << endl;
230 << "Checking whether LyX is run in place... no"
232 build_lyxdir.clear();
237 // Path of binary/../share/name of binary/
238 searchpath += NormalizePath(AddPath(binpath, "../share/") +
239 OnlyFilename(binname)) + ';';
242 FileInfo file(fullbinpath, true);
243 FollowLink = file.isLink();
246 if (LyXReadLink(fullbinpath, Link)) {
248 binpath = MakeAbsPath(OnlyPath(fullbinpath));
254 } while (FollowLink);
257 searchpath += LYX_DIR;
259 // If debugging, show complete search path
260 lyxerr[Debug::INIT] << "System directory search path: "
261 << searchpath << endl;
263 string const filename = "chkconfig.ltx";
264 string temp = FileOpenSearch(searchpath, filename, string());
265 system_lyxdir = OnlyPath(temp);
267 // Reduce "path/../path" stuff out of system directory
268 system_lyxdir = NormalizePath(system_lyxdir);
270 bool path_shown = false;
272 // Warn if environment variable is set, but unusable
273 if (!lyxdir.empty()) {
274 if (system_lyxdir != NormalizePath(lyxdir)) {
275 lyxerr <<_("LYX_DIR_11x environment variable no good.")
277 << _("System directory set to: ")
278 << system_lyxdir << endl;
283 // Warn the user if we couldn't find "chkconfig.ltx"
284 if (system_lyxdir == "./") {
285 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
286 <<_("Try the '-sysdir' command line parameter or")
287 <<_("set the environment variable LYX_DIR_11x to the "
288 "LyX system directory")
289 << _("containing the file `chkconfig.ltx'.") << endl;
291 lyxerr << _("Using built-in default ")
292 << LYX_DIR << _(" but expect problems.")
295 lyxerr << _("Expect problems.") << endl;
296 system_lyxdir = LYX_DIR;
300 // Report the system directory if debugging is on
302 lyxerr[Debug::INIT] << "System directory: '"
303 << system_lyxdir << '\'' << endl;
306 // Determine user lyx-dir
309 user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
310 lyxerr[Debug::INIT] << "User LyX directory: '"
311 << user_lyxdir << '\'' << endl;
313 // Check that user LyX directory is ok.
317 // Load the layouts first
320 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
324 // Shine up lyxrc defaults
327 // Default template path: system_dir/templates
328 if (lyxrc.template_path.empty()){
329 lyxrc.template_path = AddPath(system_lyxdir, "templates");
332 // Default lastfiles file: $HOME/.lyx/lastfiles
333 if (lyxrc.lastfiles.empty()){
334 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
337 // Calculate screen dpi as average of x-DPI and y-DPI:
338 // Disable gui when either lyxrc or easyparse says so
340 lyxrc.use_gui = false;
342 // Calculate screen dpi as average of x-DPI and y-DPI:
344 Screen * scr = DefaultScreenOfDisplay(fl_get_display());
345 lyxrc.dpi = ((HeightOfScreen(scr)* 25.4 / HeightMMOfScreen(scr)) +
346 (WidthOfScreen(scr)* 25.4 / WidthMMOfScreen(scr))) / 2;
347 lyxerr[Debug::INFO] << "DPI setting detected to be "
348 << lyxrc.dpi + 0.5 << endl;
350 lyxrc.dpi = 1; // I hope this is safe
354 // Read configuration files
357 ReadRcFile("lyxrc.defaults");
360 // Ensure that we have really read a bind file, so that LyX is
362 if (!lyxrc.hasBindFile)
363 lyxrc.ReadBindFile();
365 if (lyxerr.debugging(Debug::LYXRC)) {
369 // Create temp directory
370 system_tempdir = CreateLyXTmpDir(lyxrc.tempdir_path);
371 if (lyxerr.debugging(Debug::INIT)) {
372 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
375 // load the lastfiles mini-database
376 lyxerr[Debug::INIT] << "Reading lastfiles `"
377 << lyxrc.lastfiles << "'..." << endl;
378 lastfiles = new LastFiles(lyxrc.lastfiles,
379 lyxrc.check_lastfiles,
380 lyxrc.num_lastfiles);
382 // start up the lyxserver. (is this a bit early?) (Lgb)
383 // 0.12 this will be way to early, we need the GUI to be initialized
384 // first, so move it for now.
385 // lyxserver = new LyXServer;
389 // This one is not allowed to use anything on the main form, since that
390 // one does not exist yet. (Asger)
391 void LyX::queryUserLyXDir()
393 // Does user directory exist?
394 FileInfo fileInfo(user_lyxdir);
395 if (fileInfo.isOK() && fileInfo.isDir()) {
403 if (!AskQuestion(_("You don't have a personal LyX directory."),
404 _("It is needed to keep your own configuration."),
405 _("Should I try to set it up for you (recommended)?"))) {
406 lyxerr << _("Running without personal LyX directory.") << endl;
407 // No, let's use $HOME instead.
408 user_lyxdir = GetEnvPath("HOME");
412 // Tell the user what is going on
413 lyxerr << _("LyX: Creating directory ") << user_lyxdir
414 << _(" and running configure...") << endl;
416 // Create directory structure
417 if (!createDirectory(user_lyxdir, 0755)) {
418 // Failed, let's use $HOME instead.
419 user_lyxdir = GetEnvPath("HOME");
420 lyxerr << _("Failed. Will use ") << user_lyxdir
421 << _(" instead.") << endl;
425 // Run configure in user lyx directory
427 system(AddName(system_lyxdir, "configure").c_str());
428 lyxerr << "LyX: " << _("Done!") << endl;
432 // Read the rc file `name'
433 void LyX::ReadRcFile(string const & name)
435 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
437 string lyxrc_path = LibFileSearch(string(), name);
438 if (!lyxrc_path.empty()){
439 lyxerr[Debug::INIT] << "Found " << name
440 << " in " << lyxrc_path << endl;
441 if (lyxrc.read(lyxrc_path) < 0) {
442 WriteAlert(_("LyX Warning!"),
443 _("Error while reading ")+lyxrc_path+".",
444 _("Using built-in defaults."));
447 lyxerr[Debug::INIT] << "Could not find " << name << endl;
451 // Set debugging level and report result to user
452 void setDebuggingLevel(string const & dbgLevel)
454 lyxerr << _("Setting debug level to ") << dbgLevel << endl;
455 lyxerr.level(Debug::value(dbgLevel));
456 Debug::showLevel(lyxerr, lyxerr.level());
460 // Give command line help
461 void commandLineHelp()
463 lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
465 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
466 "Command line switches (case sensitive):\n"
467 "\t-help summarize LyX usage\n"
468 "\t-sysdir x try to set system directory to x\n"
469 "\t-width x set the width of the main window\n"
470 "\t-height y set the height of the main window\n"
471 "\t-xpos x set the x position of the main window\n"
472 "\t-ypos y set the y position of the main window\n"
473 "\t-dbg feature[,feature]...\n"
474 " select the features to debug.\n"
475 " Type `lyx -dbg' to see the list of features\n"
476 "Check the LyX man page for more options.") << endl;
480 bool LyX::easyParse(int * argc, char * argv[])
483 for(int i = 1; i < *argc; ++i) {
484 string arg = argv[i];
486 // Check for -dbg int
489 setDebuggingLevel(argv[i + 1]);
491 // Now, remove these two arguments by shifting
492 // the following two places down.
494 for (int j = i; j < (*argc); ++j)
495 argv[j] = argv[j + 2];
496 --i; // After shift, check this number again.
498 lyxerr << _("List of supported debug flags:")
500 Debug::showTags(lyxerr);
505 // Check for "-sysdir"
506 else if (arg == "-sysdir") {
508 system_lyxdir = argv[i + 1];
510 // Now, remove these two arguments by shifting
511 // the following two places down.
513 for (int j= i; j < (*argc); ++j)
514 argv[j] = argv[j + 2];
515 --i; // After shift, check this number again.
517 lyxerr << _("Missing directory for -sysdir switch!")
519 // Check for --help or -help
520 } else if (arg == "--help" || arg == "-help") {
524 // Check for "-nw": No window
525 else if (arg == "-nw") {
529 // Check for "-x": Execute commands
530 else if (arg == "-x" || arg == "--execute") {
532 batch_command = string(argv[i + 1]);
534 // Now, remove these two arguments by shifting
535 // the following two places down.
537 for (int j = i; j < (*argc); ++j)
538 argv[j] = argv[j + 2];
539 --i; // After shift, check this number again.
543 lyxerr << _("Missing command string after -x switch!") << endl;
545 // Argh. Setting gui to false segfaults..
549 else if (arg == "-e" || arg == "--export") {
551 string type(argv[i+1]);
554 for (int j = i; j < (*argc); ++j)
555 argv[j] = argv[j + 2];
556 --i; // After shift, check this number again.
560 else if (type == "ps")
562 else if (type == "text" || type == "txt")
565 if (type == "latex" || type == "postscript"
566 || type == "ascii" || type == "html")
567 batch_command = "buffer-export " + type;
569 lyxerr << _("Unknown file type '")
570 << type << _("' after ")
571 << arg << _(" switch!") << endl;
574 lyxerr << _("Missing file type [eg latex, "
576 << arg << _(" switch!") << endl;
583 void error_handler(int err_sig)
587 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
593 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
596 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
598 "Sorry, you have found a bug in LyX."
599 " If possible, please read 'Known bugs'\n"
600 "under the Help menu and then send us "
601 "a full bug report. Thanks!" << endl;
608 // Deinstall the signal handlers
609 signal(SIGHUP, SIG_DFL);
610 signal(SIGINT, SIG_DFL);
611 signal(SIGFPE, SIG_DFL);
612 signal(SIGSEGV, SIG_DFL);
613 signal(SIGTERM, SIG_DFL);
615 bufferlist.emergencyWriteAll();
617 lyxerr << "Bye." << endl;
618 if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))