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