]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
e8cc0548b1ac826c9bd1e7ad39d83df4516a4c33
[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         // Execute batch commands if available
119         if (!batch_command.empty() && last_loaded) {
120                 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
121                 //Buffer buffer("Script Buffer");
122                 //buffer.Dispatch(batch_command);
123                 last_loaded->Dispatch(batch_command);
124                 lyxerr << "We are done!" << endl;
125                 return; // Maybe we could do something more clever than aborting..
126         }
127         
128         // Let the ball begin...
129         lyxGUI->runTime();
130 }
131
132
133 // A destructor is always necessary  (asierra-970604)
134 LyX::~LyX()
135 {
136         if (lastfiles) // DEL LINE
137                 delete lastfiles;
138
139         if (lyxGUI) // DEL LINE
140                 delete lyxGUI;
141 }
142
143
144 extern "C" void error_handler(int err_sig);
145
146 void LyX::init(int */*argc*/, char **argv)
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         Screen * scr = DefaultScreenOfDisplay(fl_get_display());
339         lyxrc->dpi = ((HeightOfScreen(scr)* 25.4 / HeightMMOfScreen(scr)) +
340                       (WidthOfScreen(scr)* 25.4 / WidthMMOfScreen(scr))) / 2;
341         lyxerr[Debug::INFO] << "DPI setting detected to be "
342                        << lyxrc->dpi + 0.5 << endl;
343
344         //
345         // Read configuration files
346         //
347
348         ReadRcFile("lyxrc.defaults");
349         ReadRcFile("lyxrc");
350
351         // Ensure that we have really read a bind file, so that LyX is
352         // usable.
353         if (!lyxrc->hasBindFile)
354                 lyxrc->ReadBindFile();
355
356         if (lyxerr.debugging(Debug::LYXRC)) {
357                 lyxrc->print();
358         }
359
360         // Create temp directory        
361         system_tempdir = CreateLyXTmpDir(lyxrc->tempdir_path);
362         if (lyxerr.debugging(Debug::INIT)) {
363                 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
364         }
365
366         // load the lastfiles mini-database
367         lyxerr[Debug::INIT] << "Reading lastfiles `"
368                             << lyxrc->lastfiles << "'..." << endl; 
369         lastfiles = new LastFiles(lyxrc->lastfiles, 
370                                   lyxrc->check_lastfiles,
371                                   lyxrc->num_lastfiles);
372
373         // start up the lyxserver. (is this a bit early?) (Lgb)
374         // 0.12 this will be way to early, we need the GUI to be initialized
375         // first, so move it for now.
376         // lyxserver = new LyXServer;
377 }
378
379
380 // This one is not allowed to use anything on the main form, since that
381 // one does not exist yet. (Asger)
382 void LyX::queryUserLyXDir()
383 {
384         // Does user directory exist?
385         FileInfo fileInfo(user_lyxdir);
386         if (fileInfo.isOK() && fileInfo.isDir()) {
387                 first_start = false;
388                 return;
389         } else {
390                 first_start = true;
391         }
392         
393         // Nope
394         if (!AskQuestion(_("You don't have a personal LyX directory."),
395                          _("It is needed to keep your own configuration."),
396                          _("Should I try to set it up for you (recommended)?"))) {
397                 lyxerr << _("Running without personal LyX directory.") << endl;
398                 // No, let's use $HOME instead.
399                 user_lyxdir = GetEnvPath("HOME");
400                 return;
401         }
402
403         // Tell the user what is going on
404         lyxerr << _("LyX: Creating directory ") << user_lyxdir
405                << _(" and running configure...") << endl;
406
407         // Create directory structure
408         if (!createDirectory(user_lyxdir, 0755)) {
409                 // Failed, let's use $HOME instead.
410                 user_lyxdir = GetEnvPath("HOME");
411                 lyxerr << _("Failed. Will use ") << user_lyxdir
412                        << _(" instead.") << endl;
413                 return;
414         }
415
416         // Run configure in user lyx directory
417         Path p(user_lyxdir);
418         system(AddName(system_lyxdir, "configure").c_str());
419         lyxerr << "LyX: " << _("Done!") << endl;
420 }
421
422
423 // Read the rc file `name'
424 void LyX::ReadRcFile(string const & name)
425 {
426         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
427         
428         string lyxrc_path = LibFileSearch(string(), name);
429         if (!lyxrc_path.empty()){
430                 lyxerr[Debug::INIT] << "Found " << name
431                                     << " in " << lyxrc_path << endl;
432                 if (lyxrc->read(lyxrc_path) < 0) { 
433                         WriteAlert(_("LyX Warning!"), 
434                                    _("Error while reading ")+lyxrc_path+".",
435                                    _("Using built-in defaults."));
436                 }
437         } else
438                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
439 }
440
441
442 // Set debugging level and report result to user
443 void setDebuggingLevel(string const & dbgLevel)
444 {
445         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
446         lyxerr.level(Debug::value(dbgLevel));
447         Debug::showLevel(lyxerr, lyxerr.level());
448 }
449
450
451 // Give command line help
452 void commandLineHelp()
453 {
454         lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
455         lyxerr <<
456                 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
457                   "Command line switches (case sensitive):\n"
458                   "\t-help           summarize LyX usage\n"
459                   "\t-sysdir x       try to set system directory to x\n"
460                   "\t-width x        set the width of the main window\n"
461                   "\t-height y       set the height of the main window\n"
462                   "\t-xpos x         set the x position of the main window\n"
463                   "\t-ypos y         set the y position of the main window\n"
464                   "\t-dbg feature[,feature]...\n"
465                   "                  select the features to debug.\n"
466                   "                  Type `lyx -dbg' to see the list of features\n"
467                   "\t-Reverse        swaps foreground & background colors\n"
468                   "\t-Mono           runs LyX in black and white mode\n"
469                   "\t-FastSelection  use a fast routine for drawing selections\n\n"
470                   "Check the LyX man page for more options.") << endl;
471 }
472
473
474 bool LyX::easyParse(int * argc, char * argv[])
475 {
476         bool gui = true;
477         for(int i = 1; i < *argc; ++i) {
478                 string arg = argv[i];
479
480                 // Check for -dbg int
481                 if (arg == "-dbg") {
482                         if (i + 1 < *argc) {
483                                 setDebuggingLevel(argv[i + 1]);
484
485                                 // Now, remove these two arguments by shifting
486                                 // the following two places down.
487                                 (*argc) -= 2;
488                                 for (int j = i; j < (*argc); ++j)
489                                         argv[j] = argv[j + 2];
490                                 --i; // After shift, check this number again.
491                         } else {
492                                 lyxerr << _("List of supported debug flags:")
493                                        << endl;
494                                 Debug::showTags(lyxerr);
495                                 exit(0);
496                         }
497                         
498                 } 
499                 // Check for "-sysdir"
500                 else if (arg == "-sysdir") {
501                         if (i + 1 < *argc) {
502                                 system_lyxdir = argv[i + 1];
503
504                                 // Now, remove these two arguments by shifting
505                                 // the following two places down.
506                                 (*argc) -= 2;
507                                 for (int j= i; j < (*argc); ++j)
508                                         argv[j] = argv[j + 2];
509                                 --i; // After shift, check this number again.
510                         } else
511                                 lyxerr << _("Missing directory for -sysdir switch!")
512                                        << endl;
513                 // Check for --help or -help
514                 } else if (arg == "--help" || arg == "-help") {
515                         commandLineHelp();
516                         exit(0);
517                 } 
518                 // Check for "-nw": No window
519                 else if (arg == "-nw") {
520                         gui = false;
521                 }
522
523                 // Check for "-x": Execute commands
524                 else if (arg == "-x" || arg == "--execute") {
525                         if (i + 1 < *argc) {
526                                 batch_command = string(argv[i + 1]);
527
528                                 // Now, remove these two arguments by shifting
529                                 // the following two places down.
530                                 (*argc) -= 2;
531                                 for (int j = i; j < (*argc); ++j)
532                                         argv[j] = argv[j + 2];
533                                 --i; // After shift, check this number again.
534
535                         }
536                         else
537                                 lyxerr << _("Missing command string after  -x switch!") << endl;
538
539                         // Argh. Setting gui to false segfaults..
540                         //gui = false;
541                 }
542
543                 else if (arg == "-e" || arg == "--export") {
544                         if (i + 1 < *argc) {
545                                 string type(argv[i+1]);
546
547                                 (*argc) -= 2;
548                                 for (int j = i; j < (*argc); ++j)
549                                         argv[j] = argv[j + 2];
550                                 --i; // After shift, check this number again.
551
552                                 if (type == "tex")
553                                         type = "latex";
554                                 else if (type == "ps")
555                                         type = "postscript";
556                                 else if (type == "text" || type == "txt")
557                                         type = "ascii";
558
559                                 if (type == "latex" || type == "postscript"
560                                     || type == "ascii" || type == "html") 
561                                         batch_command = "buffer-export " + type;
562                                 else
563                                         lyxerr << _("Unknown file type '")
564                                                << type << _("' after ")
565                                                << arg << _(" switch!") << endl;
566                         }
567                         else
568                                 lyxerr << _("Missing file type [eg latex, "
569                                             "ps...] after ")
570                                        << arg << _(" switch!") << endl;
571                 }
572         }
573         return gui;
574 }
575
576
577 void error_handler(int err_sig)
578 {
579         switch (err_sig) {
580         case SIGHUP:
581                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
582                 break;
583         case SIGINT:
584                 // no comments
585                 break;
586         case SIGFPE:
587                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
588                 break;
589         case SIGSEGV:
590                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
591                 lyxerr <<
592                         "Sorry, you have found a bug in LyX."
593                         " If possible, please read 'Known bugs'\n"
594                         "under the Help menu and then send us "
595                         "a full bug report. Thanks!" << endl;
596                 break;
597         case SIGTERM:
598                 // no comments
599                 break;
600         }
601    
602         // Deinstall the signal handlers
603         signal(SIGHUP, SIG_DFL);
604         signal(SIGINT, SIG_DFL);
605         signal(SIGFPE, SIG_DFL);
606         signal(SIGSEGV, SIG_DFL);
607         signal(SIGTERM, SIG_DFL);
608
609         bufferlist.emergencyWriteAll();
610
611         lyxerr << "Bye." << endl;
612         if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
613                 lyx::abort();
614         exit(0);
615 }