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