]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
cc5e5d1a7ccfe8a15be69df252727f3610fd2625
[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 "lyx_gui_misc.h"
20 #include "lyxrc.h"
21 #include "support/path.h"
22 #include "support/filetools.h"
23 #include "bufferlist.h"
24 #include "debug.h"
25 #include "support/FileInfo.h"
26 #include "lastfiles.h"
27 #include "intl.h"
28 #include "lyxserver.h"
29 #include "layout.h"
30 #include "gettext.h"
31 #include "kbmap.h"
32
33 using std::endl;
34
35 extern void LoadLyXFile(string const &);
36
37 string system_lyxdir;
38 string build_lyxdir;
39 string system_tempdir;
40 string user_lyxdir;     // Default $HOME/.lyx
41
42 // Should this be kept global? Asger says Yes.
43 DebugStream lyxerr;
44
45 LastFiles * lastfiles;
46
47 // This is the global bufferlist object
48 BufferList bufferlist;
49
50 LyXServer * lyxserver = 0;
51 // this should be static, but I need it in buffer.C
52 bool finished = false;  // flag, that we are quitting the program
53
54 // convenient to have it here.
55 kb_keymap * toplevel_keymap;
56
57
58 LyX::LyX(int * argc, char * argv[])
59 {
60         // Prevent crash with --help
61         lyxGUI = 0;
62         lastfiles = 0;
63
64         // Here we need to parse the command line. At least
65         // we need to parse for "-dbg" and "-help"
66         bool gui = easyParse(argc, argv);
67
68         // Global bindings (this must be done as early as possible.) (Lgb)
69         toplevel_keymap = new kb_keymap;
70         // Fill the toplevel_keymap with some defaults
71         for (LyXRC::Bindings::const_iterator cit = lyxrc.bindings.begin();
72              cit != lyxrc.bindings.end(); ++cit) {
73                 toplevel_keymap->bind((*cit).first.c_str(), (*cit).second);
74         }
75
76         // Make the GUI object, and let it take care of the
77         // command line arguments that concerns it.
78         lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
79         lyxGUI = new LyXGUI(this, argc, argv, gui);
80         lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
81
82         // Initialization of LyX (reads lyxrc and more)
83         lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
84         init(argc, argv, gui);
85         lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
86
87         lyxGUI->init();
88
89         // Load the files specified in the command line.
90         // Now the GUI and LyX have taken care of their arguments, so
91         // the only thing left on the command line should be
92         // filenames.
93         if ((*argc) == 2) 
94                 lyxerr[Debug::INFO] << "Opening document..." << endl;
95         else if ((*argc) > 2)
96                 lyxerr[Debug::INFO] << "Opening documents..." << endl;
97
98         Buffer * last_loaded = 0;
99
100         for (int argi = (*argc) - 1; argi >= 1; --argi) {
101                 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
102                 if (loadb != 0) {
103                         last_loaded = loadb;
104                 }
105         }
106
107         if (first_start) {
108                 string splash = i18nLibFileSearch("examples", "splash.lyx");
109                 lyxerr.debug() << "Opening splash document "
110                                << splash << "..." << endl;
111                 Buffer * loadb = bufferlist.loadLyXFile(splash);
112                 if (loadb != 0) {
113                         last_loaded = loadb;
114                 }
115         }
116
117         if (last_loaded != 0) {
118                 lyxerr.debug() << "Yes we loaded some files." << endl;
119                 if (lyxrc.use_gui)
120                         lyxGUI->regBuf(last_loaded);
121         }
122
123         // Execute batch commands if available
124         if (!batch_command.empty() && last_loaded) {
125                 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
126                 //Buffer buffer("Script Buffer");
127                 //buffer.Dispatch(batch_command);
128                 last_loaded->Dispatch(batch_command);
129                 lyxerr << "We are done!" << endl;
130                 return; // Maybe we could do something more clever than aborting..
131         }
132         
133         // Let the ball begin...
134         lyxGUI->runTime();
135 }
136
137
138 // A destructor is always necessary  (asierra-970604)
139 LyX::~LyX()
140 {
141         delete lastfiles;
142         delete lyxGUI;
143 }
144
145
146 extern "C" void error_handler(int err_sig);
147
148 void LyX::init(int */*argc*/, char **argv, bool gui)
149 {
150         // Install the signal handlers
151         signal(SIGHUP, error_handler);
152         signal(SIGFPE, error_handler);
153         signal(SIGSEGV, error_handler);
154         signal(SIGINT, error_handler);
155         signal(SIGTERM, error_handler);
156
157         //
158         // Determine path of binary
159         //
160
161         string fullbinpath;
162         string binpath = subst(argv[0], '\\', '/');
163         string binname = OnlyFilename(argv[0]);
164         // Sorry for system specific code. (SMiyata)
165         if (suffixIs(binname, ".exe")) 
166                 binname.erase(binname.length()-4, string::npos);
167         
168         binpath = ExpandPath(binpath); // This expands ./ and ~/
169         
170         if (!AbsolutePath(binpath)) {
171                 string binsearchpath = GetEnvPath("PATH");
172                 // This will make "src/lyx" work always :-)
173                 binsearchpath += ";."; 
174                 binpath = FileOpenSearch(binsearchpath, argv[0]);
175         }
176
177         fullbinpath = binpath;
178         binpath = MakeAbsPath(OnlyPath(binpath));
179
180         // In case we are running in place and compiled with shared libraries
181         if (suffixIs(binpath, "/.libs/"))
182                 binpath.erase(binpath.length()-6, string::npos);
183
184         if (binpath.empty()) {
185                 lyxerr << _("Warning: could not determine path of binary.")
186                        << "\n"
187                        << _("If you have problems, try starting LyX with an absolute path.")
188                        << endl;
189         }
190         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
191
192         //
193         // Determine system directory.
194         //
195
196         // Directories are searched in this order:
197         // 1) -sysdir command line parameter
198         // 2) LYX_DIR_11x environment variable
199         // 3) Maybe <path of binary>/TOP_SRCDIR/lib
200         // 4) <path of binary>/../share/<name of binary>/
201         // 4a) repeat 4 after following the Symlink if <path of
202         //     binary> is a symbolic link.
203         // 5) hardcoded lyx_dir
204         // The directory is checked for the presence of the file
205         // "chkconfig.ltx", and if that is present, the directory
206         // is accepted as the system directory.
207         // If no chkconfig.ltx file is found, a warning is given,
208         // and the hardcoded lyx_dir is used.
209
210         // If we had a command line switch, system_lyxdir is already set
211         string searchpath;
212         if (!system_lyxdir.empty())
213                 searchpath= MakeAbsPath(system_lyxdir) + ';';
214
215         // LYX_DIR_11x environment variable
216         string lyxdir = GetEnvPath("LYX_DIR_11x");
217         
218         if (!lyxdir.empty()) {
219                 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
220                 searchpath += lyxdir + ';';
221         }
222
223         // <path of binary>/TOP_SRCDIR/lib
224         build_lyxdir = MakeAbsPath("../lib", binpath);
225         if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
226                 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
227                                           binpath) + ';';
228                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
229                         "place... yes" << endl;
230         } else {
231                 lyxerr[Debug::INIT]
232                         << "Checking whether LyX is run in place... no"
233                         << endl;
234                 build_lyxdir.clear();
235         }
236
237         bool FollowLink;
238         do {
239           // Path of binary/../share/name of binary/
240                 searchpath += NormalizePath(AddPath(binpath, "../share/") + 
241                       OnlyFilename(binname)) + ';';
242
243           // Follow Symlinks
244                 FileInfo file(fullbinpath, true);
245                 FollowLink = file.isLink();
246                 if (FollowLink) {
247                         string Link;
248                         if (LyXReadLink(fullbinpath, Link)) {
249                                 fullbinpath = Link;
250                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
251                         }
252                         else {
253                                 FollowLink = false;
254                         }
255                 }
256         } while (FollowLink);
257
258         // Hardcoded dir
259         searchpath += LYX_DIR;
260
261         // If debugging, show complete search path
262         lyxerr[Debug::INIT] << "System directory search path: "
263                             << searchpath << endl;
264
265         string const filename = "chkconfig.ltx";
266         string temp = FileOpenSearch(searchpath, filename, string());
267         system_lyxdir = OnlyPath(temp);
268
269         // Reduce "path/../path" stuff out of system directory
270         system_lyxdir = NormalizePath(system_lyxdir);
271
272         bool path_shown = false;
273
274         // Warn if environment variable is set, but unusable
275         if (!lyxdir.empty()) {
276                 if (system_lyxdir != NormalizePath(lyxdir)) {
277                         lyxerr <<_("LYX_DIR_11x environment variable no good.")
278                                << '\n'
279                                << _("System directory set to: ") 
280                                << system_lyxdir << endl;
281                         path_shown = true;
282                 }
283         }
284
285         // Warn the user if we couldn't find "chkconfig.ltx"
286         if (system_lyxdir == "./") {
287                 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
288                        <<_("Try the '-sysdir' command line parameter or")
289                        <<_("set the environment variable LYX_DIR_11x to the "
290                            "LyX system directory")
291                        << _("containing the file `chkconfig.ltx'.") << endl;
292                 if (!path_shown)
293                         lyxerr << _("Using built-in default ") 
294                                << LYX_DIR << _(" but expect problems.")
295                                << endl;
296                 else
297                         lyxerr << _("Expect problems.") << endl;
298                 system_lyxdir = LYX_DIR;
299                 path_shown = true;
300         }
301
302         // Report the system directory if debugging is on
303         if (!path_shown)
304                 lyxerr[Debug::INIT] << "System directory: '"
305                                     << system_lyxdir << '\'' << endl; 
306
307         //
308         // Determine user lyx-dir
309         //
310         
311         user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
312         lyxerr[Debug::INIT] << "User LyX directory: '" 
313                             <<  user_lyxdir << '\'' << endl;
314
315         // Check that user LyX directory is ok.
316         queryUserLyXDir();
317
318         //
319         // Load the layouts first
320         //
321
322         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
323         LyXSetStyle();
324
325         //
326         // Shine up lyxrc defaults
327         //
328
329         // Default template path: system_dir/templates
330         if (lyxrc.template_path.empty()){
331                 lyxrc.template_path = AddPath(system_lyxdir, "templates");
332         }
333    
334         // Default lastfiles file: $HOME/.lyx/lastfiles
335         if (lyxrc.lastfiles.empty()){
336                 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
337         }
338
339         // Disable gui when either lyxrc or easyparse says so
340         if (!gui)
341                 lyxrc.use_gui = false;
342  
343         // Calculate screen dpi as average of x-DPI and y-DPI:
344         if (lyxrc.use_gui) {
345                 lyxrc.dpi = getScreenDPI();
346                 lyxerr[Debug::INFO] << "DPI setting detected to be "
347                                                 << lyxrc.dpi + 0.5 << endl;
348         } else {
349                 lyxrc.dpi = 1; // I hope this is safe
350         }
351
352         //
353         // Read configuration files
354         //
355
356         ReadRcFile("lyxrc.defaults");
357         ReadRcFile("lyxrc");
358
359         // Ensure that we have really read a bind file, so that LyX is
360         // usable.
361         if (!lyxrc.hasBindFile)
362                 lyxrc.ReadBindFile();
363
364         if (lyxerr.debugging(Debug::LYXRC)) {
365                 lyxrc.print();
366         }
367
368         // Create temp directory        
369         system_tempdir = CreateLyXTmpDir(lyxrc.tempdir_path);
370         if (lyxerr.debugging(Debug::INIT)) {
371                 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
372         }
373
374         // load the lastfiles mini-database
375         lyxerr[Debug::INIT] << "Reading lastfiles `"
376                             << lyxrc.lastfiles << "'..." << endl; 
377         lastfiles = new LastFiles(lyxrc.lastfiles, 
378                                   lyxrc.check_lastfiles,
379                                   lyxrc.num_lastfiles);
380
381         // start up the lyxserver. (is this a bit early?) (Lgb)
382         // 0.12 this will be way to early, we need the GUI to be initialized
383         // first, so move it for now.
384         // lyxserver = new LyXServer;
385 }
386
387
388 // This one is not allowed to use anything on the main form, since that
389 // one does not exist yet. (Asger)
390 void LyX::queryUserLyXDir()
391 {
392         // Does user directory exist?
393         FileInfo fileInfo(user_lyxdir);
394         if (fileInfo.isOK() && fileInfo.isDir()) {
395                 first_start = false;
396                 return;
397         } else {
398                 first_start = true;
399         }
400         
401         // Nope
402         if (!AskQuestion(_("You don't have a personal LyX directory."),
403                          _("It is needed to keep your own configuration."),
404                          _("Should I try to set it up for you (recommended)?"))) {
405                 lyxerr << _("Running without personal LyX directory.") << endl;
406                 // No, let's use $HOME instead.
407                 user_lyxdir = GetEnvPath("HOME");
408                 return;
409         }
410
411         // Tell the user what is going on
412         lyxerr << _("LyX: Creating directory ") << user_lyxdir
413                << _(" and running configure...") << endl;
414
415         // Create directory structure
416         if (!createDirectory(user_lyxdir, 0755)) {
417                 // Failed, let's use $HOME instead.
418                 user_lyxdir = GetEnvPath("HOME");
419                 lyxerr << _("Failed. Will use ") << user_lyxdir
420                        << _(" instead.") << endl;
421                 return;
422         }
423
424         // Run configure in user lyx directory
425         Path p(user_lyxdir);
426         system(AddName(system_lyxdir, "configure").c_str());
427         lyxerr << "LyX: " << _("Done!") << endl;
428 }
429
430
431 // Read the rc file `name'
432 void LyX::ReadRcFile(string const & name)
433 {
434         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
435         
436         string lyxrc_path = LibFileSearch(string(), name);
437         if (!lyxrc_path.empty()){
438                 lyxerr[Debug::INIT] << "Found " << name
439                                     << " in " << lyxrc_path << endl;
440                 if (lyxrc.read(lyxrc_path) < 0) { 
441                         WriteAlert(_("LyX Warning!"), 
442                                    _("Error while reading ")+lyxrc_path+".",
443                                    _("Using built-in defaults."));
444                 }
445         } else
446                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
447 }
448
449
450 // Set debugging level and report result to user
451 void setDebuggingLevel(string const & dbgLevel)
452 {
453         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
454         lyxerr.level(Debug::value(dbgLevel));
455         Debug::showLevel(lyxerr, lyxerr.level());
456 }
457
458
459 // Give command line help
460 void commandLineHelp()
461 {
462         lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
463         lyxerr <<
464                 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
465                   "Command line switches (case sensitive):\n"
466                   "\t-help           summarize LyX usage\n"
467                   "\t-sysdir x       try to set system directory to x\n"
468                   "\t-width x        set the width of the main window\n"
469                   "\t-height y       set the height of the main window\n"
470                   "\t-xpos x         set the x position of the main window\n"
471                   "\t-ypos y         set the y position of the main window\n"
472                   "\t-dbg feature[,feature]...\n"
473                   "                  select the features to debug.\n"
474                   "                  Type `lyx -dbg' to see the list of features\n"
475                   "Check the LyX man page for more options.") << endl;
476 }
477
478
479 bool LyX::easyParse(int * argc, char * argv[])
480 {
481         bool gui = true;
482         for(int i = 1; i < *argc; ++i) {
483                 string arg = argv[i];
484
485                 // Check for -dbg int
486                 if (arg == "-dbg") {
487                         if (i + 1 < *argc) {
488                                 setDebuggingLevel(argv[i + 1]);
489
490                                 // Now, remove these two arguments by shifting
491                                 // the following two places down.
492                                 (*argc) -= 2;
493                                 for (int j = i; j < (*argc); ++j)
494                                         argv[j] = argv[j + 2];
495                                 --i; // After shift, check this number again.
496                         } else {
497                                 lyxerr << _("List of supported debug flags:")
498                                        << endl;
499                                 Debug::showTags(lyxerr);
500                                 exit(0);
501                         }
502                 } 
503                 // Check for "-sysdir"
504                 else if (arg == "-sysdir") {
505                         if (i + 1 < *argc) {
506                                 system_lyxdir = 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 << _("Missing directory for -sysdir switch!")
516                                        << endl;
517                 // Check for --help or -help
518                 } else if (arg == "--help" || arg == "-help") {
519                         commandLineHelp();
520                         exit(0);
521                 } 
522                 // Check for "-nw": No XWindows as for emacs this should
523                 // give a LyX that could be used in a terminal window.
524                 //else if (arg == "-nw") {
525                 //      gui = false;
526                 //}
527
528                 // Check for "-x": Execute commands
529                 else if (arg == "-x" || arg == "--execute") {
530                         if (i + 1 < *argc) {
531                                 batch_command = string(argv[i + 1]);
532
533                                 // Now, remove these two arguments by shifting
534                                 // the following two places down.
535                                 (*argc) -= 2;
536                                 for (int j = i; j < (*argc); ++j)
537                                         argv[j] = argv[j + 2];
538                                 --i; // After shift, check this number again.
539
540                         }
541                         else
542                                 lyxerr << _("Missing command string after  -x switch!") << endl;
543
544                         // Argh. Setting gui to false segfaults..
545                         //gui = false;
546                 }
547
548                 else if (arg == "-e" || arg == "--export") {
549                         if (i + 1 < *argc) {
550                                 string type(argv[i+1]);
551
552                                 (*argc) -= 2;
553                                 for (int j = i; j < (*argc); ++j)
554                                         argv[j] = argv[j + 2];
555                                 --i; // After shift, check this number again.
556
557                                 if (type == "tex")
558                                         type = "latex";
559                                 else if (type == "ps")
560                                         type = "postscript";
561                                 else if (type == "text" || type == "txt")
562                                         type = "ascii";
563
564                                 if (type == "latex" || type == "postscript"
565                                     || type == "ascii" || type == "html") 
566                                         batch_command = "buffer-export " + type;
567                                 else
568                                         lyxerr << _("Unknown file type '")
569                                                << type << _("' after ")
570                                                << arg << _(" switch!") << endl;
571                         } else
572                                 lyxerr << _("Missing file type [eg latex, "
573                                             "ps...] after ")
574                                        << arg << _(" switch!") << endl;
575                 }
576         }
577         return gui;
578 }
579
580
581 extern "C"
582 void error_handler(int err_sig)
583 {
584         switch (err_sig) {
585         case SIGHUP:
586                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
587                 break;
588         case SIGINT:
589                 // no comments
590                 break;
591         case SIGFPE:
592                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
593                 break;
594         case SIGSEGV:
595                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
596                 lyxerr <<
597                         "Sorry, you have found a bug in LyX."
598                         " If possible, please read 'Known bugs'\n"
599                         "under the Help menu and then send us "
600                         "a full bug report. Thanks!" << endl;
601                 break;
602         case SIGTERM:
603                 // no comments
604                 break;
605         }
606    
607         // Deinstall the signal handlers
608         signal(SIGHUP, SIG_DFL);
609         signal(SIGINT, SIG_DFL);
610         signal(SIGFPE, SIG_DFL);
611         signal(SIGSEGV, SIG_DFL);
612         signal(SIGTERM, SIG_DFL);
613
614         bufferlist.emergencyWriteAll();
615
616         lyxerr << "Bye." << endl;
617         if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
618                 lyx::abort();
619         exit(0);
620 }