]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
dc26313a7b370ce488e332733295d69f15dea398
[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)
137                 delete lastfiles;
138
139         if (lyxGUI)
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")) binname.erase(binname.length()-4, string::npos);
164         
165         binpath = ExpandPath(binpath); // This expands ./ and ~/
166         
167         if (!AbsolutePath(binpath)) {
168                 string binsearchpath = GetEnvPath("PATH");
169                 binsearchpath += ";."; // This will make "src/lyx" work always :-)
170                 binpath = FileOpenSearch(binsearchpath, argv[0]);
171         }
172
173         fullbinpath = binpath;
174         binpath = MakeAbsPath(OnlyPath(binpath));
175
176         if (binpath.empty()) {
177                 lyxerr << _("Warning: could not determine path of binary.")
178                        << "\n"
179                        << _("If you have problems, try starting LyX with an absolute path.")
180                        << endl;
181         }
182         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
183
184         //
185         // Determine system directory.
186         //
187
188         // Directories are searched in this order:
189         // 1) -sysdir command line parameter
190         // 2) LYX_DIR_11x environment variable
191         // 3) Maybe <path of binary>/TOP_SRCDIR/lib
192         // 4) <path of binary>/../share/<name of binary>/
193         // 4a) repeat 4 after following the Symlink if <path of
194         //     binary> is a symbolic link.
195         // 5) hardcoded lyx_dir
196         // The directory is checked for the presence of the file
197         // "chkconfig.ltx", and if that is present, the directory
198         // is accepted as the system directory.
199         // If no chkconfig.ltx file is found, a warning is given,
200         // and the hardcoded lyx_dir is used.
201
202         // If we had a command line switch, system_lyxdir is already set
203         string searchpath;
204         if (!system_lyxdir.empty())
205                 searchpath= MakeAbsPath(system_lyxdir) + ';';
206
207         // LYX_DIR_11x environment variable
208         string lyxdir = GetEnvPath("LYX_DIR_11x");
209         
210         if (!lyxdir.empty()) {
211                 lyxerr[Debug::INIT] << "LYX_DIR_11x: " << lyxdir << endl;
212                 searchpath += lyxdir + ';';
213         }
214
215         // <path of binary>/TOP_SRCDIR/lib
216         build_lyxdir = MakeAbsPath("../lib", binpath);
217         if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
218                 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
219                                           binpath) + ';';
220                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
221                         "place... yes" << endl;
222         } else {
223                 lyxerr[Debug::INIT]
224                         << "Checking whether LyX is run in place... no"
225                         << endl;
226                 build_lyxdir.clear();
227         }
228
229         bool FollowLink;
230         do {
231           // Path of binary/../share/name of binary/
232                 searchpath += NormalizePath(AddPath(binpath, "../share/") + 
233                       OnlyFilename(binname)) + ';';
234
235           // Follow Symlinks
236                 FileInfo file(fullbinpath, true);
237                 FollowLink = file.isLink();
238                 if (FollowLink) {
239                         string Link;
240                         if (LyXReadLink(fullbinpath, Link)) {
241                                 fullbinpath = Link;
242                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
243                         }
244                         else {
245                                 FollowLink = false;
246                         }
247                 }
248         } while (FollowLink);
249
250         // Hardcoded dir
251         searchpath += LYX_DIR;
252
253         // If debugging, show complete search path
254         lyxerr[Debug::INIT] << "System directory search path: "
255                             << searchpath << endl;
256
257         string const filename = "chkconfig.ltx";
258         string temp = FileOpenSearch(searchpath, filename, string());
259         system_lyxdir = OnlyPath(temp);
260
261         // Reduce "path/../path" stuff out of system directory
262         system_lyxdir = NormalizePath(system_lyxdir);
263
264         bool path_shown = false;
265
266         // Warn if environment variable is set, but unusable
267         if (!lyxdir.empty()) {
268                 if (system_lyxdir != NormalizePath(lyxdir)) {
269                         lyxerr <<_("LYX_DIR_11x environment variable no good.")
270                                << '\n'
271                                << _("System directory set to: ") 
272                                << system_lyxdir << endl;
273                         path_shown = true;
274                 }
275         }
276
277         // Warn the user if we couldn't find "chkconfig.ltx"
278         if (system_lyxdir.empty()) {
279                 lyxerr <<_("LyX Warning! Couldn't determine system directory.")
280                        <<_("Try the '-sysdir' command line parameter or")
281                        <<_("set the environment variable LYX_DIR_11x to the "
282                            "LyX system directory")
283                        << _("containing the file `chkconfig.ltx'.") << endl;
284                 if (!path_shown)
285                         lyxerr << _("Using built-in default ") 
286                                << LYX_DIR << _(" but expect problems.")
287                                << endl;
288                 else
289                         lyxerr << _("Expect problems.") << endl;
290                 system_lyxdir = LYX_DIR;
291                 path_shown = true;
292         }
293
294         // Report the system directory if debugging is on
295         if (!path_shown)
296                 lyxerr[Debug::INIT] << "System directory: '"
297                                     << system_lyxdir << '\'' << endl; 
298
299         //
300         // Determine user lyx-dir
301         //
302         
303         user_lyxdir = AddPath(GetEnvPath("HOME"), string(".") + PACKAGE);
304         lyxerr[Debug::INIT] << "User LyX directory: '" 
305                             <<  user_lyxdir << '\'' << endl;
306
307         // Check that user LyX directory is ok.
308         queryUserLyXDir();
309
310         //
311         // Load the layouts first
312         //
313
314         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
315         LyXSetStyle();
316
317         //
318         // Shine up lyxrc defaults
319         //
320
321         // Default template path: system_dir/templates
322         if (lyxrc->template_path.empty()){
323                 lyxrc->template_path = AddPath(system_lyxdir, "templates");
324         }
325    
326         // Default lastfiles file: $HOME/.lyx/lastfiles
327         if (lyxrc->lastfiles.empty()){
328                 lyxrc->lastfiles = AddName(user_lyxdir, "lastfiles");
329         }
330
331         // Calculate screen dpi as average of x-DPI and y-DPI:
332         Screen * scr = DefaultScreenOfDisplay(fl_get_display());
333         lyxrc->dpi = ((HeightOfScreen(scr)* 25.4 / HeightMMOfScreen(scr)) +
334                       (WidthOfScreen(scr)* 25.4 / WidthMMOfScreen(scr))) / 2;
335         lyxerr[Debug::INFO] << "DPI setting detected to be "
336                        << lyxrc->dpi + 0.5 << endl;
337
338         //
339         // Read configuration files
340         //
341
342         ReadRcFile("lyxrc.defaults");
343         ReadRcFile("lyxrc");
344
345         // Ensure that we have really read a bind file, so that LyX is
346         // usable.
347         if (!lyxrc->hasBindFile)
348                 lyxrc->ReadBindFile();
349
350         if (lyxerr.debugging(Debug::LYXRC)) {
351                 lyxrc->print();
352         }
353
354         // Create temp directory        
355         system_tempdir = CreateLyXTmpDir(lyxrc->tempdir_path);
356         if (lyxerr.debugging(Debug::INIT)) {
357                 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
358         }
359
360         // load the lastfiles mini-database
361         lyxerr[Debug::INIT] << "Reading lastfiles `"
362                             << lyxrc->lastfiles << "'..." << endl; 
363         lastfiles = new LastFiles(lyxrc->lastfiles, 
364                                   lyxrc->check_lastfiles,
365                                   lyxrc->num_lastfiles);
366
367         // start up the lyxserver. (is this a bit early?) (Lgb)
368         // 0.12 this will be way to early, we need the GUI to be initialized
369         // first, so move it for now.
370         // lyxserver = new LyXServer;
371 }
372
373
374 // This one is not allowed to use anything on the main form, since that
375 // one does not exist yet. (Asger)
376 void LyX::queryUserLyXDir()
377 {
378         // Does user directory exist?
379         FileInfo fileInfo(user_lyxdir);
380         if (fileInfo.isOK() && fileInfo.isDir()) {
381                 first_start = false;
382                 return;
383         } else {
384                 first_start = true;
385         }
386         
387         // Nope
388         if (!AskQuestion(_("You don't have a personal LyX directory."),
389                          _("It is needed to keep your own configuration."),
390                          _("Should I try to set it up for you (recommended)?"))) {
391                 lyxerr << _("Running without personal LyX directory.") << endl;
392                 // No, let's use $HOME instead.
393                 user_lyxdir = GetEnvPath("HOME");
394                 return;
395         }
396
397         // Tell the user what is going on
398         lyxerr << _("LyX: Creating directory ") << user_lyxdir
399                << _(" and running configure...") << endl;
400
401         // Create directory structure
402         if (!createDirectory(user_lyxdir, 0755)) {
403                 // Failed, let's use $HOME instead.
404                 user_lyxdir = GetEnvPath("HOME");
405                 lyxerr << _("Failed. Will use ") << user_lyxdir
406                        << _(" instead.") << endl;
407                 return;
408         }
409
410         // Run configure in user lyx directory
411         Path p(user_lyxdir);
412         system(AddName(system_lyxdir, "configure").c_str());
413         lyxerr << "LyX: " << _("Done!") << endl;
414 }
415
416
417 // Read the rc file `name'
418 void LyX::ReadRcFile(string const & name)
419 {
420         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
421         
422         string lyxrc_path = LibFileSearch(string(), name);
423         if (!lyxrc_path.empty()){
424                 lyxerr[Debug::INIT] << "Found " << name
425                                     << " in " << lyxrc_path << endl;
426                 if (lyxrc->read(lyxrc_path) < 0) { 
427                         WriteAlert(_("LyX Warning!"), 
428                                    _("Error while reading ")+lyxrc_path+".",
429                                    _("Using built-in defaults."));
430                 }
431         } else
432                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
433 }
434
435
436 // Set debugging level and report result to user
437 void setDebuggingLevel(string const & dbgLevel)
438 {
439         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
440         lyxerr.level(Debug::value(dbgLevel));
441         Debug::showLevel(lyxerr, lyxerr.level());
442 }
443
444
445 // Give command line help
446 void commandLineHelp()
447 {
448         lyxerr << "LyX " LYX_VERSION << " of " LYX_RELEASE << endl;
449         lyxerr <<
450                 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
451                   "Command line switches (case sensitive):\n"
452                   "\t-help           summarize LyX usage\n"
453                   "\t-sysdir x       try to set system directory to x\n"
454                   "\t-width x        set the width of the main window\n"
455                   "\t-height y       set the height of the main window\n"
456                   "\t-xpos x         set the x position of the main window\n"
457                   "\t-ypos y         set the y position of the main window\n"
458                   "\t-dbg feature[,feature]...\n"
459                   "                  select the features to debug.\n"
460                   "                  Type `lyx -dbg' to see the list of features\n"
461                   "\t-Reverse        swaps foreground & background colors\n"
462                   "\t-Mono           runs LyX in black and white mode\n"
463                   "\t-FastSelection  use a fast routine for drawing selections\n\n"
464                   "Check the LyX man page for more options.") << endl;
465 }
466
467
468 bool LyX::easyParse(int * argc, char * argv[])
469 {
470         bool gui = true;
471         for(int i = 1; i < *argc; ++i) {
472                 string arg = argv[i];
473                 // Check for -dbg int
474                 if (arg == "-dbg") {
475                         if (i + 1 < *argc) {
476                                 setDebuggingLevel(argv[i + 1]);
477
478                                 // Now, remove these two arguments by shifting
479                                 // the following two places down.
480                                 (*argc) -= 2;
481                                 for (int j = i; j < (*argc); ++j)
482                                         argv[j] = argv[j + 2];
483                                 --i; // After shift, check this number again.
484                         } else {
485                                 lyxerr << _("List of supported debug flags:")
486                                        << endl;
487                                 Debug::showTags(lyxerr);
488                                 exit(0);
489                         }
490                         
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                 // Check for "-x": Execute commands
517                 else if (arg == "-x" || arg == "--execute") {
518                         if (i + 1 < *argc) {
519                                 batch_command = string(argv[i + 1]);
520
521                                 // Now, remove these two arguments by shifting
522                                 // the following two places down.
523                                 (*argc) -= 2;
524                                 for (int j = i; j < (*argc); ++j)
525                                         argv[j] = argv[j + 2];
526                                 --i; // After shift, check this number again.
527
528                         }
529                         else
530                                 lyxerr << _("Missing command string after  -x switch!") << endl;
531
532                         // Argh. Setting gui to false segfaults..
533                         //gui = false;
534                 }
535
536                 else if (arg == "-e" || arg == "--export") {
537                         if (i + 1 < *argc) {
538                                 string type(argv[i+1]);
539
540                                 (*argc) -= 2;
541                                 for (int j = i; j < (*argc); ++j)
542                                         argv[j] = argv[j + 2];
543                                 --i; // After shift, check this number again.
544
545                                 if (type == "tex")
546                                         type = "latex";
547                                 else if (type == "ps")
548                                         type = "postscript";
549                                 else if (type == "text" || type == "txt")
550                                         type = "ascii";
551
552                                 if (type == "latex" || type == "postscript"
553                                     || type == "ascii" || type == "html") 
554                                         batch_command = "buffer-export " + type;
555                                 else
556                                         lyxerr << _("Unknown file type '")
557                                                << type << _("' after ")
558                                                << arg << _(" switch!") << endl;
559                         }
560                         else
561                                 lyxerr << _("Missing file type [eg latex, "
562                                             "ps...] after ")
563                                        << arg << _(" switch!") << endl;
564                 }
565         }
566         return gui;
567 }
568
569
570 void error_handler(int err_sig)
571 {
572         switch (err_sig) {
573         case SIGHUP:
574                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
575                 break;
576         case SIGINT:
577                 // no comments
578                 break;
579         case SIGFPE:
580                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
581                 break;
582         case SIGSEGV:
583                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
584                 lyxerr <<
585                         "Sorry, you have found a bug in LyX."
586                         " If possible, please read 'Known bugs'\n"
587                         "under the Help menu and then send us "
588                         "a full bug report. Thanks!" << endl;
589                 break;
590         case SIGTERM:
591                 // no comments
592                 break;
593         }
594    
595         // Deinstall the signal handlers
596         signal(SIGHUP, SIG_DFL);
597         signal(SIGINT, SIG_DFL);
598         signal(SIGFPE, SIG_DFL);
599         signal(SIGSEGV, SIG_DFL);
600         signal(SIGTERM, SIG_DFL);
601
602         bufferlist.emergencyWriteAll();
603
604         lyxerr << "Bye." << endl;
605         if(err_sig!= SIGHUP && (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
606                 abort();
607         exit(0);
608 }