]> git.lyx.org Git - lyx.git/blob - src/bufferlist.C
small changes to ButtonController usage
[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                                 } else {
196                                         if (buf->getUser())
197                                                 AllowInput(buf->getUser());
198                                         return false;
199                                 }
200                                 break;
201                         case 2:
202                                 if (buf->isUnnamed()) {
203                                         removeAutosaveFile(buf->fileName());
204                                 }
205                                 reask = false;
206                                 break;
207                         case 3: // Cancel
208                                 if (buf->getUser())
209                                         AllowInput(buf->getUser());
210                                 return false;
211                         }
212                 }
213                 if (buf->getUser())
214                         AllowInput(buf->getUser());
215         }
216
217         bstore.release(buf);
218         return true;
219 }
220
221
222 vector<string> BufferList::getFileNames() const
223 {
224         vector<string> nvec;
225         for(BufferStorage::const_iterator cit = bstore.begin();
226             cit != bstore.end(); ++cit) {
227                 nvec.push_back((*cit)->fileName());
228         }
229         return nvec;
230 }
231
232
233 Buffer * BufferList::first()
234 {
235         if (bstore.empty()) return 0;
236         return bstore.front();
237 }
238
239
240 Buffer * BufferList::getBuffer(int choice)
241 {
242         if (choice >= bstore.size()) return 0;
243         return bstore[choice];
244 }
245
246
247 int BufferList::unlockInset(UpdatableInset * inset)
248 {
249         if (!inset) return 1;
250         for(BufferStorage::iterator it = bstore.begin();
251             it != bstore.end(); ++it) {
252                 if ((*it)->getUser()
253                     && (*it)->getUser()->the_locking_inset == inset) {
254                         (*it)->getUser()->insetUnlock();
255                         return 0;
256                 }
257         }
258         return 1;
259 }
260
261
262 void BufferList::updateIncludedTeXfiles(string const & mastertmpdir)
263 {
264         for(BufferStorage::iterator it = bstore.begin();
265             it != bstore.end(); ++it) {
266                 if (!(*it)->isDepClean(mastertmpdir)) {
267                         string writefile = mastertmpdir;
268                         writefile += '/';
269                         writefile += (*it)->getLatexName();
270                         (*it)->makeLaTeXFile(writefile, mastertmpdir,
271                                              false, true);
272                         (*it)->markDepClean(mastertmpdir);
273                 }
274         }
275 }
276
277
278 void BufferList::emergencyWriteAll()
279 {
280         for (BufferStorage::iterator it = bstore.begin();
281              it != bstore.end(); ++it) {
282                 if (!(*it)->isLyxClean()) {
283                         bool madeit = false;
284                         
285                         lyxerr <<_("lyx: Attempting to save"
286                                    " document ");
287                         if ((*it)->isUnnamed())
288                             lyxerr << OnlyFilename((*it)->fileName());
289                         else
290                             lyxerr << (*it)->fileName();
291                         lyxerr << _(" as...") << endl;
292                         
293                         for (int i = 0; i < 3 && !madeit; ++i) {
294                                 string s;
295                                 
296                                 // We try to save three places:
297                                 // 1) Same place as document.
298                                 // 2) In HOME directory.
299                                 // 3) In "/tmp" directory.
300                                 if (i == 0) {
301                                         if ((*it)->isUnnamed())
302                                                 continue;
303                                         s = (*it)->fileName();
304                                 } else if (i == 1) {
305                                         s = AddName(GetEnvPath("HOME"),
306                                                     (*it)->fileName());
307                                 } else {
308                                         // MakeAbsPath to prepend the current
309                                         // drive letter on OS/2
310                                         s = AddName(MakeAbsPath("/tmp/"),
311                                                     (*it)->fileName());
312                                 }
313                                 s += ".emergency";
314                                 
315                                 lyxerr << "  " << i + 1 << ") " << s << endl;
316                                 
317                                 if ((*it)->writeFile(s, true)) {
318                                         (*it)->markLyxClean();
319                                         lyxerr << _("  Save seems successful. "
320                                                     "Phew.") << endl;
321                                         madeit = true;
322                                 } else if (i != 2) {
323                                         lyxerr << _("  Save failed! Trying...")
324                                                << endl;
325                                 } else {
326                                         lyxerr << _("  Save failed! Bummer. "
327                                                     "Document is lost.")
328                                                << endl;
329                                 }
330                         }
331                 }
332         }
333 }
334
335
336 Buffer * BufferList::readFile(string const & s, bool ronly)
337 {
338         Buffer * b = bstore.newBuffer(s, ronly);
339
340         string ts = s;
341         string e = OnlyPath(s);
342         string a = e;
343         // File information about normal file
344         FileInfo fileInfo2(s);
345
346         // Check if emergency save file exists and is newer.
347         e += OnlyFilename(s) + ".emergency";
348         FileInfo fileInfoE(e);
349
350         bool use_emergency = false;
351
352         if (fileInfoE.exist() && fileInfo2.exist()) {
353                 if (fileInfoE.getModificationTime()
354                     > fileInfo2.getModificationTime()) {
355                         if (AskQuestion(_("An emergency save of this document exists!"),
356                                         MakeDisplayPath(s, 50),
357                                         _("Try to load that instead?"))) {
358                                 ts = e;
359                                 // the file is not saved if we load the
360                                 // emergency file.
361                                 b->markDirty();
362                                 use_emergency = true;
363                         } else {
364                                 // Here, we should delete the emergency save
365                                 ::unlink(e.c_str());
366                         }
367                 }
368         }
369
370         if (!use_emergency) {
371                 // Now check if autosave file is newer.
372                 a += '#';
373                 a += OnlyFilename(s);
374                 a += '#';
375                 FileInfo fileInfoA(a);
376                 if (fileInfoA.exist() && fileInfo2.exist()) {
377                         if (fileInfoA.getModificationTime()
378                             > fileInfo2.getModificationTime()) {
379                                 if (AskQuestion(_("Autosave file is newer."),
380                                                 MakeDisplayPath(s, 50),
381                                                 _("Load that one instead?"))) {
382                                         ts = a;
383                                         // the file is not saved if we load the
384                                         // autosave file.
385                                         b->markDirty();
386                                 } else {
387                                         // Here, we should delete the autosave
388                                         ::unlink(a.c_str());
389                                 }
390                         }
391                 }
392         }
393         // not sure if this is the correct place to begin LyXLex
394         LyXLex lex(0, 0);
395         lex.setFile(ts);
396         if (b->readFile(lex))
397                 return b;
398         else {
399                 bstore.release(b);
400                 return 0;
401         }
402 }
403
404
405 bool BufferList::exists(string const & s) const
406 {
407         for (BufferStorage::const_iterator cit = bstore.begin();
408              cit != bstore.end(); ++cit) {
409                 if ((*cit)->fileName() == s)
410                         return true;
411         }
412         return false;
413 }
414
415
416 bool BufferList::isLoaded(Buffer const * b) const
417 {
418         BufferStorage::const_iterator cit =
419                 find(bstore.begin(), bstore.end(), b);
420         return cit != bstore.end();
421 }
422
423
424 Buffer * BufferList::getBuffer(string const & s)
425 {
426         for(BufferStorage::iterator it = bstore.begin();
427             it != bstore.end(); ++it) {
428                 if ((*it)->fileName() == s)
429                         return (*it);
430         }
431         return 0;
432 }
433
434
435 Buffer * BufferList::newFile(string const & name, string tname)
436 {
437         // get a free buffer
438         Buffer * b = bstore.newBuffer(name);
439
440         // use defaults.lyx as a default template if it exists.
441         if (tname.empty()) {
442                 tname = LibFileSearch("templates", "defaults.lyx");
443         }
444         if (!tname.empty() && IsLyXFilename(tname)) {
445                 bool templateok = false;
446                 LyXLex lex(0, 0);
447                 lex.setFile(tname);
448                 if (lex.IsOK()) {
449                         if (b->readFile(lex)) {
450                                 templateok = true;
451                         }
452                 }
453                 if (!templateok) {
454                         WriteAlert(_("Error!"), _("Unable to open template"), 
455                                    MakeDisplayPath(tname));
456                         // no template, start with empty buffer
457                         b->paragraph = new LyXParagraph;
458                 }
459         }
460         else {  // start with empty buffer
461                 b->paragraph = new LyXParagraph;
462         }
463
464 #warning Why mark a new document dirty? I deactivate this (Jug)
465         if (!lyxrc.new_ask_filename) {
466 //              b->markDirty();
467                 b->setUnnamed();
468         }
469         b->setReadonly(false);
470         
471         return b;
472 }
473
474
475 Buffer * BufferList::loadLyXFile(string const & filename, bool tolastfiles)
476 {
477         // make sure our path is absolute
478         string s = MakeAbsPath(filename);
479
480         // file already open?
481         if (exists(s)) {
482                 if (AskQuestion(_("Document is already open:"), 
483                                 MakeDisplayPath(s, 50),
484                                 _("Do you want to reload that document?"))) {
485                         // Reload is accomplished by closing and then loading
486                         if (!close(getBuffer(s))) {
487                                 return 0;
488                         }
489                         // Fall through to new load. (Asger)
490                 } else {
491                         // Here, we pretend that we just loaded the 
492                         // open document
493                         return getBuffer(s);
494                 }
495         }
496         Buffer * b = 0;
497         bool ro = false;
498         switch (IsFileWriteable(s)) {
499         case 0:
500 #if 0
501                 current_view->owner()->getMiniBuffer()->
502                         Set(_("File `") + MakeDisplayPath(s, 50) +
503                             _("' is read-only."));
504 #endif
505                 ro = true;
506                 // Fall through
507         case 1:
508                 b = readFile(s, ro);
509                 if (b) {
510                         b->lyxvc.file_found_hook(s);
511                 }
512                 break; //fine- it's r/w
513         case -1:
514                 // Here we probably should run
515                 if (LyXVC::file_not_found_hook(s)) {
516                         // Ask if the file should be checked out for
517                         // viewing/editing, if so: load it.
518                         if (AskQuestion(_("Do you want to retrieve file under version control?"))) {
519                                 // How can we know _how_ to do the checkout?
520                                 // With the current VC support it has to be,
521                                 // a RCS file since CVS do not have special ,v files.
522                                 RCS::retrive(s);
523                                 return loadLyXFile(filename, tolastfiles);
524                         }
525                 }
526                 if (AskQuestion(_("Cannot open specified file:"), 
527                                 MakeDisplayPath(s, 50),
528                                 _("Create new document with this name?")))
529                         {
530                                 // Find a free buffer
531                                 b = newFile(s, string());
532                         }
533                 break;
534         }
535
536         if (b && tolastfiles)
537                 lastfiles->newFile(b->fileName());
538
539         return b;
540 }