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