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