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