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::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(lyx::to_utf8(_("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(lyx::to_utf8(_("Rename and save?")),
116 text, 0, 1, lyx::to_utf8(_("&Rename")), lyx::to_utf8(_("&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(lyx::to_utf8(_("Choose a filename to save document as")),
133 LFUN_BUFFER_WRITE_AS,
134 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
135 string(lyxrc.document_path)),
136 make_pair(string(lyx::to_utf8(_("Templates|#T#t"))),
137 string(lyxrc.template_path)));
139 if (!isLyXFilename(fname))
142 FileFilterList const filter (lyx::to_utf8(_("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(lyx::to_utf8(_("The document %1$s already exists.\n\n"
167 "Do you want to over-write that document?")), file);
168 int const ret = Alert::prompt(lyx::to_utf8(_("Over-write document?")),
169 text, 0, 1, lyx::to_utf8(_("&Over-write")), lyx::to_utf8(_("&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(lyx::to_utf8(_("Unable to remove the temporary directory %1$s")),
216 package().temp_dir());
217 Alert::warning(lyx::to_utf8(_("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(lyx::to_utf8(_("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 // emit message signal.
289 bv_.buffer()->message(lyx::to_utf8(_("Autosave failed!")));
292 if (pid == 0) { // we are the child so...
302 void autoSave(BufferView * bv)
303 // should probably be moved into BufferList (Lgb)
304 // Perfect target for a thread...
306 if (!bv->available())
309 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
310 // We don't save now, but we'll try again later
311 bv->owner()->resetAutosaveTimer();
315 // emit message signal.
316 bv->buffer()->message(lyx::to_utf8(_("Autosaving current document...")));
318 // create autosave filename
319 string fname = bv->buffer()->filePath();
321 fname += onlyFilename(bv->buffer()->fileName());
324 AutoSaveBuffer autosave(*bv, fname);
327 bv->buffer()->markBakClean();
328 bv->owner()->resetAutosaveTimer();
333 // Copyright CHT Software Service GmbH
336 // create new file with template
339 void newFile(BufferView * bv, string const & filename)
341 // Split argument by :
343 string tmpname = split(filename, name, ':');
344 lyxerr[Debug::INFO] << "Arg is " << filename
345 << "\nName is " << name
346 << "\nTemplate is " << tmpname << endl;
348 Buffer * const b = newFile(name, tmpname);
354 // Insert ascii file (if filename is empty, prompt for one)
355 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
357 if (!bv->available())
360 // FIXME: We don't know the encoding of the file
361 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
365 // clear the selection
366 if (bv->text() == bv->getLyXText())
367 bv->cursor().clearSelection();
369 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
371 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
376 // Insert ascii file (if filename is empty, prompt for one)
377 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
382 FileDialog fileDlg(lyx::to_utf8(_("Select file to insert")),
383 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
385 FileDialog::Result result =
386 fileDlg.open(bv->owner()->buffer()->filePath(),
387 FileFilterList(), string());
389 if (result.first == FileDialog::Later)
392 fname = result.second;
398 if (!fs::is_readable(fname)) {
399 string const error = strerror(errno);
400 string const file = makeDisplayPath(fname, 50);
401 string const text = bformat(lyx::to_utf8(_("Could not read the specified document\n"
402 "%1$s\ndue to the error: %2$s")), file, error);
403 Alert::error(lyx::to_utf8(_("Could not read file")), text);
407 ifstream ifs(fname.c_str());
409 string const error = strerror(errno);
410 string const file = makeDisplayPath(fname, 50);
411 string const text = bformat(lyx::to_utf8(_("Could not open the specified document\n"
412 "%1$s\ndue to the error: %2$s")), file, error);
413 Alert::error(lyx::to_utf8(_("Could not open file")), text);
417 ifs.unsetf(ios::skipws);
418 istream_iterator<char> ii(ifs);
419 istream_iterator<char> end;
420 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
421 // We use this until the compilers get better...
422 std::vector<char> tmp;
423 copy(ii, end, back_inserter(tmp));
424 string const tmpstr(tmp.begin(), tmp.end());
426 // This is what we want to use and what we will use once the
427 // compilers get good enough.
428 //string tmpstr(ii, end); // yet a reason for using std::string
429 // alternate approach to get the file into a string:
431 copy(ii, end, back_inserter(tmpstr));
438 // This function runs "configure" and then rereads lyx.defaults to
439 // reconfigure the automatic settings.
440 void reconfigure(BufferView * bv)
442 // emit message signal.
443 bv->buffer()->message(lyx::to_utf8(_("Running configure...")));
445 // Run configure in user lyx directory
446 Path p(package().user_support());
447 string const configure_command = package().configure_command();
449 one.startscript(Systemcall::Wait, configure_command);
451 // emit message signal.
452 bv->buffer()->message(lyx::to_utf8(_("Reloading configuration...")));
453 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
454 // Re-read packages.lst
455 LaTeXFeatures::getAvailable();
457 Alert::information(lyx::to_utf8(_("System reconfigured")),
458 lyx::to_utf8(_("The system has been reconfigured.\n"
459 "You need to restart LyX to make use of any\n"
460 "updated document class specifications.")));