]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
9f949a381851492c375bd6d885362be69b7caf7d
[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() + 1 << endl;
74         container.push_back(tmpbuf);
75         return tmpbuf;
76 }
77
78
79 //
80 // Class BufferList
81 //
82
83 BufferList::BufferList()
84 {
85         _state = BufferList::OK;
86 }
87
88
89 bool BufferList::empty()
90 {
91         return bstore.empty();
92 }
93
94
95 extern void MenuWrite(Buffer *);
96
97 bool BufferList::QwriteAll()
98 {
99         bool askMoreConfirmation = false;
100         string unsaved;
101         for(BufferStorage::iterator it = bstore.begin();
102             it != bstore.end(); ++it) {
103                 if (!(*it)->isLyxClean()) {
104                         switch(AskConfirmation(_("Changes in document:"),
105                                                MakeDisplayPath((*it)->fileName(),
106                                                                50),
107                                                _("Save document?"))) {
108                         case 1: // Yes
109                                 MenuWrite((*it));
110                                 break;
111                         case 2: // No
112                                 askMoreConfirmation = true;
113                                 unsaved += MakeDisplayPath((*it)->fileName(),
114                                                            50);
115                                 unsaved += "\n";
116                                 break;
117                         case 3: // Cancel
118                                 return false;
119                         }
120                 }
121         }
122         if (askMoreConfirmation &&
123             lyxrc->exit_confirmation &&
124             !AskQuestion(_("Some documents were not saved:"),
125                          unsaved, _("Exit anyway?"))) {
126                 return false;
127         }
128
129         return true;
130 }
131
132
133 // Should probably be moved to somewhere else: BufferView? LyXView?
134 bool BufferList::write(Buffer * buf, bool makeBackup)
135 {
136         if (buf->getUser())
137                 buf->getUser()
138                         ->owner()
139                         ->getMiniBuffer()
140                         ->Set(_("Saving document"),
141                               MakeDisplayPath(buf->fileName()), "...");
142
143         // We don't need autosaves in the immediate future. (Asger)
144         buf->resetAutosaveTimers();
145
146         // make a backup
147         if (makeBackup) {
148                 string s = buf->fileName() + '~';
149                 // Rename is the wrong way of making a backup,
150                 // this is the correct way.
151                 /* truss cp fil fil2:
152                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
153                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
154                    open("LyXVC.lyx", O_RDONLY)                     = 3
155                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
156                    fstat(4, 0xEFFFF508)                            = 0
157                    fstat(3, 0xEFFFF508)                            = 0
158                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
159                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
160                    read(3, 0xEFFFD4A0, 8192)                       = 0
161                    close(4)                                        = 0
162                    close(3)                                        = 0
163                    chmod("LyXVC3.lyx", 0100644)                    = 0
164                    lseek(0, 0, SEEK_CUR)                           = 46440
165                    _exit(0)
166                 */
167
168                 // Should proabaly have some more error checking here.
169                 // Should be cleaned up in 0.13, at least a bit.
170                 // Doing it this way, also makes the inodes stay the same.
171                 // This is still not a very good solution, in particular we
172                 // might loose the owner of the backup.
173                 FileInfo finfo(buf->fileName());
174                 if (finfo.exist()) {
175                         mode_t fmode = finfo.getMode();
176                         struct utimbuf * times = new struct utimbuf;
177
178                         times->actime = finfo.getAccessTime();
179                         times->modtime = finfo.getModificationTime();
180                         ifstream ifs(buf->fileName().c_str());
181                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
182                         if (ifs && ofs) {
183                                 char c = 0;
184                                 while (ifs.get(c)) {
185                                         ofs.put(c);
186                                 }
187                                 ifs.close();
188                                 ofs.close();
189                                 chmod(s.c_str(), fmode);
190                                 
191                                 if (utime(s.c_str(), times)) {
192                                         lyxerr << "utime error." << endl;
193                                 }
194                         } else {
195                                 lyxerr << "LyX was not able to make "
196                                         "backupcopy. Beware." << endl;
197                         }
198                         delete times;
199                 }
200         }
201         
202         if (buf->writeFile(buf->fileName(), false)) {
203                 buf->markLyxClean();
204
205                 current_view->owner()->getMiniBuffer()->
206                         Set(_("Document saved as"),
207                         MakeDisplayPath(buf->fileName()));
208
209                 // now delete the autosavefile
210                 string a = OnlyPath(buf->fileName());
211                 a += '#';
212                 a += OnlyFilename(buf->fileName());
213                 a += '#';
214                 FileInfo fileinfo(a);
215                 if (fileinfo.exist()) {
216                         if (remove(a.c_str()) != 0) {
217                                 WriteFSAlert(_("Could not delete "
218                                                "auto-save file!"), a);
219                         }
220                 }
221         } else {
222                 // Saving failed, so backup is not backup
223                 if (makeBackup) {
224                         string s = buf->fileName() + '~';
225                         rename(s.c_str(), buf->fileName().c_str());
226                 }
227                 current_view->owner()->getMiniBuffer()->Set(_("Save failed!"));
228                 return false;
229         }
230
231         return true;
232 }
233
234
235 void BufferList::closeAll()
236 {
237         _state = BufferList::CLOSING;
238         while (!bstore.empty()) {
239                 close(bstore.front());
240         }
241         _state = BufferList::OK;
242 }
243
244
245 void BufferList::resize()
246 {
247         for(BufferStorage::iterator it = bstore.begin();
248             it != bstore.end(); ++it) {
249                 (*it)->resize();
250         }
251 }
252
253
254 bool BufferList::close(Buffer * buf)
255 {
256         if (buf->getUser()) buf->getUser()->insetUnlock();
257         
258         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
259                 ProhibitInput();
260                 switch(AskConfirmation(_("Changes in document:"),
261                                        MakeDisplayPath(buf->fileName(), 50),
262                                        _("Save document?"))){
263                 case 1: // Yes
264                         if (write(buf, lyxrc->make_backup)) {
265                                 lastfiles->newFile(buf->fileName());
266                         } else {
267                                 AllowInput();
268                                 return false;
269                         }
270                         break;
271                 case 3: // Cancel
272                         AllowInput();
273                         return false;
274                 }
275                 AllowInput();
276         }
277
278         bstore.release(buf);
279         return true;
280 }
281
282
283 void BufferList::makePup(int pup)
284         /* This should be changed to return a char const *const
285            in the same way as for lastfiles.[hC]
286            */
287 {
288         int ant = 0;
289         for(BufferStorage::iterator it = bstore.begin();
290             it != bstore.end(); ++it) {
291                 string relbuf = MakeDisplayPath((*it)->fileName(), 30);
292                 fl_addtopup(pup, relbuf.c_str());
293                 ++ant;
294         }
295         if (ant == 0) fl_addtopup(pup, _("No Documents Open!%t"));
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)
482 {
483         for (BufferStorage::iterator it = bstore.begin();
484              it != bstore.end(); ++it) {
485                 if ((*it)->fileName() == s)
486                         return true;
487         }
488         return false;
489 }
490
491
492 Buffer * BufferList::getBuffer(string const & s)
493 {
494         for(BufferStorage::iterator it = bstore.begin();
495             it != bstore.end(); ++it) {
496                 if ((*it)->fileName() == s)
497                         return (*it);
498         }
499         return 0;
500 }
501
502
503 Buffer * BufferList::newFile(string const & name, string tname)
504 {
505         /* get a free buffer */ 
506         Buffer * b = bstore.newBuffer(name, lyxrc);
507
508         // use defaults.lyx as a default template if it exists.
509         if (tname.empty()) {
510                 tname = LibFileSearch("templates", "defaults.lyx");
511         }
512         if (!tname.empty() && IsLyXFilename(tname)){
513                 bool templateok = false;
514                 LyXLex lex(0, 0);
515                 lex.setFile(tname);
516                 if (lex.IsOK()) {
517                         if (b->readFile(lex)) {
518                                 templateok = true;
519                         }
520                 }
521                 if (!templateok) {
522                         WriteAlert(_("Error!"), _("Unable to open template"), 
523                                    MakeDisplayPath(tname));
524                         // no template, start with empty buffer
525                         b->paragraph = new LyXParagraph;
526                 }
527         }
528         else {  // start with empty buffer
529                 b->paragraph = new LyXParagraph;
530         }
531
532         b->markDirty();
533         b->setReadonly(false);
534         
535         return b;
536 }
537
538
539 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
540 {
541         // make sure our path is absolute
542         string s = MakeAbsPath(filename);
543
544         // Is this done too early?
545         // Is it LinuxDoc?
546         if (IsSGMLFilename(s)) {
547                 FileInfo fi(s);
548                 if (fi.exist() && fi.readable()) {
549                         if (!RunLinuxDoc(-1, s)) {
550                                 s = ChangeExtension (s, ".lyx", false);
551                         } else { // sgml2lyx failed
552                                 WriteAlert(_("Error!"),
553                                            _("Could not convert file"), s);
554                                 return 0;
555                         }
556                 } else {
557                         // just change the extension and it will be
558                         // handled like a regular lyx file that does
559                         // not exist.
560                         s = ChangeExtension(s, ".lyx", false);
561                 }
562         }
563         
564         // file already open?
565         if (exists(s)) {
566                 if (AskQuestion(_("Document is already open:"), 
567                                 MakeDisplayPath(s, 50),
568                                 _("Do you want to reload that document?"))) {
569                         // Reload is accomplished by closing and then loading
570                         if (!close(getBuffer(s))) {
571                                 return 0;
572                         }
573                         // Fall through to new load. (Asger)
574                 } else {
575                         // Here, we pretend that we just loaded the 
576                         // open document
577                         return getBuffer(s);
578                 }
579         }
580         Buffer * b = 0;
581         bool ro = false;
582         switch (IsFileWriteable(s)) {
583         case 0:
584                 current_view->owner()->getMiniBuffer()->
585                         Set(_("File `")+MakeDisplayPath(s, 50)+
586                         _("' is read-only."));
587                 ro = true;
588                 // Fall through
589         case 1:
590                 b = readFile(s, ro);
591                 if (b) {
592                         b->lyxvc.file_found_hook(s);
593                 }
594                 break; //fine- it's r/w
595         case -1:
596                 // Here we probably should run
597                 if (LyXVC::file_not_found_hook(s)) {
598                         // Ask if the file should be checked out for
599                         // viewing/editing, if so: load it.
600                         if (AskQuestion(_("Do you want to retrive file under version control?"))) {
601                                 // How can we know _how_ to do the checkout?
602                                 // With the current VC support it has to be,
603                                 // a RCS file since CVS do not have special ,v files.
604                                 RCS::retrive(s);
605                                 return loadLyXFile(filename, tolastfiles);
606                         }
607                 }
608                 if (AskQuestion(_("Cannot open specified file:"), 
609                                 MakeDisplayPath(s, 50),
610                                 _("Create new document with this name?")))
611                         {
612                                 // Find a free buffer
613                                 b = newFile(s, string());
614                         }
615                 break;
616         }
617
618         if (b && tolastfiles)
619                 lastfiles->newFile(b->fileName());
620
621         return b;
622 }