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/filefilterlist.h"
38 #include "support/FileInfo.h"
39 #include "support/filetools.h"
40 #include "support/forkedcall.h"
41 #include "support/lyxlib.h"
42 #include "support/package.h"
43 #include "support/path.h"
44 #include "support/systemcall.h"
46 #include <boost/shared_ptr.hpp>
51 using lyx::support::AddName;
52 using lyx::support::bformat;
53 using lyx::support::destroyDir;
54 using lyx::support::FileFilterList;
55 using lyx::support::FileInfo;
56 using lyx::support::ForkedProcess;
57 using lyx::support::IsLyXFilename;
58 using lyx::support::LibFileSearch;
59 using lyx::support::MakeAbsPath;
60 using lyx::support::MakeDisplayPath;
61 using lyx::support::OnlyFilename;
62 using lyx::support::OnlyPath;
63 using lyx::support::Path;
64 using lyx::support::package;
65 using lyx::support::QuoteName;
66 using lyx::support::removeAutosaveFile;
67 using lyx::support::rename;
68 using lyx::support::split;
69 using lyx::support::Systemcall;
70 using lyx::support::tempName;
71 using lyx::support::unlink;
73 using boost::shared_ptr;
75 using std::back_inserter;
82 using std::istream_iterator;
85 extern BufferList bufferlist;
86 // this should be static, but I need it in buffer.C
87 bool quitting; // flag, that we are quitting the program
94 bool MenuWrite(Buffer * buffer)
97 LyX::ref().lastfiles().newFile(buffer->fileName());
101 // FIXME: we don't tell the user *WHY* the save failed !!
103 string const file = MakeDisplayPath(buffer->fileName(), 30);
105 string text = bformat(_("The document %1$s could not be saved.\n\n"
106 "Do you want to rename the document and try again?"), file);
107 int const ret = Alert::prompt(_("Rename and save?"),
108 text, 0, 1, _("&Rename"), _("&Cancel"));
111 return WriteAs(buffer);
117 bool WriteAs(Buffer * buffer, string const & filename)
119 string fname = buffer->fileName();
120 string const oldname = fname;
122 if (filename.empty()) {
124 FileDialog fileDlg(_("Choose a filename to save document as"),
126 make_pair(string(_("Documents|#o#O")),
127 string(lyxrc.document_path)),
128 make_pair(string(_("Templates|#T#t")),
129 string(lyxrc.template_path)));
131 if (!IsLyXFilename(fname))
134 FileFilterList const filter (_("LyX Documents (*.lyx)"));
136 FileDialog::Result result =
137 fileDlg.save(OnlyPath(fname),
139 OnlyFilename(fname));
141 if (result.first == FileDialog::Later)
144 fname = result.second;
149 // Make sure the absolute filename ends with appropriate suffix
150 fname = MakeAbsPath(fname);
151 if (!IsLyXFilename(fname))
156 FileInfo const myfile(fname);
158 string const file = MakeDisplayPath(fname, 30);
159 string text = bformat(_("The document %1$s already exists.\n\n"
160 "Do you want to over-write that document?"), file);
161 int const ret = Alert::prompt(_("Over-write document?"),
162 text, 0, 1, _("&Over-write"), _("&Cancel"));
168 // Ok, change the name of the buffer
169 buffer->setFileName(fname);
171 bool unnamed = buffer->isUnnamed();
172 buffer->setUnnamed(false);
174 if (!MenuWrite(buffer)) {
175 buffer->setFileName(oldname);
176 buffer->setUnnamed(unnamed);
180 removeAutosaveFile(oldname);
187 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
189 if (lyx_gui::use_gui) {
190 if (!bufferlist.quitWriteAll())
193 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
196 // Set a flag that we do quitting from the program,
197 // so no refreshes are necessary.
200 // close buffers first
201 bufferlist.closeAll();
203 // do any other cleanup procedures now
204 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
206 if (destroyDir(package().temp_dir()) != 0) {
207 string msg = bformat(_("Could not remove the temporary directory %1$s"),
208 package().temp_dir());
209 Alert::warning(_("Could not remove temporary directory"), msg);
218 class AutoSaveBuffer : public ForkedProcess {
221 AutoSaveBuffer(BufferView & bv, string const & fname)
222 : bv_(bv), fname_(fname) {}
224 virtual shared_ptr<ForkedProcess> clone() const
226 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
232 virtual int generateChild();
239 int AutoSaveBuffer::start()
241 command_ = bformat(_("Auto-saving %1$s"), fname_);
242 return run(DontWait);
246 int AutoSaveBuffer::generateChild()
248 // tmp_ret will be located (usually) in /tmp
249 // will that be a problem?
250 pid_t const pid = fork(); // If you want to debug the autosave
251 // you should set pid to -1, and comment out the
253 if (pid == 0 || pid == -1) {
254 // pid = -1 signifies that lyx was unable
255 // to fork. But we will do the save
259 string const tmp_ret = tempName(string(), "lyxauto");
260 if (!tmp_ret.empty()) {
261 bv_.buffer()->writeFile(tmp_ret);
262 // assume successful write of tmp_ret
263 if (!rename(tmp_ret, fname_)) {
265 // most likely couldn't move between filesystems
266 // unless write of tmp_ret failed
267 // so remove tmp file (if it exists)
275 // failed to write/rename tmp_ret so try writing direct
276 if (!bv_.buffer()->writeFile(fname_)) {
277 // It is dangerous to do this in the child,
278 // but safe in the parent, so...
280 bv_.owner()->message(_("Autosave failed!"));
283 if (pid == 0) { // we are the child so...
293 void AutoSave(BufferView * bv)
294 // should probably be moved into BufferList (Lgb)
295 // Perfect target for a thread...
297 if (!bv->available())
300 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
301 // We don't save now, but we'll try again later
302 bv->owner()->resetAutosaveTimer();
306 bv->owner()->message(_("Autosaving current document..."));
308 // create autosave filename
309 string fname = bv->buffer()->filePath();
311 fname += OnlyFilename(bv->buffer()->fileName());
314 AutoSaveBuffer autosave(*bv, fname);
317 bv->buffer()->markBakClean();
318 bv->owner()->resetAutosaveTimer();
323 // Copyright CHT Software Service GmbH
326 // create new file with template
329 void NewFile(BufferView * bv, string const & filename)
331 // Split argument by :
333 string tmpname = split(filename, name, ':');
334 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
335 if (name.length() == 1
336 && isalpha(static_cast<unsigned char>(name[0]))
337 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
339 name += token(tmpname, ':', 0);
340 tmpname = split(tmpname, ':');
343 lyxerr[Debug::INFO] << "Arg is " << filename
344 << "\nName is " << name
345 << "\nTemplate is " << tmpname << endl;
347 bv->newFile(name, tmpname);
351 // Insert ascii file (if filename is empty, prompt for one)
352 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
354 if (!bv->available())
357 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
361 // clear the selection
362 if (bv->text() == bv->getLyXText())
363 bv->cursor().clearSelection();
365 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
367 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
372 // Insert ascii file (if filename is empty, prompt for one)
373 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
378 FileDialog fileDlg(_("Select file to insert"),
379 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
381 FileDialog::Result result =
382 fileDlg.open(bv->owner()->buffer()->filePath(),
383 FileFilterList(), string());
385 if (result.first == FileDialog::Later)
388 fname = result.second;
396 if (!fi.readable()) {
397 string const error = strerror(errno);
398 string const file = MakeDisplayPath(fname, 50);
399 string const text = bformat(_("Could not read the specified document\n"
400 "%1$s\ndue to the error: %2$s"), file, error);
401 Alert::error(_("Could not read file"), text);
405 ifstream ifs(fname.c_str());
407 string const error = strerror(errno);
408 string const file = MakeDisplayPath(fname, 50);
409 string const text = bformat(_("Could not open the specified document\n"
410 "%1$s\ndue to the error: %2$s"), file, error);
411 Alert::error(_("Could not open file"), text);
415 ifs.unsetf(ios::skipws);
416 istream_iterator<char> ii(ifs);
417 istream_iterator<char> end;
418 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
419 // We use this until the compilers get better...
420 std::vector<char> tmp;
421 copy(ii, end, back_inserter(tmp));
422 string const tmpstr(tmp.begin(), tmp.end());
424 // This is what we want to use and what we will use once the
425 // compilers get good enough.
426 //string tmpstr(ii, end); // yet a reason for using std::string
427 // alternate approach to get the file into a string:
429 copy(ii, end, back_inserter(tmpstr));
436 // This function runs "configure" and then rereads lyx.defaults to
437 // reconfigure the automatic settings.
438 void Reconfigure(BufferView * bv)
440 bv->owner()->message(_("Running configure..."));
442 // Run configure in user lyx directory
443 Path p(package().user_support());
444 string const configure_script =
445 AddName(package().system_support(), "configure");
446 string const configure_command = "sh " + QuoteName(configure_script);
448 one.startscript(Systemcall::Wait, configure_command);
450 bv->owner()->message(_("Reloading configuration..."));
451 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
453 Alert::information(_("System reconfigured"),
454 _("The system has been reconfigured.\n"
455 "You need to restart LyX to make use of any\n"
456 "updated document class specifications."));