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