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"
47 #include <boost/shared_ptr.hpp>
48 #include <boost/filesystem/operations.hpp>
53 using lyx::support::AddName;
54 using lyx::support::bformat;
55 using lyx::support::destroyDir;
56 using lyx::support::FileFilterList;
57 using lyx::support::ForkedProcess;
58 using lyx::support::IsLyXFilename;
59 using lyx::support::LibFileSearch;
60 using lyx::support::MakeAbsPath;
61 using lyx::support::MakeDisplayPath;
62 using lyx::support::OnlyFilename;
63 using lyx::support::OnlyPath;
64 using lyx::support::Path;
65 using lyx::support::package;
66 using lyx::support::QuoteName;
67 using lyx::support::removeAutosaveFile;
68 using lyx::support::rename;
69 using lyx::support::split;
70 using lyx::support::Systemcall;
71 using lyx::support::tempName;
72 using lyx::support::unlink;
74 using boost::shared_ptr;
76 namespace fs = boost::filesystem;
78 using std::back_inserter;
85 using std::istream_iterator;
88 extern BufferList bufferlist;
89 // this should be static, but I need it in buffer.C
90 bool quitting; // flag, that we are quitting the program
97 bool MenuWrite(Buffer * buffer)
100 LyX::ref().lastfiles().newFile(buffer->fileName());
104 // FIXME: we don't tell the user *WHY* the save failed !!
106 string const file = MakeDisplayPath(buffer->fileName(), 30);
108 string text = bformat(_("The document %1$s could not be saved.\n\n"
109 "Do you want to rename the document and try again?"), file);
110 int const ret = Alert::prompt(_("Rename and save?"),
111 text, 0, 1, _("&Rename"), _("&Cancel"));
114 return WriteAs(buffer);
120 bool WriteAs(Buffer * buffer, string const & filename)
122 string fname = buffer->fileName();
123 string const oldname = fname;
125 if (filename.empty()) {
127 FileDialog fileDlg(_("Choose a filename to save document as"),
129 make_pair(string(_("Documents|#o#O")),
130 string(lyxrc.document_path)),
131 make_pair(string(_("Templates|#T#t")),
132 string(lyxrc.template_path)));
134 if (!IsLyXFilename(fname))
137 FileFilterList const filter (_("LyX Documents (*.lyx)"));
139 FileDialog::Result result =
140 fileDlg.save(OnlyPath(fname),
142 OnlyFilename(fname));
144 if (result.first == FileDialog::Later)
147 fname = result.second;
152 // Make sure the absolute filename ends with appropriate suffix
153 fname = MakeAbsPath(fname);
154 if (!IsLyXFilename(fname))
159 if (fs::exists(fname)) {
160 string const file = MakeDisplayPath(fname, 30);
161 string text = bformat(_("The document %1$s already exists.\n\n"
162 "Do you want to over-write that document?"), file);
163 int const ret = Alert::prompt(_("Over-write document?"),
164 text, 0, 1, _("&Over-write"), _("&Cancel"));
170 // Ok, change the name of the buffer
171 buffer->setFileName(fname);
173 bool unnamed = buffer->isUnnamed();
174 buffer->setUnnamed(false);
176 if (!MenuWrite(buffer)) {
177 buffer->setFileName(oldname);
178 buffer->setUnnamed(unnamed);
182 removeAutosaveFile(oldname);
189 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
191 if (lyx_gui::use_gui) {
192 if (!bufferlist.quitWriteAll())
195 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
198 // Set a flag that we do quitting from the program,
199 // so no refreshes are necessary.
202 // close buffers first
203 bufferlist.closeAll();
205 // do any other cleanup procedures now
206 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
208 if (!destroyDir(package().temp_dir())) {
210 bformat(_("Unable to remove the temporary directory %1$s"),
211 package().temp_dir());
212 Alert::warning(_("Unable to remove temporary directory"), msg);
221 class AutoSaveBuffer : public ForkedProcess {
224 AutoSaveBuffer(BufferView & bv, string const & fname)
225 : bv_(bv), fname_(fname) {}
227 virtual shared_ptr<ForkedProcess> clone() const
229 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
235 virtual int generateChild();
242 int AutoSaveBuffer::start()
244 command_ = bformat(_("Auto-saving %1$s"), fname_);
245 return run(DontWait);
249 int AutoSaveBuffer::generateChild()
251 // tmp_ret will be located (usually) in /tmp
252 // will that be a problem?
253 pid_t const pid = fork(); // If you want to debug the autosave
254 // you should set pid to -1, and comment out the
256 if (pid == 0 || pid == -1) {
257 // pid = -1 signifies that lyx was unable
258 // to fork. But we will do the save
262 string const tmp_ret = tempName(string(), "lyxauto");
263 if (!tmp_ret.empty()) {
264 bv_.buffer()->writeFile(tmp_ret);
265 // assume successful write of tmp_ret
266 if (!rename(tmp_ret, fname_)) {
268 // most likely couldn't move between filesystems
269 // unless write of tmp_ret failed
270 // so remove tmp file (if it exists)
278 // failed to write/rename tmp_ret so try writing direct
279 if (!bv_.buffer()->writeFile(fname_)) {
280 // It is dangerous to do this in the child,
281 // but safe in the parent, so...
283 bv_.owner()->message(_("Autosave failed!"));
286 if (pid == 0) { // we are the child so...
296 void AutoSave(BufferView * bv)
297 // should probably be moved into BufferList (Lgb)
298 // Perfect target for a thread...
300 if (!bv->available())
303 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
304 // We don't save now, but we'll try again later
305 bv->owner()->resetAutosaveTimer();
309 bv->owner()->message(_("Autosaving current document..."));
311 // create autosave filename
312 string fname = bv->buffer()->filePath();
314 fname += OnlyFilename(bv->buffer()->fileName());
317 AutoSaveBuffer autosave(*bv, fname);
320 bv->buffer()->markBakClean();
321 bv->owner()->resetAutosaveTimer();
326 // Copyright CHT Software Service GmbH
329 // create new file with template
332 void NewFile(BufferView * bv, string const & filename)
334 // Split argument by :
336 string tmpname = split(filename, name, ':');
337 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
338 if (name.length() == 1
339 && isalpha(static_cast<unsigned char>(name[0]))
340 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
342 name += token(tmpname, ':', 0);
343 tmpname = split(tmpname, ':');
346 lyxerr[Debug::INFO] << "Arg is " << filename
347 << "\nName is " << name
348 << "\nTemplate is " << tmpname << endl;
350 bv->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 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
364 // clear the selection
365 if (bv->text() == bv->getLyXText())
366 bv->cursor().clearSelection();
368 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
370 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
375 // Insert ascii file (if filename is empty, prompt for one)
376 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
381 FileDialog fileDlg(_("Select file to insert"),
382 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
384 FileDialog::Result result =
385 fileDlg.open(bv->owner()->buffer()->filePath(),
386 FileFilterList(), string());
388 if (result.first == FileDialog::Later)
391 fname = result.second;
397 if (!fs::is_readable(fname)) {
398 string const error = strerror(errno);
399 string const file = MakeDisplayPath(fname, 50);
400 string const text = bformat(_("Could not read the specified document\n"
401 "%1$s\ndue to the error: %2$s"), file, error);
402 Alert::error(_("Could not read file"), text);
406 ifstream ifs(fname.c_str());
408 string const error = strerror(errno);
409 string const file = MakeDisplayPath(fname, 50);
410 string const text = bformat(_("Could not open the specified document\n"
411 "%1$s\ndue to the error: %2$s"), file, error);
412 Alert::error(_("Could not open file"), text);
416 ifs.unsetf(ios::skipws);
417 istream_iterator<char> ii(ifs);
418 istream_iterator<char> end;
419 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
420 // We use this until the compilers get better...
421 std::vector<char> tmp;
422 copy(ii, end, back_inserter(tmp));
423 string const tmpstr(tmp.begin(), tmp.end());
425 // This is what we want to use and what we will use once the
426 // compilers get good enough.
427 //string tmpstr(ii, end); // yet a reason for using std::string
428 // alternate approach to get the file into a string:
430 copy(ii, end, back_inserter(tmpstr));
437 // This function runs "configure" and then rereads lyx.defaults to
438 // reconfigure the automatic settings.
439 void Reconfigure(BufferView * bv)
441 bv->owner()->message(_("Running configure..."));
443 // Run configure in user lyx directory
444 Path p(package().user_support());
445 string const configure_script =
446 AddName(package().system_support(), "configure");
447 string const configure_command = "sh " + QuoteName(configure_script);
449 one.startscript(Systemcall::Wait, configure_command);
451 bv->owner()->message(_("Reloading configuration..."));
452 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
453 // Re-read packages.lst
454 LaTeXFeatures::getAvailable();
456 Alert::information(_("System reconfigured"),
457 _("The system has been reconfigured.\n"
458 "You need to restart LyX to make use of any\n"
459 "updated document class specifications."));