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"
25 #include "lastfiles.h"
26 #include "LaTeXFeatures.h"
28 #include "lyxlayout.h"
31 #include "paragraph.h"
33 #include "frontends/Alert.h"
34 #include "frontends/FileDialog.h"
35 #include "frontends/lyx_gui.h"
36 #include "frontends/LyXView.h"
38 #include "support/filefilterlist.h"
39 #include "support/filetools.h"
40 #include "support/forkedcall.h"
41 #include "support/fs_extras.h"
42 #include "support/lyxlib.h"
43 #include "support/package.h"
44 #include "support/path.h"
45 #include "support/systemcall.h"
51 #include <boost/shared_ptr.hpp>
52 #include <boost/filesystem/operations.hpp>
57 using lyx::support::AddName;
58 using lyx::support::bformat;
59 using lyx::support::destroyDir;
60 using lyx::support::FileFilterList;
61 using lyx::support::ForkedProcess;
62 using lyx::support::IsLyXFilename;
63 using lyx::support::LibFileSearch;
64 using lyx::support::MakeAbsPath;
65 using lyx::support::MakeDisplayPath;
66 using lyx::support::OnlyFilename;
67 using lyx::support::OnlyPath;
68 using lyx::support::Path;
69 using lyx::support::package;
70 using lyx::support::QuoteName;
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().lastfiles().newFile(buffer->fileName());
108 // FIXME: we don't tell the user *WHY* the save failed !!
110 string const file = MakeDisplayPath(buffer->fileName(), 30);
112 string 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(_("Choose a filename to save document as"),
133 make_pair(string(_("Documents|#o#O")),
134 string(lyxrc.document_path)),
135 make_pair(string(_("Templates|#T#t")),
136 string(lyxrc.template_path)));
138 if (!IsLyXFilename(fname))
141 FileFilterList const filter (_("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 string const file = MakeDisplayPath(fname, 30);
165 string 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);
193 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
195 if (lyx_gui::use_gui) {
196 if (!bufferlist.quitWriteAll())
199 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
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())) {
214 bformat(_("Unable to remove the temporary directory %1$s"),
215 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_ = bformat(_("Auto-saving %1$s"), 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 bv_.owner()->message(_("Autosave failed!"));
290 if (pid == 0) { // we are the child so...
300 void AutoSave(BufferView * bv)
301 // should probably be moved into BufferList (Lgb)
302 // Perfect target for a thread...
304 if (!bv->available())
307 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
308 // We don't save now, but we'll try again later
309 bv->owner()->resetAutosaveTimer();
313 bv->owner()->message(_("Autosaving current document..."));
315 // create autosave filename
316 string fname = bv->buffer()->filePath();
318 fname += OnlyFilename(bv->buffer()->fileName());
321 AutoSaveBuffer autosave(*bv, fname);
324 bv->buffer()->markBakClean();
325 bv->owner()->resetAutosaveTimer();
330 // Copyright CHT Software Service GmbH
333 // create new file with template
336 void NewFile(BufferView * bv, string const & filename)
338 // Split argument by :
340 string tmpname = split(filename, name, ':');
341 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
342 if (name.length() == 1
343 && isalpha(static_cast<unsigned char>(name[0]))
344 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
346 name += token(tmpname, ':', 0);
347 tmpname = split(tmpname, ':');
350 lyxerr[Debug::INFO] << "Arg is " << filename
351 << "\nName is " << name
352 << "\nTemplate is " << tmpname << endl;
354 bv->newFile(name, tmpname);
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);
368 // clear the selection
369 if (bv->text() == bv->getLyXText())
370 bv->cursor().clearSelection();
372 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
374 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
379 // Insert ascii file (if filename is empty, prompt for one)
380 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
385 FileDialog fileDlg(_("Select file to insert"),
386 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
388 FileDialog::Result result =
389 fileDlg.open(bv->owner()->buffer()->filePath(),
390 FileFilterList(), string());
392 if (result.first == FileDialog::Later)
395 fname = result.second;
401 if (!fs::is_readable(fname)) {
402 string const error = strerror(errno);
403 string const file = MakeDisplayPath(fname, 50);
404 string const text = bformat(_("Could not read the specified document\n"
405 "%1$s\ndue to the error: %2$s"), file, error);
406 Alert::error(_("Could not read file"), text);
410 ifstream ifs(fname.c_str());
412 string const error = strerror(errno);
413 string const file = MakeDisplayPath(fname, 50);
414 string const text = bformat(_("Could not open the specified document\n"
415 "%1$s\ndue to the error: %2$s"), file, error);
416 Alert::error(_("Could not open file"), text);
420 ifs.unsetf(ios::skipws);
421 istream_iterator<char> ii(ifs);
422 istream_iterator<char> end;
423 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
424 // We use this until the compilers get better...
425 std::vector<char> tmp;
426 copy(ii, end, back_inserter(tmp));
427 string const tmpstr(tmp.begin(), tmp.end());
429 // This is what we want to use and what we will use once the
430 // compilers get good enough.
431 //string tmpstr(ii, end); // yet a reason for using std::string
432 // alternate approach to get the file into a string:
434 copy(ii, end, back_inserter(tmpstr));
441 // This function runs "configure" and then rereads lyx.defaults to
442 // reconfigure the automatic settings.
443 void Reconfigure(BufferView * bv)
445 bv->owner()->message(_("Running configure..."));
447 // Run configure in user lyx directory
448 Path p(package().user_support());
449 string const configure_script =
450 AddName(package().system_support(), "configure");
451 string const configure_command = "sh " + QuoteName(configure_script);
453 one.startscript(Systemcall::Wait, configure_command);
455 bv->owner()->message(_("Reloading configuration..."));
456 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
457 // Re-read packages.lst
458 LaTeXFeatures::getAvailable();
460 Alert::information(_("System reconfigured"),
461 _("The system has been reconfigured.\n"
462 "You need to restart LyX to make use of any\n"
463 "updated document class specifications."));