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