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