]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
03bbaeea256b53f8d5c4b866c792d50c42e896df
[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-2000 The LyX Team. 
8  *
9  *           This file is Copyright 1996-2000
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 #include <algorithm>
23
24 #include <sys/types.h>
25 #include <utime.h>
26
27 #include "bufferlist.h"
28 #include "lyx_main.h"
29 #include "minibuffer.h"
30 #include "support/FileInfo.h"
31 #include "support/filetools.h"
32 #include "lyx_gui_misc.h"
33 #include "lastfiles.h"
34 #include "debug.h"
35 #include "lyxrc.h"
36 #include "lyxscreen.h"
37 #include "lyxtext.h"
38 #include "lyx_cb.h"
39 #include "gettext.h"
40 #include "LyXView.h"
41 #include "vc-backend.h"
42
43 extern BufferView * current_view;
44 extern int RunLinuxDoc(int, string const &);
45
46 using std::ifstream;
47 using std::ofstream;
48 using std::ios;
49 using std::find;
50 //
51 // Class BufferStorage
52 //
53
54 void BufferStorage::release(Buffer * buf)
55 {
56         Container::iterator it = find(container.begin(), container.end(), buf);
57         if (it != container.end()) {
58                 Buffer * tmp = (*it);
59                 container.erase(it);
60                 delete tmp;
61         }
62 }
63
64
65 Buffer * BufferStorage::newBuffer(string const & s,
66                                   LyXRC * lyxrc,
67                                   bool ronly)
68 {
69         Buffer * tmpbuf = new Buffer(s, lyxrc, ronly);
70         tmpbuf->params.useClassDefaults();
71         lyxerr.debug() << "Assigning to buffer "
72                        << container.size() << endl;
73         container.push_back(tmpbuf);
74         return tmpbuf;
75 }
76
77
78 //
79 // Class BufferList
80 //
81
82 BufferList::BufferList()
83         : state_(BufferList::OK)
84 {}
85
86
87 bool BufferList::empty() const
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         if (buf->getUser())
135                 buf->getUser()
136                         ->owner()
137                         ->getMiniBuffer()
138                         ->Set(_("Saving document"),
139                               MakeDisplayPath(buf->fileName()), "...");
140
141         // We don't need autosaves in the immediate future. (Asger)
142         buf->resetAutosaveTimers();
143
144         // make a backup
145         if (makeBackup) {
146                 string s = buf->fileName() + '~';
147                 // Rename is the wrong way of making a backup,
148                 // this is the correct way.
149                 /* truss cp fil fil2:
150                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
151                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
152                    open("LyXVC.lyx", O_RDONLY)                     = 3
153                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
154                    fstat(4, 0xEFFFF508)                            = 0
155                    fstat(3, 0xEFFFF508)                            = 0
156                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
157                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
158                    read(3, 0xEFFFD4A0, 8192)                       = 0
159                    close(4)                                        = 0
160                    close(3)                                        = 0
161                    chmod("LyXVC3.lyx", 0100644)                    = 0
162                    lseek(0, 0, SEEK_CUR)                           = 46440
163                    _exit(0)
164                 */
165
166                 // Should proabaly have some more error checking here.
167                 // Should be cleaned up in 0.13, at least a bit.
168                 // Doing it this way, also makes the inodes stay the same.
169                 // This is still not a very good solution, in particular we
170                 // might loose the owner of the backup.
171                 FileInfo finfo(buf->fileName());
172                 if (finfo.exist()) {
173                         mode_t fmode = finfo.getMode();
174                         struct utimbuf * times = new struct utimbuf;
175
176                         times->actime = finfo.getAccessTime();
177                         times->modtime = finfo.getModificationTime();
178                         ifstream ifs(buf->fileName().c_str());
179                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
180                         if (ifs && ofs) {
181 #if 1
182                                 ofs << ifs.rdbuf();
183 #else
184                                 char c = 0;
185                                 while (ifs.get(c)) {
186                                         ofs.put(c);
187                                 }
188 #endif
189                                 ifs.close();
190                                 ofs.close();
191                                 chmod(s.c_str(), fmode);
192                                 
193                                 if (utime(s.c_str(), times)) {
194                                         lyxerr << "utime error." << endl;
195                                 }
196                         } else {
197                                 lyxerr << "LyX was not able to make "
198                                         "backupcopy. Beware." << endl;
199                         }
200                         delete times;
201                 }
202         }
203         
204         if (buf->writeFile(buf->fileName(), false)) {
205                 buf->markLyxClean();
206
207                 current_view->owner()->getMiniBuffer()->
208                         Set(_("Document saved as"),
209                         MakeDisplayPath(buf->fileName()));
210
211                 // now delete the autosavefile
212                 string a = OnlyPath(buf->fileName());
213                 a += '#';
214                 a += OnlyFilename(buf->fileName());
215                 a += '#';
216                 FileInfo fileinfo(a);
217                 if (fileinfo.exist()) {
218                         if (remove(a.c_str()) != 0) {
219                                 WriteFSAlert(_("Could not delete "
220                                                "auto-save file!"), a);
221                         }
222                 }
223         } else {
224                 // Saving failed, so backup is not backup
225                 if (makeBackup) {
226                         string s = buf->fileName() + '~';
227                         rename(s.c_str(), buf->fileName().c_str());
228                 }
229                 current_view->owner()->getMiniBuffer()->Set(_("Save failed!"));
230                 return false;
231         }
232
233         return true;
234 }
235
236
237 void BufferList::closeAll()
238 {
239         state_ = BufferList::CLOSING;
240         while (!bstore.empty()) {
241                 close(bstore.front());
242         }
243         state_ = BufferList::OK;
244 }
245
246
247 void BufferList::resize()
248 {
249         for(BufferStorage::iterator it = bstore.begin();
250             it != bstore.end(); ++it) {
251                 (*it)->resize();
252         }
253 }
254
255
256 bool BufferList::close(Buffer * buf)
257 {
258         if (buf->getUser()) buf->getUser()->insetUnlock();
259         
260         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
261                 ProhibitInput();
262                 switch(AskConfirmation(_("Changes in document:"),
263                                        MakeDisplayPath(buf->fileName(), 50),
264                                        _("Save document?"))){
265                 case 1: // Yes
266                         if (write(buf, lyxrc->make_backup)) {
267                                 lastfiles->newFile(buf->fileName());
268                         } else {
269                                 AllowInput();
270                                 return false;
271                         }
272                         break;
273                 case 3: // Cancel
274                         AllowInput();
275                         return false;
276                 }
277                 AllowInput();
278         }
279
280         bstore.release(buf);
281         return true;
282 }
283
284
285 vector<string> BufferList::getFileNames() const
286 {
287         vector<string> nvec;
288         for(BufferStorage::const_iterator cit = bstore.begin();
289             cit != bstore.end(); ++cit) {
290                 nvec.push_back((*cit)->fileName());
291         }
292         return nvec;
293 }
294
295
296 Buffer * BufferList::first()
297 {
298         if (bstore.empty()) return 0;
299         return bstore.front();
300 }
301
302
303 Buffer * BufferList::getBuffer(int choice)
304 {
305         if (choice >= bstore.size()) return 0;
306         return bstore[choice];
307 }
308
309
310 void BufferList::updateInset(Inset * inset, bool mark_dirty)
311 {
312         for (BufferStorage::iterator it = bstore.begin();
313              it != bstore.end(); ++it) {
314                 if ((*it)->getUser()
315                     && (*it)->getUser()->text->UpdateInset(inset)) {
316                         if (mark_dirty)
317                                 (*it)->markDirty();
318                         break;
319                 }
320         }
321 }
322
323
324 int BufferList::unlockInset(UpdatableInset * inset)
325 {
326         if (!inset) return 1;
327         for(BufferStorage::iterator it = bstore.begin();
328             it != bstore.end(); ++it) {
329                 if ((*it)->getUser()
330                     && (*it)->getUser()->the_locking_inset == inset) {
331                         (*it)->getUser()->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) const
479 {
480         for (BufferStorage::const_iterator cit = bstore.begin();
481              cit != bstore.end(); ++cit) {
482                 if ((*cit)->fileName() == s)
483                         return true;
484         }
485         return false;
486 }
487
488
489 bool BufferList::isLoaded(Buffer const * b) const
490 {
491         BufferStorage::const_iterator cit =
492                 find(bstore.begin(), bstore.end(), b);
493         return cit != bstore.end();
494 }
495
496
497 Buffer * BufferList::getBuffer(string const & s)
498 {
499         for(BufferStorage::iterator it = bstore.begin();
500             it != bstore.end(); ++it) {
501                 if ((*it)->fileName() == s)
502                         return (*it);
503         }
504         return 0;
505 }
506
507
508 Buffer * BufferList::newFile(string const & name, string tname)
509 {
510         /* get a free buffer */ 
511         Buffer * b = bstore.newBuffer(name, lyxrc);
512
513         // use defaults.lyx as a default template if it exists.
514         if (tname.empty()) {
515                 tname = LibFileSearch("templates", "defaults.lyx");
516         }
517         if (!tname.empty() && IsLyXFilename(tname)){
518                 bool templateok = false;
519                 LyXLex lex(0, 0);
520                 lex.setFile(tname);
521                 if (lex.IsOK()) {
522                         if (b->readFile(lex)) {
523                                 templateok = true;
524                         }
525                 }
526                 if (!templateok) {
527                         WriteAlert(_("Error!"), _("Unable to open template"), 
528                                    MakeDisplayPath(tname));
529                         // no template, start with empty buffer
530                         b->paragraph = new LyXParagraph;
531                 }
532         }
533         else {  // start with empty buffer
534                 b->paragraph = new LyXParagraph;
535         }
536
537         b->markDirty();
538         b->setReadonly(false);
539         
540         return b;
541 }
542
543
544 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
545 {
546         // make sure our path is absolute
547         string s = MakeAbsPath(filename);
548
549         // Is this done too early?
550         // Is it LinuxDoc?
551         if (IsSGMLFilename(s)) {
552                 FileInfo fi(s);
553                 if (fi.exist() && fi.readable()) {
554                         if (!RunLinuxDoc(-1, s)) {
555                                 s = ChangeExtension (s, ".lyx", false);
556                         } else { // sgml2lyx failed
557                                 WriteAlert(_("Error!"),
558                                            _("Could not convert file"), s);
559                                 return 0;
560                         }
561                 } else {
562                         // just change the extension and it will be
563                         // handled like a regular lyx file that does
564                         // not exist.
565                         s = ChangeExtension(s, ".lyx", false);
566                 }
567         }
568         
569         // file already open?
570         if (exists(s)) {
571                 if (AskQuestion(_("Document is already open:"), 
572                                 MakeDisplayPath(s, 50),
573                                 _("Do you want to reload that document?"))) {
574                         // Reload is accomplished by closing and then loading
575                         if (!close(getBuffer(s))) {
576                                 return 0;
577                         }
578                         // Fall through to new load. (Asger)
579                 } else {
580                         // Here, we pretend that we just loaded the 
581                         // open document
582                         return getBuffer(s);
583                 }
584         }
585         Buffer * b = 0;
586         bool ro = false;
587         switch (IsFileWriteable(s)) {
588         case 0:
589                 current_view->owner()->getMiniBuffer()->
590                         Set(_("File `")+MakeDisplayPath(s, 50)+
591                         _("' is read-only."));
592                 ro = true;
593                 // Fall through
594         case 1:
595                 b = readFile(s, ro);
596                 if (b) {
597                         b->lyxvc.file_found_hook(s);
598                 }
599                 break; //fine- it's r/w
600         case -1:
601                 // Here we probably should run
602                 if (LyXVC::file_not_found_hook(s)) {
603                         // Ask if the file should be checked out for
604                         // viewing/editing, if so: load it.
605                         if (AskQuestion(_("Do you want to retrive file under version control?"))) {
606                                 // How can we know _how_ to do the checkout?
607                                 // With the current VC support it has to be,
608                                 // a RCS file since CVS do not have special ,v files.
609                                 RCS::retrive(s);
610                                 return loadLyXFile(filename, tolastfiles);
611                         }
612                 }
613                 if (AskQuestion(_("Cannot open specified file:"), 
614                                 MakeDisplayPath(s, 50),
615                                 _("Create new document with this name?")))
616                         {
617                                 // Find a free buffer
618                                 b = newFile(s, string());
619                         }
620                 break;
621         }
622
623         if (b && tolastfiles)
624                 lastfiles->newFile(b->fileName());
625
626         return b;
627 }