1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich,
7 * Copyright 1995-2001 The LyX Team.
9 * ====================================================== */
16 #include "bufferlist.h"
17 #include "bufferview_funcs.h"
19 #include "lastfiles.h"
23 #include "BufferView.h"
25 #include "insets/insetlabel.h"
27 #include "frontends/lyx_gui.h"
28 #include "frontends/LyXView.h"
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
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"
39 #include "BoostFormat.h"
50 using std::back_inserter;
51 using std::istream_iterator;
55 extern BufferList bufferlist;
56 // this should be static, but I need it in buffer.C
57 bool quitting; // flag, that we are quitting the program
60 void ShowMessage(Buffer const * buf,
66 && buf && buf->getUser() && buf->getUser()->owner()) {
67 string const str = msg1 + ' ' + msg2 + ' ' + msg3;
68 buf->getUser()->owner()->message(str);
70 lyxerr << msg1 << msg2 << msg3 << endl;
78 bool MenuWrite(BufferView * bv, Buffer * buffer)
81 lastfiles->newFile(buffer->fileName());
85 // FIXME: we don't tell the user *WHY* the save failed !!
87 string const file = MakeDisplayPath(buffer->fileName(), 30);
90 boost::format fmt(_("The document %1$s could not be saved.\n\nDo you want to rename the document and try again?"));
92 string text = fmt.str();
94 string text = _("The document ");
95 text += file + _(" could not be saved.\n\nDo you want to rename the document and try again?");
97 int const ret = Alert::prompt(_("Rename and save?"),
98 text, 0, _("&Rename"), _("&Cancel"));
101 return WriteAs(bv, buffer);
107 bool WriteAs(BufferView * bv, Buffer * buffer, string const & filename)
109 string fname = buffer->fileName();
110 string const oldname = fname;
112 if (filename.empty()) {
114 FileDialog fileDlg(_("Choose a filename to save document as"),
116 make_pair(string(_("Documents|#o#O")),
117 string(lyxrc.document_path)),
118 make_pair(string(_("Templates|#T#t")),
119 string(lyxrc.template_path)));
121 if (!IsLyXFilename(fname))
124 FileDialog::Result result =
125 fileDlg.save(OnlyPath(fname),
126 _("*.lyx| LyX Documents (*.lyx)"),
127 OnlyFilename(fname));
129 if (result.first == FileDialog::Later)
132 fname = result.second;
137 // Make sure the absolute filename ends with appropriate suffix
138 fname = MakeAbsPath(fname);
139 if (!IsLyXFilename(fname))
144 FileInfo const myfile(fname);
146 string const file = MakeDisplayPath(fname, 30);
149 boost::format fmt(_("The document %1$s already exists.\n\nDo you want to over-write that document?"));
151 string text = fmt.str();
153 string text = _("The document ");
154 text += file + _(" already exists.\n\nDo you want to over-write that document?");
156 int const ret = Alert::prompt(_("Over-write document?"),
157 text, 1, _("&Over-write"), _("&Cancel"));
163 // Ok, change the name of the buffer
164 buffer->setFileName(fname);
166 bool unnamed = buffer->isUnnamed();
167 buffer->setUnnamed(false);
169 if (!MenuWrite(bv, buffer)) {
170 buffer->setFileName(oldname);
171 buffer->setUnnamed(unnamed);
175 removeAutosaveFile(oldname);
182 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
185 if (!bufferlist.quitWriteAll())
188 lastfiles->writeFile(lyxrc.lastfiles);
191 // Set a flag that we do quitting from the program,
192 // so no refreshes are necessary.
195 // close buffers first
196 bufferlist.closeAll();
198 // do any other cleanup procedures now
199 lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
201 if (destroyDir(system_tempdir) != 0) {
203 boost::format fmt = _("Could not remove the temporary directory %1$s");
204 fmt % system_tempdir;
205 string msg = fmt.str();
207 string msg = _("Could not remove the temporary directory ") + system_tempdir;
209 Alert::warning(_("Could not remove temporary directory"), msg);
218 class AutoSaveBuffer : public ForkedProcess {
221 AutoSaveBuffer(BufferView & bv, string const & fname)
222 : bv_(bv), fname_(fname) {}
224 virtual ForkedProcess * clone() const {
225 return new AutoSaveBuffer(*this);
231 virtual int generateChild();
238 int AutoSaveBuffer::start()
241 command_ = boost::io::str(boost::format(_("Auto-saving %1$s")) % fname_);
243 command_ = _("Auto-saving ") + fname_;
245 return runNonBlocking();
249 int AutoSaveBuffer::generateChild()
251 // tmp_ret will be located (usually) in /tmp
252 // will that be a problem?
253 pid_t const pid = fork(); // If you want to debug the autosave
254 // you should set pid to -1, and comment out the
256 if (pid == 0 || pid == -1) {
257 // pid = -1 signifies that lyx was unable
258 // to fork. But we will do the save
262 string const tmp_ret = lyx::tempName(string(), "lyxauto");
263 if (!tmp_ret.empty()) {
264 bv_.buffer()->writeFile(tmp_ret);
265 // assume successful write of tmp_ret
266 if (!lyx::rename(tmp_ret, fname_)) {
268 // most likely couldn't move between filesystems
269 // unless write of tmp_ret failed
270 // so remove tmp file (if it exists)
271 lyx::unlink(tmp_ret);
278 // failed to write/rename tmp_ret so try writing direct
279 if (!bv_.buffer()->writeFile(fname_)) {
280 // It is dangerous to do this in the child,
281 // but safe in the parent, so...
283 bv_.owner()->message(_("Autosave failed!"));
286 if (pid == 0) { // we are the child so...
296 void AutoSave(BufferView * bv)
297 // should probably be moved into BufferList (Lgb)
298 // Perfect target for a thread...
300 if (!bv->available())
303 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
304 // We don't save now, but we'll try again later
305 bv->owner()->resetAutosaveTimer();
309 bv->owner()->message(_("Autosaving current document..."));
311 // create autosave filename
312 string fname = bv->buffer()->filePath();
314 fname += OnlyFilename(bv->buffer()->fileName());
317 AutoSaveBuffer autosave(*bv, fname);
320 bv->buffer()->markBakClean();
321 bv->owner()->resetAutosaveTimer();
326 // Copyright CHT Software Service GmbH
329 // create new file with template
332 Buffer * NewFile(string const & filename)
334 // Split argument by :
336 string tmpname = split(filename, name, ':');
337 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
338 if (name.length() == 1
339 && isalpha(static_cast<unsigned char>(name[0]))
340 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
342 name += token(tmpname, ':', 0);
343 tmpname = split(tmpname, ':');
346 lyxerr[Debug::INFO] << "Arg is " << filename
347 << "\nName is " << name
348 << "\nTemplate is " << tmpname << endl;
350 // find a free buffer
351 Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
353 lastfiles->newFile(tmpbuf->fileName());
358 // Insert ascii file (if filename is empty, prompt for one)
359 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
361 if (!bv->available())
364 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
371 // clear the selection
372 bool flag = (bv->text == bv->getLyXText());
374 bv->beforeChange(bv->text);
376 bv->getLyXText()->insertStringAsLines(tmpstr);
378 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
380 bv->update(BufferView::SELECT);
384 // Insert ascii file (if filename is empty, prompt for one)
385 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
390 FileDialog fileDlg(_("Select file to insert"),
391 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
393 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
395 if (result.first == FileDialog::Later)
398 fname = result.second;
406 if (!fi.readable()) {
407 string const error = strerror(errno);
408 string const file = MakeDisplayPath(fname, 50);
410 boost::format fmt(_("Could not read the specified document\n%1$s\ndue to the error: %2$s"));
413 string text = fmt.str();
415 string text = _("Could not read the specified document\n");
416 text += file + _(" due to the error: ");
419 Alert::error(_("Could not read file"), text);
423 ifstream ifs(fname.c_str());
425 string const error = strerror(errno);
426 string const file = MakeDisplayPath(fname, 50);
428 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
431 string text = fmt.str();
433 string text = _("Could not open the specified document\n");
434 text += file + _(" due to the error: ");
437 Alert::error(_("Could not open file"), text);
441 ifs.unsetf(ios::skipws);
442 istream_iterator<char> ii(ifs);
443 istream_iterator<char> end;
444 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
445 // We use this until the compilers get better...
447 copy(ii, end, back_inserter(tmp));
448 string const tmpstr(tmp.begin(), tmp.end());
450 // This is what we want to use and what we will use once the
451 // compilers get good enough.
452 //string tmpstr(ii, end); // yet a reason for using std::string
453 // alternate approach to get the file into a string:
455 copy(ii, end, back_inserter(tmpstr));
462 string const getPossibleLabel(BufferView const & bv)
464 Paragraph * par = bv.getLyXText()->cursor.par();
465 LyXLayout_ptr layout = par->layout();
466 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
467 Paragraph * par2 = par->previous();
469 LyXLayout_ptr const & layout2 = par2->layout();
471 if (layout2->latextype != LATEX_PARAGRAPH) {
477 string text = layout->latexname().substr(0, 3);
478 if (layout->latexname() == "theorem")
479 text = "thm"; // Create a correct prefix for prettyref
482 if (layout->latextype == LATEX_PARAGRAPH ||
483 lyxrc.label_init_length < 0)
486 string par_text = par->asString(bv.buffer(), false);
487 for (int i = 0; i < lyxrc.label_init_length; ++i) {
488 if (par_text.empty())
491 par_text = split(par_text, head, ' ');
493 text += '-'; // Is it legal to use spaces in
502 // This function runs "configure" and then rereads lyx.defaults to
503 // reconfigure the automatic settings.
504 void Reconfigure(BufferView * bv)
506 bv->owner()->message(_("Running configure..."));
508 // Run configure in user lyx directory
511 one.startscript(Systemcall::Wait,
512 AddName(system_lyxdir, "configure"));
514 bv->owner()->message(_("Reloading configuration..."));
515 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
517 Alert::information(_("System reconfigured"),
518 _("The system has been reconfigured.\n"
519 "You need to restart LyX to make use of any \n"
520 "updated document class specifications."));