]> git.lyx.org Git - features.git/blob - src/lyx_main.C
Small fixes
[features.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 extern void LoadLyXFile(string const &);
34
35 string system_lyxdir;
36 string build_lyxdir;
37 string system_tempdir;
38 string user_lyxdir;     // Default $HOME/.lyx
39
40 // Should this be kept global? Asger says Yes.
41 DebugStream lyxerr;
42
43 LastFiles * lastfiles;
44
45 // This is the global bufferlist object
46 BufferList bufferlist;
47
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
51
52 // convenient to have it here.
53 kb_keymap * toplevel_keymap;
54
55
56 LyX::LyX(int * argc, char * argv[])
57 {
58         // Prevent crash with --help
59         lyxGUI = 0;
60         lastfiles = 0;
61
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);
65
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);
72         }
73
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;
79
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;
84
85         lyxGUI->init();
86
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
90         // filenames.
91         if ((*argc) == 2) 
92                 lyxerr[Debug::INFO] << "Opening document..." << endl;
93         else if ((*argc) > 2)
94                 lyxerr[Debug::INFO] << "Opening documents..." << endl;
95
96         Buffer * last_loaded = 0;
97
98         for (int argi = (*argc) - 1; argi >= 1; --argi) {
99                 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
100                 if (loadb != 0) {
101                         last_loaded = loadb;
102                 }
103         }
104
105         if (first_start) {
106                 string splash = i18nLibFileSearch("examples", "splash.lyx");
107                 lyxerr.debug() << "Opening splash document "
108                                << splash << "..." << endl;
109                 Buffer * loadb = bufferlist.loadLyXFile(splash);
110                 if (loadb != 0) {
111                         last_loaded = loadb;
112                 }
113         }
114
115         if (last_loaded != 0) {
116                 lyxerr.debug() << "Yes we loaded some files." << endl;
117                 if (lyxrc.use_gui)
118                         lyxGUI->regBuf(last_loaded);
119         }
120
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..
129         }
130         
131         // Let the ball begin...
132         lyxGUI->runTime();
133 }
134
135
136 // A destructor is always necessary  (asierra-970604)
137 LyX::~LyX()
138 {
139         delete lastfiles;
140         delete lyxGUI;
141 }
142
143
144 extern "C" void error_handler(int err_sig);
145
146 void LyX::init(int */*argc*/, char **argv, bool gui)
147 {
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);
154
155         //
156         // Determine path of binary
157         //
158
159         string fullbinpath;
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);
165         
166         binpath = ExpandPath(binpath); // This expands ./ and ~/
167         
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]);
173         }
174
175         fullbinpath = binpath;
176         binpath = MakeAbsPath(OnlyPath(binpath));
177
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);
181
182         if (binpath.empty()) {
183                 lyxerr << _("Warning: could not determine path of binary.")
184                        << "\n"
185                        << _("If you have problems, try starting LyX with an absolute path.")
186                        << endl;
187         }
188         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
189
190         //
191         // Determine system directory.
192         //
193
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.
207
208         // If we had a command line switch, system_lyxdir is already set
209         string searchpath;
210         if (!system_lyxdir.empty())
211                 searchpath= MakeAbsPath(system_lyxdir) + ';';
212
213         // LYX_DIR_11x environment variable
214         string lyxdir = GetEnvPath("LYX_DIR_11x");
215         
216         if (!lyxdir.empty()) {
217                 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
218                 searchpath += lyxdir + ';';
219         }
220
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"),
225                                           binpath) + ';';
226                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
227                         "place... yes" << endl;
228         } else {
229                 lyxerr[Debug::INIT]
230                         << "Checking whether LyX is run in place... no"
231                         << endl;
232                 build_lyxdir.clear();
233         }
234
235         bool FollowLink;
236         do {
237           // Path of binary/../share/name of binary/
238                 searchpath += NormalizePath(AddPath(binpath, "../share/") + 
239                       OnlyFilename(binname)) + ';';
240
241           // Follow Symlinks
242                 FileInfo file(fullbinpath, true);
243                 FollowLink = file.isLink();
244                 if (FollowLink) {
245                         string Link;
246                         if (LyXReadLink(fullbinpath, Link)) {
247                                 fullbinpath = Link;
248                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
249                         }
250                         else {
251                                 FollowLink = false;
252                         }
253                 }
254         } while (FollowLink);
255
256         // Hardcoded dir
257         searchpath += LYX_DIR;
258
259         // If debugging, show complete search path
260         lyxerr[Debug::INIT] << "System directory search path: "
261                             << searchpath << endl;
262
263         string const filename = "chkconfig.ltx";
264         string temp = FileOpenSearch(searchpath, filename, string());
265         system_lyxdir = OnlyPath(temp);
266
267         // Reduce "path/../path" stuff out of system directory
268         system_lyxdir = NormalizePath(system_lyxdir);
269
270         bool path_shown = false;
271
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.")
276                                << '\n'
277                                << _("System directory set to: ") 
278                                << system_lyxdir << endl;
279                         path_shown = true;
280                 }
281         }
282
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;
290                 if (!path_shown)
291                         lyxerr << _("Using built-in default ") 
292                                << LYX_DIR << _(" but expect problems.")
293                                << endl;
294                 else
295                         lyxerr << _("Expect problems.") << endl;
296                 system_lyxdir = LYX_DIR;
297                 path_shown = true;
298         }
299
300         // Report the system directory if debugging is on
301         if (!path_shown)
302                 lyxerr[Debug::INIT] << "System directory: '"
303                                     << system_lyxdir << '\'' << endl; 
304
305         //
306         // Determine user lyx-dir
307         //
308         
309         user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
310         lyxerr[Debug::INIT] << "User LyX directory: '" 
311                             <<  user_lyxdir << '\'' << endl;
312
313         // Check that user LyX directory is ok.
314         queryUserLyXDir();
315
316         //
317         // Load the layouts first
318         //
319
320         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
321         LyXSetStyle();
322
323         //
324         // Shine up lyxrc defaults
325         //
326
327         // Default template path: system_dir/templates
328         if (lyxrc.template_path.empty()){
329                 lyxrc.template_path = AddPath(system_lyxdir, "templates");
330         }
331    
332         // Default lastfiles file: $HOME/.lyx/lastfiles
333         if (lyxrc.lastfiles.empty()){
334                 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
335         }
336
337         // Calculate screen dpi as average of x-DPI and y-DPI:
338         // Disable gui when either lyxrc or easyparse says so
339         if (!gui)
340                 lyxrc.use_gui = false;
341  
342         // Calculate screen dpi as average of x-DPI and y-DPI:
343         if (lyxrc.use_gui) {
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;
349         } else {
350                 lyxrc.dpi = 1; // I hope this is safe
351         }
352
353         //
354         // Read configuration files
355         //
356
357         ReadRcFile("lyxrc.defaults");
358         ReadRcFile("lyxrc");
359
360         // Ensure that we have really read a bind file, so that LyX is
361         // usable.
362         if (!lyxrc.hasBindFile)
363                 lyxrc.ReadBindFile();
364
365         if (lyxerr.debugging(Debug::LYXRC)) {
366                 lyxrc.print();
367         }
368
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;
373         }
374
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);
381
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;
386 }
387
388
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()
392 {
393         // Does user directory exist?
394         FileInfo fileInfo(user_lyxdir);
395         if (fileInfo.isOK() && fileInfo.isDir()) {
396                 first_start = false;
397                 return;
398         } else {
399                 first_start = true;
400         }
401         
402         // Nope
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");
409                 return;
410         }
411
412         // Tell the user what is going on
413         lyxerr << _("LyX: Creating directory ") << user_lyxdir
414                << _(" and running configure...") << endl;
415
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;
422                 return;
423         }
424
425         // Run configure in user lyx directory
426         Path p(user_lyxdir);
427         system(AddName(system_lyxdir, "configure").c_str());
428         lyxerr << "LyX: " << _("Done!") << endl;
429 }
430
431
432 // Read the rc file `name'
433 void LyX::ReadRcFile(string const & name)
434 {
435         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
436         
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."));
445                 }
446         } else
447                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
448 }
449
450
451 // Set debugging level and report result to user
452 void setDebuggingLevel(string const & dbgLevel)
453 {
454         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
455         lyxerr.level(Debug::value(dbgLevel));
456         Debug::showLevel(lyxerr, lyxerr.level());
457 }
458
459
460 // Give command line help
461 void commandLineHelp()
462 {
463         lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
464         lyxerr <<
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;
477 }
478
479
480 bool LyX::easyParse(int * argc, char * argv[])
481 {
482         bool gui = true;
483         for(int i = 1; i < *argc; ++i) {
484                 string arg = argv[i];
485
486                 // Check for -dbg int
487                 if (arg == "-dbg") {
488                         if (i + 1 < *argc) {
489                                 setDebuggingLevel(argv[i + 1]);
490
491                                 // Now, remove these two arguments by shifting
492                                 // the following two places down.
493                                 (*argc) -= 2;
494                                 for (int j = i; j < (*argc); ++j)
495                                         argv[j] = argv[j + 2];
496                                 --i; // After shift, check this number again.
497                         } else {
498                                 lyxerr << _("List of supported debug flags:")
499                                        << endl;
500                                 Debug::showTags(lyxerr);
501                                 exit(0);
502                         }
503                         
504                 } 
505                 // Check for "-sysdir"
506                 else if (arg == "-sysdir") {
507                         if (i + 1 < *argc) {
508                                 system_lyxdir = argv[i + 1];
509
510                                 // Now, remove these two arguments by shifting
511                                 // the following two places down.
512                                 (*argc) -= 2;
513                                 for (int j= i; j < (*argc); ++j)
514                                         argv[j] = argv[j + 2];
515                                 --i; // After shift, check this number again.
516                         } else
517                                 lyxerr << _("Missing directory for -sysdir switch!")
518                                        << endl;
519                 // Check for --help or -help
520                 } else if (arg == "--help" || arg == "-help") {
521                         commandLineHelp();
522                         exit(0);
523                 } 
524                 // Check for "-nw": No window
525                 else if (arg == "-nw") {
526                         gui = false;
527                 }
528
529                 // Check for "-x": Execute commands
530                 else if (arg == "-x" || arg == "--execute") {
531                         if (i + 1 < *argc) {
532                                 batch_command = string(argv[i + 1]);
533
534                                 // Now, remove these two arguments by shifting
535                                 // the following two places down.
536                                 (*argc) -= 2;
537                                 for (int j = i; j < (*argc); ++j)
538                                         argv[j] = argv[j + 2];
539                                 --i; // After shift, check this number again.
540
541                         }
542                         else
543                                 lyxerr << _("Missing command string after  -x switch!") << endl;
544
545                         // Argh. Setting gui to false segfaults..
546                         //gui = false;
547                 }
548
549                 else if (arg == "-e" || arg == "--export") {
550                         if (i + 1 < *argc) {
551                                 string type(argv[i+1]);
552
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                                 if (type == "tex")
559                                         type = "latex";
560                                 else if (type == "ps")
561                                         type = "postscript";
562                                 else if (type == "text" || type == "txt")
563                                         type = "ascii";
564
565                                 if (type == "latex" || type == "postscript"
566                                     || type == "ascii" || type == "html") 
567                                         batch_command = "buffer-export " + type;
568                                 else
569                                         lyxerr << _("Unknown file type '")
570                                                << type << _("' after ")
571                                                << arg << _(" switch!") << endl;
572                         }
573                         else
574                                 lyxerr << _("Missing file type [eg latex, "
575                                             "ps...] after ")
576                                        << arg << _(" switch!") << endl;
577                 }
578         }
579         return gui;
580 }
581
582
583 void error_handler(int err_sig)
584 {
585         switch (err_sig) {
586         case SIGHUP:
587                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
588                 break;
589         case SIGINT:
590                 // no comments
591                 break;
592         case SIGFPE:
593                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
594                 break;
595         case SIGSEGV:
596                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
597                 lyxerr <<
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;
602                 break;
603         case SIGTERM:
604                 // no comments
605                 break;
606         }
607    
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);
614
615         bufferlist.emergencyWriteAll();
616
617         lyxerr << "Bye." << endl;
618         if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
619                 lyx::abort();
620         exit(0);
621 }