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