]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
83a5ad89770c4cdf18a139b60d68862f886ecf6b
[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-2001 The LyX Team. 
8  *
9  *           This file is Copyright 1996-2001
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 "support/FileInfo.h"
27 #include "support/filetools.h"
28 #include "support/lyxmanip.h"
29 #include "support/lyxfunctional.h"
30 #include "lyx_gui_misc.h"
31 #include "lastfiles.h"
32 #include "debug.h"
33 #include "lyxrc.h"
34 #include "lyxtext.h"
35 #include "lyx_cb.h"
36 #include "bufferview_funcs.h"
37 #include "BufferView.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 extern BufferView * current_view;
51
52 //
53 // Class BufferStorage
54 //
55
56 void BufferStorage::release(Buffer * buf)
57 {
58         lyx::Assert(buf);
59         Container::iterator it = find(container.begin(), container.end(), buf);
60         if (it != container.end()) {
61                 // Make sure that we don't store a LyXText in
62                 // the textcache that points to the buffer
63                 // we just deleted.
64                 Buffer * tmp = (*it);
65                 container.erase(it);
66                 textcache.removeAllWithBuffer(tmp);
67                 delete tmp;
68         }
69 }
70
71
72 Buffer * BufferStorage::newBuffer(string const & s, bool ronly)
73 {
74         Buffer * tmpbuf = new Buffer(s, ronly);
75         tmpbuf->params.useClassDefaults();
76         lyxerr[Debug::INFO] << "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 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 = !WriteAs(current_view, (*it));
118                                         else {
119                                                 reask = !MenuWrite(current_view, (*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 bool BufferList::close(Buffer * buf)
166 {
167         lyx::Assert(buf);
168         
169         // CHECK
170         // Trace back why we need to use buf->getUser here.
171         // Perhaps slight rewrite is in order? (Lgb)
172         
173         if (buf->getUser()) buf->getUser()->insetUnlock();
174         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
175                 if (buf->getUser())
176                         ProhibitInput(buf->getUser());
177                 string fname;
178                 if (buf->isUnnamed())
179                         fname = OnlyFilename(buf->fileName());
180                 else
181                         fname = MakeDisplayPath(buf->fileName(), 50);
182                 bool reask = true;
183                 while (reask) {
184                         switch (AskConfirmation(_("Changes in document:"),
185                                                fname,
186                                                _("Save document?"))){
187                         case 1: // Yes
188                                 if (buf->isUnnamed())
189                                         reask = !WriteAs(current_view, buf);
190                                 else if (buf->save()) {
191                                         lastfiles->newFile(buf->fileName());
192                                         reask = false;
193                                 } else {
194                                         if (buf->getUser())
195                                                 AllowInput(buf->getUser());
196                                         return false;
197                                 }
198                                 break;
199                         case 2:
200                                 if (buf->isUnnamed()) {
201                                         removeAutosaveFile(buf->fileName());
202                                 }
203                                 reask = false;
204                                 break;
205                         case 3: // Cancel
206                                 if (buf->getUser())
207                                         AllowInput(buf->getUser());
208                                 return false;
209                         }
210                 }
211                 if (buf->getUser())
212                         AllowInput(buf->getUser());
213         }
214
215         bstore.release(buf);
216         return true;
217 }
218
219
220 vector<string> const BufferList::getFileNames() const
221 {
222         vector<string> nvec;
223         std::copy(bstore.begin(), bstore.end(),
224                   lyx::back_inserter_fun(nvec, &Buffer::fileName));
225         return nvec;
226 }
227
228
229 Buffer * BufferList::first()
230 {
231         if (bstore.empty()) return 0;
232         return bstore.front();
233 }
234
235
236 Buffer * BufferList::getBuffer(unsigned int choice)
237 {
238         if (choice >= bstore.size()) return 0;
239         return bstore[choice];
240 }
241
242
243 int BufferList::unlockInset(UpdatableInset * inset)
244 {
245         lyx::Assert(inset);
246         
247         //if (!inset) return 1;
248         for (BufferStorage::iterator it = bstore.begin();
249              it != bstore.end(); ++it) {
250                 if ((*it)->getUser()
251                     && (*it)->getUser()->theLockingInset() == inset) {
252                         (*it)->getUser()->insetUnlock();
253                         return 0;
254                 }
255         }
256         return 1;
257 }
258
259
260 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
261 {
262         for (BufferStorage::iterator it = bstore.begin();
263              it != bstore.end(); ++it) {
264                 if (!(*it)->isDepClean(mastertmpdir)) {
265                         string writefile = mastertmpdir;
266                         writefile += '/';
267                         writefile += (*it)->getLatexName();
268                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
269                                              false, true);
270                         (*it)->markDepClean(mastertmpdir);
271                 }
272         }
273 }
274
275
276 void BufferList::emergencyWriteAll()
277 {
278         for_each(bstore.begin(), bstore.end(),
279                  lyx::class_fun(*this, &BufferList::emergencyWrite));
280 }
281
282
283 void BufferList::emergencyWrite(Buffer * buf) 
284 {
285         // assert(buf) // this is not good since C assert takes an int
286                        // and a pointer is a long (JMarc)
287         assert(buf != 0); // use c assert to avoid a loop
288
289         
290         // No need to save if the buffer has not changed.
291         if (buf->isLyxClean()) return;
292         
293         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
294                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
295                       : buf->fileName().c_str()) << endl;
296         
297         // We try to save three places:
298
299         // 1) Same place as document. Unless it is an unnamed doc.
300         if (!buf->isUnnamed()) {
301                 string s = buf->fileName();
302                 s += ".emergency";
303                 lyxerr << "  " << s << endl;
304                 if (buf->writeFile(s, true)) {
305                         buf->markLyxClean();
306                         lyxerr << _("  Save seems successful. Phew.") << endl;
307                         return;
308                 } else {
309                         lyxerr << _("  Save failed! Trying...") << endl;
310                 }
311         }
312         
313         // 2) In HOME directory.
314         string s = AddName(GetEnvPath("HOME"), buf->fileName());
315         s += ".emergency";
316         lyxerr << " " << s << endl;
317         if (buf->writeFile(s, true)) {
318                 buf->markLyxClean();
319                 lyxerr << _("  Save seems successful. Phew.") << endl;
320                 return;
321         }
322         
323         lyxerr << _("  Save failed! Trying...") << endl;
324         
325         // 3) In "/tmp" directory.
326         // MakeAbsPath to prepend the current
327         // drive letter on OS/2
328         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
329         s += ".emergency";
330         lyxerr << " " << s << endl;
331         if (buf->writeFile(s, true)) {
332                 buf->markLyxClean();
333                 lyxerr << _("  Save seems successful. Phew.") << endl;
334                 return;
335         }
336         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
337 }
338
339
340
341 Buffer * BufferList::readFile(string const & s, bool ronly)
342 {
343         Buffer * b = bstore.newBuffer(s, ronly);
344
345         string ts = s;
346         string e = OnlyPath(s);
347         string a = e;
348         // File information about normal file
349         FileInfo fileInfo2(s);
350
351         // Check if emergency save file exists and is newer.
352         e += OnlyFilename(s) + ".emergency";
353         FileInfo fileInfoE(e);
354
355         bool use_emergency = false;
356
357         if (fileInfoE.exist() && fileInfo2.exist()) {
358                 if (fileInfoE.getModificationTime()
359                     > fileInfo2.getModificationTime()) {
360                         if (AskQuestion(_("An emergency save of this document exists!"),
361                                         MakeDisplayPath(s, 50),
362                                         _("Try to load that instead?"))) {
363                                 ts = e;
364                                 // the file is not saved if we load the
365                                 // emergency file.
366                                 b->markDirty();
367                                 use_emergency = true;
368                         } else {
369                                 // Here, we should delete the emergency save
370                                 lyx::unlink(e);
371                         }
372                 }
373         }
374
375         if (!use_emergency) {
376                 // Now check if autosave file is newer.
377                 a += '#';
378                 a += OnlyFilename(s);
379                 a += '#';
380                 FileInfo fileInfoA(a);
381                 if (fileInfoA.exist() && fileInfo2.exist()) {
382                         if (fileInfoA.getModificationTime()
383                             > fileInfo2.getModificationTime()) {
384                                 if (AskQuestion(_("Autosave file is newer."),
385                                                 MakeDisplayPath(s, 50),
386                                                 _("Load that one instead?"))) {
387                                         ts = a;
388                                         // the file is not saved if we load the
389                                         // autosave file.
390                                         b->markDirty();
391                                 } else {
392                                         // Here, we should delete the autosave
393                                         lyx::unlink(a);
394                                 }
395                         }
396                 }
397         }
398         // not sure if this is the correct place to begin LyXLex
399         LyXLex lex(0, 0);
400         lex.setFile(ts);
401         if (b->readFile(lex))
402                 return b;
403         else {
404                 bstore.release(b);
405                 return 0;
406         }
407 }
408
409
410 bool BufferList::exists(string const & s) const
411 {
412         return find_if(bstore.begin(), bstore.end(),
413                        lyx::compare_memfun(&Buffer::fileName, s))
414                 != bstore.end();
415 }
416
417
418 bool BufferList::isLoaded(Buffer const * b) const
419 {
420         lyx::Assert(b);
421         
422         BufferStorage::const_iterator cit =
423                 find(bstore.begin(), bstore.end(), b);
424         return cit != bstore.end();
425 }
426
427
428 Buffer * BufferList::getBuffer(string const & s)
429 {
430         BufferStorage::iterator it =
431                 find_if(bstore.begin(), bstore.end(),
432                         lyx::compare_memfun(&Buffer::fileName, s));
433         return it != bstore.end() ? (*it) : 0;
434 }
435
436
437 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
438 {
439         // get a free buffer
440         Buffer * b = bstore.newBuffer(name);
441
442         // use defaults.lyx as a default template if it exists.
443         if (tname.empty()) {
444                 tname = LibFileSearch("templates", "defaults.lyx");
445         }
446         if (!tname.empty()) {
447                 bool templateok = false;
448                 LyXLex lex(0, 0);
449                 lex.setFile(tname);
450                 if (lex.IsOK()) {
451                         if (b->readFile(lex)) {
452                                 templateok = true;
453                         }
454                 }
455                 if (!templateok) {
456                         WriteAlert(_("Error!"), _("Unable to open template"), 
457                                    MakeDisplayPath(tname));
458                         // no template, start with empty buffer
459                         b->paragraph = new Paragraph;
460                 }
461         } else {  // start with empty buffer
462                 b->paragraph = new Paragraph;
463         }
464
465         if (!lyxrc.new_ask_filename && !isNamed) {
466                 b->setUnnamed();
467                 b->setFileName(name);
468         }
469
470         b->setReadonly(false);
471         
472         return b;
473 }
474
475
476 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
477 {
478         // make sure our path is absolute
479         string const s = MakeAbsPath(filename);
480
481         // file already open?
482         if (exists(s)) {
483                 if (AskQuestion(_("Document is already open:"), 
484                                 MakeDisplayPath(s, 50),
485                                 _("Do you want to reload that document?"))) {
486                         // Reload is accomplished by closing and then loading
487                         if (!close(getBuffer(s))) {
488                                 return 0;
489                         }
490                         // Fall through to new load. (Asger)
491                 } else {
492                         // Here, we pretend that we just loaded the 
493                         // open document
494                         return getBuffer(s);
495                 }
496         }
497         Buffer * b = 0;
498         bool ro = false;
499         switch (IsFileWriteable(s)) {
500         case 0:
501                 ro = true;
502                 // Fall through
503         case 1:
504                 b = readFile(s, ro);
505                 if (b) {
506                         b->lyxvc.file_found_hook(s);
507                 }
508                 break; //fine- it's r/w
509         case -1:
510                 // Here we probably should run
511                 if (LyXVC::file_not_found_hook(s)) {
512                         // Ask if the file should be checked out for
513                         // viewing/editing, if so: load it.
514                         if (AskQuestion(_("Do you want to retrieve file under version control?"))) {
515                                 // How can we know _how_ to do the checkout?
516                                 // With the current VC support it has to be,
517                                 // a RCS file since CVS do not have special ,v files.
518                                 RCS::retrive(s);
519                                 return loadLyXFile(filename, tolastfiles);
520                         }
521                 }
522                 if (AskQuestion(_("Cannot open specified file:"), 
523                                 MakeDisplayPath(s, 50),
524                                 _("Create new document with this name?")))
525                         {
526                                 // Find a free buffer
527                                 b = newFile(s, string(), true);
528                         }
529                 break;
530         }
531
532         if (b && tolastfiles)
533                 lastfiles->newFile(b->fileName());
534
535         return b;
536 }