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