]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
cb0ca686376cc486f261bdaab020ebef2e985fad
[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                         struct utimbuf * times = new struct utimbuf;
166
167                         times->actime = finfo.getAccessTime();
168                         times->modtime = finfo.getModificationTime();
169                         long blksize = finfo.getBlockSize();
170                         lyxerr.debug() << "BlockSize: " << blksize << endl;
171                         FilePtr fin(buf->fileName(), FilePtr::read);
172                         FilePtr fout(s, FilePtr::truncate);
173                         if (fin() && fout()) {
174                                 char * cbuf = new char[blksize+1];
175                                 size_t c_read = 0;
176                                 size_t c_write = 0;
177                                 do {
178                                         c_read = fread(cbuf, 1, blksize, fin);
179                                         if (c_read != 0)
180                                                 c_write = 
181                                                         fwrite(cbuf, 1, c_read, fout);
182                                 } while (c_read);
183                                 fin.close();
184                                 fout.close();
185                                 chmod(s.c_str(), fmode);
186                                 
187                                 if (utime(s.c_str(), times)) {
188                                         lyxerr << "utime error." << endl;
189                                 }
190                                 delete [] cbuf;
191                         } else {
192                                 lyxerr << "LyX was not able to make backupcopy. Beware." << endl;
193                         }
194                         delete[] times;
195                 }
196         }
197         
198         if (buf->writeFile(buf->fileName(), false)) {
199                 buf->markLyxClean();
200
201                 minibuffer->Set(_("Document saved as"),
202                                 MakeDisplayPath(buf->fileName()));
203
204                 // now delete the autosavefile
205                 string a = OnlyPath(buf->fileName());
206                 a += '#';
207                 a += OnlyFilename(buf->fileName());
208                 a += '#';
209                 FileInfo fileinfo(a);
210                 if (fileinfo.exist()) {
211                         if (remove(a.c_str()) != 0) {
212                                 WriteFSAlert(_("Could not delete "
213                                                "auto-save file!"), a);
214                         }
215                 }
216         } else {
217                 // Saving failed, so backup is not backup
218                 if (makeBackup) {
219                         string s = buf->fileName() + '~';
220                         rename(s.c_str(), buf->fileName().c_str());
221                 }
222                 minibuffer->Set(_("Save failed!"));
223                 return false;
224         }
225
226         return true;
227 }
228
229
230 void BufferList::closeAll()
231 {
232         _state = BufferList::CLOSING;
233         while (!bstore.empty()) {
234                 close(bstore.front());
235         }
236         _state = BufferList::OK;
237 }
238
239
240 void BufferList::resize()
241 {
242         for(BufferStorage::iterator it = bstore.begin();
243             it != bstore.end(); ++it) {
244                 (*it)->resize();
245         }
246 }
247
248
249 bool BufferList::close(Buffer * buf)
250 {
251         buf->InsetUnlock();
252         
253         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
254                 ProhibitInput();
255                 switch(AskConfirmation(_("Changes in document:"),
256                               MakeDisplayPath(buf->fileName(), 50),
257                                       _("Save document?"))){
258                 case 1: // Yes
259                         if (write(buf)) {
260                                 lastfiles->newFile(buf->fileName());
261                         } else {
262                                 AllowInput();
263                                 return false;
264                         }
265                         break;
266                 case 3: // Cancel
267                         AllowInput();
268                         return false;
269                 }
270                 AllowInput();
271         }
272
273         bstore.release(buf);
274         return true;
275 }
276
277
278 void BufferList::makePup(int pup)
279         /* This should be changed to return a char const *const
280            in the same way as for lastfiles.[hC]
281            */
282 {
283         int ant = 0;
284         for(BufferStorage::iterator it = bstore.begin();
285             it != bstore.end(); ++it) {
286                 string relbuf = MakeDisplayPath((*it)->fileName(), 30);
287                 fl_addtopup(pup, relbuf.c_str());
288                 ++ant;
289         }
290         if (ant == 0) fl_addtopup(pup, _("No Documents Open!%t"));
291 }
292
293
294 Buffer * BufferList::first()
295 {
296         if (bstore.empty()) return 0;
297         return bstore.front();
298 }
299
300
301 Buffer * BufferList::getBuffer(int choice)
302 {
303         if (choice >= bstore.size()) return 0;
304         return bstore[choice];
305 }
306
307
308 void BufferList::updateInset(Inset * inset, bool mark_dirty)
309 {
310         for (BufferStorage::iterator it = bstore.begin();
311              it != bstore.end(); ++it) {
312 #ifdef MOVE_TEXT
313                 if ((*it)->getUser() && (*it)->getUser()->text->UpdateInset(inset)) {
314                         if (mark_dirty)
315                                 (*it)->markDirty();
316                         break;
317                 }
318 #else
319                 if ((*it)->text && (*it)->text->UpdateInset(inset)) {
320                         if (mark_dirty)
321                                 (*it)->markDirty();
322                         break;
323                 }
324 #endif
325         }
326 }
327
328
329 int BufferList::unlockInset(UpdatableInset * inset)
330 {
331         if (!inset) return 1;
332         for(BufferStorage::iterator it = bstore.begin();
333             it != bstore.end(); ++it) {
334                 if ((*it)->the_locking_inset == inset) {
335                         (*it)->InsetUnlock();
336                         return 0;
337                 }
338         }
339         return 1;
340 }
341
342
343 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
344 {
345         for(BufferStorage::iterator it = bstore.begin();
346             it != bstore.end(); ++it) {
347                 if (!(*it)->isDepClean(mastertmpdir)) {
348                         string writefile = mastertmpdir;
349                         writefile += '/';
350                         writefile += ChangeExtension((*it)->fileName(),
351                                                      ".tex", true);
352                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
353                                              false, true);
354                         (*it)->markDepClean(mastertmpdir);
355                                                      
356                 }
357         }
358 }
359
360
361 void BufferList::emergencyWriteAll()
362 {
363         for (BufferStorage::iterator it = bstore.begin();
364              it != bstore.end(); ++it) {
365                 if (!(*it)->isLyxClean()) {
366                         bool madeit = false;
367                         
368                         lyxerr <<_("lyx: Attempting to save"
369                                       " document ")
370                                << (*it)->fileName()
371                                << _(" as...") << endl;
372                         
373                         for (int i = 0; i < 3 && !madeit; ++i) {
374                                 string s;
375                                 
376                                 // We try to save three places:
377                                 // 1) Same place as document.
378                                 // 2) In HOME directory.
379                                 // 3) In "/tmp" directory.
380                                 if (i == 0) {
381                                         s = (*it)->fileName();
382                                 } else if (i == 1) {
383                                         s = AddName(GetEnvPath("HOME"),
384                                                     (*it)->fileName());
385                                 } else { // MakeAbsPath to prepend the current drive letter on OS/2
386                                         s = AddName(MakeAbsPath("/tmp/"),
387                                                     (*it)->fileName());
388                                 }
389                                 s += ".emergency";
390                                 
391                                 lyxerr << "  " << i + 1 << ") " << s << endl;
392                                 
393                                 if ((*it)->writeFile(s, true)) {
394                                         (*it)->markLyxClean();
395                                         lyxerr << _("  Save seems successful. "
396                                                     "Phew.") << endl;
397                                         madeit = true;
398                                 } else if (i != 2) {
399                                         lyxerr << _("  Save failed! Trying...")
400                                                << endl;
401                                 } else {
402                                         lyxerr << _("  Save failed! Bummer. Document is lost.") << 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                 minibuffer->Set(_("File `")+MakeDisplayPath(s, 50)+
583                                 _("' is read-only."));
584                 ro = true;
585                 // Fall through
586         case 1:
587                 b = readFile(s, ro);
588                 if (b) {
589                         b->lyxvc.file_found_hook(s);
590                 }
591                 break; //fine- it's r/w
592         case -1:
593                 // Here we probably should run
594                 if (LyXVC::file_not_found_hook(s)) {
595                         // Ask if the file should be checked out for
596                         // viewing/editing, if so: load it.
597                         lyxerr << "Do you want to checkout?" << endl;
598                 }
599                 if (AskQuestion(_("Cannot open specified file:"), 
600                                 MakeDisplayPath(s, 50),
601                                 _("Create new document with this name?")))
602                 {
603                         // Find a free buffer
604                         b = newFile(s, string());
605                 }
606                 break;
607         }
608
609         if (b && tolastfiles)
610                 lastfiles->newFile(b->fileName());
611
612         return b;
613 }