]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
bc98091fe0834039ff94d62cf470ccb1636af2f7
[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-2000 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include <cstdlib>
14 #include <csignal>
15
16 #include "version.h"
17 #include "lyx_main.h"
18 #include "lyx_gui.h"
19 #include "lyx_gui_misc.h"
20 #include "lyxrc.h"
21 #include "support/path.h"
22 #include "support/filetools.h"
23 #include "bufferlist.h"
24 #include "debug.h"
25 #include "support/FileInfo.h"
26 #include "lastfiles.h"
27 #include "intl.h"
28 #include "lyxserver.h"
29 #include "layout.h"
30 #include "gettext.h"
31 #include "kbmap.h"
32
33 extern void LoadLyXFile(string const &);
34
35 string system_lyxdir;
36 string build_lyxdir;
37 string system_tempdir;
38 string user_lyxdir;     // Default $HOME/.lyx
39
40 // Should this be kept global? Asger says Yes.
41 DebugStream lyxerr;
42
43 LastFiles * lastfiles;
44 LyXRC * lyxrc;
45
46 // This is the global bufferlist object
47 BufferList bufferlist;
48
49 LyXServer * lyxserver = 0;
50 // this should be static, but I need it in buffer.C
51 bool finished = false;  // flag, that we are quitting the program
52
53 // convenient to have it here.
54 kb_keymap * toplevel_keymap;
55
56
57 LyX::LyX(int * argc, char * argv[])
58 {
59         // Prevent crash with --help
60         lyxGUI = 0;
61         lastfiles = 0;
62
63         // Here we need to parse the command line. At least
64         // we need to parse for "-dbg" and "-help"
65         bool gui = easyParse(argc, argv);
66
67         // Global bindings (this must be done as early as possible.) (Lgb)
68         toplevel_keymap = new kb_keymap;
69
70         lyxerr[Debug::INIT] << "Initializing lyxrc" << endl;
71         lyxrc = new LyXRC;
72
73         // Make the GUI object, and let it take care of the
74         // command line arguments that concerns it.
75         lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
76         lyxGUI = new LyXGUI(this, argc, argv, gui);
77         lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
78
79         // Initialization of LyX (reads lyxrc and more)
80         lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
81         init(argc, argv);
82         lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
83
84         lyxGUI->init();
85
86         // Load the files specified in the command line.
87         // Now the GUI and LyX have taken care of their arguments, so
88         // the only thing left on the command line should be
89         // filenames.
90         if ((*argc) == 2) 
91                 lyxerr[Debug::INFO] << "Opening document..." << endl;
92         else if ((*argc) > 2)
93                 lyxerr[Debug::INFO] << "Opening documents..." << endl;
94
95         Buffer * last_loaded = 0;
96
97         for (int argi = (*argc) - 1; argi >= 1; --argi) {
98                 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
99                 if (loadb != 0) {
100                         last_loaded = loadb;
101                 }
102         }
103
104         if (first_start) {
105                 string splash = i18nLibFileSearch("examples", "splash.lyx");
106                 lyxerr.debug() << "Opening splash document "
107                                << splash << "..." << endl;
108                 Buffer * loadb = bufferlist.loadLyXFile(splash);
109                 if (loadb != 0) {
110                         last_loaded = loadb;
111                 }
112         }
113
114         if (last_loaded != 0) {
115                 lyxerr.debug() << "Yes we loaded some files." << endl;
116                 lyxGUI->regBuf(last_loaded);
117         }
118
119         // Execute batch commands if available
120         if (!batch_command.empty() && last_loaded) {
121                 lyxerr << "About to handle -x '" << batch_command << "'" << endl;
122                 //Buffer buffer("Script Buffer");
123                 //buffer.Dispatch(batch_command);
124                 last_loaded->Dispatch(batch_command);
125                 lyxerr << "We are done!" << endl;
126                 return; // Maybe we could do something more clever than aborting..
127         }
128         
129         // Let the ball begin...
130         lyxGUI->runTime();
131 }
132
133
134 // A destructor is always necessary  (asierra-970604)
135 LyX::~LyX()
136 {
137         delete lastfiles;
138         delete lyxGUI;
139 }
140
141
142 extern "C" void error_handler(int err_sig);
143
144 void LyX::init(int */*argc*/, char **argv)
145 {
146         // Install the signal handlers
147         signal(SIGHUP, error_handler);
148         signal(SIGFPE, error_handler);
149         signal(SIGSEGV, error_handler);
150         signal(SIGINT, error_handler);
151         signal(SIGTERM, error_handler);
152
153         //
154         // Determine path of binary
155         //
156
157         string fullbinpath;
158         string binpath = subst(argv[0], '\\', '/');
159         string binname = OnlyFilename(argv[0]);
160         // Sorry for system specific code. (SMiyata)
161         if (suffixIs(binname, ".exe")) 
162                 binname.erase(binname.length()-4, string::npos);
163         
164         binpath = ExpandPath(binpath); // This expands ./ and ~/
165         
166         if (!AbsolutePath(binpath)) {
167                 string binsearchpath = GetEnvPath("PATH");
168                 // This will make "src/lyx" work always :-)
169                 binsearchpath += ";."; 
170                 binpath = FileOpenSearch(binsearchpath, argv[0]);
171         }
172
173         fullbinpath = binpath;
174         binpath = MakeAbsPath(OnlyPath(binpath));
175
176         // In case we are running in place and compiled with shared libraries
177         if (suffixIs(binpath, "/.libs/"))
178                 binpath.erase(binpath.length()-6, string::npos);
179
180         if (binpath.empty()) {
181                 lyxerr << _("Warning: could not determine path of binary.")
182                        << "\n"
183                        << _("If you have problems, try starting LyX with an absolute path.")
184                        << endl;
185         }
186         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
187
188         //
189         // Determine system directory.
190         //
191
192         // Directories are searched in this order:
193         // 1) -sysdir command line parameter
194         // 2) LYX_DIR_11x environment variable
195         // 3) Maybe <path of binary>/TOP_SRCDIR/lib
196         // 4) <path of binary>/../share/<name of binary>/
197         // 4a) repeat 4 after following the Symlink if <path of
198         //     binary> is a symbolic link.
199         // 5) hardcoded lyx_dir
200         // The directory is checked for the presence of the file
201         // "chkconfig.ltx", and if that is present, the directory
202         // is accepted as the system directory.
203         // If no chkconfig.ltx file is found, a warning is given,
204         // and the hardcoded lyx_dir is used.
205
206         // If we had a command line switch, system_lyxdir is already set
207         string searchpath;
208         if (!system_lyxdir.empty())
209                 searchpath= MakeAbsPath(system_lyxdir) + ';';
210
211         // LYX_DIR_11x environment variable
212         string lyxdir = GetEnvPath("LYX_DIR_11x");
213         
214         if (!lyxdir.empty()) {
215                 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
216                 searchpath += lyxdir + ';';
217         }
218
219         // <path of binary>/TOP_SRCDIR/lib
220         build_lyxdir = MakeAbsPath("../lib", binpath);
221         if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
222                 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
223                                           binpath) + ';';
224                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
225                         "place... yes" << endl;
226         } else {
227                 lyxerr[Debug::INIT]
228                         << "Checking whether LyX is run in place... no"
229                         << endl;
230                 build_lyxdir.clear();
231         }
232
233         bool FollowLink;
234         do {
235           // Path of binary/../share/name of binary/
236                 searchpath += NormalizePath(AddPath(binpath, "../share/") + 
237                       OnlyFilename(binname)) + ';';
238
239           // Follow Symlinks
240                 FileInfo file(fullbinpath, true);
241                 FollowLink = file.isLink();
242                 if (FollowLink) {
243                         string Link;
244                         if (LyXReadLink(fullbinpath, Link)) {
245                                 fullbinpath = Link;
246                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
247                         }
248                         else {
249                                 FollowLink = false;
250                         }
251                 }
252         } while (FollowLink);
253
254         // Hardcoded dir
255         searchpath += LYX_DIR;
256
257         // If debugging, show complete search path
258         lyxerr[Debug::INIT] << "System directory search path: "
259                             << searchpath << endl;
260
261         string const filename = "chkconfig.ltx";
262         string temp = FileOpenSearch(searchpath, filename, string());
263         system_lyxdir = OnlyPath(temp);
264
265         // Reduce "path/../path" stuff out of system directory
266         system_lyxdir = NormalizePath(system_lyxdir);
267
268         bool path_shown = false;
269
270         // Warn if environment variable is set, but unusable
271         if (!lyxdir.empty()) {
272                 if (system_lyxdir != NormalizePath(lyxdir)) {
273                         lyxerr <<_("LYX_DIR_11x environment variable no good.")
274                                << '\n'
275                                << _("System directory set to: ") 
276                                << system_lyxdir << endl;
277                         path_shown = true;
278                 }
279         }
280
281         // Warn the user if we couldn't find "chkconfig.ltx"
282         if (system_lyxdir == "./") {
283                 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
284                        <<_("Try the '-sysdir' command line parameter or")
285                        <<_("set the environment variable LYX_DIR_11x to the "
286                            "LyX system directory")
287                        << _("containing the file `chkconfig.ltx'.") << endl;
288                 if (!path_shown)
289                         lyxerr << _("Using built-in default ") 
290                                << LYX_DIR << _(" but expect problems.")
291                                << endl;
292                 else
293                         lyxerr << _("Expect problems.") << endl;
294                 system_lyxdir = LYX_DIR;
295                 path_shown = true;
296         }
297
298         // Report the system directory if debugging is on
299         if (!path_shown)
300                 lyxerr[Debug::INIT] << "System directory: '"
301                                     << system_lyxdir << '\'' << endl; 
302
303         //
304         // Determine user lyx-dir
305         //
306         
307         user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
308         lyxerr[Debug::INIT] << "User LyX directory: '" 
309                             <<  user_lyxdir << '\'' << endl;
310
311         // Check that user LyX directory is ok.
312         queryUserLyXDir();
313
314         //
315         // Load the layouts first
316         //
317
318         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
319         LyXSetStyle();
320
321         //
322         // Shine up lyxrc defaults
323         //
324
325         // Default template path: system_dir/templates
326         if (lyxrc->template_path.empty()){
327                 lyxrc->template_path = AddPath(system_lyxdir, "templates");
328         }
329    
330         // Default lastfiles file: $HOME/.lyx/lastfiles
331         if (lyxrc->lastfiles.empty()){
332                 lyxrc->lastfiles = AddName(user_lyxdir, "lastfiles");
333         }
334
335         // Calculate screen dpi as average of x-DPI and y-DPI:
336         Screen * scr = DefaultScreenOfDisplay(fl_get_display());
337         lyxrc->dpi = ((HeightOfScreen(scr)* 25.4 / HeightMMOfScreen(scr)) +
338                       (WidthOfScreen(scr)* 25.4 / WidthMMOfScreen(scr))) / 2;
339         lyxerr[Debug::INFO] << "DPI setting detected to be "
340                        << lyxrc->dpi + 0.5 << endl;
341
342         //
343         // Read configuration files
344         //
345
346         ReadRcFile("lyxrc.defaults");
347         ReadRcFile("lyxrc");
348
349         // Ensure that we have really read a bind file, so that LyX is
350         // usable.
351         if (!lyxrc->hasBindFile)
352                 lyxrc->ReadBindFile();
353
354         if (lyxerr.debugging(Debug::LYXRC)) {
355                 lyxrc->print();
356         }
357
358         // Create temp directory        
359         system_tempdir = CreateLyXTmpDir(lyxrc->tempdir_path);
360         if (lyxerr.debugging(Debug::INIT)) {
361                 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
362         }
363
364         // load the lastfiles mini-database
365         lyxerr[Debug::INIT] << "Reading lastfiles `"
366                             << lyxrc->lastfiles << "'..." << endl; 
367         lastfiles = new LastFiles(lyxrc->lastfiles, 
368                                   lyxrc->check_lastfiles,
369                                   lyxrc->num_lastfiles);
370
371         // start up the lyxserver. (is this a bit early?) (Lgb)
372         // 0.12 this will be way to early, we need the GUI to be initialized
373         // first, so move it for now.
374         // lyxserver = new LyXServer;
375 }
376
377
378 // This one is not allowed to use anything on the main form, since that
379 // one does not exist yet. (Asger)
380 void LyX::queryUserLyXDir()
381 {
382         // Does user directory exist?
383         FileInfo fileInfo(user_lyxdir);
384         if (fileInfo.isOK() && fileInfo.isDir()) {
385                 first_start = false;
386                 return;
387         } else {
388                 first_start = true;
389         }
390         
391         // Nope
392         if (!AskQuestion(_("You don't have a personal LyX directory."),
393                          _("It is needed to keep your own configuration."),
394                          _("Should I try to set it up for you (recommended)?"))) {
395                 lyxerr << _("Running without personal LyX directory.") << endl;
396                 // No, let's use $HOME instead.
397                 user_lyxdir = GetEnvPath("HOME");
398                 return;
399         }
400
401         // Tell the user what is going on
402         lyxerr << _("LyX: Creating directory ") << user_lyxdir
403                << _(" and running configure...") << endl;
404
405         // Create directory structure
406         if (!createDirectory(user_lyxdir, 0755)) {
407                 // Failed, let's use $HOME instead.
408                 user_lyxdir = GetEnvPath("HOME");
409                 lyxerr << _("Failed. Will use ") << user_lyxdir
410                        << _(" instead.") << endl;
411                 return;
412         }
413
414         // Run configure in user lyx directory
415         Path p(user_lyxdir);
416         system(AddName(system_lyxdir, "configure").c_str());
417         lyxerr << "LyX: " << _("Done!") << endl;
418 }
419
420
421 // Read the rc file `name'
422 void LyX::ReadRcFile(string const & name)
423 {
424         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
425         
426         string lyxrc_path = LibFileSearch(string(), name);
427         if (!lyxrc_path.empty()){
428                 lyxerr[Debug::INIT] << "Found " << name
429                                     << " in " << lyxrc_path << endl;
430                 if (lyxrc->read(lyxrc_path) < 0) { 
431                         WriteAlert(_("LyX Warning!"), 
432                                    _("Error while reading ")+lyxrc_path+".",
433                                    _("Using built-in defaults."));
434                 }
435         } else
436                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
437 }
438
439
440 // Set debugging level and report result to user
441 void setDebuggingLevel(string const & dbgLevel)
442 {
443         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
444         lyxerr.level(Debug::value(dbgLevel));
445         Debug::showLevel(lyxerr, lyxerr.level());
446 }
447
448
449 // Give command line help
450 void commandLineHelp()
451 {
452         lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
453         lyxerr <<
454                 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
455                   "Command line switches (case sensitive):\n"
456                   "\t-help           summarize LyX usage\n"
457                   "\t-sysdir x       try to set system directory to x\n"
458                   "\t-width x        set the width of the main window\n"
459                   "\t-height y       set the height of the main window\n"
460                   "\t-xpos x         set the x position of the main window\n"
461                   "\t-ypos y         set the y position of the main window\n"
462                   "\t-dbg feature[,feature]...\n"
463                   "                  select the features to debug.\n"
464                   "                  Type `lyx -dbg' to see the list of features\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
475                 // Check for -dbg int
476                 if (arg == "-dbg") {
477                         if (i + 1 < *argc) {
478                                 setDebuggingLevel(argv[i + 1]);
479
480                                 // Now, remove these two arguments by shifting
481                                 // the following two places down.
482                                 (*argc) -= 2;
483                                 for (int j = i; j < (*argc); ++j)
484                                         argv[j] = argv[j + 2];
485                                 --i; // After shift, check this number again.
486                         } else {
487                                 lyxerr << _("List of supported debug flags:")
488                                        << endl;
489                                 Debug::showTags(lyxerr);
490                                 exit(0);
491                         }
492                         
493                 } 
494                 // Check for "-sysdir"
495                 else if (arg == "-sysdir") {
496                         if (i + 1 < *argc) {
497                                 system_lyxdir = argv[i + 1];
498
499                                 // Now, remove these two arguments by shifting
500                                 // the following two places down.
501                                 (*argc) -= 2;
502                                 for (int j= i; j < (*argc); ++j)
503                                         argv[j] = argv[j + 2];
504                                 --i; // After shift, check this number again.
505                         } else
506                                 lyxerr << _("Missing directory for -sysdir switch!")
507                                        << endl;
508                 // Check for --help or -help
509                 } else if (arg == "--help" || arg == "-help") {
510                         commandLineHelp();
511                         exit(0);
512                 } 
513                 // Check for "-nw": No window
514                 else if (arg == "-nw") {
515                         gui = false;
516                 }
517
518                 // Check for "-x": Execute commands
519                 else if (arg == "-x" || arg == "--execute") {
520                         if (i + 1 < *argc) {
521                                 batch_command = string(argv[i + 1]);
522
523                                 // Now, remove these two arguments by shifting
524                                 // the following two places down.
525                                 (*argc) -= 2;
526                                 for (int j = i; j < (*argc); ++j)
527                                         argv[j] = argv[j + 2];
528                                 --i; // After shift, check this number again.
529
530                         }
531                         else
532                                 lyxerr << _("Missing command string after  -x switch!") << endl;
533
534                         // Argh. Setting gui to false segfaults..
535                         //gui = false;
536                 }
537
538                 else if (arg == "-e" || arg == "--export") {
539                         if (i + 1 < *argc) {
540                                 string type(argv[i+1]);
541
542                                 (*argc) -= 2;
543                                 for (int j = i; j < (*argc); ++j)
544                                         argv[j] = argv[j + 2];
545                                 --i; // After shift, check this number again.
546
547                                 if (type == "tex")
548                                         type = "latex";
549                                 else if (type == "ps")
550                                         type = "postscript";
551                                 else if (type == "text" || type == "txt")
552                                         type = "ascii";
553
554                                 if (type == "latex" || type == "postscript"
555                                     || type == "ascii" || type == "html") 
556                                         batch_command = "buffer-export " + type;
557                                 else
558                                         lyxerr << _("Unknown file type '")
559                                                << type << _("' after ")
560                                                << arg << _(" switch!") << endl;
561                         }
562                         else
563                                 lyxerr << _("Missing file type [eg latex, "
564                                             "ps...] after ")
565                                        << arg << _(" switch!") << endl;
566                 }
567         }
568         return gui;
569 }
570
571
572 void error_handler(int err_sig)
573 {
574         switch (err_sig) {
575         case SIGHUP:
576                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
577                 break;
578         case SIGINT:
579                 // no comments
580                 break;
581         case SIGFPE:
582                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
583                 break;
584         case SIGSEGV:
585                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
586                 lyxerr <<
587                         "Sorry, you have found a bug in LyX."
588                         " If possible, please read 'Known bugs'\n"
589                         "under the Help menu and then send us "
590                         "a full bug report. Thanks!" << endl;
591                 break;
592         case SIGTERM:
593                 // no comments
594                 break;
595         }
596    
597         // Deinstall the signal handlers
598         signal(SIGHUP, SIG_DFL);
599         signal(SIGINT, SIG_DFL);
600         signal(SIGFPE, SIG_DFL);
601         signal(SIGSEGV, SIG_DFL);
602         signal(SIGTERM, SIG_DFL);
603
604         bufferlist.emergencyWriteAll();
605
606         lyxerr << "Bye." << endl;
607         if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
608                 lyx::abort();
609         exit(0);
610 }