3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Angus Leeming
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
20 #include "bufferlist.h"
21 #include "BufferView.h"
22 #include "buffer_funcs.h"
27 #include "LaTeXFeatures.h"
29 #include "lyxlayout.h"
32 #include "paragraph.h"
34 #include "frontends/Alert.h"
35 #include "frontends/FileDialog.h"
36 #include "frontends/lyx_gui.h"
37 #include "frontends/LyXView.h"
39 #include "support/filefilterlist.h"
40 #include "support/filetools.h"
41 #include "support/forkedcall.h"
42 #include "support/fs_extras.h"
43 #include "support/lyxlib.h"
44 #include "support/package.h"
45 #include "support/path.h"
46 #include "support/systemcall.h"
48 #if !defined (HAVE_FORK)
52 #include <boost/shared_ptr.hpp>
53 #include <boost/filesystem/operations.hpp>
58 using lyx::support::addName;
59 using lyx::support::bformat;
60 using lyx::support::destroyDir;
61 using lyx::support::FileFilterList;
62 using lyx::support::ForkedProcess;
63 using lyx::support::isLyXFilename;
64 using lyx::support::libFileSearch;
65 using lyx::support::makeAbsPath;
66 using lyx::support::makeDisplayPath;
67 using lyx::support::onlyFilename;
68 using lyx::support::onlyPath;
69 using lyx::support::Path;
70 using lyx::support::package;
71 using lyx::support::quoteName;
72 using lyx::support::removeAutosaveFile;
73 using lyx::support::rename;
74 using lyx::support::split;
75 using lyx::support::Systemcall;
76 using lyx::support::tempName;
77 using lyx::support::unlink;
79 using boost::shared_ptr;
81 namespace fs = boost::filesystem;
83 using std::back_inserter;
90 using std::istream_iterator;
93 extern BufferList bufferlist;
94 // this should be static, but I need it in buffer.C
95 bool quitting; // flag, that we are quitting the program
102 bool menuWrite(Buffer * buffer)
104 if (buffer->save()) {
105 LyX::ref().session().addLastFile(buffer->fileName());
109 // FIXME: we don't tell the user *WHY* the save failed !!
111 string const file = makeDisplayPath(buffer->fileName(), 30);
113 string text = bformat(_("The document %1$s could not be saved.\n\n"
114 "Do you want to rename the document and try again?"), file);
115 int const ret = Alert::prompt(_("Rename and save?"),
116 text, 0, 1, _("&Rename"), _("&Cancel"));
119 return writeAs(buffer);
125 bool writeAs(Buffer * buffer, string const & filename)
127 string fname = buffer->fileName();
128 string const oldname = fname;
130 if (filename.empty()) {
132 FileDialog fileDlg(_("Choose a filename to save document as"),
133 LFUN_BUFFER_WRITE_AS,
134 make_pair(string(_("Documents|#o#O")),
135 string(lyxrc.document_path)),
136 make_pair(string(_("Templates|#T#t")),
137 string(lyxrc.template_path)));
139 if (!isLyXFilename(fname))
142 FileFilterList const filter (_("LyX Documents (*.lyx)"));
144 FileDialog::Result result =
145 fileDlg.save(onlyPath(fname),
147 onlyFilename(fname));
149 if (result.first == FileDialog::Later)
152 fname = result.second;
157 // Make sure the absolute filename ends with appropriate suffix
158 fname = makeAbsPath(fname);
159 if (!isLyXFilename(fname))
164 if (fs::exists(fname)) {
165 string const file = makeDisplayPath(fname, 30);
166 string text = bformat(_("The document %1$s already exists.\n\n"
167 "Do you want to over-write that document?"), file);
168 int const ret = Alert::prompt(_("Over-write document?"),
169 text, 0, 1, _("&Over-write"), _("&Cancel"));
175 // Ok, change the name of the buffer
176 buffer->setFileName(fname);
178 bool unnamed = buffer->isUnnamed();
179 buffer->setUnnamed(false);
181 if (!menuWrite(buffer)) {
182 buffer->setFileName(oldname);
183 buffer->setUnnamed(unnamed);
187 removeAutosaveFile(oldname);
192 void quitLyX(bool noask)
194 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
196 if (lyx_gui::use_gui) {
197 if (!noask && !bufferlist.quitWriteAll())
200 LyX::cref().session().writeFile();
203 // Set a flag that we do quitting from the program,
204 // so no refreshes are necessary.
207 // close buffers first
208 bufferlist.closeAll();
210 // do any other cleanup procedures now
211 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
213 if (!destroyDir(package().temp_dir())) {
215 bformat(_("Unable to remove the temporary directory %1$s"),
216 package().temp_dir());
217 Alert::warning(_("Unable to remove temporary directory"), msg);
226 class AutoSaveBuffer : public ForkedProcess {
229 AutoSaveBuffer(BufferView & bv, string const & fname)
230 : bv_(bv), fname_(fname) {}
232 virtual shared_ptr<ForkedProcess> clone() const
234 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
240 virtual int generateChild();
247 int AutoSaveBuffer::start()
249 command_ = bformat(_("Auto-saving %1$s"), fname_);
250 return run(DontWait);
254 int AutoSaveBuffer::generateChild()
256 // tmp_ret will be located (usually) in /tmp
257 // will that be a problem?
258 pid_t const pid = fork(); // If you want to debug the autosave
259 // you should set pid to -1, and comment out the
261 if (pid == 0 || pid == -1) {
262 // pid = -1 signifies that lyx was unable
263 // to fork. But we will do the save
267 string const tmp_ret = tempName(string(), "lyxauto");
268 if (!tmp_ret.empty()) {
269 bv_.buffer()->writeFile(tmp_ret);
270 // assume successful write of tmp_ret
271 if (!rename(tmp_ret, fname_)) {
273 // most likely couldn't move between filesystems
274 // unless write of tmp_ret failed
275 // so remove tmp file (if it exists)
283 // failed to write/rename tmp_ret so try writing direct
284 if (!bv_.buffer()->writeFile(fname_)) {
285 // It is dangerous to do this in the child,
286 // but safe in the parent, so...
288 bv_.owner()->message(_("Autosave failed!"));
291 if (pid == 0) { // we are the child so...
301 void autoSave(BufferView * bv)
302 // should probably be moved into BufferList (Lgb)
303 // Perfect target for a thread...
305 if (!bv->available())
308 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
309 // We don't save now, but we'll try again later
310 bv->owner()->resetAutosaveTimer();
314 bv->owner()->message(_("Autosaving current document..."));
316 // create autosave filename
317 string fname = bv->buffer()->filePath();
319 fname += onlyFilename(bv->buffer()->fileName());
322 AutoSaveBuffer autosave(*bv, fname);
325 bv->buffer()->markBakClean();
326 bv->owner()->resetAutosaveTimer();
331 // Copyright CHT Software Service GmbH
334 // create new file with template
337 void newFile(BufferView * bv, string const & filename)
339 // Split argument by :
341 string tmpname = split(filename, name, ':');
342 lyxerr[Debug::INFO] << "Arg is " << filename
343 << "\nName is " << name
344 << "\nTemplate is " << tmpname << endl;
346 bv->setBuffer(newFile(name, tmpname));
350 // Insert ascii file (if filename is empty, prompt for one)
351 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
353 if (!bv->available())
356 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
360 // clear the selection
361 if (bv->text() == bv->getLyXText())
362 bv->cursor().clearSelection();
364 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
366 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
371 // Insert ascii file (if filename is empty, prompt for one)
372 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
377 FileDialog fileDlg(_("Select file to insert"),
378 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
380 FileDialog::Result result =
381 fileDlg.open(bv->owner()->buffer()->filePath(),
382 FileFilterList(), string());
384 if (result.first == FileDialog::Later)
387 fname = result.second;
393 if (!fs::is_readable(fname)) {
394 string const error = strerror(errno);
395 string const file = makeDisplayPath(fname, 50);
396 string const text = bformat(_("Could not read the specified document\n"
397 "%1$s\ndue to the error: %2$s"), file, error);
398 Alert::error(_("Could not read file"), text);
402 ifstream ifs(fname.c_str());
404 string const error = strerror(errno);
405 string const file = makeDisplayPath(fname, 50);
406 string const text = bformat(_("Could not open the specified document\n"
407 "%1$s\ndue to the error: %2$s"), file, error);
408 Alert::error(_("Could not open file"), text);
412 ifs.unsetf(ios::skipws);
413 istream_iterator<char> ii(ifs);
414 istream_iterator<char> end;
415 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
416 // We use this until the compilers get better...
417 std::vector<char> tmp;
418 copy(ii, end, back_inserter(tmp));
419 string const tmpstr(tmp.begin(), tmp.end());
421 // This is what we want to use and what we will use once the
422 // compilers get good enough.
423 //string tmpstr(ii, end); // yet a reason for using std::string
424 // alternate approach to get the file into a string:
426 copy(ii, end, back_inserter(tmpstr));
433 // This function runs "configure" and then rereads lyx.defaults to
434 // reconfigure the automatic settings.
435 void reconfigure(BufferView * bv)
437 bv->owner()->message(_("Running configure..."));
439 // Run configure in user lyx directory
440 Path p(package().user_support());
441 string const configure_command = package().configure_command();
443 one.startscript(Systemcall::Wait, configure_command);
445 bv->owner()->message(_("Reloading configuration..."));
446 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
447 // Re-read packages.lst
448 LaTeXFeatures::getAvailable();
450 Alert::information(_("System reconfigured"),
451 _("The system has been reconfigured.\n"
452 "You need to restart LyX to make use of any\n"
453 "updated document class specifications."));