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>
59 using lyx::support::addName;
60 using lyx::support::bformat;
61 using lyx::support::destroyDir;
62 using lyx::support::FileFilterList;
63 using lyx::support::ForkedProcess;
64 using lyx::support::isLyXFilename;
65 using lyx::support::libFileSearch;
66 using lyx::support::makeAbsPath;
67 using lyx::support::makeDisplayPath;
68 using lyx::support::onlyFilename;
69 using lyx::support::onlyPath;
70 using lyx::support::Path;
71 using lyx::support::package;
72 using lyx::support::quoteName;
73 using lyx::support::removeAutosaveFile;
74 using lyx::support::rename;
75 using lyx::support::split;
76 using lyx::support::Systemcall;
77 using lyx::support::tempName;
78 using lyx::support::unlink;
80 using boost::shared_ptr;
82 namespace fs = boost::filesystem;
84 using std::back_inserter;
91 using std::istream_iterator;
94 extern BufferList bufferlist;
95 // this should be static, but I need it in buffer.C
96 bool quitting; // flag, that we are quitting the program
103 bool menuWrite(Buffer * buffer)
105 if (buffer->save()) {
106 LyX::ref().session().addLastFile(buffer->fileName());
110 // FIXME: we don't tell the user *WHY* the save failed !!
112 string const file = makeDisplayPath(buffer->fileName(), 30);
114 string text = bformat(_("The document %1$s could not be saved.\n\n"
115 "Do you want to rename the document and try again?"), file);
116 int const ret = Alert::prompt(_("Rename and save?"),
117 text, 0, 1, _("&Rename"), _("&Cancel"));
120 return writeAs(buffer);
126 bool writeAs(Buffer * buffer, string const & filename)
128 string fname = buffer->fileName();
129 string const oldname = fname;
131 if (filename.empty()) {
133 FileDialog fileDlg(_("Choose a filename to save document as"),
134 LFUN_BUFFER_WRITE_AS,
135 make_pair(string(_("Documents|#o#O")),
136 string(lyxrc.document_path)),
137 make_pair(string(_("Templates|#T#t")),
138 string(lyxrc.template_path)));
140 if (!isLyXFilename(fname))
143 FileFilterList const filter (_("LyX Documents (*.lyx)"));
145 FileDialog::Result result =
146 fileDlg.save(onlyPath(fname),
148 onlyFilename(fname));
150 if (result.first == FileDialog::Later)
153 fname = result.second;
158 // Make sure the absolute filename ends with appropriate suffix
159 fname = makeAbsPath(fname);
160 if (!isLyXFilename(fname))
165 if (fs::exists(fname)) {
166 string const file = makeDisplayPath(fname, 30);
167 string text = bformat(_("The document %1$s already exists.\n\n"
168 "Do you want to over-write that document?"), file);
169 int const ret = Alert::prompt(_("Over-write document?"),
170 text, 0, 1, _("&Over-write"), _("&Cancel"));
176 // Ok, change the name of the buffer
177 buffer->setFileName(fname);
179 bool unnamed = buffer->isUnnamed();
180 buffer->setUnnamed(false);
182 if (!menuWrite(buffer)) {
183 buffer->setFileName(oldname);
184 buffer->setUnnamed(unnamed);
188 removeAutosaveFile(oldname);
193 void quitLyX(bool noask)
195 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
197 if (lyx_gui::use_gui) {
198 if (!noask && !bufferlist.quitWriteAll())
201 LyX::cref().session().writeFile();
204 // Set a flag that we do quitting from the program,
205 // so no refreshes are necessary.
208 // close buffers first
209 bufferlist.closeAll();
211 // do any other cleanup procedures now
212 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
214 if (!destroyDir(package().temp_dir())) {
216 bformat(_("Unable to remove the temporary directory %1$s"),
217 package().temp_dir());
218 Alert::warning(_("Unable to remove temporary directory"), msg);
227 class AutoSaveBuffer : public ForkedProcess {
230 AutoSaveBuffer(BufferView & bv, string const & fname)
231 : bv_(bv), fname_(fname) {}
233 virtual shared_ptr<ForkedProcess> clone() const
235 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
241 virtual int generateChild();
248 int AutoSaveBuffer::start()
250 command_ = bformat(_("Auto-saving %1$s"), fname_);
251 return run(DontWait);
255 int AutoSaveBuffer::generateChild()
257 // tmp_ret will be located (usually) in /tmp
258 // will that be a problem?
259 pid_t const pid = fork(); // If you want to debug the autosave
260 // you should set pid to -1, and comment out the
262 if (pid == 0 || pid == -1) {
263 // pid = -1 signifies that lyx was unable
264 // to fork. But we will do the save
268 string const tmp_ret = tempName(string(), "lyxauto");
269 if (!tmp_ret.empty()) {
270 bv_.buffer()->writeFile(tmp_ret);
271 // assume successful write of tmp_ret
272 if (!rename(tmp_ret, fname_)) {
274 // most likely couldn't move between filesystems
275 // unless write of tmp_ret failed
276 // so remove tmp file (if it exists)
284 // failed to write/rename tmp_ret so try writing direct
285 if (!bv_.buffer()->writeFile(fname_)) {
286 // It is dangerous to do this in the child,
287 // but safe in the parent, so...
289 // emit message signal.
290 bv_.buffer()->message(_("Autosave failed!"));
293 if (pid == 0) { // we are the child so...
303 void autoSave(BufferView * bv)
304 // should probably be moved into BufferList (Lgb)
305 // Perfect target for a thread...
307 if (!bv->available())
310 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
311 // We don't save now, but we'll try again later
312 bv->owner()->resetAutosaveTimer();
316 // emit message signal.
317 bv->buffer()->message(_("Autosaving current document..."));
319 // create autosave filename
320 string fname = bv->buffer()->filePath();
322 fname += onlyFilename(bv->buffer()->fileName());
325 AutoSaveBuffer autosave(*bv, fname);
328 bv->buffer()->markBakClean();
329 bv->owner()->resetAutosaveTimer();
334 // Copyright CHT Software Service GmbH
337 // create new file with template
340 void newFile(BufferView * bv, string const & filename)
342 // Split argument by :
344 string tmpname = split(filename, name, ':');
345 lyxerr[Debug::INFO] << "Arg is " << filename
346 << "\nName is " << name
347 << "\nTemplate is " << tmpname << endl;
349 Buffer * const b = newFile(name, tmpname);
355 // Insert ascii file (if filename is empty, prompt for one)
356 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
358 if (!bv->available())
361 // FIXME: We don't know the encoding of the file
362 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
366 // clear the selection
367 if (bv->text() == bv->getLyXText())
368 bv->cursor().clearSelection();
370 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
372 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
377 // Insert ascii file (if filename is empty, prompt for one)
378 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
383 FileDialog fileDlg(_("Select file to insert"),
384 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
386 FileDialog::Result result =
387 fileDlg.open(bv->owner()->buffer()->filePath(),
388 FileFilterList(), string());
390 if (result.first == FileDialog::Later)
393 fname = result.second;
399 if (!fs::is_readable(fname)) {
400 string const error = strerror(errno);
401 string const file = makeDisplayPath(fname, 50);
402 string const text = bformat(_("Could not read the specified document\n"
403 "%1$s\ndue to the error: %2$s"), file, error);
404 Alert::error(_("Could not read file"), text);
408 ifstream ifs(fname.c_str());
410 string const error = strerror(errno);
411 string const file = makeDisplayPath(fname, 50);
412 string const text = bformat(_("Could not open the specified document\n"
413 "%1$s\ndue to the error: %2$s"), file, error);
414 Alert::error(_("Could not open file"), text);
418 ifs.unsetf(ios::skipws);
419 istream_iterator<char> ii(ifs);
420 istream_iterator<char> end;
421 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
422 // We use this until the compilers get better...
423 std::vector<char> tmp;
424 copy(ii, end, back_inserter(tmp));
425 string const tmpstr(tmp.begin(), tmp.end());
427 // This is what we want to use and what we will use once the
428 // compilers get good enough.
429 //string tmpstr(ii, end); // yet a reason for using std::string
430 // alternate approach to get the file into a string:
432 copy(ii, end, back_inserter(tmpstr));
439 // This function runs "configure" and then rereads lyx.defaults to
440 // reconfigure the automatic settings.
441 void reconfigure(BufferView * bv)
443 // emit message signal.
444 bv->buffer()->message(_("Running configure..."));
446 // Run configure in user lyx directory
447 Path p(package().user_support());
448 string const configure_command = package().configure_command();
450 one.startscript(Systemcall::Wait, configure_command);
452 // emit message signal.
453 bv->buffer()->message(_("Reloading configuration..."));
454 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
455 // Re-read packages.lst
456 LaTeXFeatures::getAvailable();
458 Alert::information(_("System reconfigured"),
459 _("The system has been reconfigured.\n"
460 "You need to restart LyX to make use of any\n"
461 "updated document class specifications."));