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