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