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