]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
7532c2ac846b6e72f0263a395ed3c0601e5d6bfc
[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(),
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         minibuffer->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                 minibuffer->Set(_("Document saved as"),
205                                 MakeDisplayPath(buf->fileName()));
206
207                 // now delete the autosavefile
208                 string a = OnlyPath(buf->fileName());
209                 a += '#';
210                 a += OnlyFilename(buf->fileName());
211                 a += '#';
212                 FileInfo fileinfo(a);
213                 if (fileinfo.exist()) {
214                         if (remove(a.c_str()) != 0) {
215                                 WriteFSAlert(_("Could not delete "
216                                                "auto-save file!"), a);
217                         }
218                 }
219         } else {
220                 // Saving failed, so backup is not backup
221                 if (makeBackup) {
222                         string s = buf->fileName() + '~';
223                         rename(s.c_str(), buf->fileName().c_str());
224                 }
225                 minibuffer->Set(_("Save failed!"));
226                 return false;
227         }
228
229         return true;
230 }
231
232
233 void BufferList::closeAll()
234 {
235         _state = BufferList::CLOSING;
236         while (!bstore.empty()) {
237                 close(bstore.front());
238         }
239         _state = BufferList::OK;
240 }
241
242
243 void BufferList::resize()
244 {
245         for(BufferStorage::iterator it = bstore.begin();
246             it != bstore.end(); ++it) {
247                 (*it)->resize();
248         }
249 }
250
251
252 bool BufferList::close(Buffer * buf)
253 {
254         buf->InsetUnlock();
255         
256         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
257                 ProhibitInput();
258                 switch(AskConfirmation(_("Changes in document:"),
259                                        MakeDisplayPath(buf->fileName(), 50),
260                                        _("Save document?"))){
261                 case 1: // Yes
262                         if (write(buf)) {
263                                 lastfiles->newFile(buf->fileName());
264                         } else {
265                                 AllowInput();
266                                 return false;
267                         }
268                         break;
269                 case 3: // Cancel
270                         AllowInput();
271                         return false;
272                 }
273                 AllowInput();
274         }
275
276         bstore.release(buf);
277         return true;
278 }
279
280
281 void BufferList::makePup(int pup)
282         /* This should be changed to return a char const *const
283            in the same way as for lastfiles.[hC]
284            */
285 {
286         int ant = 0;
287         for(BufferStorage::iterator it = bstore.begin();
288             it != bstore.end(); ++it) {
289                 string relbuf = MakeDisplayPath((*it)->fileName(), 30);
290                 fl_addtopup(pup, relbuf.c_str());
291                 ++ant;
292         }
293         if (ant == 0) fl_addtopup(pup, _("No Documents Open!%t"));
294 }
295
296
297 Buffer * BufferList::first()
298 {
299         if (bstore.empty()) return 0;
300         return bstore.front();
301 }
302
303
304 Buffer * BufferList::getBuffer(int choice)
305 {
306         if (choice >= bstore.size()) return 0;
307         return bstore[choice];
308 }
309
310
311 void BufferList::updateInset(Inset * inset, bool mark_dirty)
312 {
313         for (BufferStorage::iterator it = bstore.begin();
314              it != bstore.end(); ++it) {
315                 if ((*it)->getUser()
316                     && (*it)->getUser()->text->UpdateInset(inset)) {
317                         if (mark_dirty)
318                                 (*it)->markDirty();
319                         break;
320                 }
321         }
322 }
323
324
325 int BufferList::unlockInset(UpdatableInset * inset)
326 {
327         if (!inset) return 1;
328         for(BufferStorage::iterator it = bstore.begin();
329             it != bstore.end(); ++it) {
330                 if ((*it)->the_locking_inset == inset) {
331                         (*it)->InsetUnlock();
332                         return 0;
333                 }
334         }
335         return 1;
336 }
337
338
339 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
340 {
341         for(BufferStorage::iterator it = bstore.begin();
342             it != bstore.end(); ++it) {
343                 if (!(*it)->isDepClean(mastertmpdir)) {
344                         string writefile = mastertmpdir;
345                         writefile += '/';
346                         writefile += ChangeExtension((*it)->fileName(),
347                                                      ".tex", true);
348                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
349                                              false, true);
350                         (*it)->markDepClean(mastertmpdir);
351                 }
352         }
353 }
354
355
356 void BufferList::emergencyWriteAll()
357 {
358         for (BufferStorage::iterator it = bstore.begin();
359              it != bstore.end(); ++it) {
360                 if (!(*it)->isLyxClean()) {
361                         bool madeit = false;
362                         
363                         lyxerr <<_("lyx: Attempting to save"
364                                    " document ")
365                                << (*it)->fileName()
366                                << _(" as...") << endl;
367                         
368                         for (int i = 0; i < 3 && !madeit; ++i) {
369                                 string s;
370                                 
371                                 // We try to save three places:
372                                 // 1) Same place as document.
373                                 // 2) In HOME directory.
374                                 // 3) In "/tmp" directory.
375                                 if (i == 0) {
376                                         s = (*it)->fileName();
377                                 } else if (i == 1) {
378                                         s = AddName(GetEnvPath("HOME"),
379                                                     (*it)->fileName());
380                                 } else {
381                                         // MakeAbsPath to prepend the current
382                                         // drive letter on OS/2
383                                         s = AddName(MakeAbsPath("/tmp/"),
384                                                     (*it)->fileName());
385                                 }
386                                 s += ".emergency";
387                                 
388                                 lyxerr << "  " << i + 1 << ") " << s << endl;
389                                 
390                                 if ((*it)->writeFile(s, true)) {
391                                         (*it)->markLyxClean();
392                                         lyxerr << _("  Save seems successful. "
393                                                     "Phew.") << endl;
394                                         madeit = true;
395                                 } else if (i != 2) {
396                                         lyxerr << _("  Save failed! Trying...")
397                                                << endl;
398                                 } else {
399                                         lyxerr << _("  Save failed! Bummer. "
400                                                     "Document is lost.")
401                                                << endl;
402                                 }
403                         }
404                 }
405         }
406 }
407
408
409 Buffer * BufferList::readFile(string const & s, bool ronly)
410 {
411         Buffer * b = bstore.newBuffer(s, lyxrc, ronly);
412
413         string ts = s;
414         string e = OnlyPath(s);
415         string a = e;
416         // File information about normal file
417         FileInfo fileInfo2(s);
418
419         // Check if emergency save file exists and is newer.
420         e += OnlyFilename(s) + ".emergency";
421         FileInfo fileInfoE(e);
422
423         bool use_emergency = false;
424
425         if (fileInfoE.exist() && fileInfo2.exist()) {
426                 if (fileInfoE.getModificationTime()
427                     > fileInfo2.getModificationTime()) {
428                         if (AskQuestion(_("An emergency save of this document exists!"),
429                                         MakeDisplayPath(s, 50),
430                                         _("Try to load that instead?"))) {
431                                 ts = e;
432                                 // the file is not saved if we load the
433                                 // emergency file.
434                                 b->markDirty();
435                                 use_emergency = true;
436                         } else {
437                                 // Here, we should delete the emergency save
438                                 unlink(e.c_str());
439                         }
440                 }
441         }
442
443         if (!use_emergency) {
444                 // Now check if autosave file is newer.
445                 a += '#';
446                 a += OnlyFilename(s);
447                 a += '#';
448                 FileInfo fileInfoA(a);
449                 if (fileInfoA.exist() && fileInfo2.exist()) {
450                         if (fileInfoA.getModificationTime()
451                             > fileInfo2.getModificationTime()) {
452                                 if (AskQuestion(_("Autosave file is newer."),
453                                                 MakeDisplayPath(s, 50),
454                                                 _("Load that one instead?"))) {
455                                         ts = a;
456                                         // the file is not saved if we load the
457                                         // autosave file.
458                                         b->markDirty();
459                                 } else {
460                                         // Here, we should delete the autosave
461                                         unlink(a.c_str());
462                                 }
463                         }
464                 }
465         }
466         // not sure if this is the correct place to begin LyXLex
467         LyXLex lex(0, 0);
468         lex.setFile(ts);
469         if (b->readFile(lex))
470                 return b;
471         else {
472                 bstore.release(b);
473                 return 0;
474         }
475 }
476
477
478 bool BufferList::exists(string const & s)
479 {
480         for (BufferStorage::iterator it = bstore.begin();
481              it != bstore.end(); ++it) {
482                 if ((*it)->fileName() == s)
483                         return true;
484         }
485         return false;
486 }
487
488
489 Buffer * BufferList::getBuffer(string const & s)
490 {
491         for(BufferStorage::iterator it = bstore.begin();
492             it != bstore.end(); ++it) {
493                 if ((*it)->fileName() == s)
494                         return (*it);
495         }
496         return 0;
497 }
498
499
500 Buffer * BufferList::newFile(string const & name, string tname)
501 {
502         /* get a free buffer */ 
503         Buffer * b = bstore.newBuffer(name, lyxrc);
504
505         // use defaults.lyx as a default template if it exists.
506         if (tname.empty()) {
507                 tname = LibFileSearch("templates", "defaults.lyx");
508         }
509         if (!tname.empty() && IsLyXFilename(tname)){
510                 bool templateok = false;
511                 LyXLex lex(0, 0);
512                 lex.setFile(tname);
513                 if (lex.IsOK()) {
514                         if (b->readFile(lex)) {
515                                 templateok = true;
516                         }
517                 }
518                 if (!templateok) {
519                         WriteAlert(_("Error!"), _("Unable to open template"), 
520                                    MakeDisplayPath(tname));
521                         // no template, start with empty buffer
522                         b->paragraph = new LyXParagraph;
523                 }
524         }
525         else {  // start with empty buffer
526                 b->paragraph = new LyXParagraph;
527         }
528
529         b->markDirty();
530         b->setReadonly(false);
531         
532         return b;
533 }
534
535
536 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
537 {
538         // make sure our path is absolute
539         string s = MakeAbsPath(filename);
540
541         // Is this done too early?
542         // Is it LinuxDoc?
543         if (IsSGMLFilename(s)) {
544                 FileInfo fi(s);
545                 if (fi.exist() && fi.readable()) {
546                         if (!RunLinuxDoc(-1, s)) {
547                                 s = ChangeExtension (s, ".lyx", false);
548                         } else { // sgml2lyx failed
549                                 WriteAlert(_("Error!"),
550                                            _("Could not convert file"), s);
551                                 return 0;
552                         }
553                 } else {
554                         // just change the extension and it will be
555                         // handled like a regular lyx file that does
556                         // not exist.
557                         s = ChangeExtension(s, ".lyx", false);
558                 }
559         }
560         
561         // file already open?
562         if (exists(s)) {
563                 if (AskQuestion(_("Document is already open:"), 
564                                 MakeDisplayPath(s, 50),
565                                 _("Do you want to reload that document?"))) {
566                         // Reload is accomplished by closing and then loading
567                         if (!close(getBuffer(s))) {
568                                 return 0;
569                         }
570                         // Fall through to new load. (Asger)
571                 } else {
572                         // Here, we pretend that we just loaded the 
573                         // open document
574                         return getBuffer(s);
575                 }
576         }
577         Buffer * b = 0;
578         bool ro = false;
579         switch (IsFileWriteable(s)) {
580         case 0:
581                 minibuffer->Set(_("File `")+MakeDisplayPath(s, 50)+
582                                 _("' is read-only."));
583                 ro = true;
584                 // Fall through
585         case 1:
586                 b = readFile(s, ro);
587                 if (b) {
588                         b->lyxvc.file_found_hook(s);
589                 }
590                 break; //fine- it's r/w
591         case -1:
592                 // Here we probably should run
593                 if (LyXVC::file_not_found_hook(s)) {
594                         // Ask if the file should be checked out for
595                         // viewing/editing, if so: load it.
596                         lyxerr << "Do you want to checkout?" << endl;
597                 }
598                 if (AskQuestion(_("Cannot open specified file:"), 
599                                 MakeDisplayPath(s, 50),
600                                 _("Create new document with this name?")))
601                         {
602                                 // Find a free buffer
603                                 b = newFile(s, string());
604                         }
605                 break;
606         }
607
608         if (b && tolastfiles)
609                 lastfiles->newFile(b->fileName());
610
611         return b;
612 }