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