]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
remove lowercase, better layout handling and some variable renameing
[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()) return 0;
247         return bstore.front();
248 }
249
250
251 Buffer * BufferList::getBuffer(unsigned int choice)
252 {
253         if (choice >= bstore.size()) return 0;
254         return bstore[choice];
255 }
256
257
258 int BufferList::unlockInset(UpdatableInset * inset)
259 {
260         lyx::Assert(inset);
261         
262         BufferStorage::iterator it = bstore.begin();
263         BufferStorage::iterator end = bstore.end();
264         for (; it != end; ++it) {
265                 if ((*it)->getUser()
266                     && (*it)->getUser()->theLockingInset() == inset) {
267                         (*it)->getUser()->insetUnlock();
268                         return 0;
269                 }
270         }
271         return 1;
272 }
273
274
275 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
276 {
277         BufferStorage::iterator it = bstore.begin();
278         BufferStorage::iterator end = bstore.end();
279         for (; it != end; ++it) {
280                 if (!(*it)->isDepClean(mastertmpdir)) {
281                         string writefile = mastertmpdir;
282                         writefile += '/';
283                         writefile += (*it)->getLatexName();
284                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
285                                              false, true);
286                         (*it)->markDepClean(mastertmpdir);
287                 }
288         }
289 }
290
291
292 void BufferList::emergencyWriteAll()
293 {
294         for_each(bstore.begin(), bstore.end(),
295                  lyx::class_fun(*this, &BufferList::emergencyWrite));
296 }
297
298
299 void BufferList::emergencyWrite(Buffer * buf) 
300 {
301         // assert(buf) // this is not good since C assert takes an int
302                        // and a pointer is a long (JMarc)
303         assert(buf != 0); // use c assert to avoid a loop
304
305         
306         // No need to save if the buffer has not changed.
307         if (buf->isLyxClean())
308                 return;
309         
310         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
311                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
312                       : buf->fileName().c_str()) << endl;
313         
314         // We try to save three places:
315
316         // 1) Same place as document. Unless it is an unnamed doc.
317         if (!buf->isUnnamed()) {
318                 string s = buf->fileName();
319                 s += ".emergency";
320                 lyxerr << "  " << s << endl;
321                 if (buf->writeFile(s, true)) {
322                         buf->markLyxClean();
323                         lyxerr << _("  Save seems successful. Phew.") << endl;
324                         return;
325                 } else {
326                         lyxerr << _("  Save failed! Trying...") << endl;
327                 }
328         }
329         
330         // 2) In HOME directory.
331         string s = AddName(GetEnvPath("HOME"), buf->fileName());
332         s += ".emergency";
333         lyxerr << " " << s << endl;
334         if (buf->writeFile(s, true)) {
335                 buf->markLyxClean();
336                 lyxerr << _("  Save seems successful. Phew.") << endl;
337                 return;
338         }
339         
340         lyxerr << _("  Save failed! Trying...") << endl;
341         
342         // 3) In "/tmp" directory.
343         // MakeAbsPath to prepend the current
344         // drive letter on OS/2
345         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
346         s += ".emergency";
347         lyxerr << " " << s << endl;
348         if (buf->writeFile(s, true)) {
349                 buf->markLyxClean();
350                 lyxerr << _("  Save seems successful. Phew.") << endl;
351                 return;
352         }
353         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
354 }
355
356
357
358 Buffer * BufferList::readFile(string const & s, bool ronly)
359 {
360         string ts(s);
361         string e = OnlyPath(s);
362         string a = e;
363         // File information about normal file
364         FileInfo fileInfo2(s);
365
366         if (!fileInfo2.exist()) {
367                 Alert::alert(_("Error!"), _("Cannot open file"), 
368                         MakeDisplayPath(s));
369                 return 0;
370         }
371  
372         Buffer * b = bstore.newBuffer(s, ronly);
373
374         // Check if emergency save file exists and is newer.
375         e += OnlyFilename(s) + ".emergency";
376         FileInfo fileInfoE(e);
377
378         bool use_emergency = false;
379
380         if (fileInfoE.exist() && fileInfo2.exist()) {
381                 if (fileInfoE.getModificationTime()
382                     > fileInfo2.getModificationTime()) {
383                         if (Alert::askQuestion(_("An emergency save of this document exists!"),
384                                         MakeDisplayPath(s, 50),
385                                         _("Try to load that instead?"))) {
386                                 ts = e;
387                                 // the file is not saved if we load the
388                                 // emergency file.
389                                 b->markDirty();
390                                 use_emergency = true;
391                         } else {
392                                 // Here, we should delete the emergency save
393                                 lyx::unlink(e);
394                         }
395                 }
396         }
397
398         if (!use_emergency) {
399                 // Now check if autosave file is newer.
400                 a += '#';
401                 a += OnlyFilename(s);
402                 a += '#';
403                 FileInfo fileInfoA(a);
404                 if (fileInfoA.exist() && fileInfo2.exist()) {
405                         if (fileInfoA.getModificationTime()
406                             > fileInfo2.getModificationTime()) {
407                                 if (Alert::askQuestion(_("Autosave file is newer."),
408                                                 MakeDisplayPath(s, 50),
409                                                 _("Load that one instead?"))) {
410                                         ts = a;
411                                         // the file is not saved if we load the
412                                         // autosave file.
413                                         b->markDirty();
414                                 } else {
415                                         // Here, we should delete the autosave
416                                         lyx::unlink(a);
417                                 }
418                         }
419                 }
420         }
421         // not sure if this is the correct place to begin LyXLex
422         LyXLex lex(0, 0);
423         lex.setFile(ts);
424         if (b->readFile(lex))
425                 return b;
426         else {
427                 bstore.release(b);
428                 return 0;
429         }
430 }
431
432
433 bool BufferList::exists(string const & s) const
434 {
435         return find_if(bstore.begin(), bstore.end(),
436                        lyx::compare_memfun(&Buffer::fileName, s))
437                 != bstore.end();
438 }
439
440
441 bool BufferList::isLoaded(Buffer const * b) const
442 {
443         lyx::Assert(b);
444         
445         BufferStorage::const_iterator cit =
446                 find(bstore.begin(), bstore.end(), b);
447         return cit != bstore.end();
448 }
449
450
451 Buffer * BufferList::getBuffer(string const & s)
452 {
453         BufferStorage::iterator it =
454                 find_if(bstore.begin(), bstore.end(),
455                         lyx::compare_memfun(&Buffer::fileName, s));
456         return it != bstore.end() ? (*it) : 0;
457 }
458
459
460 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
461 {
462         // get a free buffer
463         Buffer * b = bstore.newBuffer(name);
464
465         // use defaults.lyx as a default template if it exists.
466         if (tname.empty()) {
467                 tname = LibFileSearch("templates", "defaults.lyx");
468         }
469         if (!tname.empty()) {
470                 bool templateok = false;
471                 LyXLex lex(0, 0);
472                 lex.setFile(tname);
473                 if (lex.isOK()) {
474                         if (b->readFile(lex)) {
475                                 templateok = true;
476                         }
477                 }
478                 if (!templateok) {
479                         Alert::alert(_("Error!"), _("Unable to open template"), 
480                                    MakeDisplayPath(tname));
481                         // no template, start with empty buffer
482                         b->paragraph = new Paragraph;
483                         b->paragraph->layout(textclasslist[b->params.textclass].defaultLayoutName());
484                 }
485         } else {  // start with empty buffer
486                 b->paragraph = new Paragraph;
487                         b->paragraph->layout(textclasslist[b->params.textclass].defaultLayoutName());
488         }
489
490         if (!lyxrc.new_ask_filename && !isNamed) {
491                 b->setUnnamed();
492                 b->setFileName(name);
493         }
494
495         b->setReadonly(false);
496         
497         return b;
498 }
499
500
501 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
502 {
503         // get absolute path of file and add ".lyx" to the filename if
504         // necessary
505         string s = FileSearch(string(), filename, "lyx");
506         if (s.empty()) {
507                 s = filename;
508         }
509
510         // file already open?
511         if (exists(s)) {
512                 if (Alert::askQuestion(_("Document is already open:"), 
513                                 MakeDisplayPath(s, 50),
514                                 _("Do you want to reload that document?"))) {
515                         // Reload is accomplished by closing and then loading
516                         if (!close(getBuffer(s))) {
517                                 return 0;
518                         }
519                         // Fall through to new load. (Asger)
520                 } else {
521                         // Here, we pretend that we just loaded the 
522                         // open document
523                         return getBuffer(s);
524                 }
525         }
526         Buffer * b = 0;
527         bool ro = false;
528         switch (IsFileWriteable(s)) {
529         case 0:
530                 ro = true;
531                 // Fall through
532         case 1:
533                 b = readFile(s, ro);
534                 if (b) {
535                         b->lyxvc.file_found_hook(s);
536                 }
537                 break; //fine- it's r/w
538         case -1:
539                 // Here we probably should run
540                 if (LyXVC::file_not_found_hook(s)) {
541                         // Ask if the file should be checked out for
542                         // viewing/editing, if so: load it.
543                         if (Alert::askQuestion(_("Do you want to retrieve file under version control?"))) {
544                                 // How can we know _how_ to do the checkout?
545                                 // With the current VC support it has to be,
546                                 // a RCS file since CVS do not have special ,v files.
547                                 RCS::retrieve(s);
548                                 return loadLyXFile(filename, tolastfiles);
549                         }
550                 }
551                 if (Alert::askQuestion(_("Cannot open specified file:"), 
552                                 MakeDisplayPath(s, 50),
553                                 _("Create new document with this name?")))
554                         {
555                                 // Find a free buffer
556                                 b = newFile(s, string(), true);
557                         }
558                 break;
559         }
560
561         if (b && tolastfiles)
562                 lastfiles->newFile(b->fileName());
563
564         return b;
565 }