]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
fe8dba7576d3b02e4482e89349db3e56d4060c7d
[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 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         // We try to save three places:
295
296         // 1) Same place as document. Unless it is an unnamed doc.
297         if (!buf->isUnnamed()) {
298                 string s = buf->fileName();
299                 s += ".emergency";
300                 lyxerr << "  " << s << endl;
301                 if (buf->writeFile(s, true)) {
302                         buf->markLyxClean();
303                         lyxerr << _("  Save seems successful. Phew.") << endl;
304                         return;
305                 } else {
306                         lyxerr << _("  Save failed! Trying...") << endl;
307                 }
308         }
309         
310         // 2) In HOME directory.
311         string s = AddName(GetEnvPath("HOME"), buf->fileName());
312         s += ".emergency";
313         lyxerr << " " << s << endl;
314         if (buf->writeFile(s, true)) {
315                 buf->markLyxClean();
316                 lyxerr << _("  Save seems successful. Phew.") << endl;
317                 return;
318         }
319         
320         lyxerr << _("  Save failed! Trying...") << endl;
321         
322         // 3) In "/tmp" directory.
323         // MakeAbsPath to prepend the current
324         // drive letter on OS/2
325         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
326         s += ".emergency";
327         lyxerr << " " << s << endl;
328         if (buf->writeFile(s, true)) {
329                 buf->markLyxClean();
330                 lyxerr << _("  Save seems successful. Phew.") << endl;
331                 return;
332         }
333         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
334 }
335
336
337
338 Buffer * BufferList::readFile(string const & s, bool ronly)
339 {
340         Buffer * b = bstore.newBuffer(s, ronly);
341
342         string ts = s;
343         string e = OnlyPath(s);
344         string a = e;
345         // File information about normal file
346         FileInfo fileInfo2(s);
347
348         // Check if emergency save file exists and is newer.
349         e += OnlyFilename(s) + ".emergency";
350         FileInfo fileInfoE(e);
351
352         bool use_emergency = false;
353
354         if (fileInfoE.exist() && fileInfo2.exist()) {
355                 if (fileInfoE.getModificationTime()
356                     > fileInfo2.getModificationTime()) {
357                         if (AskQuestion(_("An emergency save of this document exists!"),
358                                         MakeDisplayPath(s, 50),
359                                         _("Try to load that instead?"))) {
360                                 ts = e;
361                                 // the file is not saved if we load the
362                                 // emergency file.
363                                 b->markDirty();
364                                 use_emergency = true;
365                         } else {
366                                 // Here, we should delete the emergency save
367                                 lyx::unlink(e);
368                         }
369                 }
370         }
371
372         if (!use_emergency) {
373                 // Now check if autosave file is newer.
374                 a += '#';
375                 a += OnlyFilename(s);
376                 a += '#';
377                 FileInfo fileInfoA(a);
378                 if (fileInfoA.exist() && fileInfo2.exist()) {
379                         if (fileInfoA.getModificationTime()
380                             > fileInfo2.getModificationTime()) {
381                                 if (AskQuestion(_("Autosave file is newer."),
382                                                 MakeDisplayPath(s, 50),
383                                                 _("Load that one instead?"))) {
384                                         ts = a;
385                                         // the file is not saved if we load the
386                                         // autosave file.
387                                         b->markDirty();
388                                 } else {
389                                         // Here, we should delete the autosave
390                                         lyx::unlink(a);
391                                 }
392                         }
393                 }
394         }
395         // not sure if this is the correct place to begin LyXLex
396         LyXLex lex(0, 0);
397         lex.setFile(ts);
398         if (b->readFile(lex))
399                 return b;
400         else {
401                 bstore.release(b);
402                 return 0;
403         }
404 }
405
406
407 bool BufferList::exists(string const & s) const
408 {
409         return find_if(bstore.begin(), bstore.end(),
410                        compare_memfun(&Buffer::fileName, s)) != bstore.end();
411 }
412
413
414 bool BufferList::isLoaded(Buffer const * b) const
415 {
416         BufferStorage::const_iterator cit =
417                 find(bstore.begin(), bstore.end(), b);
418         return cit != bstore.end();
419 }
420
421
422 Buffer * BufferList::getBuffer(string const & s)
423 {
424         BufferStorage::iterator it =
425                 find_if(bstore.begin(), bstore.end(),
426                         compare_memfun(&Buffer::fileName, s));
427         return it != bstore.end() ? (*it) : 0;
428 }
429
430
431 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
432 {
433         // get a free buffer
434         Buffer * b = bstore.newBuffer(name);
435
436         // use defaults.lyx as a default template if it exists.
437         if (tname.empty()) {
438                 tname = LibFileSearch("templates", "defaults.lyx");
439         }
440         if (!tname.empty() && IsLyXFilename(tname)) {
441                 bool templateok = false;
442                 LyXLex lex(0, 0);
443                 lex.setFile(tname);
444                 if (lex.IsOK()) {
445                         if (b->readFile(lex)) {
446                                 templateok = true;
447                         }
448                 }
449                 if (!templateok) {
450                         WriteAlert(_("Error!"), _("Unable to open template"), 
451                                    MakeDisplayPath(tname));
452                         // no template, start with empty buffer
453                         b->paragraph = new LyXParagraph;
454                 }
455         } else {  // start with empty buffer
456                 b->paragraph = new LyXParagraph;
457         }
458
459         if (!lyxrc.new_ask_filename) {
460                 if (!isNamed)
461                         b->setUnnamed();
462         }
463         b->setReadonly(false);
464         
465         return b;
466 }
467
468
469 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
470 {
471         // make sure our path is absolute
472         string const s = MakeAbsPath(filename);
473
474         // file already open?
475         if (exists(s)) {
476                 if (AskQuestion(_("Document is already open:"), 
477                                 MakeDisplayPath(s, 50),
478                                 _("Do you want to reload that document?"))) {
479                         // Reload is accomplished by closing and then loading
480                         if (!close(getBuffer(s))) {
481                                 return 0;
482                         }
483                         // Fall through to new load. (Asger)
484                 } else {
485                         // Here, we pretend that we just loaded the 
486                         // open document
487                         return getBuffer(s);
488                 }
489         }
490         Buffer * b = 0;
491         bool ro = false;
492         switch (IsFileWriteable(s)) {
493         case 0:
494 #if 0
495                 current_view->owner()->getMiniBuffer()->
496                         Set(_("File `") + MakeDisplayPath(s, 50) +
497                             _("' is read-only."));
498 #endif
499                 ro = true;
500                 // Fall through
501         case 1:
502                 b = readFile(s, ro);
503                 if (b) {
504                         b->lyxvc.file_found_hook(s);
505                 }
506                 break; //fine- it's r/w
507         case -1:
508                 // Here we probably should run
509                 if (LyXVC::file_not_found_hook(s)) {
510                         // Ask if the file should be checked out for
511                         // viewing/editing, if so: load it.
512                         if (AskQuestion(_("Do you want to retrieve file under version control?"))) {
513                                 // How can we know _how_ to do the checkout?
514                                 // With the current VC support it has to be,
515                                 // a RCS file since CVS do not have special ,v files.
516                                 RCS::retrive(s);
517                                 return loadLyXFile(filename, tolastfiles);
518                         }
519                 }
520                 if (AskQuestion(_("Cannot open specified file:"), 
521                                 MakeDisplayPath(s, 50),
522                                 _("Create new document with this name?")))
523                         {
524                                 // Find a free buffer
525                                 b = newFile(s, string(), true);
526                         }
527                 break;
528         }
529
530         if (b && tolastfiles)
531                 lastfiles->newFile(b->fileName());
532
533         return b;
534 }