]> git.lyx.org Git - features.git/blob - src/bufferlist.C
ok, some more changes, this time I have gotten the fonttable and insettable in lyxpar...
[features.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 #include <sys/types.h>
23 #include <utime.h>
24
25 #include "bufferlist.h"
26 #include "lyx_main.h"
27 #include "minibuffer.h"
28 #include "support/FileInfo.h"
29 #include "support/filetools.h"
30 #include "lyx_gui_misc.h"
31 #include "lastfiles.h"
32 #include "debug.h"
33 #include "lyxrc.h"
34 #include "lyxscreen.h"
35 #include "lyxtext.h"
36 #include "lyx_cb.h"
37 #include "gettext.h"
38 #include "LyXView.h"
39
40 extern BufferView * current_view;
41 extern int RunLinuxDoc(int, string const &);
42
43 using std::ifstream;
44 using std::ofstream;
45 using std::ios;
46
47 //
48 // Class BufferStorage
49 //
50
51 void BufferStorage::release(Buffer * buf)
52 {
53         for(Container::iterator it = container.begin();
54             it != container.end(); ++it) {
55                 if ((*it) == buf) {
56                         Buffer * tmpbuf = (*it);
57                         container.erase(it);
58                         delete tmpbuf;
59                         break;
60                 }
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() + 1 << endl;
73         container.push_back(tmpbuf);
74         return tmpbuf;
75 }
76
77
78 //
79 // Class BufferList
80 //
81
82 BufferList::BufferList()
83 {
84         _state = BufferList::OK;
85 }
86
87
88 bool BufferList::empty()
89 {
90         return bstore.empty();
91 }
92
93
94 extern void MenuWrite(Buffer *);
95
96 bool BufferList::QwriteAll()
97 {
98         bool askMoreConfirmation = false;
99         string unsaved;
100         for(BufferStorage::iterator it = bstore.begin();
101             it != bstore.end(); ++it) {
102                 if (!(*it)->isLyxClean()) {
103                         switch(AskConfirmation(_("Changes in document:"),
104                                                MakeDisplayPath((*it)->fileName(),
105                                                                50),
106                                                _("Save document?"))) {
107                         case 1: // Yes
108                                 MenuWrite((*it));
109                                 break;
110                         case 2: // No
111                                 askMoreConfirmation = true;
112                                 unsaved += MakeDisplayPath((*it)->fileName(),
113                                                            50);
114                                 unsaved += "\n";
115                                 break;
116                         case 3: // Cancel
117                                 return false;
118                         }
119                 }
120         }
121         if (askMoreConfirmation &&
122             lyxrc->exit_confirmation &&
123             !AskQuestion(_("Some documents were not saved:"),
124                          unsaved, _("Exit anyway?"))) {
125                 return false;
126         }
127
128         return true;
129 }
130
131
132 // Should probably be moved to somewhere else: BufferView? LyXView?
133 bool BufferList::write(Buffer * buf, bool makeBackup)
134 {
135         if (buf->getUser())
136                 buf->getUser()
137                         ->owner()
138                         ->getMiniBuffer()
139                         ->Set(_("Saving document"),
140                               MakeDisplayPath(buf->fileName()), "...");
141
142         // We don't need autosaves in the immediate future. (Asger)
143         buf->resetAutosaveTimers();
144
145         // make a backup
146         if (makeBackup) {
147                 string s = buf->fileName() + '~';
148                 // Rename is the wrong way of making a backup,
149                 // this is the correct way.
150                 /* truss cp fil fil2:
151                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
152                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
153                    open("LyXVC.lyx", O_RDONLY)                     = 3
154                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
155                    fstat(4, 0xEFFFF508)                            = 0
156                    fstat(3, 0xEFFFF508)                            = 0
157                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
158                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
159                    read(3, 0xEFFFD4A0, 8192)                       = 0
160                    close(4)                                        = 0
161                    close(3)                                        = 0
162                    chmod("LyXVC3.lyx", 0100644)                    = 0
163                    lseek(0, 0, SEEK_CUR)                           = 46440
164                    _exit(0)
165                 */
166
167                 // Should proabaly have some more error checking here.
168                 // Should be cleaned up in 0.13, at least a bit.
169                 // Doing it this way, also makes the inodes stay the same.
170                 // This is still not a very good solution, in particular we
171                 // might loose the owner of the backup.
172                 FileInfo finfo(buf->fileName());
173                 if (finfo.exist()) {
174                         mode_t fmode = finfo.getMode();
175                         struct utimbuf * times = new struct utimbuf;
176
177                         times->actime = finfo.getAccessTime();
178                         times->modtime = finfo.getModificationTime();
179                         ifstream ifs(buf->fileName().c_str());
180                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
181                         if (ifs && ofs) {
182                                 char c = 0;
183                                 while (ifs.get(c)) {
184                                         ofs.put(c);
185                                 }
186                                 ifs.close();
187                                 ofs.close();
188                                 chmod(s.c_str(), fmode);
189                                 
190                                 if (utime(s.c_str(), times)) {
191                                         lyxerr << "utime error." << endl;
192                                 }
193                         } else {
194                                 lyxerr << "LyX was not able to make "
195                                         "backupcopy. Beware." << endl;
196                         }
197                         delete[] times;
198                 }
199         }
200         
201         if (buf->writeFile(buf->fileName(), false)) {
202                 buf->markLyxClean();
203
204                 current_view->owner()->getMiniBuffer()->
205                         Set(_("Document saved as"),
206                         MakeDisplayPath(buf->fileName()));
207
208                 // now delete the autosavefile
209                 string a = OnlyPath(buf->fileName());
210                 a += '#';
211                 a += OnlyFilename(buf->fileName());
212                 a += '#';
213                 FileInfo fileinfo(a);
214                 if (fileinfo.exist()) {
215                         if (remove(a.c_str()) != 0) {
216                                 WriteFSAlert(_("Could not delete "
217                                                "auto-save file!"), a);
218                         }
219                 }
220         } else {
221                 // Saving failed, so backup is not backup
222                 if (makeBackup) {
223                         string s = buf->fileName() + '~';
224                         rename(s.c_str(), buf->fileName().c_str());
225                 }
226                 current_view->owner()->getMiniBuffer()->Set(_("Save failed!"));
227                 return false;
228         }
229
230         return true;
231 }
232
233
234 void BufferList::closeAll()
235 {
236         _state = BufferList::CLOSING;
237         while (!bstore.empty()) {
238                 close(bstore.front());
239         }
240         _state = BufferList::OK;
241 }
242
243
244 void BufferList::resize()
245 {
246         for(BufferStorage::iterator it = bstore.begin();
247             it != bstore.end(); ++it) {
248                 (*it)->resize();
249         }
250 }
251
252
253 bool BufferList::close(Buffer * buf)
254 {
255         if (buf->getUser()) buf->getUser()->insetUnlock();
256         
257         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
258                 ProhibitInput();
259                 switch(AskConfirmation(_("Changes in document:"),
260                                        MakeDisplayPath(buf->fileName(), 50),
261                                        _("Save document?"))){
262                 case 1: // Yes
263                         if (write(buf, lyxrc->make_backup)) {
264                                 lastfiles->newFile(buf->fileName());
265                         } else {
266                                 AllowInput();
267                                 return false;
268                         }
269                         break;
270                 case 3: // Cancel
271                         AllowInput();
272                         return false;
273                 }
274                 AllowInput();
275         }
276
277         bstore.release(buf);
278         return true;
279 }
280
281
282 void BufferList::makePup(int pup)
283         /* This should be changed to return a char const *const
284            in the same way as for lastfiles.[hC]
285            */
286 {
287         int ant = 0;
288         for(BufferStorage::iterator it = bstore.begin();
289             it != bstore.end(); ++it) {
290                 string relbuf = MakeDisplayPath((*it)->fileName(), 30);
291                 fl_addtopup(pup, relbuf.c_str());
292                 ++ant;
293         }
294         if (ant == 0) fl_addtopup(pup, _("No Documents Open!%t"));
295 }
296
297
298 Buffer * BufferList::first()
299 {
300         if (bstore.empty()) return 0;
301         return bstore.front();
302 }
303
304
305 Buffer * BufferList::getBuffer(int choice)
306 {
307         if (choice >= bstore.size()) return 0;
308         return bstore[choice];
309 }
310
311
312 void BufferList::updateInset(Inset * inset, bool mark_dirty)
313 {
314         for (BufferStorage::iterator it = bstore.begin();
315              it != bstore.end(); ++it) {
316                 if ((*it)->getUser()
317                     && (*it)->getUser()->text->UpdateInset(inset)) {
318                         if (mark_dirty)
319                                 (*it)->markDirty();
320                         break;
321                 }
322         }
323 }
324
325
326 int BufferList::unlockInset(UpdatableInset * inset)
327 {
328         if (!inset) return 1;
329         for(BufferStorage::iterator it = bstore.begin();
330             it != bstore.end(); ++it) {
331                 if ((*it)->getUser()
332                     && (*it)->getUser()->the_locking_inset == inset) {
333                         (*it)->getUser()->insetUnlock();
334                         return 0;
335                 }
336         }
337         return 1;
338 }
339
340
341 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
342 {
343         for(BufferStorage::iterator it = bstore.begin();
344             it != bstore.end(); ++it) {
345                 if (!(*it)->isDepClean(mastertmpdir)) {
346                         string writefile = mastertmpdir;
347                         writefile += '/';
348                         writefile += ChangeExtension((*it)->fileName(),
349                                                      ".tex", true);
350                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
351                                              false, true);
352                         (*it)->markDepClean(mastertmpdir);
353                 }
354         }
355 }
356
357
358 void BufferList::emergencyWriteAll()
359 {
360         for (BufferStorage::iterator it = bstore.begin();
361              it != bstore.end(); ++it) {
362                 if (!(*it)->isLyxClean()) {
363                         bool madeit = false;
364                         
365                         lyxerr <<_("lyx: Attempting to save"
366                                    " document ")
367                                << (*it)->fileName()
368                                << _(" as...") << endl;
369                         
370                         for (int i = 0; i < 3 && !madeit; ++i) {
371                                 string s;
372                                 
373                                 // We try to save three places:
374                                 // 1) Same place as document.
375                                 // 2) In HOME directory.
376                                 // 3) In "/tmp" directory.
377                                 if (i == 0) {
378                                         s = (*it)->fileName();
379                                 } else if (i == 1) {
380                                         s = AddName(GetEnvPath("HOME"),
381                                                     (*it)->fileName());
382                                 } else {
383                                         // MakeAbsPath to prepend the current
384                                         // drive letter on OS/2
385                                         s = AddName(MakeAbsPath("/tmp/"),
386                                                     (*it)->fileName());
387                                 }
388                                 s += ".emergency";
389                                 
390                                 lyxerr << "  " << i + 1 << ") " << s << endl;
391                                 
392                                 if ((*it)->writeFile(s, true)) {
393                                         (*it)->markLyxClean();
394                                         lyxerr << _("  Save seems successful. "
395                                                     "Phew.") << endl;
396                                         madeit = true;
397                                 } else if (i != 2) {
398                                         lyxerr << _("  Save failed! Trying...")
399                                                << endl;
400                                 } else {
401                                         lyxerr << _("  Save failed! Bummer. "
402                                                     "Document is lost.")
403                                                << endl;
404                                 }
405                         }
406                 }
407         }
408 }
409
410
411 Buffer * BufferList::readFile(string const & s, bool ronly)
412 {
413         Buffer * b = bstore.newBuffer(s, lyxrc, ronly);
414
415         string ts = s;
416         string e = OnlyPath(s);
417         string a = e;
418         // File information about normal file
419         FileInfo fileInfo2(s);
420
421         // Check if emergency save file exists and is newer.
422         e += OnlyFilename(s) + ".emergency";
423         FileInfo fileInfoE(e);
424
425         bool use_emergency = false;
426
427         if (fileInfoE.exist() && fileInfo2.exist()) {
428                 if (fileInfoE.getModificationTime()
429                     > fileInfo2.getModificationTime()) {
430                         if (AskQuestion(_("An emergency save of this document exists!"),
431                                         MakeDisplayPath(s, 50),
432                                         _("Try to load that instead?"))) {
433                                 ts = e;
434                                 // the file is not saved if we load the
435                                 // emergency file.
436                                 b->markDirty();
437                                 use_emergency = true;
438                         } else {
439                                 // Here, we should delete the emergency save
440                                 unlink(e.c_str());
441                         }
442                 }
443         }
444
445         if (!use_emergency) {
446                 // Now check if autosave file is newer.
447                 a += '#';
448                 a += OnlyFilename(s);
449                 a += '#';
450                 FileInfo fileInfoA(a);
451                 if (fileInfoA.exist() && fileInfo2.exist()) {
452                         if (fileInfoA.getModificationTime()
453                             > fileInfo2.getModificationTime()) {
454                                 if (AskQuestion(_("Autosave file is newer."),
455                                                 MakeDisplayPath(s, 50),
456                                                 _("Load that one instead?"))) {
457                                         ts = a;
458                                         // the file is not saved if we load the
459                                         // autosave file.
460                                         b->markDirty();
461                                 } else {
462                                         // Here, we should delete the autosave
463                                         unlink(a.c_str());
464                                 }
465                         }
466                 }
467         }
468         // not sure if this is the correct place to begin LyXLex
469         LyXLex lex(0, 0);
470         lex.setFile(ts);
471         if (b->readFile(lex))
472                 return b;
473         else {
474                 bstore.release(b);
475                 return 0;
476         }
477 }
478
479
480 bool BufferList::exists(string const & s)
481 {
482         for (BufferStorage::iterator it = bstore.begin();
483              it != bstore.end(); ++it) {
484                 if ((*it)->fileName() == s)
485                         return true;
486         }
487         return false;
488 }
489
490
491 Buffer * BufferList::getBuffer(string const & s)
492 {
493         for(BufferStorage::iterator it = bstore.begin();
494             it != bstore.end(); ++it) {
495                 if ((*it)->fileName() == s)
496                         return (*it);
497         }
498         return 0;
499 }
500
501
502 Buffer * BufferList::newFile(string const & name, string tname)
503 {
504         /* get a free buffer */ 
505         Buffer * b = bstore.newBuffer(name, lyxrc);
506
507         // use defaults.lyx as a default template if it exists.
508         if (tname.empty()) {
509                 tname = LibFileSearch("templates", "defaults.lyx");
510         }
511         if (!tname.empty() && IsLyXFilename(tname)){
512                 bool templateok = false;
513                 LyXLex lex(0, 0);
514                 lex.setFile(tname);
515                 if (lex.IsOK()) {
516                         if (b->readFile(lex)) {
517                                 templateok = true;
518                         }
519                 }
520                 if (!templateok) {
521                         WriteAlert(_("Error!"), _("Unable to open template"), 
522                                    MakeDisplayPath(tname));
523                         // no template, start with empty buffer
524                         b->paragraph = new LyXParagraph;
525                 }
526         }
527         else {  // start with empty buffer
528                 b->paragraph = new LyXParagraph;
529         }
530
531         b->markDirty();
532         b->setReadonly(false);
533         
534         return b;
535 }
536
537
538 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
539 {
540         // make sure our path is absolute
541         string s = MakeAbsPath(filename);
542
543         // Is this done too early?
544         // Is it LinuxDoc?
545         if (IsSGMLFilename(s)) {
546                 FileInfo fi(s);
547                 if (fi.exist() && fi.readable()) {
548                         if (!RunLinuxDoc(-1, s)) {
549                                 s = ChangeExtension (s, ".lyx", false);
550                         } else { // sgml2lyx failed
551                                 WriteAlert(_("Error!"),
552                                            _("Could not convert file"), s);
553                                 return 0;
554                         }
555                 } else {
556                         // just change the extension and it will be
557                         // handled like a regular lyx file that does
558                         // not exist.
559                         s = ChangeExtension(s, ".lyx", false);
560                 }
561         }
562         
563         // file already open?
564         if (exists(s)) {
565                 if (AskQuestion(_("Document is already open:"), 
566                                 MakeDisplayPath(s, 50),
567                                 _("Do you want to reload that document?"))) {
568                         // Reload is accomplished by closing and then loading
569                         if (!close(getBuffer(s))) {
570                                 return 0;
571                         }
572                         // Fall through to new load. (Asger)
573                 } else {
574                         // Here, we pretend that we just loaded the 
575                         // open document
576                         return getBuffer(s);
577                 }
578         }
579         Buffer * b = 0;
580         bool ro = false;
581         switch (IsFileWriteable(s)) {
582         case 0:
583                 current_view->owner()->getMiniBuffer()->
584                         Set(_("File `")+MakeDisplayPath(s, 50)+
585                         _("' is read-only."));
586                 ro = true;
587                 // Fall through
588         case 1:
589                 b = readFile(s, ro);
590                 if (b) {
591                         b->lyxvc.file_found_hook(s);
592                 }
593                 break; //fine- it's r/w
594         case -1:
595                 // Here we probably should run
596                 if (LyXVC::file_not_found_hook(s)) {
597                         // Ask if the file should be checked out for
598                         // viewing/editing, if so: load it.
599                         lyxerr << "Do you want to checkout?" << endl;
600                 }
601                 if (AskQuestion(_("Cannot open specified file:"), 
602                                 MakeDisplayPath(s, 50),
603                                 _("Create new document with this name?")))
604                         {
605                                 // Find a free buffer
606                                 b = newFile(s, string());
607                         }
608                 break;
609         }
610
611         if (b && tolastfiles)
612                 lastfiles->newFile(b->fileName());
613
614         return b;
615 }