]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
5373667768a23f928b734564b34e443000fe3e73
[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 #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
36 extern BufferView * current_view;
37 extern MiniBuffer * minibuffer;
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, 50);
108                                 unsaved += "\n";
109                                 break;
110                         case 3: // Cancel
111                                 return false;
112                         }
113                 }
114         }
115         if (askMoreConfirmation &&
116             lyxrc->exit_confirmation &&
117             !AskQuestion(_("Some documents were not saved:"),
118                          unsaved, _("Exit anyway?"))) {
119                 return false;
120         }
121
122         return true;
123 }
124
125
126 // Should probably be moved to somewhere else: BufferView? LyXView?
127 bool BufferList::write(Buffer * buf, bool makeBackup)
128 {
129         minibuffer->Set(_("Saving document"),
130                         MakeDisplayPath(buf->filename), "...");
131
132         // We don't need autosaves in the immediate future. (Asger)
133         buf->resetAutosaveTimers();
134
135         // make a backup
136         if (makeBackup) {
137                 string s = buf->filename + '~';
138                 // Rename is the wrong way of making a backup,
139                 // this is the correct way.
140                 /* truss cp fil fil2:
141                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
142                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
143                    open("LyXVC.lyx", O_RDONLY)                     = 3
144                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
145                    fstat(4, 0xEFFFF508)                            = 0
146                    fstat(3, 0xEFFFF508)                            = 0
147                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
148                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
149                    read(3, 0xEFFFD4A0, 8192)                       = 0
150                    close(4)                                        = 0
151                    close(3)                                        = 0
152                    chmod("LyXVC3.lyx", 0100644)                    = 0
153                    lseek(0, 0, SEEK_CUR)                           = 46440
154                    _exit(0)
155                  */
156
157                 // Should proabaly have some more error checking here.
158                 // Should be cleaned up in 0.13, at least a bit.
159                 // Doing it this way, also makes the inodes stay the same.
160                 // This is still not a very good solution, in particular we
161                 // might loose the owner of the backup.
162                 FileInfo finfo(buf->filename);
163                 if (finfo.exist()) {
164                         mode_t fmode = finfo.getMode();
165
166                         struct utimbuf *times = 
167                                 (struct utimbuf*)new char[sizeof(struct utimbuf)];
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, c_read, fout);
183                                 } while (c_read);
184                                 fin.close();
185                                 fout.close();
186                                 chmod(s.c_str(), fmode);
187                                 
188                                 if (utime(s.c_str(), times)) {
189                                         lyxerr << "utime error." << endl;
190                                 }
191                                 delete [] cbuf;
192                         } else {
193                                 lyxerr << "LyX was not able to make backupcopy. Beware." << endl;
194                         }
195                         delete[] times;
196                 }
197         }
198         
199         if (buf->writeFile(buf->filename, false)) {
200                 buf->markLyxClean();
201
202                 minibuffer->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                 minibuffer->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->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)->text && (*it)->text->UpdateInset(inset)) {
314                         if (mark_dirty)
315                                 (*it)->markDirty();
316                         break;
317                 }
318         }
319 }
320
321
322 int BufferList::unlockInset(UpdatableInset * inset)
323 {
324         if (!inset) return 1;
325         for(BufferStorage::iterator it = bstore.begin();
326             it != bstore.end(); ++it) {
327                 if ((*it)->the_locking_inset == inset) {
328                         (*it)->InsetUnlock();
329                         return 0;
330                 }
331         }
332         return 1;
333 }
334
335
336 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
337 {
338         for(BufferStorage::iterator it = bstore.begin();
339             it != bstore.end(); ++it) {
340                 if (!(*it)->isDepClean(mastertmpdir)) {
341                         string writefile = mastertmpdir;
342                         writefile += '/';
343                         writefile += ChangeExtension((*it)->getFileName(),
344                                                      ".tex", true);
345                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
346                                              false, true);
347                         (*it)->markDepClean(mastertmpdir);
348                                                      
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 { // MakeAbsPath to prepend the current drive letter on OS/2
379                                         s = AddName(MakeAbsPath("/tmp/"),
380                                                     (*it)->filename);
381                                 }
382                                 s += ".emergency";
383                                 
384                                 lyxerr << "  " << i + 1 << ") " << s << endl;
385                                 
386                                 if ((*it)->writeFile(s, true)) {
387                                         (*it)->markLyxClean();
388                                         lyxerr << _("  Save seems successful. "
389                                                     "Phew.") << endl;
390                                         madeit = true;
391                                 } else if (i != 2) {
392                                         lyxerr << _("  Save failed! Trying...")
393                                                << endl;
394                                 } else {
395                                         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
396                                 }
397                         }
398                 }
399         }
400 }
401
402
403 Buffer * BufferList::readFile(string const & s, bool ronly)
404 {
405         Buffer * b = bstore.newBuffer(s, lyxrc, ronly);
406
407         string ts = s;
408         string e = OnlyPath(s);
409         string a = e;
410         // File information about normal file
411         FileInfo fileInfo2(s);
412
413         // Check if emergency save file exists and is newer.
414         e += OnlyFilename(s) + ".emergency";
415         FileInfo fileInfoE(e);
416
417         bool use_emergency = false;
418
419         if (fileInfoE.exist() && fileInfo2.exist()) {
420                 if (fileInfoE.getModificationTime()
421                     > fileInfo2.getModificationTime()) {
422                         if (AskQuestion(_("An emergency save of this document exists!"),
423                                         MakeDisplayPath(s, 50),
424                                         _("Try to load that instead?"))) {
425                                 ts = e;
426                                 // the file is not saved if we load the
427                                 // emergency file.
428                                 b->markDirty();
429                                 use_emergency = true;
430                         } else {
431                                 // Here, we should delete the emergency save
432                                 unlink(e.c_str());
433                         }
434                 }
435         }
436
437         if (!use_emergency) {
438                 // Now check if autosave file is newer.
439                 a += '#';
440                 a += OnlyFilename(s);
441                 a += '#';
442                 FileInfo fileInfoA(a);
443                 if (fileInfoA.exist() && fileInfo2.exist()) {
444                         if (fileInfoA.getModificationTime()
445                             > fileInfo2.getModificationTime()) {
446                                 if (AskQuestion(_("Autosave file is newer."),
447                                                 MakeDisplayPath(s, 50),
448                                                 _("Load that one instead?"))) {
449                                         ts = a;
450                                         // the file is not saved if we load the
451                                         // autosave file.
452                                         b->markDirty();
453                                 } else {
454                                         // Here, we should delete the autosave
455                                         unlink(a.c_str());
456                                 }
457                         }
458                 }
459         }
460         // not sure if this is the correct place to begin LyXLex
461         LyXLex lex(0, 0);
462         lex.setFile(ts);
463         if (b->readFile(lex))
464                 return b;
465         else {
466                 bstore.release(b);
467                 return 0;
468         }
469 }
470
471
472 bool BufferList::exists(string const & s)
473 {
474         for (BufferStorage::iterator it = bstore.begin();
475              it != bstore.end(); ++it) {
476                 if ((*it)->filename == s)
477                         return true;
478         }
479         return false;
480 }
481
482
483 Buffer * BufferList::getBuffer(string const & s)
484 {
485         for(BufferStorage::iterator it = bstore.begin();
486             it != bstore.end(); ++it) {
487                 if ((*it)->filename == s)
488                         return (*it);
489         }
490         return 0;
491 }
492
493
494 Buffer * BufferList::newFile(string const & name, string tname)
495 {
496         /* get a free buffer */ 
497         Buffer * b = bstore.newBuffer(name, lyxrc);
498
499         // use defaults.lyx as a default template if it exists.
500         if (tname.empty()) {
501                 tname = LibFileSearch("templates", "defaults.lyx");
502         }
503         if (!tname.empty() && IsLyXFilename(tname)){
504                 bool templateok = false;
505                 LyXLex lex(0, 0);
506                 lex.setFile(tname);
507                 if (lex.IsOK()) {
508                         if (b->readFile(lex)) {
509                                 templateok = true;
510                         }
511                 }
512                 if (!templateok) {
513                         WriteAlert(_("Error!"), _("Unable to open template"), 
514                                    MakeDisplayPath(tname));
515                         // no template, start with empty buffer
516                         b->paragraph = new LyXParagraph;
517                 }
518         }
519         else {  // start with empty buffer
520                 b->paragraph = new LyXParagraph;
521         }
522
523         b->markDirty();
524         b->setReadonly(false);
525         
526         return b;
527 }
528
529
530 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
531 {
532         // make sure our path is absolute
533         string s = MakeAbsPath(filename);
534
535         // Is this done too early?
536         // Is it LinuxDoc?
537         if (IsSGMLFilename(s)) {
538                 FileInfo fi(s);
539                 if (fi.exist() && fi.readable()) {
540                         if (!RunLinuxDoc(-1, s)) {
541                                 s = ChangeExtension (s, ".lyx", false);
542                         } else { // sgml2lyx failed
543                                 WriteAlert(_("Error!"),
544                                            _("Could not convert file"), s);
545                                 return 0;
546                         }
547                 } else {
548                         // just change the extension and it will be
549                         // handled like a regular lyx file that does
550                         // not exist.
551                         s = ChangeExtension(s, ".lyx", false);
552                 }
553         }
554         
555         // file already open?
556         if (exists(s)) {
557                 if (AskQuestion(_("Document is already open:"), 
558                                 MakeDisplayPath(s, 50),
559                                 _("Do you want to reload that document?"))) {
560                         // Reload is accomplished by closing and then loading
561                         if (!close(getBuffer(s))) {
562                                 return 0;
563                         }
564                         // Fall through to new load. (Asger)
565                 } else {
566                         // Here, we pretend that we just loaded the 
567                         // open document
568                         return getBuffer(s);
569                 }
570         }
571         Buffer * b = 0;
572         bool ro = false;
573         switch (IsFileWriteable(s)) {
574         case 0:
575                 minibuffer->Set(_("File `")+MakeDisplayPath(s, 50)+
576                                 _("' is read-only."));
577                 ro = true;
578                 // Fall through
579         case 1:
580                 b = readFile(s, ro);
581                 if (b) {
582                         b->lyxvc.file_found_hook(s);
583                 }
584                 break; //fine- it's r/w
585         case -1:
586                 // Here we probably should run
587                 if (LyXVC::file_not_found_hook(s)) {
588                         // Ask if the file should be checked out for
589                         // viewing/editing, if so: load it.
590                         lyxerr << "Do you want to checkout?" << endl;
591                 }
592                 if (AskQuestion(_("Cannot open specified file:"), 
593                                 MakeDisplayPath(s, 50),
594                                 _("Create new document with this name?")))
595                 {
596                         // Find a free buffer
597                         b = newFile(s, string());
598                 }
599                 break;
600         }
601
602         if (b && tolastfiles)
603                 lastfiles->newFile(b->getFileName());
604
605         return b;
606 }