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