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