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