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