]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
cc9098ce4b4d3f8bf3610ff506787c239fcbded7
[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 #include "LyXView.h"
36
37 extern BufferView * current_view;
38 extern void BeforeChange();
39 extern int RunLinuxDoc(int, string const &);
40
41 //
42 // Class BufferStorage
43 //
44
45 void BufferStorage::release(Buffer * buf)
46 {
47         for(Container::iterator it = container.begin();
48             it != container.end(); ++it) {
49                 if ((*it) == buf) {
50                         Buffer * tmpbuf = (*it);
51                         container.erase(it);
52                         delete tmpbuf;
53                         break;
54                 }
55         }
56 }
57
58
59 Buffer * BufferStorage::newBuffer(string const & s,
60                                   LyXRC * lyxrc,
61                                   bool ronly)
62 {
63         Buffer * tmpbuf = new Buffer(s, lyxrc, ronly);
64         tmpbuf->params.useClassDefaults();
65         lyxerr.debug() << "Assigning to buffer "
66                        << container.size() + 1 << endl;
67         container.push_back(tmpbuf);
68         return tmpbuf;
69 }
70
71
72 //
73 // Class BufferList
74 //
75
76 BufferList::BufferList()
77 {
78         _state = BufferList::OK;
79 }
80
81
82 bool BufferList::empty()
83 {
84         return bstore.empty();
85 }
86
87
88 extern void MenuWrite(Buffer *);
89
90 bool BufferList::QwriteAll()
91 {
92         bool askMoreConfirmation = false;
93         string unsaved;
94         for(BufferStorage::iterator it = bstore.begin();
95             it != bstore.end(); ++it) {
96                 if (!(*it)->isLyxClean()) {
97                         switch(AskConfirmation(_("Changes in document:"),
98                                                MakeDisplayPath((*it)->fileName(),
99                                                                50),
100                                                _("Save document?"))) {
101                         case 1: // Yes
102                                 MenuWrite((*it));
103                                 break;
104                         case 2: // No
105                                 askMoreConfirmation = true;
106                                 unsaved += MakeDisplayPath((*it)->fileName(),
107                                                            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         current_view->owner()->getMiniBuffer()->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                         ifstream ifs(buf->fileName().c_str());
172                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
173                         if (ifs && ofs) {
174                                 char c = 0;
175                                 while (ifs.get(c)) {
176                                         ofs.put(c);
177                                 };
178                                 ifs.close();
179                                 ofs.close();
180                                 chmod(s.c_str(), fmode);
181                                 
182                                 if (utime(s.c_str(), times)) {
183                                         lyxerr << "utime error." << endl;
184                                 }
185                         } else {
186                                 lyxerr << "LyX was not able to make "
187                                         "backupcopy. Beware." << endl;
188                         }
189                         delete[] times;
190                 }
191         }
192         
193         if (buf->writeFile(buf->fileName(), false)) {
194                 buf->markLyxClean();
195
196                 current_view->owner()->getMiniBuffer()->
197                         Set(_("Document saved as"),
198                         MakeDisplayPath(buf->fileName()));
199
200                 // now delete the autosavefile
201                 string a = OnlyPath(buf->fileName());
202                 a += '#';
203                 a += OnlyFilename(buf->fileName());
204                 a += '#';
205                 FileInfo fileinfo(a);
206                 if (fileinfo.exist()) {
207                         if (remove(a.c_str()) != 0) {
208                                 WriteFSAlert(_("Could not delete "
209                                                "auto-save file!"), a);
210                         }
211                 }
212         } else {
213                 // Saving failed, so backup is not backup
214                 if (makeBackup) {
215                         string s = buf->fileName() + '~';
216                         rename(s.c_str(), buf->fileName().c_str());
217                 }
218                 current_view->owner()->getMiniBuffer()->Set(_("Save failed!"));
219                 return false;
220         }
221
222         return true;
223 }
224
225
226 void BufferList::closeAll()
227 {
228         _state = BufferList::CLOSING;
229         while (!bstore.empty()) {
230                 close(bstore.front());
231         }
232         _state = BufferList::OK;
233 }
234
235
236 void BufferList::resize()
237 {
238         for(BufferStorage::iterator it = bstore.begin();
239             it != bstore.end(); ++it) {
240                 (*it)->resize();
241         }
242 }
243
244
245 bool BufferList::close(Buffer * buf)
246 {
247         buf->InsetUnlock();
248         
249         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
250                 ProhibitInput();
251                 switch(AskConfirmation(_("Changes in document:"),
252                                        MakeDisplayPath(buf->fileName(), 50),
253                                        _("Save document?"))){
254                 case 1: // Yes
255                         if (write(buf)) {
256                                 lastfiles->newFile(buf->fileName());
257                         } else {
258                                 AllowInput();
259                                 return false;
260                         }
261                         break;
262                 case 3: // Cancel
263                         AllowInput();
264                         return false;
265                 }
266                 AllowInput();
267         }
268
269         bstore.release(buf);
270         return true;
271 }
272
273
274 void BufferList::makePup(int pup)
275         /* This should be changed to return a char const *const
276            in the same way as for lastfiles.[hC]
277            */
278 {
279         int ant = 0;
280         for(BufferStorage::iterator it = bstore.begin();
281             it != bstore.end(); ++it) {
282                 string relbuf = MakeDisplayPath((*it)->fileName(), 30);
283                 fl_addtopup(pup, relbuf.c_str());
284                 ++ant;
285         }
286         if (ant == 0) fl_addtopup(pup, _("No Documents Open!%t"));
287 }
288
289
290 Buffer * BufferList::first()
291 {
292         if (bstore.empty()) return 0;
293         return bstore.front();
294 }
295
296
297 Buffer * BufferList::getBuffer(int choice)
298 {
299         if (choice >= bstore.size()) return 0;
300         return bstore[choice];
301 }
302
303
304 void BufferList::updateInset(Inset * inset, bool mark_dirty)
305 {
306         for (BufferStorage::iterator it = bstore.begin();
307              it != bstore.end(); ++it) {
308                 if ((*it)->getUser()
309                     && (*it)->getUser()->text->UpdateInset(inset)) {
310                         if (mark_dirty)
311                                 (*it)->markDirty();
312                         break;
313                 }
314         }
315 }
316
317
318 int BufferList::unlockInset(UpdatableInset * inset)
319 {
320         if (!inset) return 1;
321         for(BufferStorage::iterator it = bstore.begin();
322             it != bstore.end(); ++it) {
323                 if ((*it)->the_locking_inset == inset) {
324                         (*it)->InsetUnlock();
325                         return 0;
326                 }
327         }
328         return 1;
329 }
330
331
332 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
333 {
334         for(BufferStorage::iterator it = bstore.begin();
335             it != bstore.end(); ++it) {
336                 if (!(*it)->isDepClean(mastertmpdir)) {
337                         string writefile = mastertmpdir;
338                         writefile += '/';
339                         writefile += ChangeExtension((*it)->fileName(),
340                                                      ".tex", true);
341                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
342                                              false, true);
343                         (*it)->markDepClean(mastertmpdir);
344                 }
345         }
346 }
347
348
349 void BufferList::emergencyWriteAll()
350 {
351         for (BufferStorage::iterator it = bstore.begin();
352              it != bstore.end(); ++it) {
353                 if (!(*it)->isLyxClean()) {
354                         bool madeit = false;
355                         
356                         lyxerr <<_("lyx: Attempting to save"
357                                    " document ")
358                                << (*it)->fileName()
359                                << _(" as...") << endl;
360                         
361                         for (int i = 0; i < 3 && !madeit; ++i) {
362                                 string s;
363                                 
364                                 // We try to save three places:
365                                 // 1) Same place as document.
366                                 // 2) In HOME directory.
367                                 // 3) In "/tmp" directory.
368                                 if (i == 0) {
369                                         s = (*it)->fileName();
370                                 } else if (i == 1) {
371                                         s = AddName(GetEnvPath("HOME"),
372                                                     (*it)->fileName());
373                                 } else {
374                                         // MakeAbsPath to prepend the current
375                                         // drive letter on OS/2
376                                         s = AddName(MakeAbsPath("/tmp/"),
377                                                     (*it)->fileName());
378                                 }
379                                 s += ".emergency";
380                                 
381                                 lyxerr << "  " << i + 1 << ") " << s << endl;
382                                 
383                                 if ((*it)->writeFile(s, true)) {
384                                         (*it)->markLyxClean();
385                                         lyxerr << _("  Save seems successful. "
386                                                     "Phew.") << endl;
387                                         madeit = true;
388                                 } else if (i != 2) {
389                                         lyxerr << _("  Save failed! Trying...")
390                                                << endl;
391                                 } else {
392                                         lyxerr << _("  Save failed! Bummer. "
393                                                     "Document is lost.")
394                                                << endl;
395                                 }
396                         }
397                 }
398         }
399 }
400
401
402 Buffer * BufferList::readFile(string const & s, bool ronly)
403 {
404         Buffer * b = bstore.newBuffer(s, lyxrc, ronly);
405
406         string ts = s;
407         string e = OnlyPath(s);
408         string a = e;
409         // File information about normal file
410         FileInfo fileInfo2(s);
411
412         // Check if emergency save file exists and is newer.
413         e += OnlyFilename(s) + ".emergency";
414         FileInfo fileInfoE(e);
415
416         bool use_emergency = false;
417
418         if (fileInfoE.exist() && fileInfo2.exist()) {
419                 if (fileInfoE.getModificationTime()
420                     > fileInfo2.getModificationTime()) {
421                         if (AskQuestion(_("An emergency save of this document exists!"),
422                                         MakeDisplayPath(s, 50),
423                                         _("Try to load that instead?"))) {
424                                 ts = e;
425                                 // the file is not saved if we load the
426                                 // emergency file.
427                                 b->markDirty();
428                                 use_emergency = true;
429                         } else {
430                                 // Here, we should delete the emergency save
431                                 unlink(e.c_str());
432                         }
433                 }
434         }
435
436         if (!use_emergency) {
437                 // Now check if autosave file is newer.
438                 a += '#';
439                 a += OnlyFilename(s);
440                 a += '#';
441                 FileInfo fileInfoA(a);
442                 if (fileInfoA.exist() && fileInfo2.exist()) {
443                         if (fileInfoA.getModificationTime()
444                             > fileInfo2.getModificationTime()) {
445                                 if (AskQuestion(_("Autosave file is newer."),
446                                                 MakeDisplayPath(s, 50),
447                                                 _("Load that one instead?"))) {
448                                         ts = a;
449                                         // the file is not saved if we load the
450                                         // autosave file.
451                                         b->markDirty();
452                                 } else {
453                                         // Here, we should delete the autosave
454                                         unlink(a.c_str());
455                                 }
456                         }
457                 }
458         }
459         // not sure if this is the correct place to begin LyXLex
460         LyXLex lex(0, 0);
461         lex.setFile(ts);
462         if (b->readFile(lex))
463                 return b;
464         else {
465                 bstore.release(b);
466                 return 0;
467         }
468 }
469
470
471 bool BufferList::exists(string const & s)
472 {
473         for (BufferStorage::iterator it = bstore.begin();
474              it != bstore.end(); ++it) {
475                 if ((*it)->fileName() == s)
476                         return true;
477         }
478         return false;
479 }
480
481
482 Buffer * BufferList::getBuffer(string const & s)
483 {
484         for(BufferStorage::iterator it = bstore.begin();
485             it != bstore.end(); ++it) {
486                 if ((*it)->fileName() == s)
487                         return (*it);
488         }
489         return 0;
490 }
491
492
493 Buffer * BufferList::newFile(string const & name, string tname)
494 {
495         /* get a free buffer */ 
496         Buffer * b = bstore.newBuffer(name, lyxrc);
497
498         // use defaults.lyx as a default template if it exists.
499         if (tname.empty()) {
500                 tname = LibFileSearch("templates", "defaults.lyx");
501         }
502         if (!tname.empty() && IsLyXFilename(tname)){
503                 bool templateok = false;
504                 LyXLex lex(0, 0);
505                 lex.setFile(tname);
506                 if (lex.IsOK()) {
507                         if (b->readFile(lex)) {
508                                 templateok = true;
509                         }
510                 }
511                 if (!templateok) {
512                         WriteAlert(_("Error!"), _("Unable to open template"), 
513                                    MakeDisplayPath(tname));
514                         // no template, start with empty buffer
515                         b->paragraph = new LyXParagraph;
516                 }
517         }
518         else {  // start with empty buffer
519                 b->paragraph = new LyXParagraph;
520         }
521
522         b->markDirty();
523         b->setReadonly(false);
524         
525         return b;
526 }
527
528
529 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
530 {
531         // make sure our path is absolute
532         string s = MakeAbsPath(filename);
533
534         // Is this done too early?
535         // Is it LinuxDoc?
536         if (IsSGMLFilename(s)) {
537                 FileInfo fi(s);
538                 if (fi.exist() && fi.readable()) {
539                         if (!RunLinuxDoc(-1, s)) {
540                                 s = ChangeExtension (s, ".lyx", false);
541                         } else { // sgml2lyx failed
542                                 WriteAlert(_("Error!"),
543                                            _("Could not convert file"), s);
544                                 return 0;
545                         }
546                 } else {
547                         // just change the extension and it will be
548                         // handled like a regular lyx file that does
549                         // not exist.
550                         s = ChangeExtension(s, ".lyx", false);
551                 }
552         }
553         
554         // file already open?
555         if (exists(s)) {
556                 if (AskQuestion(_("Document is already open:"), 
557                                 MakeDisplayPath(s, 50),
558                                 _("Do you want to reload that document?"))) {
559                         // Reload is accomplished by closing and then loading
560                         if (!close(getBuffer(s))) {
561                                 return 0;
562                         }
563                         // Fall through to new load. (Asger)
564                 } else {
565                         // Here, we pretend that we just loaded the 
566                         // open document
567                         return getBuffer(s);
568                 }
569         }
570         Buffer * b = 0;
571         bool ro = false;
572         switch (IsFileWriteable(s)) {
573         case 0:
574                 current_view->owner()->getMiniBuffer()->
575                         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->fileName());
604
605         return b;
606 }