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/FileInfo.h"
40 #include "support/filetools.h"
41 #include "support/forkedcall.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>
52 using lyx::support::AddName;
53 using lyx::support::bformat;
54 using lyx::support::destroyDir;
55 using lyx::support::FileFilterList;
56 using lyx::support::FileInfo;
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 using std::back_inserter;
83 using std::istream_iterator;
86 extern BufferList bufferlist;
87 // this should be static, but I need it in buffer.C
88 bool quitting; // flag, that we are quitting the program
95 bool MenuWrite(Buffer * buffer)
98 LyX::ref().lastfiles().newFile(buffer->fileName());
102 // FIXME: we don't tell the user *WHY* the save failed !!
104 string const file = MakeDisplayPath(buffer->fileName(), 30);
106 string text = bformat(_("The document %1$s could not be saved.\n\n"
107 "Do you want to rename the document and try again?"), file);
108 int const ret = Alert::prompt(_("Rename and save?"),
109 text, 0, 1, _("&Rename"), _("&Cancel"));
112 return WriteAs(buffer);
118 bool WriteAs(Buffer * buffer, string const & filename)
120 string fname = buffer->fileName();
121 string const oldname = fname;
123 if (filename.empty()) {
125 FileDialog fileDlg(_("Choose a filename to save document as"),
127 make_pair(string(_("Documents|#o#O")),
128 string(lyxrc.document_path)),
129 make_pair(string(_("Templates|#T#t")),
130 string(lyxrc.template_path)));
132 if (!IsLyXFilename(fname))
135 FileFilterList const filter (_("LyX Documents (*.lyx)"));
137 FileDialog::Result result =
138 fileDlg.save(OnlyPath(fname),
140 OnlyFilename(fname));
142 if (result.first == FileDialog::Later)
145 fname = result.second;
150 // Make sure the absolute filename ends with appropriate suffix
151 fname = MakeAbsPath(fname);
152 if (!IsLyXFilename(fname))
157 FileInfo const myfile(fname);
159 string const file = MakeDisplayPath(fname, 30);
160 string text = bformat(_("The document %1$s already exists.\n\n"
161 "Do you want to over-write that document?"), file);
162 int const ret = Alert::prompt(_("Over-write document?"),
163 text, 0, 1, _("&Over-write"), _("&Cancel"));
169 // Ok, change the name of the buffer
170 buffer->setFileName(fname);
172 bool unnamed = buffer->isUnnamed();
173 buffer->setUnnamed(false);
175 if (!MenuWrite(buffer)) {
176 buffer->setFileName(oldname);
177 buffer->setUnnamed(unnamed);
181 removeAutosaveFile(oldname);
188 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
190 if (lyx_gui::use_gui) {
191 if (!bufferlist.quitWriteAll())
194 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
197 // Set a flag that we do quitting from the program,
198 // so no refreshes are necessary.
201 // close buffers first
202 bufferlist.closeAll();
204 // do any other cleanup procedures now
205 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
207 if (destroyDir(package().temp_dir()) != 0) {
208 string msg = bformat(_("Could not remove the temporary directory %1$s"),
209 package().temp_dir());
210 Alert::warning(_("Could not remove temporary directory"), msg);
219 class AutoSaveBuffer : public ForkedProcess {
222 AutoSaveBuffer(BufferView & bv, string const & fname)
223 : bv_(bv), fname_(fname) {}
225 virtual shared_ptr<ForkedProcess> clone() const
227 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
233 virtual int generateChild();
240 int AutoSaveBuffer::start()
242 command_ = bformat(_("Auto-saving %1$s"), fname_);
243 return run(DontWait);
247 int AutoSaveBuffer::generateChild()
249 // tmp_ret will be located (usually) in /tmp
250 // will that be a problem?
251 pid_t const pid = fork(); // If you want to debug the autosave
252 // you should set pid to -1, and comment out the
254 if (pid == 0 || pid == -1) {
255 // pid = -1 signifies that lyx was unable
256 // to fork. But we will do the save
260 string const tmp_ret = tempName(string(), "lyxauto");
261 if (!tmp_ret.empty()) {
262 bv_.buffer()->writeFile(tmp_ret);
263 // assume successful write of tmp_ret
264 if (!rename(tmp_ret, fname_)) {
266 // most likely couldn't move between filesystems
267 // unless write of tmp_ret failed
268 // so remove tmp file (if it exists)
276 // failed to write/rename tmp_ret so try writing direct
277 if (!bv_.buffer()->writeFile(fname_)) {
278 // It is dangerous to do this in the child,
279 // but safe in the parent, so...
281 bv_.owner()->message(_("Autosave failed!"));
284 if (pid == 0) { // we are the child so...
294 void AutoSave(BufferView * bv)
295 // should probably be moved into BufferList (Lgb)
296 // Perfect target for a thread...
298 if (!bv->available())
301 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
302 // We don't save now, but we'll try again later
303 bv->owner()->resetAutosaveTimer();
307 bv->owner()->message(_("Autosaving current document..."));
309 // create autosave filename
310 string fname = bv->buffer()->filePath();
312 fname += OnlyFilename(bv->buffer()->fileName());
315 AutoSaveBuffer autosave(*bv, fname);
318 bv->buffer()->markBakClean();
319 bv->owner()->resetAutosaveTimer();
324 // Copyright CHT Software Service GmbH
327 // create new file with template
330 void NewFile(BufferView * bv, string const & filename)
332 // Split argument by :
334 string tmpname = split(filename, name, ':');
335 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
336 if (name.length() == 1
337 && isalpha(static_cast<unsigned char>(name[0]))
338 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
340 name += token(tmpname, ':', 0);
341 tmpname = split(tmpname, ':');
344 lyxerr[Debug::INFO] << "Arg is " << filename
345 << "\nName is " << name
346 << "\nTemplate is " << tmpname << endl;
348 bv->newFile(name, tmpname);
352 // Insert ascii file (if filename is empty, prompt for one)
353 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
355 if (!bv->available())
358 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
362 // clear the selection
363 if (bv->text() == bv->getLyXText())
364 bv->cursor().clearSelection();
366 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
368 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
373 // Insert ascii file (if filename is empty, prompt for one)
374 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
379 FileDialog fileDlg(_("Select file to insert"),
380 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
382 FileDialog::Result result =
383 fileDlg.open(bv->owner()->buffer()->filePath(),
384 FileFilterList(), string());
386 if (result.first == FileDialog::Later)
389 fname = result.second;
397 if (!fi.readable()) {
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."));