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::package;
71 using lyx::support::removeAutosaveFile;
72 using lyx::support::rename;
73 using lyx::support::split;
74 using lyx::support::Systemcall;
75 using lyx::support::tempName;
76 using lyx::support::unlink;
78 using boost::shared_ptr;
80 namespace fs = boost::filesystem;
82 using std::back_inserter;
89 using std::istream_iterator;
92 extern BufferList bufferlist;
93 // this should be static, but I need it in buffer.C
94 bool quitting; // flag, that we are quitting the program
101 bool menuWrite(Buffer * buffer)
103 if (buffer->save()) {
104 LyX::ref().session().addLastFile(buffer->fileName());
108 // FIXME: we don't tell the user *WHY* the save failed !!
110 docstring const file = makeDisplayPath(buffer->fileName(), 30);
112 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
113 "Do you want to rename the document and try again?"), file);
114 int const ret = Alert::prompt(_("Rename and save?"),
115 text, 0, 1, _("&Rename"), _("&Cancel"));
118 return writeAs(buffer);
124 bool writeAs(Buffer * buffer, string const & filename)
126 string fname = buffer->fileName();
127 string const oldname = fname;
129 if (filename.empty()) {
131 FileDialog fileDlg(lyx::to_utf8(_("Choose a filename to save document as")),
132 LFUN_BUFFER_WRITE_AS,
133 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
134 string(lyxrc.document_path)),
135 make_pair(string(lyx::to_utf8(_("Templates|#T#t"))),
136 string(lyxrc.template_path)));
138 if (!isLyXFilename(fname))
141 FileFilterList const filter (lyx::to_utf8(_("LyX Documents (*.lyx)")));
143 FileDialog::Result result =
144 fileDlg.save(onlyPath(fname),
146 onlyFilename(fname));
148 if (result.first == FileDialog::Later)
151 fname = result.second;
156 // Make sure the absolute filename ends with appropriate suffix
157 fname = makeAbsPath(fname);
158 if (!isLyXFilename(fname))
163 if (fs::exists(fname)) {
164 docstring const file = makeDisplayPath(fname, 30);
165 docstring text = bformat(_("The document %1$s already exists.\n\n"
166 "Do you want to over-write that document?"), file);
167 int const ret = Alert::prompt(_("Over-write document?"),
168 text, 0, 1, _("&Over-write"), _("&Cancel"));
174 // Ok, change the name of the buffer
175 buffer->setFileName(fname);
177 bool unnamed = buffer->isUnnamed();
178 buffer->setUnnamed(false);
180 if (!menuWrite(buffer)) {
181 buffer->setFileName(oldname);
182 buffer->setUnnamed(unnamed);
186 removeAutosaveFile(oldname);
191 void quitLyX(bool noask)
193 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
195 if (lyx_gui::use_gui) {
196 if (!noask && !bufferlist.quitWriteAll())
199 LyX::cref().session().writeFile();
202 // Set a flag that we do quitting from the program,
203 // so no refreshes are necessary.
206 // close buffers first
207 bufferlist.closeAll();
209 // do any other cleanup procedures now
210 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
212 if (!destroyDir(package().temp_dir())) {
213 docstring const msg =
214 bformat(_("Unable to remove the temporary directory %1$s"),
215 lyx::from_utf8(package().temp_dir()));
216 Alert::warning(_("Unable to remove temporary directory"), msg);
225 class AutoSaveBuffer : public ForkedProcess {
228 AutoSaveBuffer(BufferView & bv, string const & fname)
229 : bv_(bv), fname_(fname) {}
231 virtual shared_ptr<ForkedProcess> clone() const
233 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
239 virtual int generateChild();
246 int AutoSaveBuffer::start()
248 command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
249 return run(DontWait);
253 int AutoSaveBuffer::generateChild()
255 // tmp_ret will be located (usually) in /tmp
256 // will that be a problem?
257 pid_t const pid = fork(); // If you want to debug the autosave
258 // you should set pid to -1, and comment out the
260 if (pid == 0 || pid == -1) {
261 // pid = -1 signifies that lyx was unable
262 // to fork. But we will do the save
266 string const tmp_ret = tempName(string(), "lyxauto");
267 if (!tmp_ret.empty()) {
268 bv_.buffer()->writeFile(tmp_ret);
269 // assume successful write of tmp_ret
270 if (!rename(tmp_ret, fname_)) {
272 // most likely couldn't move between filesystems
273 // unless write of tmp_ret failed
274 // so remove tmp file (if it exists)
282 // failed to write/rename tmp_ret so try writing direct
283 if (!bv_.buffer()->writeFile(fname_)) {
284 // It is dangerous to do this in the child,
285 // but safe in the parent, so...
287 // emit message signal.
288 bv_.buffer()->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...
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 // emit message signal.
315 bv->buffer()->message(_("Autosaving current document..."));
317 // create autosave filename
318 string fname = bv->buffer()->filePath();
320 fname += onlyFilename(bv->buffer()->fileName());
323 AutoSaveBuffer autosave(*bv, fname);
326 bv->buffer()->markBakClean();
327 bv->owner()->resetAutosaveTimer();
332 // Copyright CHT Software Service GmbH
335 // create new file with template
338 void newFile(BufferView * bv, string const & filename)
340 // Split argument by :
342 string tmpname = split(filename, name, ':');
343 lyxerr[Debug::INFO] << "Arg is " << filename
344 << "\nName is " << name
345 << "\nTemplate is " << tmpname << endl;
347 Buffer * const b = newFile(name, tmpname);
353 // Insert ascii file (if filename is empty, prompt for one)
354 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
359 // FIXME: We don't know the encoding of the file
360 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
364 // clear the selection
365 LyXText const & text = bv->buffer()->text();
366 if (&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 docstring const error = lyx::from_ascii(strerror(errno));
400 docstring const file = makeDisplayPath(fname, 50);
401 docstring const text = bformat(_("Could not read the specified document\n"
402 "%1$s\ndue to the error: %2$s"), file, error);
403 Alert::error(_("Could not read file"), text);
407 ifstream ifs(fname.c_str());
409 docstring const error = lyx::from_ascii(strerror(errno));
410 docstring const file = makeDisplayPath(fname, 50);
411 docstring const text = bformat(_("Could not open the specified document\n"
412 "%1$s\ndue to the error: %2$s"), file, error);
413 Alert::error(_("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(_("Running configure..."));
445 // Run configure in user lyx directory
446 lyx::support::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(_("Reloading configuration..."));
453 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
454 // Re-read packages.lst
455 LaTeXFeatures::getAvailable();
457 Alert::information(_("System reconfigured"),
458 _("The system has been reconfigured.\n"
459 "You need to restart LyX to make use of any\n"
460 "updated document class specifications."));