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