]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
57f704e1cdc41c01323727a5dc0ae547dd09c9c6
[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 <assert.h>
22 #include <algorithm>
23 #include <functional>
24
25 #include "bufferlist.h"
26 #include "lyx_main.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 "BufferView.h"
39 #include "gettext.h"
40 #include "LyXView.h"
41 #include "vc-backend.h"
42 #include "TextCache.h"
43
44 using std::vector;
45 using std::find;
46 using std::endl;
47 using std::find_if;
48 using std::for_each;
49 using std::mem_fun;
50
51 extern BufferView * current_view;
52
53 //
54 // Class BufferStorage
55 //
56
57 void BufferStorage::release(Buffer * buf)
58 {
59         lyx::Assert(buf);
60         Container::iterator it = find(container.begin(), container.end(), buf);
61         if (it != container.end()) {
62                 // Make sure that we don't store a LyXText in
63                 // the textcache that points to the buffer
64                 // we just deleted.
65                 Buffer * tmp = (*it);
66                 container.erase(it);
67                 textcache.removeAllWithBuffer(tmp);
68                 delete tmp;
69         }
70 }
71
72
73 Buffer * BufferStorage::newBuffer(string const & s, bool ronly)
74 {
75         Buffer * tmpbuf = new Buffer(s, ronly);
76         tmpbuf->params.useClassDefaults();
77         lyxerr[Debug::INFO] << "Assigning to buffer "
78                             << container.size() << endl;
79         container.push_back(tmpbuf);
80         return tmpbuf;
81 }
82
83
84 //
85 // Class BufferList
86 //
87
88 BufferList::BufferList()
89         : state_(BufferList::OK)
90 {}
91
92
93 bool BufferList::empty() const
94 {
95         return bstore.empty();
96 }
97
98
99 bool BufferList::qwriteAll()
100 {
101         bool askMoreConfirmation = false;
102         string unsaved;
103         for (BufferStorage::iterator it = bstore.begin();
104             it != bstore.end(); ++it) {
105                 if (!(*it)->isLyxClean()) {
106                         string fname;
107                         if ((*it)->isUnnamed())
108                                 fname = OnlyFilename((*it)->fileName());
109                         else
110                                 fname = MakeDisplayPath((*it)->fileName(), 50);
111                         bool reask = true;
112                         while (reask) {
113                                 switch (AskConfirmation(_("Changes in document:"),
114                                                        fname,
115                                                        _("Save document?"))) {
116                                 case 1: // Yes
117                                         if ((*it)->isUnnamed())
118                                                 reask = !WriteAs(current_view, (*it));
119                                         else {
120                                                 reask = !MenuWrite(current_view, (*it));
121                                         }
122                                         break;
123                                 case 2: // No
124                                         // if we crash after this we could
125                                         // have no autosave file but I guess
126                                         // this is really inprobable (Jug)
127                                         if ((*it)->isUnnamed()) {
128                                                 removeAutosaveFile((*it)->fileName());
129                                         }
130                                         askMoreConfirmation = true;
131                                         unsaved += MakeDisplayPath(fname, 50);
132                                         unsaved += "\n";
133                                         reask = false;
134                                         break;
135                                 case 3: // Cancel
136                                         return false;
137                                 }
138                         }
139                 }
140         }
141         if (askMoreConfirmation &&
142             lyxrc.exit_confirmation &&
143             !AskQuestion(_("Some documents were not saved:"),
144                          unsaved, _("Exit anyway?"))) {
145                 return false;
146         }
147
148         return true;
149 }
150
151
152 void BufferList::closeAll()
153 {
154         state_ = BufferList::CLOSING;
155         // Since we are closing we can just as well delete all
156         // in the textcache this will also speed the closing/quiting up a bit.
157         textcache.clear();
158         
159         while (!bstore.empty()) {
160                 close(bstore.front());
161         }
162         state_ = BufferList::OK;
163 }
164
165
166 bool BufferList::close(Buffer * buf)
167 {
168         lyx::Assert(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                         buf->getUser()->owner()->prohibitInput();
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 = !WriteAs(current_view, buf);
191                                 else if (buf->save()) {
192                                         lastfiles->newFile(buf->fileName());
193                                         reask = false;
194                                 } else {
195                                         if (buf->getUser())
196                                                 buf->getUser()->owner()->allowInput();
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                                         buf->getUser()->owner()->allowInput();
209                                 return false;
210                         }
211                 }
212                 if (buf->getUser())
213                         buf->getUser()->owner()->allowInput();
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                   lyx::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         lyx::Assert(inset);
247         
248         //if (!inset) return 1;
249         for (BufferStorage::iterator it = bstore.begin();
250              it != bstore.end(); ++it) {
251                 if ((*it)->getUser()
252                     && (*it)->getUser()->theLockingInset() == inset) {
253                         (*it)->getUser()->insetUnlock();
254                         return 0;
255                 }
256         }
257         return 1;
258 }
259
260
261 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
262 {
263         for (BufferStorage::iterator it = bstore.begin();
264              it != bstore.end(); ++it) {
265                 if (!(*it)->isDepClean(mastertmpdir)) {
266                         string writefile = mastertmpdir;
267                         writefile += '/';
268                         writefile += (*it)->getLatexName();
269                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
270                                              false, true);
271                         (*it)->markDepClean(mastertmpdir);
272                 }
273         }
274 }
275
276
277 void BufferList::emergencyWriteAll()
278 {
279         for_each(bstore.begin(), bstore.end(),
280                  lyx::class_fun(*this, &BufferList::emergencyWrite));
281 }
282
283
284 void BufferList::emergencyWrite(Buffer * buf) 
285 {
286         // assert(buf) // this is not good since C assert takes an int
287                        // and a pointer is a long (JMarc)
288         assert(buf != 0); // use c assert to avoid a loop
289
290         
291         // No need to save if the buffer has not changed.
292         if (buf->isLyxClean()) return;
293         
294         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
295                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
296                       : buf->fileName().c_str()) << endl;
297         
298         // We try to save three places:
299
300         // 1) Same place as document. Unless it is an unnamed doc.
301         if (!buf->isUnnamed()) {
302                 string s = buf->fileName();
303                 s += ".emergency";
304                 lyxerr << "  " << s << endl;
305                 if (buf->writeFile(s, true)) {
306                         buf->markLyxClean();
307                         lyxerr << _("  Save seems successful. Phew.") << endl;
308                         return;
309                 } else {
310                         lyxerr << _("  Save failed! Trying...") << endl;
311                 }
312         }
313         
314         // 2) In HOME directory.
315         string s = AddName(GetEnvPath("HOME"), buf->fileName());
316         s += ".emergency";
317         lyxerr << " " << s << endl;
318         if (buf->writeFile(s, true)) {
319                 buf->markLyxClean();
320                 lyxerr << _("  Save seems successful. Phew.") << endl;
321                 return;
322         }
323         
324         lyxerr << _("  Save failed! Trying...") << endl;
325         
326         // 3) In "/tmp" directory.
327         // MakeAbsPath to prepend the current
328         // drive letter on OS/2
329         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
330         s += ".emergency";
331         lyxerr << " " << s << endl;
332         if (buf->writeFile(s, true)) {
333                 buf->markLyxClean();
334                 lyxerr << _("  Save seems successful. Phew.") << endl;
335                 return;
336         }
337         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
338 }
339
340
341
342 Buffer * BufferList::readFile(string const & s, bool ronly)
343 {
344         Buffer * b = bstore.newBuffer(s, ronly);
345
346         string ts = s;
347         string e = OnlyPath(s);
348         string a = e;
349         // File information about normal file
350         FileInfo fileInfo2(s);
351
352         // Check if emergency save file exists and is newer.
353         e += OnlyFilename(s) + ".emergency";
354         FileInfo fileInfoE(e);
355
356         bool use_emergency = false;
357
358         if (fileInfoE.exist() && fileInfo2.exist()) {
359                 if (fileInfoE.getModificationTime()
360                     > fileInfo2.getModificationTime()) {
361                         if (AskQuestion(_("An emergency save of this document exists!"),
362                                         MakeDisplayPath(s, 50),
363                                         _("Try to load that instead?"))) {
364                                 ts = e;
365                                 // the file is not saved if we load the
366                                 // emergency file.
367                                 b->markDirty();
368                                 use_emergency = true;
369                         } else {
370                                 // Here, we should delete the emergency save
371                                 lyx::unlink(e);
372                         }
373                 }
374         }
375
376         if (!use_emergency) {
377                 // Now check if autosave file is newer.
378                 a += '#';
379                 a += OnlyFilename(s);
380                 a += '#';
381                 FileInfo fileInfoA(a);
382                 if (fileInfoA.exist() && fileInfo2.exist()) {
383                         if (fileInfoA.getModificationTime()
384                             > fileInfo2.getModificationTime()) {
385                                 if (AskQuestion(_("Autosave file is newer."),
386                                                 MakeDisplayPath(s, 50),
387                                                 _("Load that one instead?"))) {
388                                         ts = a;
389                                         // the file is not saved if we load the
390                                         // autosave file.
391                                         b->markDirty();
392                                 } else {
393                                         // Here, we should delete the autosave
394                                         lyx::unlink(a);
395                                 }
396                         }
397                 }
398         }
399         // not sure if this is the correct place to begin LyXLex
400         LyXLex lex(0, 0);
401         lex.setFile(ts);
402         if (b->readFile(lex))
403                 return b;
404         else {
405                 bstore.release(b);
406                 return 0;
407         }
408 }
409
410
411 bool BufferList::exists(string const & s) const
412 {
413         return find_if(bstore.begin(), bstore.end(),
414                        lyx::compare_memfun(&Buffer::fileName, s))
415                 != bstore.end();
416 }
417
418
419 bool BufferList::isLoaded(Buffer const * b) const
420 {
421         lyx::Assert(b);
422         
423         BufferStorage::const_iterator cit =
424                 find(bstore.begin(), bstore.end(), b);
425         return cit != bstore.end();
426 }
427
428
429 Buffer * BufferList::getBuffer(string const & s)
430 {
431         BufferStorage::iterator it =
432                 find_if(bstore.begin(), bstore.end(),
433                         lyx::compare_memfun(&Buffer::fileName, s));
434         return it != bstore.end() ? (*it) : 0;
435 }
436
437
438 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
439 {
440         // get a free buffer
441         Buffer * b = bstore.newBuffer(name);
442
443         // use defaults.lyx as a default template if it exists.
444         if (tname.empty()) {
445                 tname = LibFileSearch("templates", "defaults.lyx");
446         }
447         if (!tname.empty()) {
448                 bool templateok = false;
449                 LyXLex lex(0, 0);
450                 lex.setFile(tname);
451                 if (lex.IsOK()) {
452                         if (b->readFile(lex)) {
453                                 templateok = true;
454                         }
455                 }
456                 if (!templateok) {
457                         WriteAlert(_("Error!"), _("Unable to open template"), 
458                                    MakeDisplayPath(tname));
459                         // no template, start with empty buffer
460                         b->paragraph = new Paragraph;
461                 }
462         } else {  // start with empty buffer
463                 b->paragraph = new Paragraph;
464         }
465
466         if (!lyxrc.new_ask_filename && !isNamed) {
467                 b->setUnnamed();
468                 b->setFileName(name);
469         }
470
471         b->setReadonly(false);
472         
473         return b;
474 }
475
476
477 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
478 {
479         // make sure our path is absolute
480         string const s = MakeAbsPath(filename);
481
482         // file already open?
483         if (exists(s)) {
484                 if (AskQuestion(_("Document is already open:"), 
485                                 MakeDisplayPath(s, 50),
486                                 _("Do you want to reload that document?"))) {
487                         // Reload is accomplished by closing and then loading
488                         if (!close(getBuffer(s))) {
489                                 return 0;
490                         }
491                         // Fall through to new load. (Asger)
492                 } else {
493                         // Here, we pretend that we just loaded the 
494                         // open document
495                         return getBuffer(s);
496                 }
497         }
498         Buffer * b = 0;
499         bool ro = false;
500         switch (IsFileWriteable(s)) {
501         case 0:
502                 ro = true;
503                 // Fall through
504         case 1:
505                 b = readFile(s, ro);
506                 if (b) {
507                         b->lyxvc.file_found_hook(s);
508                 }
509                 break; //fine- it's r/w
510         case -1:
511                 // Here we probably should run
512                 if (LyXVC::file_not_found_hook(s)) {
513                         // Ask if the file should be checked out for
514                         // viewing/editing, if so: load it.
515                         if (AskQuestion(_("Do you want to retrieve file under version control?"))) {
516                                 // How can we know _how_ to do the checkout?
517                                 // With the current VC support it has to be,
518                                 // a RCS file since CVS do not have special ,v files.
519                                 RCS::retrive(s);
520                                 return loadLyXFile(filename, tolastfiles);
521                         }
522                 }
523                 if (AskQuestion(_("Cannot open specified file:"), 
524                                 MakeDisplayPath(s, 50),
525                                 _("Create new document with this name?")))
526                         {
527                                 // Find a free buffer
528                                 b = newFile(s, string(), true);
529                         }
530                 break;
531         }
532
533         if (b && tolastfiles)
534                 lastfiles->newFile(b->fileName());
535
536         return b;
537 }