]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
fix some of the bugs reported, should hopefully be a bit better now.
[lyx.git] / src / bufferlist.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Word Processor
5  *
6  *          Copyright 1995 Matthias Ettrich
7  *          Copyright 1995-1999 The LyX Team. 
8  *
9  *           This file is Copyright 1996-1999
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #ifdef __GNUG__
16 #pragma implementation
17 #endif
18
19 #include <config.h>
20
21 #include <fstream>
22 #include <sys/types.h>
23 #include <utime.h>
24
25 #include "bufferlist.h"
26 #include "lyx_main.h"
27 #include "minibuffer.h"
28 #include "support/FileInfo.h"
29 #include "support/filetools.h"
30 #include "lyx_gui_misc.h"
31 #include "lastfiles.h"
32 #include "debug.h"
33 #include "lyxrc.h"
34 #include "lyxscreen.h"
35 #include "lyxtext.h"
36 #include "lyx_cb.h"
37 #include "gettext.h"
38 #include "LyXView.h"
39 #include "vc-backend.h"
40
41 extern BufferView * current_view;
42 extern int RunLinuxDoc(int, string const &);
43
44 using std::ifstream;
45 using std::ofstream;
46 using std::ios;
47
48 //
49 // Class BufferStorage
50 //
51
52 void BufferStorage::release(Buffer * buf)
53 {
54         for(Container::iterator it = container.begin();
55             it != container.end(); ++it) {
56                 if ((*it) == buf) {
57                         Buffer * tmpbuf = (*it);
58                         container.erase(it);
59                         delete tmpbuf;
60                         break;
61                 }
62         }
63 }
64
65
66 Buffer * BufferStorage::newBuffer(string const & s,
67                                   LyXRC * lyxrc,
68                                   bool ronly)
69 {
70         Buffer * tmpbuf = new Buffer(s, lyxrc, ronly);
71         tmpbuf->params.useClassDefaults();
72         lyxerr.debug() << "Assigning to buffer "
73                        << container.size() << endl;
74         container.push_back(tmpbuf);
75         return tmpbuf;
76 }
77
78
79 //
80 // Class BufferList
81 //
82
83 BufferList::BufferList()
84         : state_(BufferList::OK)
85 {}
86
87
88 bool BufferList::empty()
89 {
90         return bstore.empty();
91 }
92
93
94 extern void MenuWrite(Buffer *);
95
96 bool BufferList::QwriteAll()
97 {
98         bool askMoreConfirmation = false;
99         string unsaved;
100         for(BufferStorage::iterator it = bstore.begin();
101             it != bstore.end(); ++it) {
102                 if (!(*it)->isLyxClean()) {
103                         switch(AskConfirmation(_("Changes in document:"),
104                                                MakeDisplayPath((*it)->fileName(),
105                                                                50),
106                                                _("Save document?"))) {
107                         case 1: // Yes
108                                 MenuWrite((*it));
109                                 break;
110                         case 2: // No
111                                 askMoreConfirmation = true;
112                                 unsaved += MakeDisplayPath((*it)->fileName(),
113                                                            50);
114                                 unsaved += "\n";
115                                 break;
116                         case 3: // Cancel
117                                 return false;
118                         }
119                 }
120         }
121         if (askMoreConfirmation &&
122             lyxrc->exit_confirmation &&
123             !AskQuestion(_("Some documents were not saved:"),
124                          unsaved, _("Exit anyway?"))) {
125                 return false;
126         }
127
128         return true;
129 }
130
131
132 // Should probably be moved to somewhere else: BufferView? LyXView?
133 bool BufferList::write(Buffer * buf, bool makeBackup)
134 {
135         if (buf->getUser())
136                 buf->getUser()
137                         ->owner()
138                         ->getMiniBuffer()
139                         ->Set(_("Saving document"),
140                               MakeDisplayPath(buf->fileName()), "...");
141
142         // We don't need autosaves in the immediate future. (Asger)
143         buf->resetAutosaveTimers();
144
145         // make a backup
146         if (makeBackup) {
147                 string s = buf->fileName() + '~';
148                 // Rename is the wrong way of making a backup,
149                 // this is the correct way.
150                 /* truss cp fil fil2:
151                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
152                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
153                    open("LyXVC.lyx", O_RDONLY)                     = 3
154                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
155                    fstat(4, 0xEFFFF508)                            = 0
156                    fstat(3, 0xEFFFF508)                            = 0
157                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
158                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
159                    read(3, 0xEFFFD4A0, 8192)                       = 0
160                    close(4)                                        = 0
161                    close(3)                                        = 0
162                    chmod("LyXVC3.lyx", 0100644)                    = 0
163                    lseek(0, 0, SEEK_CUR)                           = 46440
164                    _exit(0)
165                 */
166
167                 // Should proabaly have some more error checking here.
168                 // Should be cleaned up in 0.13, at least a bit.
169                 // Doing it this way, also makes the inodes stay the same.
170                 // This is still not a very good solution, in particular we
171                 // might loose the owner of the backup.
172                 FileInfo finfo(buf->fileName());
173                 if (finfo.exist()) {
174                         mode_t fmode = finfo.getMode();
175                         struct utimbuf * times = new struct utimbuf;
176
177                         times->actime = finfo.getAccessTime();
178                         times->modtime = finfo.getModificationTime();
179                         ifstream ifs(buf->fileName().c_str());
180                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
181                         if (ifs && ofs) {
182                                 char c = 0;
183                                 while (ifs.get(c)) {
184                                         ofs.put(c);
185                                 }
186                                 ifs.close();
187                                 ofs.close();
188                                 chmod(s.c_str(), fmode);
189                                 
190                                 if (utime(s.c_str(), times)) {
191                                         lyxerr << "utime error." << endl;
192                                 }
193                         } else {
194                                 lyxerr << "LyX was not able to make "
195                                         "backupcopy. Beware." << endl;
196                         }
197                         delete times;
198                 }
199         }
200         
201         if (buf->writeFile(buf->fileName(), false)) {
202                 buf->markLyxClean();
203
204                 current_view->owner()->getMiniBuffer()->
205                         Set(_("Document saved as"),
206                         MakeDisplayPath(buf->fileName()));
207
208                 // now delete the autosavefile
209                 string a = OnlyPath(buf->fileName());
210                 a += '#';
211                 a += OnlyFilename(buf->fileName());
212                 a += '#';
213                 FileInfo fileinfo(a);
214                 if (fileinfo.exist()) {
215                         if (remove(a.c_str()) != 0) {
216                                 WriteFSAlert(_("Could not delete "
217                                                "auto-save file!"), a);
218                         }
219                 }
220         } else {
221                 // Saving failed, so backup is not backup
222                 if (makeBackup) {
223                         string s = buf->fileName() + '~';
224                         rename(s.c_str(), buf->fileName().c_str());
225                 }
226                 current_view->owner()->getMiniBuffer()->Set(_("Save failed!"));
227                 return false;
228         }
229
230         return true;
231 }
232
233
234 void BufferList::closeAll()
235 {
236         state_ = BufferList::CLOSING;
237         while (!bstore.empty()) {
238                 close(bstore.front());
239         }
240         state_ = BufferList::OK;
241 }
242
243
244 void BufferList::resize()
245 {
246         for(BufferStorage::iterator it = bstore.begin();
247             it != bstore.end(); ++it) {
248                 (*it)->resize();
249         }
250 }
251
252
253 bool BufferList::close(Buffer * buf)
254 {
255         if (buf->getUser()) buf->getUser()->insetUnlock();
256         
257         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
258                 ProhibitInput();
259                 switch(AskConfirmation(_("Changes in document:"),
260                                        MakeDisplayPath(buf->fileName(), 50),
261                                        _("Save document?"))){
262                 case 1: // Yes
263                         if (write(buf, lyxrc->make_backup)) {
264                                 lastfiles->newFile(buf->fileName());
265                         } else {
266                                 AllowInput();
267                                 return false;
268                         }
269                         break;
270                 case 3: // Cancel
271                         AllowInput();
272                         return false;
273                 }
274                 AllowInput();
275         }
276
277         bstore.release(buf);
278         return true;
279 }
280
281
282 vector<string> BufferList::getFileNames() const
283 {
284         vector<string> nvec;
285         for(BufferStorage::const_iterator cit = bstore.begin();
286             cit != bstore.end(); ++cit) {
287                 nvec.push_back((*cit)->fileName());
288         }
289         return nvec;
290 }
291
292
293 Buffer * BufferList::first()
294 {
295         if (bstore.empty()) return 0;
296         return bstore.front();
297 }
298
299
300 Buffer * BufferList::getBuffer(int choice)
301 {
302         if (choice >= bstore.size()) return 0;
303         return bstore[choice];
304 }
305
306
307 void BufferList::updateInset(Inset * inset, bool mark_dirty)
308 {
309         for (BufferStorage::iterator it = bstore.begin();
310              it != bstore.end(); ++it) {
311                 if ((*it)->getUser()
312                     && (*it)->getUser()->text->UpdateInset(inset)) {
313                         if (mark_dirty)
314                                 (*it)->markDirty();
315                         break;
316                 }
317         }
318 }
319
320
321 int BufferList::unlockInset(UpdatableInset * inset)
322 {
323         if (!inset) return 1;
324         for(BufferStorage::iterator it = bstore.begin();
325             it != bstore.end(); ++it) {
326                 if ((*it)->getUser()
327                     && (*it)->getUser()->the_locking_inset == inset) {
328                         (*it)->getUser()->insetUnlock();
329                         return 0;
330                 }
331         }
332         return 1;
333 }
334
335
336 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
337 {
338         for(BufferStorage::iterator it = bstore.begin();
339             it != bstore.end(); ++it) {
340                 if (!(*it)->isDepClean(mastertmpdir)) {
341                         string writefile = mastertmpdir;
342                         writefile += '/';
343                         writefile += ChangeExtension((*it)->fileName(),
344                                                      ".tex", true);
345                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
346                                              false, true);
347                         (*it)->markDepClean(mastertmpdir);
348                 }
349         }
350 }
351
352
353 void BufferList::emergencyWriteAll()
354 {
355         for (BufferStorage::iterator it = bstore.begin();
356              it != bstore.end(); ++it) {
357                 if (!(*it)->isLyxClean()) {
358                         bool madeit = false;
359                         
360                         lyxerr <<_("lyx: Attempting to save"
361                                    " document ")
362                                << (*it)->fileName()
363                                << _(" as...") << endl;
364                         
365                         for (int i = 0; i < 3 && !madeit; ++i) {
366                                 string s;
367                                 
368                                 // We try to save three places:
369                                 // 1) Same place as document.
370                                 // 2) In HOME directory.
371                                 // 3) In "/tmp" directory.
372                                 if (i == 0) {
373                                         s = (*it)->fileName();
374                                 } else if (i == 1) {
375                                         s = AddName(GetEnvPath("HOME"),
376                                                     (*it)->fileName());
377                                 } else {
378                                         // MakeAbsPath to prepend the current
379                                         // drive letter on OS/2
380                                         s = AddName(MakeAbsPath("/tmp/"),
381                                                     (*it)->fileName());
382                                 }
383                                 s += ".emergency";
384                                 
385                                 lyxerr << "  " << i + 1 << ") " << s << endl;
386                                 
387                                 if ((*it)->writeFile(s, true)) {
388                                         (*it)->markLyxClean();
389                                         lyxerr << _("  Save seems successful. "
390                                                     "Phew.") << endl;
391                                         madeit = true;
392                                 } else if (i != 2) {
393                                         lyxerr << _("  Save failed! Trying...")
394                                                << endl;
395                                 } else {
396                                         lyxerr << _("  Save failed! Bummer. "
397                                                     "Document is lost.")
398                                                << endl;
399                                 }
400                         }
401                 }
402         }
403 }
404
405
406 Buffer * BufferList::readFile(string const & s, bool ronly)
407 {
408         Buffer * b = bstore.newBuffer(s, lyxrc, ronly);
409
410         string ts = s;
411         string e = OnlyPath(s);
412         string a = e;
413         // File information about normal file
414         FileInfo fileInfo2(s);
415
416         // Check if emergency save file exists and is newer.
417         e += OnlyFilename(s) + ".emergency";
418         FileInfo fileInfoE(e);
419
420         bool use_emergency = false;
421
422         if (fileInfoE.exist() && fileInfo2.exist()) {
423                 if (fileInfoE.getModificationTime()
424                     > fileInfo2.getModificationTime()) {
425                         if (AskQuestion(_("An emergency save of this document exists!"),
426                                         MakeDisplayPath(s, 50),
427                                         _("Try to load that instead?"))) {
428                                 ts = e;
429                                 // the file is not saved if we load the
430                                 // emergency file.
431                                 b->markDirty();
432                                 use_emergency = true;
433                         } else {
434                                 // Here, we should delete the emergency save
435                                 unlink(e.c_str());
436                         }
437                 }
438         }
439
440         if (!use_emergency) {
441                 // Now check if autosave file is newer.
442                 a += '#';
443                 a += OnlyFilename(s);
444                 a += '#';
445                 FileInfo fileInfoA(a);
446                 if (fileInfoA.exist() && fileInfo2.exist()) {
447                         if (fileInfoA.getModificationTime()
448                             > fileInfo2.getModificationTime()) {
449                                 if (AskQuestion(_("Autosave file is newer."),
450                                                 MakeDisplayPath(s, 50),
451                                                 _("Load that one instead?"))) {
452                                         ts = a;
453                                         // the file is not saved if we load the
454                                         // autosave file.
455                                         b->markDirty();
456                                 } else {
457                                         // Here, we should delete the autosave
458                                         unlink(a.c_str());
459                                 }
460                         }
461                 }
462         }
463         // not sure if this is the correct place to begin LyXLex
464         LyXLex lex(0, 0);
465         lex.setFile(ts);
466         if (b->readFile(lex))
467                 return b;
468         else {
469                 bstore.release(b);
470                 return 0;
471         }
472 }
473
474
475 bool BufferList::exists(string const & s)
476 {
477         for (BufferStorage::iterator it = bstore.begin();
478              it != bstore.end(); ++it) {
479                 if ((*it)->fileName() == s)
480                         return true;
481         }
482         return false;
483 }
484
485
486 Buffer * BufferList::getBuffer(string const & s)
487 {
488         for(BufferStorage::iterator it = bstore.begin();
489             it != bstore.end(); ++it) {
490                 if ((*it)->fileName() == s)
491                         return (*it);
492         }
493         return 0;
494 }
495
496
497 Buffer * BufferList::newFile(string const & name, string tname)
498 {
499         /* get a free buffer */ 
500         Buffer * b = bstore.newBuffer(name, lyxrc);
501
502         // use defaults.lyx as a default template if it exists.
503         if (tname.empty()) {
504                 tname = LibFileSearch("templates", "defaults.lyx");
505         }
506         if (!tname.empty() && IsLyXFilename(tname)){
507                 bool templateok = false;
508                 LyXLex lex(0, 0);
509                 lex.setFile(tname);
510                 if (lex.IsOK()) {
511                         if (b->readFile(lex)) {
512                                 templateok = true;
513                         }
514                 }
515                 if (!templateok) {
516                         WriteAlert(_("Error!"), _("Unable to open template"), 
517                                    MakeDisplayPath(tname));
518                         // no template, start with empty buffer
519                         b->paragraph = new LyXParagraph;
520                 }
521         }
522         else {  // start with empty buffer
523                 b->paragraph = new LyXParagraph;
524         }
525
526         b->markDirty();
527         b->setReadonly(false);
528         
529         return b;
530 }
531
532
533 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
534 {
535         // make sure our path is absolute
536         string s = MakeAbsPath(filename);
537
538         // Is this done too early?
539         // Is it LinuxDoc?
540         if (IsSGMLFilename(s)) {
541                 FileInfo fi(s);
542                 if (fi.exist() && fi.readable()) {
543                         if (!RunLinuxDoc(-1, s)) {
544                                 s = ChangeExtension (s, ".lyx", false);
545                         } else { // sgml2lyx failed
546                                 WriteAlert(_("Error!"),
547                                            _("Could not convert file"), s);
548                                 return 0;
549                         }
550                 } else {
551                         // just change the extension and it will be
552                         // handled like a regular lyx file that does
553                         // not exist.
554                         s = ChangeExtension(s, ".lyx", false);
555                 }
556         }
557         
558         // file already open?
559         if (exists(s)) {
560                 if (AskQuestion(_("Document is already open:"), 
561                                 MakeDisplayPath(s, 50),
562                                 _("Do you want to reload that document?"))) {
563                         // Reload is accomplished by closing and then loading
564                         if (!close(getBuffer(s))) {
565                                 return 0;
566                         }
567                         // Fall through to new load. (Asger)
568                 } else {
569                         // Here, we pretend that we just loaded the 
570                         // open document
571                         return getBuffer(s);
572                 }
573         }
574         Buffer * b = 0;
575         bool ro = false;
576         switch (IsFileWriteable(s)) {
577         case 0:
578                 current_view->owner()->getMiniBuffer()->
579                         Set(_("File `")+MakeDisplayPath(s, 50)+
580                         _("' is read-only."));
581                 ro = true;
582                 // Fall through
583         case 1:
584                 b = readFile(s, ro);
585                 if (b) {
586                         b->lyxvc.file_found_hook(s);
587                 }
588                 break; //fine- it's r/w
589         case -1:
590                 // Here we probably should run
591                 if (LyXVC::file_not_found_hook(s)) {
592                         // Ask if the file should be checked out for
593                         // viewing/editing, if so: load it.
594                         if (AskQuestion(_("Do you want to retrive file under version control?"))) {
595                                 // How can we know _how_ to do the checkout?
596                                 // With the current VC support it has to be,
597                                 // a RCS file since CVS do not have special ,v files.
598                                 RCS::retrive(s);
599                                 return loadLyXFile(filename, tolastfiles);
600                         }
601                 }
602                 if (AskQuestion(_("Cannot open specified file:"), 
603                                 MakeDisplayPath(s, 50),
604                                 _("Create new document with this name?")))
605                         {
606                                 // Find a free buffer
607                                 b = newFile(s, string());
608                         }
609                 break;
610         }
611
612         if (b && tolastfiles)
613                 lastfiles->newFile(b->fileName());
614
615         return b;
616 }