]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
lowercase style on reading .lyx
[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
35 #include "frontends/Alert.h"
36
37 #include "support/FileInfo.h"
38 #include "support/filetools.h"
39 #include "support/lyxmanip.h"
40 #include "support/lyxfunctional.h"
41 #include "support/LAssert.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)->isLyxClean()) {
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         if (!unsaved.empty() && lyxrc.exit_confirmation) {
155                 return Alert::askQuestion(_("Some documents were not saved:"),
156                                           unsaved, _("Exit anyway?"));
157         }
158
159         return true;
160 }
161
162
163 void BufferList::closeAll()
164 {
165         state_ = BufferList::CLOSING;
166         // Since we are closing we can just as well delete all
167         // in the textcache this will also speed the closing/quiting up a bit.
168         textcache.clear();
169         
170         while (!bstore.empty()) {
171                 close(bstore.front());
172         }
173         state_ = BufferList::OK;
174 }
175
176
177 bool BufferList::close(Buffer * buf)
178 {
179         lyx::Assert(buf);
180         
181         // CHECK
182         // Trace back why we need to use buf->getUser here.
183         // Perhaps slight rewrite is in order? (Lgb)
184         
185         if (buf->getUser())
186                 buf->getUser()->insetUnlock();
187         
188         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
189                 if (buf->getUser())
190                         buf->getUser()->owner()->prohibitInput();
191                 string fname;
192                 if (buf->isUnnamed())
193                         fname = OnlyFilename(buf->fileName());
194                 else
195                         fname = MakeDisplayPath(buf->fileName(), 50);
196                 bool reask = true;
197                 while (reask) {
198                         switch (Alert::askConfirmation(_("Changes in document:"),
199                                                fname,
200                                                _("Save document?"))) {
201                         case 1: // Yes
202                                 if (buf->isUnnamed())
203                                         reask = !WriteAs(current_view, buf);
204                                 else if (buf->save()) {
205                                         lastfiles->newFile(buf->fileName());
206                                         reask = false;
207                                 } else {
208                                         if (buf->getUser())
209                                                 buf->getUser()->owner()->allowInput();
210                                         return false;
211                                 }
212                                 break;
213                         case 2:
214                                 if (buf->isUnnamed()) {
215                                         removeAutosaveFile(buf->fileName());
216                                 }
217                                 reask = false;
218                                 break;
219                         case 3: // Cancel
220                                 if (buf->getUser())
221                                         buf->getUser()->owner()->allowInput();
222                                 return false;
223                         }
224                 }
225                 if (buf->getUser())
226                         buf->getUser()->owner()->allowInput();
227         }
228
229         bstore.release(buf);
230         return true;
231 }
232
233
234 vector<string> const BufferList::getFileNames() const
235 {
236         vector<string> nvec;
237         std::copy(bstore.begin(), bstore.end(),
238                   lyx::back_inserter_fun(nvec, &Buffer::fileName));
239         return nvec;
240 }
241
242
243 Buffer * BufferList::first()
244 {
245         if (bstore.empty()) return 0;
246         return bstore.front();
247 }
248
249
250 Buffer * BufferList::getBuffer(unsigned int choice)
251 {
252         if (choice >= bstore.size()) return 0;
253         return bstore[choice];
254 }
255
256
257 int BufferList::unlockInset(UpdatableInset * inset)
258 {
259         lyx::Assert(inset);
260         
261         BufferStorage::iterator it = bstore.begin();
262         BufferStorage::iterator end = bstore.end();
263         for (; it != end; ++it) {
264                 if ((*it)->getUser()
265                     && (*it)->getUser()->theLockingInset() == inset) {
266                         (*it)->getUser()->insetUnlock();
267                         return 0;
268                 }
269         }
270         return 1;
271 }
272
273
274 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
275 {
276         BufferStorage::iterator it = bstore.begin();
277         BufferStorage::iterator end = bstore.end();
278         for (; it != end; ++it) {
279                 if (!(*it)->isDepClean(mastertmpdir)) {
280                         string writefile = mastertmpdir;
281                         writefile += '/';
282                         writefile += (*it)->getLatexName();
283                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
284                                              false, true);
285                         (*it)->markDepClean(mastertmpdir);
286                 }
287         }
288 }
289
290
291 void BufferList::emergencyWriteAll()
292 {
293         for_each(bstore.begin(), bstore.end(),
294                  lyx::class_fun(*this, &BufferList::emergencyWrite));
295 }
296
297
298 void BufferList::emergencyWrite(Buffer * buf) 
299 {
300         // assert(buf) // this is not good since C assert takes an int
301                        // and a pointer is a long (JMarc)
302         assert(buf != 0); // use c assert to avoid a loop
303
304         
305         // No need to save if the buffer has not changed.
306         if (buf->isLyxClean())
307                 return;
308         
309         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
310                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
311                       : buf->fileName().c_str()) << endl;
312         
313         // We try to save three places:
314
315         // 1) Same place as document. Unless it is an unnamed doc.
316         if (!buf->isUnnamed()) {
317                 string s = buf->fileName();
318                 s += ".emergency";
319                 lyxerr << "  " << s << endl;
320                 if (buf->writeFile(s, true)) {
321                         buf->markLyxClean();
322                         lyxerr << _("  Save seems successful. Phew.") << endl;
323                         return;
324                 } else {
325                         lyxerr << _("  Save failed! Trying...") << endl;
326                 }
327         }
328         
329         // 2) In HOME directory.
330         string s = AddName(GetEnvPath("HOME"), buf->fileName());
331         s += ".emergency";
332         lyxerr << " " << s << endl;
333         if (buf->writeFile(s, true)) {
334                 buf->markLyxClean();
335                 lyxerr << _("  Save seems successful. Phew.") << endl;
336                 return;
337         }
338         
339         lyxerr << _("  Save failed! Trying...") << endl;
340         
341         // 3) In "/tmp" directory.
342         // MakeAbsPath to prepend the current
343         // drive letter on OS/2
344         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
345         s += ".emergency";
346         lyxerr << " " << s << endl;
347         if (buf->writeFile(s, true)) {
348                 buf->markLyxClean();
349                 lyxerr << _("  Save seems successful. Phew.") << endl;
350                 return;
351         }
352         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
353 }
354
355
356
357 Buffer * BufferList::readFile(string const & s, bool ronly)
358 {
359         string ts(s);
360         string e = OnlyPath(s);
361         string a = e;
362         // File information about normal file
363         FileInfo fileInfo2(s);
364
365         if (!fileInfo2.exist()) {
366                 Alert::alert(_("Error!"), _("Cannot open file"), 
367                         MakeDisplayPath(s));
368                 return 0;
369         }
370  
371         Buffer * b = bstore.newBuffer(s, ronly);
372
373         // Check if emergency save file exists and is newer.
374         e += OnlyFilename(s) + ".emergency";
375         FileInfo fileInfoE(e);
376
377         bool use_emergency = false;
378
379         if (fileInfoE.exist() && fileInfo2.exist()) {
380                 if (fileInfoE.getModificationTime()
381                     > fileInfo2.getModificationTime()) {
382                         if (Alert::askQuestion(_("An emergency save of this document exists!"),
383                                         MakeDisplayPath(s, 50),
384                                         _("Try to load that instead?"))) {
385                                 ts = e;
386                                 // the file is not saved if we load the
387                                 // emergency file.
388                                 b->markDirty();
389                                 use_emergency = true;
390                         } else {
391                                 // Here, we should delete the emergency save
392                                 lyx::unlink(e);
393                         }
394                 }
395         }
396
397         if (!use_emergency) {
398                 // Now check if autosave file is newer.
399                 a += '#';
400                 a += OnlyFilename(s);
401                 a += '#';
402                 FileInfo fileInfoA(a);
403                 if (fileInfoA.exist() && fileInfo2.exist()) {
404                         if (fileInfoA.getModificationTime()
405                             > fileInfo2.getModificationTime()) {
406                                 if (Alert::askQuestion(_("Autosave file is newer."),
407                                                 MakeDisplayPath(s, 50),
408                                                 _("Load that one instead?"))) {
409                                         ts = a;
410                                         // the file is not saved if we load the
411                                         // autosave file.
412                                         b->markDirty();
413                                 } else {
414                                         // Here, we should delete the autosave
415                                         lyx::unlink(a);
416                                 }
417                         }
418                 }
419         }
420         // not sure if this is the correct place to begin LyXLex
421         LyXLex lex(0, 0);
422         lex.setFile(ts);
423         if (b->readFile(lex))
424                 return b;
425         else {
426                 bstore.release(b);
427                 return 0;
428         }
429 }
430
431
432 bool BufferList::exists(string const & s) const
433 {
434         return find_if(bstore.begin(), bstore.end(),
435                        lyx::compare_memfun(&Buffer::fileName, s))
436                 != bstore.end();
437 }
438
439
440 bool BufferList::isLoaded(Buffer const * b) const
441 {
442         lyx::Assert(b);
443         
444         BufferStorage::const_iterator cit =
445                 find(bstore.begin(), bstore.end(), b);
446         return cit != bstore.end();
447 }
448
449
450 Buffer * BufferList::getBuffer(string const & s)
451 {
452         BufferStorage::iterator it =
453                 find_if(bstore.begin(), bstore.end(),
454                         lyx::compare_memfun(&Buffer::fileName, s));
455         return it != bstore.end() ? (*it) : 0;
456 }
457
458
459 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
460 {
461         // get a free buffer
462         Buffer * b = bstore.newBuffer(name);
463
464         // use defaults.lyx as a default template if it exists.
465         if (tname.empty()) {
466                 tname = LibFileSearch("templates", "defaults.lyx");
467         }
468         if (!tname.empty()) {
469                 bool templateok = false;
470                 LyXLex lex(0, 0);
471                 lex.setFile(tname);
472                 if (lex.isOK()) {
473                         if (b->readFile(lex)) {
474                                 templateok = true;
475                         }
476                 }
477                 if (!templateok) {
478                         Alert::alert(_("Error!"), _("Unable to open template"), 
479                                    MakeDisplayPath(tname));
480                         // no template, start with empty buffer
481                         b->paragraph = new Paragraph;
482                 }
483         } else {  // start with empty buffer
484                 b->paragraph = new Paragraph;
485         }
486
487         if (!lyxrc.new_ask_filename && !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 }