]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
ws cleanup
[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 "LyXView.h"
32 #include "vc-backend.h"
33 #include "TextCache.h"
34 #include "lyxtextclasslist.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)->isLyxClean()) {
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         if (!unsaved.empty() && lyxrc.exit_confirmation) {
156                 return Alert::askQuestion(_("Some documents were not saved:"),
157                                           unsaved, _("Exit anyway?"));
158         }
159
160         return true;
161 }
162
163
164 void BufferList::closeAll()
165 {
166         state_ = BufferList::CLOSING;
167         // Since we are closing we can just as well delete all
168         // in the textcache this will also speed the closing/quiting up a bit.
169         textcache.clear();
170
171         while (!bstore.empty()) {
172                 close(bstore.front());
173         }
174         state_ = BufferList::OK;
175 }
176
177
178 bool BufferList::close(Buffer * buf)
179 {
180         lyx::Assert(buf);
181
182         // CHECK
183         // Trace back why we need to use buf->getUser here.
184         // Perhaps slight rewrite is in order? (Lgb)
185
186         if (buf->getUser())
187                 buf->getUser()->insetUnlock();
188
189         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
190                 if (buf->getUser())
191                         buf->getUser()->owner()->prohibitInput();
192                 string fname;
193                 if (buf->isUnnamed())
194                         fname = OnlyFilename(buf->fileName());
195                 else
196                         fname = MakeDisplayPath(buf->fileName(), 50);
197                 bool reask = true;
198                 while (reask) {
199                         switch (Alert::askConfirmation(_("Changes in document:"),
200                                                fname,
201                                                _("Save document?"))) {
202                         case 1: // Yes
203                                 if (buf->isUnnamed())
204                                         reask = !WriteAs(current_view, buf);
205                                 else if (buf->save()) {
206                                         lastfiles->newFile(buf->fileName());
207                                         reask = false;
208                                 } else {
209                                         if (buf->getUser())
210                                                 buf->getUser()->owner()->allowInput();
211                                         return false;
212                                 }
213                                 break;
214                         case 2:
215                                 if (buf->isUnnamed()) {
216                                         removeAutosaveFile(buf->fileName());
217                                 }
218                                 reask = false;
219                                 break;
220                         case 3: // Cancel
221                                 if (buf->getUser())
222                                         buf->getUser()->owner()->allowInput();
223                                 return false;
224                         }
225                 }
226                 if (buf->getUser())
227                         buf->getUser()->owner()->allowInput();
228         }
229
230         bstore.release(buf);
231         return true;
232 }
233
234
235 vector<string> const BufferList::getFileNames() const
236 {
237         vector<string> nvec;
238         std::copy(bstore.begin(), bstore.end(),
239                   lyx::back_inserter_fun(nvec, &Buffer::fileName));
240         return nvec;
241 }
242
243
244 Buffer * BufferList::first()
245 {
246         if (bstore.empty())
247                 return 0;
248         return bstore.front();
249 }
250
251
252 Buffer * BufferList::getBuffer(unsigned int choice)
253 {
254         if (choice >= bstore.size())
255                 return 0;
256         return bstore[choice];
257 }
258
259
260 int BufferList::unlockInset(UpdatableInset * inset)
261 {
262         lyx::Assert(inset);
263
264         BufferStorage::iterator it = bstore.begin();
265         BufferStorage::iterator end = bstore.end();
266         for (; it != end; ++it) {
267                 if ((*it)->getUser()
268                     && (*it)->getUser()->theLockingInset() == inset) {
269                         (*it)->getUser()->insetUnlock();
270                         return 0;
271                 }
272         }
273         return 1;
274 }
275
276
277 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
278 {
279         BufferStorage::iterator it = bstore.begin();
280         BufferStorage::iterator end = bstore.end();
281         for (; it != end; ++it) {
282                 if (!(*it)->isDepClean(mastertmpdir)) {
283                         string writefile = mastertmpdir;
284                         writefile += '/';
285                         writefile += (*it)->getLatexName();
286                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
287                                              false, true);
288                         (*it)->markDepClean(mastertmpdir);
289                 }
290         }
291 }
292
293
294 void BufferList::emergencyWriteAll()
295 {
296         for_each(bstore.begin(), bstore.end(),
297                  lyx::class_fun(*this, &BufferList::emergencyWrite));
298 }
299
300
301 void BufferList::emergencyWrite(Buffer * buf)
302 {
303         // assert(buf) // this is not good since C assert takes an int
304                        // and a pointer is a long (JMarc)
305         assert(buf != 0); // use c assert to avoid a loop
306
307
308         // No need to save if the buffer has not changed.
309         if (buf->isLyxClean())
310                 return;
311
312         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
313                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
314                       : buf->fileName().c_str()) << endl;
315
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, true)) {
324                         buf->markLyxClean();
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, true)) {
337                 buf->markLyxClean();
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, true)) {
351                 buf->markLyxClean();
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))
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)) {
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->paragraph = new Paragraph;
485                         b->paragraph->layout(textclasslist[b->params.textclass].defaultLayoutName());
486                 }
487         } else {  // start with empty buffer
488                 b->paragraph = new Paragraph;
489                         b->paragraph->layout(textclasslist[b->params.textclass].defaultLayoutName());
490         }
491
492         if (!lyxrc.new_ask_filename && !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 }