]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
include shuffling and a mathed compile fix
[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 "lyx_gui_misc.h"
24 #include "lastfiles.h"
25 #include "debug.h"
26 #include "lyxrc.h"
27 #include "lyxtext.h"
28 #include "lyx_cb.h"
29 #include "bufferview_funcs.h"
30 #include "BufferView.h"
31 #include "gettext.h"
32 #include "LyXView.h"
33 #include "vc-backend.h"
34 #include "TextCache.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 <assert.h>
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, 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         for (BufferStorage::iterator it = bstore.begin();
141              it != bstore.end(); ++it)
142         {
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()) buf->getUser()->insetUnlock();
186         if (buf->paragraph && !buf->isLyxClean() && !quitting) {
187                 if (buf->getUser())
188                         buf->getUser()->owner()->prohibitInput();
189                 string fname;
190                 if (buf->isUnnamed())
191                         fname = OnlyFilename(buf->fileName());
192                 else
193                         fname = MakeDisplayPath(buf->fileName(), 50);
194                 bool reask = true;
195                 while (reask) {
196                         switch (Alert::askConfirmation(_("Changes in document:"),
197                                                fname,
198                                                _("Save document?"))){
199                         case 1: // Yes
200                                 if (buf->isUnnamed())
201                                         reask = !WriteAs(current_view, buf);
202                                 else if (buf->save()) {
203                                         lastfiles->newFile(buf->fileName());
204                                         reask = false;
205                                 } else {
206                                         if (buf->getUser())
207                                                 buf->getUser()->owner()->allowInput();
208                                         return false;
209                                 }
210                                 break;
211                         case 2:
212                                 if (buf->isUnnamed()) {
213                                         removeAutosaveFile(buf->fileName());
214                                 }
215                                 reask = false;
216                                 break;
217                         case 3: // Cancel
218                                 if (buf->getUser())
219                                         buf->getUser()->owner()->allowInput();
220                                 return false;
221                         }
222                 }
223                 if (buf->getUser())
224                         buf->getUser()->owner()->allowInput();
225         }
226
227         bstore.release(buf);
228         return true;
229 }
230
231
232 vector<string> const BufferList::getFileNames() const
233 {
234         vector<string> nvec;
235         std::copy(bstore.begin(), bstore.end(),
236                   lyx::back_inserter_fun(nvec, &Buffer::fileName));
237         return nvec;
238 }
239
240
241 Buffer * BufferList::first()
242 {
243         if (bstore.empty()) return 0;
244         return bstore.front();
245 }
246
247
248 Buffer * BufferList::getBuffer(unsigned int choice)
249 {
250         if (choice >= bstore.size()) return 0;
251         return bstore[choice];
252 }
253
254
255 int BufferList::unlockInset(UpdatableInset * inset)
256 {
257         lyx::Assert(inset);
258         
259         //if (!inset) return 1;
260         for (BufferStorage::iterator it = bstore.begin();
261              it != bstore.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         for (BufferStorage::iterator it = bstore.begin();
275              it != bstore.end(); ++it) {
276                 if (!(*it)->isDepClean(mastertmpdir)) {
277                         string writefile = mastertmpdir;
278                         writefile += '/';
279                         writefile += (*it)->getLatexName();
280                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
281                                              false, true);
282                         (*it)->markDepClean(mastertmpdir);
283                 }
284         }
285 }
286
287
288 void BufferList::emergencyWriteAll()
289 {
290         for_each(bstore.begin(), bstore.end(),
291                  lyx::class_fun(*this, &BufferList::emergencyWrite));
292 }
293
294
295 void BufferList::emergencyWrite(Buffer * buf) 
296 {
297         // assert(buf) // this is not good since C assert takes an int
298                        // and a pointer is a long (JMarc)
299         assert(buf != 0); // use c assert to avoid a loop
300
301         
302         // No need to save if the buffer has not changed.
303         if (buf->isLyxClean()) return;
304         
305         lyxerr << fmt(_("lyx: Attempting to save document %s as..."),
306                       buf->isUnnamed() ? OnlyFilename(buf->fileName()).c_str()
307                       : buf->fileName().c_str()) << endl;
308         
309         // We try to save three places:
310
311         // 1) Same place as document. Unless it is an unnamed doc.
312         if (!buf->isUnnamed()) {
313                 string s = buf->fileName();
314                 s += ".emergency";
315                 lyxerr << "  " << s << endl;
316                 if (buf->writeFile(s, true)) {
317                         buf->markLyxClean();
318                         lyxerr << _("  Save seems successful. Phew.") << endl;
319                         return;
320                 } else {
321                         lyxerr << _("  Save failed! Trying...") << endl;
322                 }
323         }
324         
325         // 2) In HOME directory.
326         string s = AddName(GetEnvPath("HOME"), buf->fileName());
327         s += ".emergency";
328         lyxerr << " " << s << endl;
329         if (buf->writeFile(s, true)) {
330                 buf->markLyxClean();
331                 lyxerr << _("  Save seems successful. Phew.") << endl;
332                 return;
333         }
334         
335         lyxerr << _("  Save failed! Trying...") << endl;
336         
337         // 3) In "/tmp" directory.
338         // MakeAbsPath to prepend the current
339         // drive letter on OS/2
340         s = AddName(MakeAbsPath("/tmp/"), buf->fileName());
341         s += ".emergency";
342         lyxerr << " " << s << endl;
343         if (buf->writeFile(s, true)) {
344                 buf->markLyxClean();
345                 lyxerr << _("  Save seems successful. Phew.") << endl;
346                 return;
347         }
348         lyxerr << _("  Save failed! Bummer. Document is lost.") << endl;
349 }
350
351
352
353 Buffer * BufferList::readFile(string const & s, bool ronly)
354 {
355         Buffer * b = bstore.newBuffer(s, 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         // Check if emergency save file exists and is newer.
370         e += OnlyFilename(s) + ".emergency";
371         FileInfo fileInfoE(e);
372
373         bool use_emergency = false;
374
375         if (fileInfoE.exist() && fileInfo2.exist()) {
376                 if (fileInfoE.getModificationTime()
377                     > fileInfo2.getModificationTime()) {
378                         if (Alert::askQuestion(_("An emergency save of this document exists!"),
379                                         MakeDisplayPath(s, 50),
380                                         _("Try to load that instead?"))) {
381                                 ts = e;
382                                 // the file is not saved if we load the
383                                 // emergency file.
384                                 b->markDirty();
385                                 use_emergency = true;
386                         } else {
387                                 // Here, we should delete the emergency save
388                                 lyx::unlink(e);
389                         }
390                 }
391         }
392
393         if (!use_emergency) {
394                 // Now check if autosave file is newer.
395                 a += '#';
396                 a += OnlyFilename(s);
397                 a += '#';
398                 FileInfo fileInfoA(a);
399                 if (fileInfoA.exist() && fileInfo2.exist()) {
400                         if (fileInfoA.getModificationTime()
401                             > fileInfo2.getModificationTime()) {
402                                 if (Alert::askQuestion(_("Autosave file is newer."),
403                                                 MakeDisplayPath(s, 50),
404                                                 _("Load that one instead?"))) {
405                                         ts = a;
406                                         // the file is not saved if we load the
407                                         // autosave file.
408                                         b->markDirty();
409                                 } else {
410                                         // Here, we should delete the autosave
411                                         lyx::unlink(a);
412                                 }
413                         }
414                 }
415         }
416         // not sure if this is the correct place to begin LyXLex
417         LyXLex lex(0, 0);
418         lex.setFile(ts);
419         if (b->readFile(lex))
420                 return b;
421         else {
422                 bstore.release(b);
423                 return 0;
424         }
425 }
426
427
428 bool BufferList::exists(string const & s) const
429 {
430         return find_if(bstore.begin(), bstore.end(),
431                        lyx::compare_memfun(&Buffer::fileName, s))
432                 != bstore.end();
433 }
434
435
436 bool BufferList::isLoaded(Buffer const * b) const
437 {
438         lyx::Assert(b);
439         
440         BufferStorage::const_iterator cit =
441                 find(bstore.begin(), bstore.end(), b);
442         return cit != bstore.end();
443 }
444
445
446 Buffer * BufferList::getBuffer(string const & s)
447 {
448         BufferStorage::iterator it =
449                 find_if(bstore.begin(), bstore.end(),
450                         lyx::compare_memfun(&Buffer::fileName, s));
451         return it != bstore.end() ? (*it) : 0;
452 }
453
454
455 Buffer * BufferList::newFile(string const & name, string tname, bool isNamed)
456 {
457         // get a free buffer
458         Buffer * b = bstore.newBuffer(name);
459
460         // use defaults.lyx as a default template if it exists.
461         if (tname.empty()) {
462                 tname = LibFileSearch("templates", "defaults.lyx");
463         }
464         if (!tname.empty()) {
465                 bool templateok = false;
466                 LyXLex lex(0, 0);
467                 lex.setFile(tname);
468                 if (lex.isOK()) {
469                         if (b->readFile(lex)) {
470                                 templateok = true;
471                         }
472                 }
473                 if (!templateok) {
474                         Alert::alert(_("Error!"), _("Unable to open template"), 
475                                    MakeDisplayPath(tname));
476                         // no template, start with empty buffer
477                         b->paragraph = new Paragraph;
478                 }
479         } else {  // start with empty buffer
480                 b->paragraph = new Paragraph;
481         }
482
483         if (!lyxrc.new_ask_filename && !isNamed) {
484                 b->setUnnamed();
485                 b->setFileName(name);
486         }
487
488         b->setReadonly(false);
489         
490         return b;
491 }
492
493
494 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
495 {
496         // get absolute path of file and add ".lyx" to the filename if
497         // necessary
498         string s = FileSearch(string(), filename, "lyx");
499         if (s.empty()) {
500                 s = filename;
501         }
502
503         // file already open?
504         if (exists(s)) {
505                 if (Alert::askQuestion(_("Document is already open:"), 
506                                 MakeDisplayPath(s, 50),
507                                 _("Do you want to reload that document?"))) {
508                         // Reload is accomplished by closing and then loading
509                         if (!close(getBuffer(s))) {
510                                 return 0;
511                         }
512                         // Fall through to new load. (Asger)
513                 } else {
514                         // Here, we pretend that we just loaded the 
515                         // open document
516                         return getBuffer(s);
517                 }
518         }
519         Buffer * b = 0;
520         bool ro = false;
521         switch (IsFileWriteable(s)) {
522         case 0:
523                 ro = true;
524                 // Fall through
525         case 1:
526                 b = readFile(s, ro);
527                 if (b) {
528                         b->lyxvc.file_found_hook(s);
529                 }
530                 break; //fine- it's r/w
531         case -1:
532                 // Here we probably should run
533                 if (LyXVC::file_not_found_hook(s)) {
534                         // Ask if the file should be checked out for
535                         // viewing/editing, if so: load it.
536                         if (Alert::askQuestion(_("Do you want to retrieve file under version control?"))) {
537                                 // How can we know _how_ to do the checkout?
538                                 // With the current VC support it has to be,
539                                 // a RCS file since CVS do not have special ,v files.
540                                 RCS::retrive(s);
541                                 return loadLyXFile(filename, tolastfiles);
542                         }
543                 }
544                 if (Alert::askQuestion(_("Cannot open specified file:"), 
545                                 MakeDisplayPath(s, 50),
546                                 _("Create new document with this name?")))
547                         {
548                                 // Find a free buffer
549                                 b = newFile(s, string(), true);
550                         }
551                 break;
552         }
553
554         if (b && tolastfiles)
555                 lastfiles->newFile(b->fileName());
556
557         return b;
558 }