]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
661d0149e56aae2f7d65dd2a94affee9e9c4113b
[lyx.git] / src / lyx_main.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include <cstdlib>
14 #include <csignal>
15
16 #include "version.h"
17 #include "lyx_main.h"
18 #include "lyx_gui.h"
19 #include "LyXView.h"
20 #include "lyxfunc.h"
21 #include "lyx_gui_misc.h"
22 #include "lyxrc.h"
23 #include "support/path.h"
24 #include "support/filetools.h"
25 #include "bufferlist.h"
26 #include "debug.h"
27 #include "support/FileInfo.h"
28 #include "lastfiles.h"
29 #include "intl.h"
30 #include "lyxserver.h"
31 #include "layout.h"
32 #include "gettext.h"
33 #include "kbmap.h"
34
35 using std::endl;
36
37 extern void LoadLyXFile(string const &);
38
39 string system_lyxdir;
40 string build_lyxdir;
41 string system_tempdir;
42 string user_lyxdir;     // Default $HOME/.lyx
43
44 // Should this be kept global? Asger says Yes.
45 DebugStream lyxerr;
46
47 LastFiles * lastfiles;
48
49 // This is the global bufferlist object
50 BufferList bufferlist;
51
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
55
56 // convenient to have it here.
57 kb_keymap * toplevel_keymap;
58
59
60 LyX::LyX(int * argc, char * argv[])
61 {
62         // Prevent crash with --help
63         lyxGUI = 0;
64         lastfiles = 0;
65
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);
69
70         // Global bindings (this must be done as early as possible.) (Lgb)
71         toplevel_keymap = new kb_keymap;
72         
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);
77         }
78
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;
84
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;
89
90         lyxGUI->init();
91
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
95         // filenames.
96         if ((*argc) == 2) 
97                 lyxerr[Debug::INFO] << "Opening document..." << endl;
98         else if ((*argc) > 2)
99                 lyxerr[Debug::INFO] << "Opening documents..." << endl;
100
101         Buffer * last_loaded = 0;
102
103         for (int argi = (*argc) - 1; argi >= 1; --argi) {
104                 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
105                 if (loadb != 0) {
106                         last_loaded = loadb;
107                 }
108         }
109
110         if (first_start) {
111                 string splash = i18nLibFileSearch("examples", "splash.lyx");
112                 lyxerr.debug() << "Opening splash document "
113                                << splash << "..." << endl;
114                 Buffer * loadb = bufferlist.loadLyXFile(splash);
115                 if (loadb != 0) {
116                         last_loaded = loadb;
117                 }
118         }
119
120         if (last_loaded != 0) {
121                 lyxerr.debug() << "Yes we loaded some files." << endl;
122                 if (lyxrc.use_gui)
123                         lyxGUI->regBuf(last_loaded);
124         }
125
126         // Execute batch commands if available
127         if (!batch_command.empty()) {
128                 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
129
130                 // no buffer loaded, create one
131                 if (!last_loaded)
132                         last_loaded = bufferlist.newFile("tmpfile", string());
133
134                 // try to dispatch to last loaded buffer first
135                 bool dispatched = last_loaded->Dispatch(batch_command);
136
137                 // if this was successful, return. 
138                 // Maybe we could do something more clever than aborting...
139                 if (dispatched) {
140                         lyxerr << "We are done!" << endl;
141                         return;
142                 }
143
144                 // otherwise, let the GUI handle the batch command
145                 lyxGUI->regBuf(last_loaded);
146                 lyxGUI->getLyXView()->getLyXFunc()->Dispatch(batch_command);
147
148                 // fall through...
149         }
150         
151         // Let the ball begin...
152         lyxGUI->runTime();
153 }
154
155
156 // A destructor is always necessary  (asierra-970604)
157 LyX::~LyX()
158 {
159         delete lastfiles;
160         delete lyxGUI;
161 }
162
163
164 extern "C" void error_handler(int err_sig);
165
166 void LyX::init(int */*argc*/, char **argv, bool gui)
167 {
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);
174
175         //
176         // Determine path of binary
177         //
178
179         string fullbinpath;
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);
185         
186         binpath = ExpandPath(binpath); // This expands ./ and ~/
187         
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]);
193         }
194
195         fullbinpath = binpath;
196         binpath = MakeAbsPath(OnlyPath(binpath));
197
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);
201
202         if (binpath.empty()) {
203                 lyxerr << _("Warning: could not determine path of binary.")
204                        << "\n"
205                        << _("If you have problems, try starting LyX with an absolute path.")
206                        << endl;
207         }
208         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
209
210         //
211         // Determine system directory.
212         //
213
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.
227
228         // If we had a command line switch, system_lyxdir is already set
229         string searchpath;
230         if (!system_lyxdir.empty())
231                 searchpath= MakeAbsPath(system_lyxdir) + ';';
232
233         // LYX_DIR_11x environment variable
234         string lyxdir = GetEnvPath("LYX_DIR_11x");
235         
236         if (!lyxdir.empty()) {
237                 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
238                 searchpath += lyxdir + ';';
239         }
240
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"),
245                                           binpath) + ';';
246                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
247                         "place... yes" << endl;
248         } else {
249                 lyxerr[Debug::INIT]
250                         << "Checking whether LyX is run in place... no"
251                         << endl;
252                 build_lyxdir.erase();
253         }
254
255         bool FollowLink;
256         do {
257           // Path of binary/../share/name of binary/
258                 searchpath += NormalizePath(AddPath(binpath, "../share/") + 
259                       OnlyFilename(binname)) + ';';
260
261           // Follow Symlinks
262                 FileInfo file(fullbinpath, true);
263                 FollowLink = file.isLink();
264                 if (FollowLink) {
265                         string Link;
266                         if (LyXReadLink(fullbinpath, Link)) {
267                                 fullbinpath = Link;
268                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
269                         }
270                         else {
271                                 FollowLink = false;
272                         }
273                 }
274         } while (FollowLink);
275
276         // Hardcoded dir
277         searchpath += LYX_DIR;
278
279         // If debugging, show complete search path
280         lyxerr[Debug::INIT] << "System directory search path: "
281                             << searchpath << endl;
282
283         string const filename = "chkconfig.ltx";
284         string temp = FileOpenSearch(searchpath, filename, string());
285         system_lyxdir = OnlyPath(temp);
286
287         // Reduce "path/../path" stuff out of system directory
288         system_lyxdir = NormalizePath(system_lyxdir);
289
290         bool path_shown = false;
291
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.")
296                                << '\n'
297                                << _("System directory set to: ") 
298                                << system_lyxdir << endl;
299                         path_shown = true;
300                 }
301         }
302
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;
310                 if (!path_shown)
311                         lyxerr << _("Using built-in default ") 
312                                << LYX_DIR << _(" but expect problems.")
313                                << endl;
314                 else
315                         lyxerr << _("Expect problems.") << endl;
316                 system_lyxdir = LYX_DIR;
317                 path_shown = true;
318         }
319
320         // Report the system directory if debugging is on
321         if (!path_shown)
322                 lyxerr[Debug::INIT] << "System directory: '"
323                                     << system_lyxdir << '\'' << endl; 
324
325         //
326         // Determine user lyx-dir
327         //
328         
329         user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
330         lyxerr[Debug::INIT] << "User LyX directory: '" 
331                             <<  user_lyxdir << '\'' << endl;
332
333         // Check that user LyX directory is ok.
334         queryUserLyXDir();
335
336         //
337         // Load the layouts first
338         //
339
340         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
341         LyXSetStyle();
342
343         //
344         // Shine up lyxrc defaults
345         //
346
347         // Default template path: system_dir/templates
348         if (lyxrc.template_path.empty()){
349                 lyxrc.template_path = AddPath(system_lyxdir, "templates");
350         }
351    
352         // Default lastfiles file: $HOME/.lyx/lastfiles
353         if (lyxrc.lastfiles.empty()){
354                 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
355         }
356
357         // Disable gui when either lyxrc or easyparse says so
358         if (!gui)
359                 lyxrc.use_gui = false;
360  
361         // Calculate screen dpi as average of x-DPI and y-DPI:
362         if (lyxrc.use_gui) {
363                 lyxrc.dpi = getScreenDPI();
364                 lyxerr[Debug::INFO] << "DPI setting detected to be "
365                                                 << lyxrc.dpi + 0.5 << endl;
366         } else {
367                 lyxrc.dpi = 1; // I hope this is safe
368         }
369
370         //
371         // Read configuration files
372         //
373
374         ReadRcFile("lyxrc.defaults");
375         ReadRcFile("lyxrc");
376
377         // Ensure that we have really read a bind file, so that LyX is
378         // usable.
379         if (!lyxrc.hasBindFile)
380                 lyxrc.ReadBindFile();
381
382         if (lyxerr.debugging(Debug::LYXRC)) {
383                 lyxrc.print();
384         }
385
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;
390         }
391
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);
398
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;
403 }
404
405
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()
409 {
410         // Does user directory exist?
411         FileInfo fileInfo(user_lyxdir);
412         if (fileInfo.isOK() && fileInfo.isDir()) {
413                 first_start = false;
414                 return;
415         } else {
416                 first_start = true;
417         }
418         
419         // Nope
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");
426                 return;
427         }
428
429         // Tell the user what is going on
430         lyxerr << _("LyX: Creating directory ") << user_lyxdir
431                << _(" and running configure...") << endl;
432
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;
439                 return;
440         }
441
442         // Run configure in user lyx directory
443         Path p(user_lyxdir);
444         system(AddName(system_lyxdir, "configure").c_str());
445         lyxerr << "LyX: " << _("Done!") << endl;
446 }
447
448
449 // Read the rc file `name'
450 void LyX::ReadRcFile(string const & name)
451 {
452         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
453         
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."));
462                 }
463         } else
464                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
465 }
466
467
468 // Set debugging level and report result to user
469 void setDebuggingLevel(string const & dbgLevel)
470 {
471         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
472         lyxerr.level(Debug::value(dbgLevel));
473         Debug::showLevel(lyxerr, lyxerr.level());
474 }
475
476
477 // Give command line help
478 void commandLineHelp()
479 {
480         lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
481         lyxerr <<
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;
494 }
495
496
497 bool LyX::easyParse(int * argc, char * argv[])
498 {
499         bool gui = true;
500         for(int i = 1; i < *argc; ++i) {
501                 string arg = argv[i];
502
503                 // Check for -dbg int
504                 if (arg == "-dbg") {
505                         if (i + 1 < *argc) {
506                                 setDebuggingLevel(argv[i + 1]);
507
508                                 // Now, remove these two arguments by shifting
509                                 // the following two places down.
510                                 (*argc) -= 2;
511                                 for (int j = i; j < (*argc); ++j)
512                                         argv[j] = argv[j + 2];
513                                 --i; // After shift, check this number again.
514                         } else {
515                                 lyxerr << _("List of supported debug flags:")
516                                        << endl;
517                                 Debug::showTags(lyxerr);
518                                 exit(0);
519                         }
520                 } 
521                 // Check for "-sysdir"
522                 else if (arg == "-sysdir") {
523                         if (i + 1 < *argc) {
524                                 system_lyxdir = argv[i + 1];
525
526                                 // Now, remove these two arguments by shifting
527                                 // the following two places down.
528                                 (*argc) -= 2;
529                                 for (int j= i; j < (*argc); ++j)
530                                         argv[j] = argv[j + 2];
531                                 --i; // After shift, check this number again.
532                         } else
533                                 lyxerr << _("Missing directory for -sysdir switch!")
534                                        << endl;
535                 // Check for --help or -help
536                 } else if (arg == "--help" || arg == "-help") {
537                         commandLineHelp();
538                         exit(0);
539                 } 
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") {
543                 //      gui = false;
544                 //}
545
546                 // Check for "-x": Execute commands
547                 else if (arg == "-x" || arg == "--execute") {
548                         if (i + 1 < *argc) {
549                                 batch_command = string(argv[i + 1]);
550
551                                 // Now, remove these two arguments by shifting
552                                 // the following two places down.
553                                 (*argc) -= 2;
554                                 for (int j = i; j < (*argc); ++j)
555                                         argv[j] = argv[j + 2];
556                                 --i; // After shift, check this number again.
557
558                         }
559                         else
560                                 lyxerr << _("Missing command string after  -x switch!") << endl;
561
562                         // Argh. Setting gui to false segfaults..
563                         //gui = false;
564                 }
565
566                 else if (arg == "-e" || arg == "--export") {
567                         if (i + 1 < *argc) {
568                                 string type(argv[i+1]);
569
570                                 (*argc) -= 2;
571                                 for (int j = i; j < (*argc); ++j)
572                                         argv[j] = argv[j + 2];
573                                 --i; // After shift, check this number again.
574
575                                 if (type == "tex")
576                                         type = "latex";
577                                 else if (type == "ps")
578                                         type = "postscript";
579                                 else if (type == "text" || type == "txt")
580                                         type = "ascii";
581
582                                 if (type == "latex" || type == "postscript"
583                                     || type == "ascii" || type == "html") 
584                                         batch_command = "buffer-export " + type;
585                                 else
586                                         lyxerr << _("Unknown file type '")
587                                                << type << _("' after ")
588                                                << arg << _(" switch!") << endl;
589                         } else
590                                 lyxerr << _("Missing file type [eg latex, "
591                                             "ps...] after ")
592                                        << arg << _(" switch!") << endl;
593                 }
594
595                 else if (arg == "--import") {
596                         if (i + 1 < *argc) {
597                                 string type(argv[i+1]);
598                                 string file(argv[i+2]);
599
600                                 (*argc) -= 3;
601                                 for (int j = i; j < (*argc); ++j)
602                                         argv[j] = argv[j + 3];
603                                 --i; // After shift, check this number again.
604         
605                                 batch_command = "buffer-import " + type + " " + file;
606                                 lyxerr << "batch_command: "
607                                        << batch_command << endl;
608
609                         } else
610                                 lyxerr << _("Missing type [eg latex, "
611                                             "ps...] after ")
612                                        << arg << _(" switch!") << endl;
613                 }
614         }
615
616         return gui;
617 }
618
619
620 extern "C"
621 void error_handler(int err_sig)
622 {
623         switch (err_sig) {
624         case SIGHUP:
625                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
626                 break;
627         case SIGINT:
628                 // no comments
629                 break;
630         case SIGFPE:
631                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
632                 break;
633         case SIGSEGV:
634                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
635                 lyxerr <<
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;
640                 break;
641         case SIGTERM:
642                 // no comments
643                 break;
644         }
645    
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);
652
653         bufferlist.emergencyWriteAll();
654
655         lyxerr << "Bye." << endl;
656         if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
657                 lyx::abort();
658         exit(0);
659 }