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"
22 #include "buffer_funcs.h"
27 #include "LaTeXFeatures.h"
29 #include "lyxlayout.h"
32 #include "paragraph.h"
34 #include "frontends/Alert.h"
35 #include "frontends/FileDialog.h"
36 #include "frontends/lyx_gui.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 #if !defined (HAVE_FORK)
51 #include <boost/shared_ptr.hpp>
52 #include <boost/filesystem/operations.hpp>
58 using lyx::support::addName;
59 using lyx::support::bformat;
60 using lyx::support::destroyDir;
61 using lyx::support::FileFilterList;
62 using lyx::support::ForkedProcess;
63 using lyx::support::isLyXFilename;
64 using lyx::support::libFileSearch;
65 using lyx::support::makeAbsPath;
66 using lyx::support::makeDisplayPath;
67 using lyx::support::onlyFilename;
68 using lyx::support::onlyPath;
69 using lyx::support::package;
70 using lyx::support::removeAutosaveFile;
71 using lyx::support::rename;
72 using lyx::support::split;
73 using lyx::support::Systemcall;
74 using lyx::support::tempName;
75 using lyx::support::unlink;
77 using boost::shared_ptr;
79 namespace fs = boost::filesystem;
81 using std::back_inserter;
88 using std::istream_iterator;
91 extern BufferList bufferlist;
92 // this should be static, but I need it in buffer.C
93 bool quitting; // flag, that we are quitting the program
100 bool menuWrite(Buffer * buffer)
102 if (buffer->save()) {
103 LyX::ref().session().addLastFile(buffer->fileName());
107 // FIXME: we don't tell the user *WHY* the save failed !!
109 docstring const file = makeDisplayPath(buffer->fileName(), 30);
111 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
112 "Do you want to rename the document and try again?"), file);
113 int const ret = Alert::prompt(_("Rename and save?"),
114 text, 0, 1, _("&Rename"), _("&Cancel"));
117 return writeAs(buffer);
123 bool writeAs(Buffer * buffer, string const & filename)
125 string fname = buffer->fileName();
126 string const oldname = fname;
128 if (filename.empty()) {
130 FileDialog fileDlg(lyx::to_utf8(_("Choose a filename to save document as")),
131 LFUN_BUFFER_WRITE_AS,
132 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
133 string(lyxrc.document_path)),
134 make_pair(string(lyx::to_utf8(_("Templates|#T#t"))),
135 string(lyxrc.template_path)));
137 if (!isLyXFilename(fname))
140 FileFilterList const filter (lyx::to_utf8(_("LyX Documents (*.lyx)")));
142 FileDialog::Result result =
143 fileDlg.save(onlyPath(fname),
145 onlyFilename(fname));
147 if (result.first == FileDialog::Later)
150 fname = result.second;
155 // Make sure the absolute filename ends with appropriate suffix
156 fname = makeAbsPath(fname);
157 if (!isLyXFilename(fname))
162 if (fs::exists(fname)) {
163 docstring const file = makeDisplayPath(fname, 30);
164 docstring text = bformat(_("The document %1$s already exists.\n\n"
165 "Do you want to over-write that document?"), file);
166 int const ret = Alert::prompt(_("Over-write document?"),
167 text, 0, 1, _("&Over-write"), _("&Cancel"));
173 // Ok, change the name of the buffer
174 buffer->setFileName(fname);
176 bool unnamed = buffer->isUnnamed();
177 buffer->setUnnamed(false);
179 if (!menuWrite(buffer)) {
180 buffer->setFileName(oldname);
181 buffer->setUnnamed(unnamed);
185 removeAutosaveFile(oldname);
190 void quitLyX(bool noask)
192 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
194 if (lyx_gui::use_gui) {
195 if (!noask && !bufferlist.quitWriteAll())
198 LyX::cref().session().writeFile();
201 // Set a flag that we do quitting from the program,
202 // so no refreshes are necessary.
205 // close buffers first
206 bufferlist.closeAll();
208 // do any other cleanup procedures now
209 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
211 if (!destroyDir(package().temp_dir())) {
212 docstring const msg =
213 bformat(_("Unable to remove the temporary directory %1$s"),
214 lyx::from_utf8(package().temp_dir()));
215 Alert::warning(_("Unable to remove temporary directory"), msg);
224 class AutoSaveBuffer : public ForkedProcess {
227 AutoSaveBuffer(BufferView & bv, string const & fname)
228 : bv_(bv), fname_(fname) {}
230 virtual shared_ptr<ForkedProcess> clone() const
232 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
238 virtual int generateChild();
245 int AutoSaveBuffer::start()
247 command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
248 return run(DontWait);
252 int AutoSaveBuffer::generateChild()
254 // tmp_ret will be located (usually) in /tmp
255 // will that be a problem?
256 pid_t const pid = fork(); // If you want to debug the autosave
257 // you should set pid to -1, and comment out the
259 if (pid == 0 || pid == -1) {
260 // pid = -1 signifies that lyx was unable
261 // to fork. But we will do the save
265 string const tmp_ret = tempName(string(), "lyxauto");
266 if (!tmp_ret.empty()) {
267 bv_.buffer()->writeFile(tmp_ret);
268 // assume successful write of tmp_ret
269 if (!rename(tmp_ret, fname_)) {
271 // most likely couldn't move between filesystems
272 // unless write of tmp_ret failed
273 // so remove tmp file (if it exists)
281 // failed to write/rename tmp_ret so try writing direct
282 if (!bv_.buffer()->writeFile(fname_)) {
283 // It is dangerous to do this in the child,
284 // but safe in the parent, so...
286 // emit message signal.
287 bv_.buffer()->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...
307 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
308 // We don't save now, but we'll try again later
309 bv->buffer()->resetAutosaveTimers();
313 // emit message signal.
314 bv->buffer()->message(_("Autosaving current document..."));
316 // create autosave filename
317 string fname = bv->buffer()->filePath();
319 fname += onlyFilename(bv->buffer()->fileName());
322 AutoSaveBuffer autosave(*bv, fname);
325 bv->buffer()->markBakClean();
326 bv->buffer()->resetAutosaveTimers();
331 // Copyright CHT Software Service GmbH
334 // create new file with template
337 void newFile(BufferView * bv, string const & filename)
339 // Split argument by :
341 string tmpname = split(filename, name, ':');
342 lyxerr[Debug::INFO] << "Arg is " << filename
343 << "\nName is " << name
344 << "\nTemplate is " << tmpname << endl;
346 Buffer * const b = newFile(name, tmpname);
352 // Insert ascii file (if filename is empty, prompt for one)
353 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
358 // FIXME: We don't know the encoding of the file
359 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
363 // clear the selection
364 LyXText const & text = bv->buffer()->text();
365 if (&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(lyx::to_utf8(_("Select file to insert")),
382 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
384 FileDialog::Result result =
385 fileDlg.open(bv->buffer()->filePath(),
386 FileFilterList(), string());
388 if (result.first == FileDialog::Later)
391 fname = result.second;
397 if (!fs::is_readable(fname)) {
398 docstring const error = lyx::from_ascii(strerror(errno));
399 docstring const file = makeDisplayPath(fname, 50);
400 docstring 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 docstring const error = lyx::from_ascii(strerror(errno));
409 docstring const file = makeDisplayPath(fname, 50);
410 docstring 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 // emit message signal.
442 bv->buffer()->message(_("Running configure..."));
444 // Run configure in user lyx directory
445 lyx::support::Path p(package().user_support());
446 string const configure_command = package().configure_command();
448 one.startscript(Systemcall::Wait, configure_command);
450 // emit message signal.
451 bv->buffer()->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."));