]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
merge from the string-switch branch and ready for a prelease.
[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-1999 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 "pathstack.h"
22 #include "support/filetools.h"
23 #include "bufferlist.h"
24 #include "error.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
32 extern void LoadLyXFile(string const &);
33
34 string system_lyxdir;
35 string build_lyxdir;
36 string system_tempdir;
37 string user_lyxdir;     // Default $HOME/.lyx
38
39 // Should this be kept global? Asger says Yes.
40 Error lyxerr;
41
42 LastFiles *lastfiles;
43 LyXRC *lyxrc;
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 // from spellchecker.C
56 #if 0
57 extern void sigchldhandler(int sig);
58 #endif
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         lyxerr.debug("Initializing lyxrc");
74         lyxrc = new LyXRC;
75
76         // Make the GUI object, and let it take care of the
77         // command line arguments that concerns it.
78         lyxerr.debug("Initializing LyXGUI...");
79         lyxGUI = new LyXGUI(this, argc, argv, gui);
80         lyxerr.debug("Initializing LyXGUI...done");
81
82         // Initialization of LyX (reads lyxrc and more)
83         lyxerr.debug("Initializing LyX::init...");
84         init(argc, argv);
85         lyxerr.debug("Initializing LyX::init...done");
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("Opening document...");
95         else if ((*argc)>2)
96                 lyxerr.debug("Opening documents...");
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 "+splash+"...");
110                 Buffer * loadb = bufferlist.loadLyXFile(splash);
111                 if (loadb != 0) {
112                         last_loaded = loadb;
113                 }
114         }
115
116         if (last_loaded != 0) {
117                 lyxerr.debug("Yes we loaded some files.");
118                 lyxGUI->regBuf(last_loaded);
119         }
120         
121         // Let the ball begin...
122         lyxGUI->runTime();
123 }
124
125
126 // A destructor is always necessary  (asierra-970604)
127 LyX::~LyX()
128 {
129         if (lastfiles)
130                 delete lastfiles;
131
132         if (lyxGUI)
133                 delete lyxGUI;
134 }
135
136
137 extern "C" void error_handler(int err_sig);
138
139 void LyX::init(int */*argc*/, char **argv)
140 {
141         // Install the signal handlers
142         signal(SIGHUP, error_handler);
143         signal(SIGFPE, error_handler);
144         signal(SIGSEGV, error_handler);
145         signal(SIGINT, error_handler);
146         signal(SIGTERM, error_handler);
147
148 #if 0
149         // Install the SIGCHLD handler
150         act_.sa_handler = sigchldhandler;
151         //act_.sa_mask = SIGCHLD;
152         act_.sa_flags = 0;
153         //act_.sa_flags = SA_RESTART; //perhaps
154         sigaction(SIGCHLD, &act_, 0);
155 #endif
156         //
157         // Determine path of binary
158         //
159
160         string fullbinpath, binpath = argv[0];
161         subst(binpath, '\\', '/');
162         string binname = OnlyFilename(argv[0]);
163         // Sorry for system specific code. (SMiyata)
164         if (suffixIs(binname, ".exe")) 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                 binsearchpath += ";."; // This will make "src/lyx" work always :-)
171                 binpath = FileOpenSearch(binsearchpath, argv[0]);
172         }
173
174         fullbinpath = binpath;
175         binpath = MakeAbsPath(OnlyPath(binpath));
176
177         if (binpath.empty()) {
178                 lyxerr.print(_("Warning: could not determine path of binary."));
179                 lyxerr.print(_("If you have problems, try starting LyX with an absolute path."));
180         }
181         lyxerr.debug("Path of binary: " + binpath);
182
183         //
184         // Determine system directory.
185         //
186
187         // Directories are searched in this order:
188         // 1) -sysdir command line parameter
189         // 2) LYX_DIR_10x environment variable
190         // 3) Maybe <path of binary>/TOP_SRCDIR/lib
191         // 4) <path of binary>/../share/<name of binary>/
192         // 4a) repeat 4 after following the Symlink if <path of
193         //     binary> is a symbolic link.
194         // 5) hardcoded lyx_dir
195         // The directory is checked for the presence of the file
196         // "chkconfig.ltx", and if that is present, the directory
197         // is accepted as the system directory.
198         // If no chkconfig.ltx file is found, a warning is given,
199         // and the hardcoded lyx_dir is used.
200
201         // If we had a command line switch, system_lyxdir is already set
202         string searchpath;
203         if (!system_lyxdir.empty())
204                 searchpath=MakeAbsPath(system_lyxdir) + ';';
205
206         // LYX_DIR_10x environment variable
207         string lyxdir = GetEnvPath("LYX_DIR_10x");
208         
209         if (!lyxdir.empty()) {
210                 lyxerr.debug("LYX_DIR_10x: " + lyxdir, Error::INIT);
211                 searchpath += lyxdir + ';';
212         }
213
214         // <path of binary>/TOP_SRCDIR/lib
215         build_lyxdir = MakeAbsPath("../lib", binpath);
216         if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
217                 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
218                                           binpath) + ';';
219                 lyxerr.debug("Checking whether LyX is run in "
220                               "place... yes", Error::INIT);
221         } else {
222                 lyxerr.debug("Checking whether LyX is run in place... no",
223                               Error::INIT);
224                 build_lyxdir.erase();
225         }
226
227
228         bool FollowLink;
229         do {
230           // Path of binary/../share/name of binary/
231                 searchpath += NormalizePath(AddPath(binpath, "../share/") + 
232                       OnlyFilename(binname)) + ';';
233
234           // Follow Symlinks
235                 FileInfo file(fullbinpath,true);
236                 FollowLink = file.isLink();
237                 if (FollowLink) {
238                         string Link;
239                         if (LyXReadLink(fullbinpath,Link)) {
240                                 fullbinpath = Link;
241                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
242                         }
243                         else {
244                                 FollowLink = false;
245                         }
246                 }
247         } while (FollowLink);
248
249         // Hardcoded dir
250         searchpath += LYX_DIR;
251
252         // If debugging, show complete search path
253         lyxerr.debug("System directory search path: "+searchpath, Error::INIT);
254
255         string const filename = "chkconfig.ltx";
256         string temp = FileOpenSearch(searchpath, filename, string());
257         system_lyxdir = OnlyPath(temp);
258
259         // Reduce "path/../path" stuff out of system directory
260         system_lyxdir = NormalizePath(system_lyxdir);
261
262         bool path_shown = false;
263
264         // Warn if environment variable is set, but unusable
265         if (!lyxdir.empty()) {
266                 if (system_lyxdir != NormalizePath(lyxdir)) {
267                         lyxerr.print(_("LYX_DIR_10x environment variable no good."));
268                         lyxerr.print(_("System directory set to: ") 
269                                      + system_lyxdir);
270                         path_shown = true;
271                 }
272         }
273
274         // Warn the user if we couldn't find "chkconfig.ltx"
275         if (system_lyxdir.empty()) {
276                 lyxerr.print(_("LyX Warning! Couldn't determine system directory."));
277                 lyxerr.print(_("Try the '-sysdir' command line parameter or"));
278                 lyxerr.print(_("set the environment variable LYX_DIR_10x to the "
279                               "LyX system directory"));
280                 lyxerr.print(_("containing the file `chkconfig.ltx'."));
281                 if (!path_shown)
282                         lyxerr.print(_("Using built-in default ") 
283                                      + string(LYX_DIR) + _(" but expect problems."));
284                 else
285                         lyxerr.print(_("Expect problems."));
286                 system_lyxdir = LYX_DIR;
287                 path_shown = true;
288         }
289
290         // Report the system directory if debugging is on
291         if (!path_shown)
292                 lyxerr.debug("System directory: '" + system_lyxdir + '\'', 
293                               Error::INIT);
294
295         //
296         // Determine user lyx-dir
297         //
298         
299         user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + LYX_NAME);
300         lyxerr.debug("User LyX directory: '" 
301                      + user_lyxdir + '\'', Error::INIT);
302
303         // Check that user LyX directory is ok.
304         queryUserLyXDir();
305
306         //
307         // Load the layouts first
308         //
309
310         lyxerr.debug("Reading layouts...", Error::INIT);
311         LyXSetStyle();
312
313         //
314         // Shine up lyxrc defaults
315         //
316
317         // Default template path: system_dir/templates
318         if (lyxrc->template_path.empty()){
319                 lyxrc->template_path = AddPath(system_lyxdir, "templates");
320         }
321    
322         // Default lastfiles file: $HOME/.lyx/lastfiles
323         if (lyxrc->lastfiles.empty()){
324                 lyxrc->lastfiles = AddName(user_lyxdir, "lastfiles");
325         }
326
327         // Calculate screen dpi as average of x-DPI and y-DPI:
328         Screen * scr=(DefaultScreenOfDisplay(fl_get_display()));
329         lyxrc->dpi = ((HeightOfScreen(scr)* 25.4 / HeightMMOfScreen(scr)) +
330                       (WidthOfScreen(scr)* 25.4 / WidthMMOfScreen(scr))) / 2;
331         lyxerr.debug(string("DPI setting detected to be ") + 
332                       tostr(lyxrc->dpi+0.5));
333
334         //
335         // Read configuration files
336         //
337
338         ReadRcFile("lyxrc.defaults");
339         ReadRcFile("lyxrc");
340
341         // Ensure that we have really read a bind file, so that LyX is
342         // usable.
343         if (!lyxrc->hasBindFile)
344                 lyxrc->ReadBindFile();
345
346         if (lyxerr.debugging(Error::LYXRC)) {
347                 lyxrc->Print();
348         }
349
350         // Create temp directory        
351         system_tempdir = CreateLyXTmpDir(lyxrc->tempdir_path);
352         if (lyxerr.debugging(Error::INIT)) {
353                 lyxerr.print("LyX tmp dir: `" + system_tempdir + '\'');
354         }
355
356         // load the lastfiles mini-database
357         lyxerr.debug("Reading lastfiles `" + lyxrc->lastfiles + "'...", 
358                       Error::INIT);
359         lastfiles = new LastFiles(lyxrc->lastfiles, 
360                                   lyxrc->check_lastfiles,
361                                   lyxrc->num_lastfiles);
362
363         // start up the lyxserver. (is this a bit early?) (Lgb)
364         // 0.12 this will be way to early, we need the GUI to be initialized
365         // first, so move it for now.
366         // lyxserver = new LyXServer;
367 }
368
369
370 // This one is not allowed to use anything on the main form, since that
371 // one does not exist yet. (Asger)
372 void LyX::queryUserLyXDir()
373 {
374         // Does user directory exist?
375         FileInfo fileInfo(user_lyxdir);
376         if (fileInfo.isOK() && fileInfo.isDir()) {
377                 first_start = false;
378                 return;
379         } else {
380                 first_start = true;
381         }
382         
383         // Nope
384         if (!AskQuestion(_("You don't have a personal LyX directory."),
385                          _("It is needed to keep your own configuration."),
386                          _("Should I try to set it up for you (recommended)?"))) {
387                 lyxerr.print(_("Running without personal LyX directory."));
388                 // No, let's use $HOME instead.
389                 user_lyxdir = GetEnvPath("HOME");
390                 return;
391         }
392
393         // Tell the user what is going on
394         lyxerr.print(_("LyX: Creating directory ") + user_lyxdir + _(" and running configure..."));
395
396         // Create directory structure
397         if (!createDirectory(user_lyxdir, 0755)) {
398                 // Failed, let's use $HOME instead.
399                 user_lyxdir = GetEnvPath("HOME");
400                 lyxerr.print(_("Failed. Will use ") + user_lyxdir + _(" instead."));
401                 return;
402         }
403
404         // Run configure in user lyx directory
405         PathPush(user_lyxdir);
406         system(AddName(system_lyxdir,"configure").c_str());
407         PathPop();
408         lyxerr.print(string("LyX: ") + _("Done!"));
409 }
410
411
412 // Read the rc file `name'
413 void LyX::ReadRcFile(string const & name)
414 {
415         lyxerr.debug("About to read "+name+"...", Error::INIT);
416         
417         string lyxrc_path = LibFileSearch(string(), name);
418         if (!lyxrc_path.empty()){
419                 lyxerr.debug("Found "+name+" in " + lyxrc_path, Error::INIT);
420                 if (lyxrc->Read(lyxrc_path) < 0) { 
421                         WriteAlert(_("LyX Warning!"), 
422                                    _("Error while reading ")+lyxrc_path+".",
423                                    _("Using built-in defaults."));
424                 }
425         } else
426                 lyxerr.debug("Could not find "+name, Error::INIT);
427 }
428
429
430 // Set debugging level and report result to user
431 void setDebuggingLevel(int dbgLevel)
432 {
433         lyxerr.print(string(_("Setting debug level to ")) + tostr(dbgLevel));
434         lyxerr.setDebugLevel(dbgLevel);
435         lyxerr.debug(string("Debugging INFO #") + tostr(Error::INFO),
436                      Error::INFO);
437         lyxerr.debug(string("Debugging INIT #") + tostr(Error::INIT),
438                      Error::INIT);
439         lyxerr.debug(string("Debugging KEY #") + tostr(Error::KEY),
440                      Error::KEY);
441         lyxerr.debug(string("Debugging TOOLBAR #") + tostr(Error::TOOLBAR), 
442                      Error::TOOLBAR);
443         lyxerr.debug(string("Debugging LEX and PARSER #") +
444                      tostr(Error::LEX_PARSER),
445                      Error::LEX_PARSER);
446         lyxerr.debug(string("Debugging LYXRC #") + tostr(Error::LYXRC),
447                      Error::LYXRC);
448         lyxerr.debug(string("Debugging KBMAP #") + tostr(Error::KBMAP),
449                      Error::KBMAP);
450         lyxerr.debug(string("Debugging LATEX #") + tostr(Error::LATEX),
451                      Error::LATEX);
452         lyxerr.debug(string("Debugging MATHED #") + tostr(Error::MATHED), 
453                      Error::MATHED);
454         lyxerr.debug(string("Debugging FONT #") + tostr(Error::FONT),
455                      Error::FONT);
456         lyxerr.debug(string("Debugging TCLASS #") + tostr(Error::TCLASS), 
457                      Error::TCLASS);
458         lyxerr.debug(string("Debugging LYXVC #") + tostr(Error::LYXVC),
459                      Error::LYXVC);
460         lyxerr.debug(string("Debugging LYXSERVER #") + tostr(Error::LYXSERVER),
461                      Error::LYXVC);
462 }
463
464
465 // Give command line help
466 void commandLineHelp()
467 {
468         lyxerr.print(_("LyX " LYX_VERSION " of " LYX_RELEASE ".\n"));
469         lyxerr.print(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"));
470         lyxerr.print(_("Command line switches (case sensitive):"));
471         lyxerr.print(_("   -help           summarize LyX usage"));
472         lyxerr.print(_("   -sysdir x       try to set system directory to x"));
473         lyxerr.print(_("   -width x        set the width of the main window"));
474         lyxerr.print(_("   -height y       set the height of the main window"));
475         lyxerr.print(_("   -xpos x         set the x position of the main window"));
476         lyxerr.print(_("   -ypos y         set the y position of the main window"));
477         lyxerr.print(_("   -dbg n          where n is a sum of debugging options. Try -dbg 65535 -help"));
478         lyxerr.print(_("   -Reverse        swaps foreground & background colors"));
479         lyxerr.print(_("   -Mono           runs LyX in black and white mode"));
480         lyxerr.print(_("   -FastSelection  use a fast routine for drawing selections\n"));
481         lyxerr.print(_("Check the LyX man page for more options."));
482 }
483
484
485 bool LyX::easyParse(int *argc, char *argv[])
486 {
487         bool gui = true;
488         for(int i=1; i < *argc; i++) {
489                 string arg = argv[i];
490                 // Check for -dbg int
491                 if (arg == "-dbg") {
492                         if (i+1 < *argc) {
493                                 int erri = 0;
494                                 sscanf(argv[i+1],"%d", &erri);
495
496                                 setDebuggingLevel(erri);
497
498                                 // Now, remove these two arguments by shifting
499                                 // the following two places down.
500                                 (*argc) -= 2;
501                                 for (int j=i; j < (*argc); j++)
502                                         argv[j] = argv[j+2];
503                                 i--; // After shift, check this number again.
504                         } else
505                                 lyxerr.print(_("Missing number for -dbg switch!"));
506                 } 
507                 // Check for "-sysdir"
508                 else if (arg == "-sysdir") {
509                         if (i+1 < *argc) {
510                                 system_lyxdir = argv[i+1];
511
512                                 // Now, remove these two arguments by shifting
513                                 // the following two places down.
514                                 (*argc) -= 2;
515                                 for (int j=i; j < (*argc); j++)
516                                         argv[j] = argv[j+2];
517                                 i--; // After shift, check this number again.
518                         } else
519                                 lyxerr.print(_("Missing directory for -sysdir switch!"));
520                 // Check for --help or -help
521                 } else if (arg == "--help" || arg == "-help") {
522                         commandLineHelp();
523                         exit(0);
524                 } 
525                 // Check for "-nw": No window
526                 else if (arg == "-nw") {
527                         gui = false;
528                 }
529         }
530         return gui;
531 }
532
533
534 void error_handler(int err_sig)
535 {
536         switch (err_sig) {
537         case SIGHUP:
538                 fprintf(stderr, "\nlyx: SIGHUP signal caught\n");
539                 break;
540         case SIGINT:
541                 // no comments
542                 break;
543         case SIGFPE:
544                 fprintf(stderr, "\nlyx: SIGFPE signal caught\n");
545                 break;
546         case SIGSEGV:
547                 fprintf(stderr, "\nlyx: SIGSEGV signal caught\n");
548                 fprintf(stderr,
549                         "Sorry, you have found a bug in LyX."
550                         " If possible, please read 'Known bugs'\n"
551                         "under the Help menu and then send us "
552                         "a full bug report. Thanks!\n");
553                 break;
554         case SIGTERM:
555                 // no comments
556                 break;
557         }
558    
559         // Deinstall the signal handlers
560         signal(SIGHUP, SIG_DFL);
561         signal(SIGINT, SIG_DFL);
562         signal(SIGFPE, SIG_DFL);
563         signal(SIGSEGV, SIG_DFL);
564         signal(SIGTERM, SIG_DFL);
565
566         bufferlist.emergencyWriteAll();
567
568         lyxerr.print("Bye.");
569         if(err_sig!=SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
570                 abort();
571         exit(0);
572 }