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