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