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"
27 #include "lyxlayout.h"
30 #include "paragraph.h"
32 #include "frontends/Alert.h"
33 #include "frontends/FileDialog.h"
34 #include "frontends/lyx_gui.h"
35 #include "frontends/LyXView.h"
37 #include "support/FileInfo.h"
38 #include "support/filetools.h"
39 #include "support/forkedcall.h"
40 #include "support/globbing.h"
41 #include "support/lyxlib.h"
42 #include "support/os.h"
43 #include "support/path.h"
44 #include "support/path_defines.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::QuoteName;
66 using lyx::support::removeAutosaveFile;
67 using lyx::support::rename;
68 using lyx::support::split;
69 using lyx::support::system_lyxdir;
70 using lyx::support::Systemcall;
71 using lyx::support::tempName;
72 using lyx::support::unlink;
73 using lyx::support::user_lyxdir;
75 namespace os = lyx::support::os;
77 using boost::shared_ptr;
79 using std::back_inserter;
86 using std::istream_iterator;
89 extern BufferList bufferlist;
90 // this should be static, but I need it in buffer.C
91 bool quitting; // flag, that we are quitting the program
98 bool MenuWrite(Buffer * buffer)
100 if (buffer->save()) {
101 LyX::ref().lastfiles().newFile(buffer->fileName());
105 // FIXME: we don't tell the user *WHY* the save failed !!
107 string const file = MakeDisplayPath(buffer->fileName(), 30);
109 string text = bformat(_("The document %1$s could not be saved.\n\n"
110 "Do you want to rename the document and try again?"), file);
111 int const ret = Alert::prompt(_("Rename and save?"),
112 text, 0, 1, _("&Rename"), _("&Cancel"));
115 return WriteAs(buffer);
121 bool WriteAs(Buffer * buffer, string const & filename)
123 string fname = buffer->fileName();
124 string const oldname = fname;
126 if (filename.empty()) {
128 FileDialog fileDlg(_("Choose a filename to save document as"),
130 make_pair(string(_("Documents|#o#O")),
131 string(lyxrc.document_path)),
132 make_pair(string(_("Templates|#T#t")),
133 string(lyxrc.template_path)));
135 if (!IsLyXFilename(fname))
138 FileFilterList const filter (_("LyX Documents (*.lyx)"));
140 FileDialog::Result result =
141 fileDlg.save(OnlyPath(fname),
143 OnlyFilename(fname));
145 if (result.first == FileDialog::Later)
148 fname = result.second;
153 // Make sure the absolute filename ends with appropriate suffix
154 fname = MakeAbsPath(fname);
155 if (!IsLyXFilename(fname))
160 FileInfo const myfile(fname);
162 string const file = MakeDisplayPath(fname, 30);
163 string text = bformat(_("The document %1$s already exists.\n\n"
164 "Do you want to over-write that document?"), file);
165 int const ret = Alert::prompt(_("Over-write document?"),
166 text, 0, 1, _("&Over-write"), _("&Cancel"));
172 // Ok, change the name of the buffer
173 buffer->setFileName(fname);
175 bool unnamed = buffer->isUnnamed();
176 buffer->setUnnamed(false);
178 if (!MenuWrite(buffer)) {
179 buffer->setFileName(oldname);
180 buffer->setUnnamed(unnamed);
184 removeAutosaveFile(oldname);
191 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
193 if (lyx_gui::use_gui) {
194 if (!bufferlist.quitWriteAll())
197 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
200 // Set a flag that we do quitting from the program,
201 // so no refreshes are necessary.
204 // close buffers first
205 bufferlist.closeAll();
207 // do any other cleanup procedures now
208 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
210 if (destroyDir(os::getTmpDir()) != 0) {
211 string msg = bformat(_("Could not remove the temporary directory %1$s"),
213 Alert::warning(_("Could not remove temporary directory"), msg);
222 class AutoSaveBuffer : public ForkedProcess {
225 AutoSaveBuffer(BufferView & bv, string const & fname)
226 : bv_(bv), fname_(fname) {}
228 virtual shared_ptr<ForkedProcess> clone() const
230 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
236 virtual int generateChild();
243 int AutoSaveBuffer::start()
245 command_ = bformat(_("Auto-saving %1$s"), fname_);
246 return run(DontWait);
250 int AutoSaveBuffer::generateChild()
252 // tmp_ret will be located (usually) in /tmp
253 // will that be a problem?
254 pid_t const pid = fork(); // If you want to debug the autosave
255 // you should set pid to -1, and comment out the
257 if (pid == 0 || pid == -1) {
258 // pid = -1 signifies that lyx was unable
259 // to fork. But we will do the save
263 string const tmp_ret = tempName(string(), "lyxauto");
264 if (!tmp_ret.empty()) {
265 bv_.buffer()->writeFile(tmp_ret);
266 // assume successful write of tmp_ret
267 if (!rename(tmp_ret, fname_)) {
269 // most likely couldn't move between filesystems
270 // unless write of tmp_ret failed
271 // so remove tmp file (if it exists)
279 // failed to write/rename tmp_ret so try writing direct
280 if (!bv_.buffer()->writeFile(fname_)) {
281 // It is dangerous to do this in the child,
282 // but safe in the parent, so...
284 bv_.owner()->message(_("Autosave failed!"));
287 if (pid == 0) { // we are the child so...
297 void AutoSave(BufferView * bv)
298 // should probably be moved into BufferList (Lgb)
299 // Perfect target for a thread...
301 if (!bv->available())
304 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
305 // We don't save now, but we'll try again later
306 bv->owner()->resetAutosaveTimer();
310 bv->owner()->message(_("Autosaving current document..."));
312 // create autosave filename
313 string fname = bv->buffer()->filePath();
315 fname += OnlyFilename(bv->buffer()->fileName());
318 AutoSaveBuffer autosave(*bv, fname);
321 bv->buffer()->markBakClean();
322 bv->owner()->resetAutosaveTimer();
327 // Copyright CHT Software Service GmbH
330 // create new file with template
333 void NewFile(BufferView * bv, string const & filename)
335 // Split argument by :
337 string tmpname = split(filename, name, ':');
338 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
339 if (name.length() == 1
340 && isalpha(static_cast<unsigned char>(name[0]))
341 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
343 name += token(tmpname, ':', 0);
344 tmpname = split(tmpname, ':');
347 lyxerr[Debug::INFO] << "Arg is " << filename
348 << "\nName is " << name
349 << "\nTemplate is " << tmpname << endl;
351 bv->newFile(name, tmpname);
355 // Insert ascii file (if filename is empty, prompt for one)
356 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
358 if (!bv->available())
361 string const tmpstr = 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(_("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;
400 if (!fi.readable()) {
401 string const error = strerror(errno);
402 string const file = MakeDisplayPath(fname, 50);
403 string const text = bformat(_("Could not read the specified document\n"
404 "%1$s\ndue to the error: %2$s"), file, error);
405 Alert::error(_("Could not read file"), text);
409 ifstream ifs(fname.c_str());
411 string const error = strerror(errno);
412 string const file = MakeDisplayPath(fname, 50);
413 string const text = bformat(_("Could not open the specified document\n"
414 "%1$s\ndue to the error: %2$s"), file, error);
415 Alert::error(_("Could not open file"), text);
419 ifs.unsetf(ios::skipws);
420 istream_iterator<char> ii(ifs);
421 istream_iterator<char> end;
422 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
423 // We use this until the compilers get better...
424 std::vector<char> tmp;
425 copy(ii, end, back_inserter(tmp));
426 string const tmpstr(tmp.begin(), tmp.end());
428 // This is what we want to use and what we will use once the
429 // compilers get good enough.
430 //string tmpstr(ii, end); // yet a reason for using std::string
431 // alternate approach to get the file into a string:
433 copy(ii, end, back_inserter(tmpstr));
440 // This function runs "configure" and then rereads lyx.defaults to
441 // reconfigure the automatic settings.
442 void Reconfigure(BufferView * bv)
444 bv->owner()->message(_("Running configure..."));
446 // Run configure in user lyx directory
447 Path p(user_lyxdir());
449 one.startscript(Systemcall::Wait,
450 QuoteName(AddName(system_lyxdir(), "configure")));
452 bv->owner()->message(_("Reloading configuration..."));
453 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
455 Alert::information(_("System reconfigured"),
456 _("The system has been reconfigured.\n"
457 "You need to restart LyX to make use of any\n"
458 "updated document class specifications."));