]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
use more std::functors add some of my own, some change to fl_display etc. read the...
[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 <algorithm>
22 #include <functional>
23
24 #include "bufferlist.h"
25 #include "lyx_main.h"
26 #include "minibuffer.h"
27 #include "support/FileInfo.h"
28 #include "support/filetools.h"
29 #include "support/lyxmanip.h"
30 #include "support/lyxfunctional.h"
31 #include "lyx_gui_misc.h"
32 #include "lastfiles.h"
33 #include "debug.h"
34 #include "lyxrc.h"
35 #include "lyxtext.h"
36 #include "lyx_cb.h"
37 #include "bufferview_funcs.h"
38 #include "gettext.h"
39 #include "LyXView.h"
40 #include "vc-backend.h"
41 #include "TextCache.h"
42
43 using std::vector;
44 using std::find;
45 using std::endl;
46
47 //
48 // Class BufferStorage
49 //
50
51 void BufferStorage::release(Buffer * buf)
52 {
53         Container::iterator it = find(container.begin(), container.end(), buf);
54         if (it != container.end()) {
55                 // Make sure that we don't store a LyXText in
56                 // the textcache that points to the buffer
57                 // we just deleted.
58                 Buffer * tmp = (*it);
59                 container.erase(it);
60                 textcache.removeAllWithBuffer(tmp);
61                 delete tmp;
62         }
63 }
64
65
66 Buffer * BufferStorage::newBuffer(string const & s, bool ronly)
67 {
68         Buffer * tmpbuf = new Buffer(s, ronly);
69         tmpbuf->params.useClassDefaults();
70         lyxerr.debug() << "Assigning to buffer "
71                        << container.size() << endl;
72         container.push_back(tmpbuf);
73         return tmpbuf;
74 }
75
76
77 //
78 // Class BufferList
79 //
80
81 BufferList::BufferList()
82         : state_(BufferList::OK)
83 {}
84
85
86 bool BufferList::empty() const
87 {
88         return bstore.empty();
89 }
90
91
92 extern bool MenuWrite(Buffer *);
93 extern bool MenuWriteAs(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                         string fname;
103                         if ((*it)->isUnnamed())
104                                 fname = OnlyFilename((*it)->fileName());
105                         else
106                                 fname = MakeDisplayPath((*it)->fileName(), 50);
107                         bool reask = true;
108                         while(reask) {
109                                 switch(AskConfirmation(_("Changes in document:"),
110                                                        fname,
111                                                        _("Save document?"))) {
112                                 case 1: // Yes
113                                         if ((*it)->isUnnamed())
114                                                 reask = !MenuWriteAs((*it));
115                                         else {
116                                                 reask = !MenuWrite((*it));
117                                         }
118                                         break;
119                                 case 2: // No
120                                         // if we crash after this we could
121                                         // have no autosave file but I guess
122                                         // this is really inprobable (Jug)
123                                         if ((*it)->isUnnamed()) {
124                                                 removeAutosaveFile((*it)->fileName());
125                                         }
126                                         askMoreConfirmation = true;
127                                         unsaved += MakeDisplayPath(fname, 50);
128                                         unsaved += "\n";
129                                         reask = false;
130                                         break;
131                                 case 3: // Cancel
132                                         return false;
133                                 }
134                         }
135                 }
136         }
137         if (askMoreConfirmation &&
138             lyxrc.exit_confirmation &&
139             !AskQuestion(_("Some documents were not saved:"),
140                          unsaved, _("Exit anyway?"))) {
141                 return false;
142         }
143
144         return true;
145 }
146
147
148 void BufferList::closeAll()
149 {
150         state_ = BufferList::CLOSING;
151         // Since we are closing we can just as well delete all
152         // in the textcache this will also speed the closing/quiting up a bit.
153         textcache.clear();
154         
155         while (!bstore.empty()) {
156                 close(bstore.front());
157         }
158         state_ = BufferList::OK;
159 }
160
161
162 void BufferList::resize()
163 {
164         for_each(bstore.begin(), bstore.end(), mem_fun(&Buffer::resize));
165 }
166
167
168 bool BufferList::close(Buffer * buf)
169 {
170         // CHECK
171         // Trace back why we need to use buf->getUser here.
172         // Perhaps slight rewrite is in order? (Lgb)
173         
174         if (buf->getUser()) buf->getUser()->insetUnlock();
175         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
176                 if (buf->getUser())
177                         ProhibitInput(buf->getUser());
178                 string fname;
179                 if (buf->isUnnamed())
180                         fname = OnlyFilename(buf->fileName());
181                 else
182                         fname = MakeDisplayPath(buf->fileName(), 50);
183                 bool reask = true;
184                 while (reask) {
185                         switch(AskConfirmation(_("Changes in document:"),
186                                                fname,
187                                                _("Save document?"))){
188                         case 1: // Yes
189                                 if (buf->isUnnamed())
190                                         reask = !MenuWriteAs(buf);
191                                 else if (buf->save()) {
192                                         lastfiles->newFile(buf->fileName());
193                                         reask = false;
194                                 } else {
195                                         if (buf->getUser())
196                                                 AllowInput(buf->getUser());
197                                         return false;
198                                 }
199                                 break;
200                         case 2:
201                                 if (buf->isUnnamed()) {
202                                         removeAutosaveFile(buf->fileName());
203                                 }
204                                 reask = false;
205                                 break;
206                         case 3: // Cancel
207                                 if (buf->getUser())
208                                         AllowInput(buf->getUser());
209                                 return false;
210                         }
211                 }
212                 if (buf->getUser())
213                         AllowInput(buf->getUser());
214         }
215
216         bstore.release(buf);
217         return true;
218 }
219
220
221 vector<string> const BufferList::getFileNames() const
222 {
223         vector<string> nvec;
224         std::copy(bstore.begin(), bstore.end(),
225                   back_inserter_fun(nvec, &Buffer::fileName));
226         return nvec;
227 }
228
229
230 Buffer * BufferList::first()
231 {
232         if (bstore.empty()) return 0;
233         return bstore.front();
234 }
235
236
237 Buffer * BufferList::getBuffer(unsigned int choice)
238 {
239         if (choice >= bstore.size()) return 0;
240         return bstore[choice];
241 }
242
243
244 int BufferList::unlockInset(UpdatableInset * inset)
245 {
246         if (!inset) return 1;
247         for (BufferStorage::iterator it = bstore.begin();
248              it != bstore.end(); ++it) {
249                 if ((*it)->getUser()
250                     && (*it)->getUser()->theLockingInset() == inset) {
251                         (*it)->getUser()->insetUnlock();
252                         return 0;
253                 }
254         }
255         return 1;
256 }
257
258
259 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
260 {
261         for (BufferStorage::iterator it = bstore.begin();
262              it != bstore.end(); ++it) {
263                 if (!(*it)->isDepClean(mastertmpdir)) {
264                         string writefile = mastertmpdir;
265                         writefile += '/';
266                         writefile += (*it)->getLatexName();
267                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
268                                              false, true);
269                         (*it)->markDepClean(mastertmpdir);
270                 }
271         }
272 }
273
274
275 void BufferList::emergencyWriteAll()
276 {
277         for_each(bstore.begin(), bstore.end(),
278                  class_fun(*this, &BufferList::emergencyWrite));
279 }
280
281
282 void BufferList::emergencyWrite(Buffer * buf) 
283 {
284         // No need to save if the buffer has not changed.
285         if (buf->isLyxClean()) return;
286         
287         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
288                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
289                       : buf->fileName().c_str()) << endl;
290         
291         //if (buf->isUnnamed())
292         //      lyxerr << OnlyFilename(buf->fileName());
293         //else
294         //      lyxerr << buf->fileName();
295         //lyxerr << _(" as...") << endl;
296         
297         // Let's unroll this loop (Lgb)
298 #if 0
299         bool madeit = false;
300         
301         for (int i = 0; i < 3 && !madeit; ++i) {
302                 string s;
303                 
304                 // We try to save three places:
305                 // 1) Same place as document.
306                 // 2) In HOME directory.
307                 // 3) In "/tmp" directory.
308                 if (i == 0) {
309                         if (buf->isUnnamed())
310                                 continue;
311                         s = buf->fileName();
312                 } else if (i == 1) {
313                         s = AddName(GetEnvPath("HOME"), buf->fileName());
314                 } else {
315                         // MakeAbsPath to prepend the current
316                         // drive letter on OS/2
317                         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
318                 }
319                 s += ".emergency";
320                 
321                 lyxerr << "  " << i + 1 << ") " << s << endl;
322                 
323                 if (buf->writeFile(s, true)) {
324                         buf->markLyxClean();
325                         lyxerr << _("  Save seems successful. Phew.") << endl;
326                         madeit = true;
327                 } else if (i != 2) {
328                         lyxerr << _("  Save failed! Trying...") << endl;
329                 } else {
330                         lyxerr << _("  Save failed! Bummer. Document is lost.")
331                                << endl;
332                 }
333         }
334 #else
335         // We try to save three places:
336
337         // 1) Same place as document. Unless it is an unnamed doc.
338         if (!buf->isUnnamed()) {
339                 string s = buf->fileName();
340                 s += ".emergency";
341                 lyxerr << "  " << s << endl;
342                 if (buf->writeFile(s, true)) {
343                         buf->markLyxClean();
344                         lyxerr << _("  Save seems successful. Phew.") << endl;
345                         return;
346                 } else {
347                         lyxerr << _("  Save failed! Trying...") << endl;
348                 }
349         }
350         
351         // 2) In HOME directory.
352         string s = AddName(GetEnvPath("HOME"), buf->fileName());
353         s += ".emergency";
354         lyxerr << " " << s << endl;
355         if (buf->writeFile(s, true)) {
356                 buf->markLyxClean();
357                 lyxerr << _("  Save seems successful. Phew.") << endl;
358                 return;
359         }
360         
361         lyxerr << _("  Save failed! Trying...") << endl;
362         
363         // 3) In "/tmp" directory.
364         // MakeAbsPath to prepend the current
365         // drive letter on OS/2
366         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
367         s += ".emergency";
368         lyxerr << " " << s << endl;
369         if (buf->writeFile(s, true)) {
370                 buf->markLyxClean();
371                 lyxerr << _("  Save seems successful. Phew.") << endl;
372                 return;
373         }
374         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
375 #endif
376 }
377
378
379
380 Buffer * BufferList::readFile(string const & s, bool ronly)
381 {
382         Buffer * b = bstore.newBuffer(s, ronly);
383
384         string ts = s;
385         string e = OnlyPath(s);
386         string a = e;
387         // File information about normal file
388         FileInfo fileInfo2(s);
389
390         // Check if emergency save file exists and is newer.
391         e += OnlyFilename(s) + ".emergency";
392         FileInfo fileInfoE(e);
393
394         bool use_emergency = false;
395
396         if (fileInfoE.exist() && fileInfo2.exist()) {
397                 if (fileInfoE.getModificationTime()
398                     > fileInfo2.getModificationTime()) {
399                         if (AskQuestion(_("An emergency save of this document exists!"),
400                                         MakeDisplayPath(s, 50),
401                                         _("Try to load that instead?"))) {
402                                 ts = e;
403                                 // the file is not saved if we load the
404                                 // emergency file.
405                                 b->markDirty();
406                                 use_emergency = true;
407                         } else {
408                                 // Here, we should delete the emergency save
409                                 lyx::unlink(e);
410                         }
411                 }
412         }
413
414         if (!use_emergency) {
415                 // Now check if autosave file is newer.
416                 a += '#';
417                 a += OnlyFilename(s);
418                 a += '#';
419                 FileInfo fileInfoA(a);
420                 if (fileInfoA.exist() && fileInfo2.exist()) {
421                         if (fileInfoA.getModificationTime()
422                             > fileInfo2.getModificationTime()) {
423                                 if (AskQuestion(_("Autosave file is newer."),
424                                                 MakeDisplayPath(s, 50),
425                                                 _("Load that one instead?"))) {
426                                         ts = a;
427                                         // the file is not saved if we load the
428                                         // autosave file.
429                                         b->markDirty();
430                                 } else {
431                                         // Here, we should delete the autosave
432                                         lyx::unlink(a);
433                                 }
434                         }
435                 }
436         }
437         // not sure if this is the correct place to begin LyXLex
438         LyXLex lex(0, 0);
439         lex.setFile(ts);
440         if (b->readFile(lex))
441                 return b;
442         else {
443                 bstore.release(b);
444                 return 0;
445         }
446 }
447
448
449 bool BufferList::exists(string const & s) const
450 {
451         return find_if(bstore.begin(), bstore.end(),
452                        compare_memfun(&Buffer::fileName, s)) != bstore.end();
453 }
454
455
456 bool BufferList::isLoaded(Buffer const * b) const
457 {
458         BufferStorage::const_iterator cit =
459                 find(bstore.begin(), bstore.end(), b);
460         return cit != bstore.end();
461 }
462
463
464 Buffer * BufferList::getBuffer(string const & s)
465 {
466         BufferStorage::iterator it =
467                 find_if(bstore.begin(), bstore.end(),
468                         compare_memfun(&Buffer::fileName, s));
469         return it != bstore.end() ? (*it) : 0;
470 }
471
472
473 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
474 {
475         // get a free buffer
476         Buffer * b = bstore.newBuffer(name);
477
478         // use defaults.lyx as a default template if it exists.
479         if (tname.empty()) {
480                 tname = LibFileSearch("templates", "defaults.lyx");
481         }
482         if (!tname.empty() && IsLyXFilename(tname)) {
483                 bool templateok = false;
484                 LyXLex lex(0, 0);
485                 lex.setFile(tname);
486                 if (lex.IsOK()) {
487                         if (b->readFile(lex)) {
488                                 templateok = true;
489                         }
490                 }
491                 if (!templateok) {
492                         WriteAlert(_("Error!"), _("Unable to open template"), 
493                                    MakeDisplayPath(tname));
494                         // no template, start with empty buffer
495                         b->paragraph = new LyXParagraph;
496                 }
497         } else {  // start with empty buffer
498                 b->paragraph = new LyXParagraph;
499         }
500
501         if (!lyxrc.new_ask_filename) {
502                 if (!isNamed)
503                         b->setUnnamed();
504         }
505         b->setReadonly(false);
506         
507         return b;
508 }
509
510
511 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
512 {
513         // make sure our path is absolute
514         string const s = MakeAbsPath(filename);
515
516         // file already open?
517         if (exists(s)) {
518                 if (AskQuestion(_("Document is already open:"), 
519                                 MakeDisplayPath(s, 50),
520                                 _("Do you want to reload that document?"))) {
521                         // Reload is accomplished by closing and then loading
522                         if (!close(getBuffer(s))) {
523                                 return 0;
524                         }
525                         // Fall through to new load. (Asger)
526                 } else {
527                         // Here, we pretend that we just loaded the 
528                         // open document
529                         return getBuffer(s);
530                 }
531         }
532         Buffer * b = 0;
533         bool ro = false;
534         switch (IsFileWriteable(s)) {
535         case 0:
536 #if 0
537                 current_view->owner()->getMiniBuffer()->
538                         Set(_("File `") + MakeDisplayPath(s, 50) +
539                             _("' is read-only."));
540 #endif
541                 ro = true;
542                 // Fall through
543         case 1:
544                 b = readFile(s, ro);
545                 if (b) {
546                         b->lyxvc.file_found_hook(s);
547                 }
548                 break; //fine- it's r/w
549         case -1:
550                 // Here we probably should run
551                 if (LyXVC::file_not_found_hook(s)) {
552                         // Ask if the file should be checked out for
553                         // viewing/editing, if so: load it.
554                         if (AskQuestion(_("Do you want to retrieve file under version control?"))) {
555                                 // How can we know _how_ to do the checkout?
556                                 // With the current VC support it has to be,
557                                 // a RCS file since CVS do not have special ,v files.
558                                 RCS::retrive(s);
559                                 return loadLyXFile(filename, tolastfiles);
560                         }
561                 }
562                 if (AskQuestion(_("Cannot open specified file:"), 
563                                 MakeDisplayPath(s, 50),
564                                 _("Create new document with this name?")))
565                         {
566                                 // Find a free buffer
567                                 b = newFile(s, string(), true);
568                         }
569                 break;
570         }
571
572         if (b && tolastfiles)
573                 lastfiles->newFile(b->fileName());
574
575         return b;
576 }