]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
don't rm emergency saves ever
[lyx.git] / src / lyx_cb.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *          Copyright 1995 Matthias Ettrich,
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyx_cb.h"
14 #include "lyx_main.h"
15 #include "buffer.h"
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
18 #include "debug.h"
19 #include "lastfiles.h"
20 #include "lyxrc.h"
21 #include "lyxtext.h"
22 #include "gettext.h"
23 #include "BufferView.h"
24
25 #include "insets/insetlabel.h"
26
27 #include "frontends/lyx_gui.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
31
32 #include "support/FileInfo.h"
33 #include "support/filetools.h"
34 #include "support/forkedcall.h"
35 #include "support/path.h"
36 #include "support/systemcall.h"
37 #include "support/lstrings.h"
38
39 #include "support/BoostFormat.h"
40
41 #include <fstream>
42 #include <algorithm>
43 #include <utility>
44 #include <cerrno>
45
46 using std::vector;
47 using std::ifstream;
48 using std::copy;
49 using std::endl;
50 using std::ios;
51 using std::back_inserter;
52 using std::istream_iterator;
53 using std::pair;
54 using std::make_pair;
55
56 extern BufferList bufferlist;
57 // this should be static, but I need it in buffer.C
58 bool quitting;  // flag, that we are quitting the program
59
60
61 void ShowMessage(Buffer const * buf,
62                  string const & msg1,
63                  string const & msg2,
64                  string const & msg3)
65 {
66         if (lyx_gui::use_gui
67             && buf && buf->getUser() && buf->getUser()->owner()) {
68                         string const str = msg1 + ' ' + msg2 + ' ' + msg3;
69                         buf->getUser()->owner()->message(str);
70         } else
71                 lyxerr << msg1 << msg2 << msg3 << endl;
72 }
73
74
75 //
76 // Menu callbacks
77 //
78
79 bool MenuWrite(BufferView * bv, Buffer * buffer)
80 {
81         if (buffer->save()) {
82                 lastfiles->newFile(buffer->fileName());
83                 return true;
84         }
85
86         // FIXME: we don't tell the user *WHY* the save failed !!
87
88         string const file = MakeDisplayPath(buffer->fileName(), 30);
89
90 #if USE_BOOST_FORMAT
91         boost::format fmt(_("The document %1$s could not be saved.\n\nDo you want to rename the document and try again?"));
92         fmt % file;
93         string text = fmt.str();
94 #else
95         string text = _("The document ");
96         text += file + _(" could not be saved.\n\nDo you want to rename the document and try again?");
97 #endif
98         int const ret = Alert::prompt(_("Rename and save?"),
99                 text, 0, 1, _("&Rename"), _("&Cancel"));
100
101         if (ret == 0)
102                 return WriteAs(bv, buffer);
103         return false;
104 }
105
106
107
108 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
109 {
110         string fname = buffer->fileName();
111         string const oldname = fname;
112
113         if (filename.empty()) {
114
115                 FileDialog fileDlg(_("Choose a filename to save document as"),
116                         LFUN_WRITEAS,
117                         make_pair(string(_("Documents|#o#O")),
118                                   string(lyxrc.document_path)),
119                         make_pair(string(_("Templates|#T#t")),
120                                   string(lyxrc.template_path)));
121
122                 if (!IsLyXFilename(fname))
123                         fname += ".lyx";
124
125                 FileDialog::Result result =
126                         fileDlg.save(OnlyPath(fname),
127                                        _("*.lyx| LyX Documents (*.lyx)"),
128                                        OnlyFilename(fname));
129
130                 if (result.first == FileDialog::Later)
131                         return false;
132
133                 fname = result.second;
134
135                 if (fname.empty())
136                         return false;
137
138                 // Make sure the absolute filename ends with appropriate suffix
139                 fname = MakeAbsPath(fname);
140                 if (!IsLyXFilename(fname))
141                         fname += ".lyx";
142         } else
143                 fname = filename;
144
145         FileInfo const myfile(fname);
146         if (myfile.isOK()) {
147                 string const file = MakeDisplayPath(fname, 30);
148
149 #if USE_BOOST_FORMAT
150                 boost::format fmt(_("The document %1$s already exists.\n\nDo you want to over-write that document?"));
151                 fmt % file;
152                 string text = fmt.str();
153 #else
154                 string text = _("The document ");
155                 text += file + _(" already exists.\n\nDo you want to over-write that document?");
156 #endif
157                 int const ret = Alert::prompt(_("Over-write document?"),
158                         text, 0, 1, _("&Over-write"), _("&Cancel"));
159
160                 if (ret == 1)
161                         return false;
162         }
163
164         // Ok, change the name of the buffer
165         buffer->setFileName(fname);
166         buffer->markDirty();
167         bool unnamed = buffer->isUnnamed();
168         buffer->setUnnamed(false);
169
170         if (!MenuWrite(bv, buffer)) {
171                 buffer->setFileName(oldname);
172                 buffer->setUnnamed(unnamed);
173                 return false;
174         }
175
176         removeAutosaveFile(oldname);
177         return true;
178 }
179
180
181 void QuitLyX()
182 {
183         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
184
185         if (lyx_gui::use_gui) {
186                 if (!bufferlist.quitWriteAll())
187                         return;
188
189                 lastfiles->writeFile(lyxrc.lastfiles);
190         }
191
192         // Set a flag that we do quitting from the program,
193         // so no refreshes are necessary.
194         quitting = true;
195
196         // close buffers first
197         bufferlist.closeAll();
198
199         // do any other cleanup procedures now
200         lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
201
202         if (destroyDir(system_tempdir) != 0) {
203 #if USE_BOOST_FORMAT
204                 boost::format fmt = _("Could not remove the temporary directory %1$s");
205                 fmt % system_tempdir;
206                 string msg = fmt.str();
207 #else
208                 string msg = _("Could not remove the temporary directory ") + system_tempdir;
209 #endif
210                 Alert::warning(_("Could not remove temporary directory"), msg);
211         }
212
213         lyx_gui::exit();
214 }
215
216
217 namespace {
218
219 class AutoSaveBuffer : public ForkedProcess {
220 public:
221         ///
222         AutoSaveBuffer(BufferView & bv, string const & fname)
223                 : bv_(bv), fname_(fname) {}
224         ///
225         virtual ForkedProcess * clone() const {
226                 return new AutoSaveBuffer(*this);
227         }
228         ///
229         int start();
230 private:
231         ///
232         virtual int generateChild();
233         ///
234         BufferView & bv_;
235         string fname_;
236 };
237
238
239 int AutoSaveBuffer::start()
240 {
241 #if USE_BOOST_FORMAT
242         command_ = boost::io::str(boost::format(_("Auto-saving %1$s")) % fname_);
243 #else
244         command_ = _("Auto-saving ") + fname_;
245 #endif
246         return runNonBlocking();
247 }
248
249
250 int AutoSaveBuffer::generateChild()
251 {
252         // tmp_ret will be located (usually) in /tmp
253         // will that be a problem?
254         pid_t const pid = fork(); // If you want to debug the autosave
255         // you should set pid to -1, and comment out the
256         // fork.
257         if (pid == 0 || pid == -1) {
258                 // pid = -1 signifies that lyx was unable
259                 // to fork. But we will do the save
260                 // anyway.
261                 bool failed = false;
262
263                 string const tmp_ret = lyx::tempName(string(), "lyxauto");
264                 if (!tmp_ret.empty()) {
265                         bv_.buffer()->writeFile(tmp_ret);
266                         // assume successful write of tmp_ret
267                         if (!lyx::rename(tmp_ret, fname_)) {
268                                 failed = true;
269                                 // most likely couldn't move between filesystems
270                                 // unless write of tmp_ret failed
271                                 // so remove tmp file (if it exists)
272                                 lyx::unlink(tmp_ret);
273                         }
274                 } else {
275                         failed = true;
276                 }
277
278                 if (failed) {
279                         // failed to write/rename tmp_ret so try writing direct
280                         if (!bv_.buffer()->writeFile(fname_)) {
281                                 // It is dangerous to do this in the child,
282                                 // but safe in the parent, so...
283                                 if (pid == -1)
284                                         bv_.owner()->message(_("Autosave failed!"));
285                         }
286                 }
287                 if (pid == 0) { // we are the child so...
288                         _exit(0);
289                 }
290         }
291         return pid;
292 }
293
294 } // namespace anon
295
296
297 void AutoSave(BufferView * bv)
298         // should probably be moved into BufferList (Lgb)
299         // Perfect target for a thread...
300 {
301         if (!bv->available())
302                 return;
303
304         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
305                 // We don't save now, but we'll try again later
306                 bv->owner()->resetAutosaveTimer();
307                 return;
308         }
309
310         bv->owner()->message(_("Autosaving current document..."));
311
312         // create autosave filename
313         string fname = bv->buffer()->filePath();
314         fname += '#';
315         fname += OnlyFilename(bv->buffer()->fileName());
316         fname += '#';
317
318         AutoSaveBuffer autosave(*bv, fname);
319         autosave.start();
320
321         bv->buffer()->markBakClean();
322         bv->owner()->resetAutosaveTimer();
323 }
324
325
326 //
327 // Copyright CHT Software Service GmbH
328 // Uwe C. Schroeder
329 //
330 // create new file with template
331 // SERVERCMD !
332 //
333 Buffer * NewFile(string const & filename)
334 {
335         // Split argument by :
336         string name;
337         string tmpname = split(filename, name, ':');
338 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
339         if (name.length() == 1
340             && isalpha(static_cast<unsigned char>(name[0]))
341             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
342                 name += ':';
343                 name += token(tmpname, ':', 0);
344                 tmpname = split(tmpname, ':');
345         }
346 #endif
347         lyxerr[Debug::INFO] << "Arg is " << filename
348                             << "\nName is " << name
349                             << "\nTemplate is " << tmpname << endl;
350
351         // find a free buffer
352         Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
353         if (tmpbuf)
354                 lastfiles->newFile(tmpbuf->fileName());
355         return tmpbuf;
356 }
357
358
359 // Insert ascii file (if filename is empty, prompt for one)
360 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
361 {
362         if (!bv->available())
363                 return;
364
365         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
366         if (tmpstr.empty())
367                 return;
368
369         // clear the selection
370         bool flag = (bv->text == bv->getLyXText());
371         if (flag)
372                 bv->beforeChange(bv->text);
373         if (!asParagraph)
374                 bv->getLyXText()->insertStringAsLines(tmpstr);
375         else
376                 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
377         if (flag)
378                 bv->update(BufferView::SELECT);
379 }
380
381
382 // Insert ascii file (if filename is empty, prompt for one)
383 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
384 {
385         string fname = f;
386
387         if (fname.empty()) {
388                 FileDialog fileDlg(_("Select file to insert"),
389                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
390
391                 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
392
393                 if (result.first == FileDialog::Later)
394                         return string();
395
396                 fname = result.second;
397
398                 if (fname.empty())
399                         return string();
400         }
401
402         FileInfo fi(fname);
403
404         if (!fi.readable()) {
405                 string const error = strerror(errno);
406                 string const file = MakeDisplayPath(fname, 50);
407 #if USE_BOOST_FORMAT
408                 boost::format fmt(_("Could not read the specified document\n%1$s\ndue to the error: %2$s"));
409                 fmt % file;
410                 fmt % error;
411                 string text = fmt.str();
412 #else
413                 string text = _("Could not read the specified document\n");
414                 text += file + _(" due to the error: ");
415                 text += error;
416 #endif
417                 Alert::error(_("Could not read file"), text);
418                 return string();
419         }
420
421         ifstream ifs(fname.c_str());
422         if (!ifs) {
423                 string const error = strerror(errno);
424                 string const file = MakeDisplayPath(fname, 50);
425 #if USE_BOOST_FORMAT
426                 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
427                 fmt % file;
428                 fmt % error;
429                 string text = fmt.str();
430 #else
431                 string text = _("Could not open the specified document\n");
432                 text += file + _(" due to the error: ");
433                 text += error;
434 #endif
435                 Alert::error(_("Could not open file"), text);
436                 return string();
437         }
438
439         ifs.unsetf(ios::skipws);
440         istream_iterator<char> ii(ifs);
441         istream_iterator<char> end;
442 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
443         // We use this until the compilers get better...
444         vector<char> tmp;
445         copy(ii, end, back_inserter(tmp));
446         string const tmpstr(tmp.begin(), tmp.end());
447 #else
448         // This is what we want to use and what we will use once the
449         // compilers get good enough.
450         //string tmpstr(ii, end); // yet a reason for using std::string
451         // alternate approach to get the file into a string:
452         string tmpstr;
453         copy(ii, end, back_inserter(tmpstr));
454 #endif
455
456         return tmpstr;
457 }
458
459
460 string const getPossibleLabel(BufferView const & bv)
461 {
462         Paragraph * par = &*bv.getLyXText()->cursor.par();
463         LyXLayout_ptr layout = par->layout();
464         if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
465                 Paragraph * par2 = par->previous();
466
467                 LyXLayout_ptr const & layout2 = par2->layout();
468
469                 if (layout2->latextype != LATEX_PARAGRAPH) {
470                         par = par2;
471                         layout = layout2;
472                 }
473         }
474
475         string text = layout->latexname().substr(0, 3);
476         if (layout->latexname() == "theorem")
477                 text = "thm"; // Create a correct prefix for prettyref
478
479         text += ':';
480         if (layout->latextype == LATEX_PARAGRAPH ||
481             lyxrc.label_init_length < 0)
482                 text.erase();
483
484         string par_text = par->asString(bv.buffer(), false);
485         for (int i = 0; i < lyxrc.label_init_length; ++i) {
486                 if (par_text.empty())
487                         break;
488                 string head;
489                 par_text = split(par_text, head, ' ');
490                 if (i > 0)
491                         text += '-'; // Is it legal to use spaces in
492                 // labels ?
493                 text += head;
494         }
495
496         return text;
497 }
498
499
500 // This function runs "configure" and then rereads lyx.defaults to
501 // reconfigure the automatic settings.
502 void Reconfigure(BufferView * bv)
503 {
504         bv->owner()->message(_("Running configure..."));
505
506         // Run configure in user lyx directory
507         Path p(user_lyxdir);
508         Systemcall one;
509         one.startscript(Systemcall::Wait,
510                         AddName(system_lyxdir, "configure"));
511         p.pop();
512         bv->owner()->message(_("Reloading configuration..."));
513         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
514
515         Alert::information(_("System reconfigured"),
516                 _("The system has been reconfigured.\n"
517                 "You need to restart LyX to make use of any \n"
518                 "updated document class specifications."));
519 }