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/Application.h"
36 #include "frontends/FileDialog.h"
37 #include "frontends/lyx_gui.h"
39 #include "support/filefilterlist.h"
40 #include "support/filetools.h"
41 #include "support/fontutils.h"
42 #include "support/forkedcall.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
45 #include "support/package.h"
46 #include "support/path.h"
47 #include "support/systemcall.h"
49 #if !defined (HAVE_FORK)
53 #include <boost/shared_ptr.hpp>
54 #include <boost/filesystem/operations.hpp>
60 using lyx::support::addName;
61 using lyx::support::bformat;
62 using lyx::support::destroyDir;
63 using lyx::support::FileFilterList;
64 using lyx::support::ForkedProcess;
65 using lyx::support::isLyXFilename;
66 using lyx::support::libFileSearch;
67 using lyx::support::makeAbsPath;
68 using lyx::support::makeDisplayPath;
69 using lyx::support::onlyFilename;
70 using lyx::support::onlyPath;
71 using lyx::support::package;
72 using lyx::support::removeAutosaveFile;
73 using lyx::support::rename;
74 using lyx::support::split;
75 using lyx::support::Systemcall;
76 using lyx::support::tempName;
77 using lyx::support::unlink;
79 using boost::shared_ptr;
81 namespace Alert = lyx::frontend::Alert;
82 namespace fs = boost::filesystem;
84 using std::back_inserter;
91 using std::istream_iterator;
94 // this should be static, but I need it in buffer.C
95 bool quitting; // flag, that we are quitting the program
102 bool menuWrite(Buffer * buffer)
104 if (buffer->save()) {
105 LyX::ref().session().addLastFile(buffer->fileName());
109 // FIXME: we don't tell the user *WHY* the save failed !!
111 docstring const file = makeDisplayPath(buffer->fileName(), 30);
113 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
114 "Do you want to rename the document and try again?"), file);
115 int const ret = Alert::prompt(_("Rename and save?"),
116 text, 0, 1, _("&Rename"), _("&Cancel"));
119 return writeAs(buffer);
125 bool writeAs(Buffer * buffer, string const & filename)
127 string fname = buffer->fileName();
128 string const oldname = fname;
130 if (filename.empty()) {
133 FileDialog fileDlg(_("Choose a filename to save document as"),
134 LFUN_BUFFER_WRITE_AS,
135 make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
136 make_pair(_("Templates|#T#t"), lyx::from_utf8(lyxrc.template_path)));
138 if (!isLyXFilename(fname))
141 FileFilterList const filter (_("LyX Documents (*.lyx)"));
143 FileDialog::Result result =
144 fileDlg.save(lyx::from_utf8(onlyPath(fname)),
146 lyx::from_utf8(onlyFilename(fname)));
148 if (result.first == FileDialog::Later)
151 fname = lyx::to_utf8(result.second);
156 // Make sure the absolute filename ends with appropriate suffix
157 fname = makeAbsPath(fname);
158 if (!isLyXFilename(fname))
163 if (fs::exists(fname)) {
164 docstring const file = makeDisplayPath(fname, 30);
165 docstring text = bformat(_("The document %1$s already exists.\n\n"
166 "Do you want to over-write that document?"), file);
167 int const ret = Alert::prompt(_("Over-write document?"),
168 text, 0, 1, _("&Over-write"), _("&Cancel"));
174 // Ok, change the name of the buffer
175 buffer->setFileName(fname);
177 bool unnamed = buffer->isUnnamed();
178 buffer->setUnnamed(false);
180 if (!menuWrite(buffer)) {
181 buffer->setFileName(oldname);
182 buffer->setUnnamed(unnamed);
186 removeAutosaveFile(oldname);
191 void quitLyX(bool noask)
193 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
195 if (lyx_gui::use_gui) {
196 if (!noask && !theBufferList().quitWriteAll())
199 LyX::cref().session().writeFile();
202 // Set a flag that we do quitting from the program,
203 // so no refreshes are necessary.
206 // close buffers first
207 theBufferList().closeAll();
209 // do any other cleanup procedures now
210 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
212 if (!destroyDir(package().temp_dir())) {
213 docstring const msg =
214 bformat(_("Unable to remove the temporary directory %1$s"),
215 lyx::from_utf8(package().temp_dir()));
216 Alert::warning(_("Unable to remove temporary directory"), msg);
220 // Restore original font resources after Application is destroyed.
221 lyx::support::restoreFontResources();
227 class AutoSaveBuffer : public ForkedProcess {
230 AutoSaveBuffer(BufferView & bv, string const & fname)
231 : bv_(bv), fname_(fname) {}
233 virtual shared_ptr<ForkedProcess> clone() const
235 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
241 virtual int generateChild();
248 int AutoSaveBuffer::start()
250 command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
251 return run(DontWait);
255 int AutoSaveBuffer::generateChild()
257 // tmp_ret will be located (usually) in /tmp
258 // will that be a problem?
259 pid_t const pid = fork(); // If you want to debug the autosave
260 // you should set pid to -1, and comment out the
262 if (pid == 0 || pid == -1) {
263 // pid = -1 signifies that lyx was unable
264 // to fork. But we will do the save
268 string const tmp_ret = tempName(string(), "lyxauto");
269 if (!tmp_ret.empty()) {
270 bv_.buffer()->writeFile(tmp_ret);
271 // assume successful write of tmp_ret
272 if (!rename(tmp_ret, fname_)) {
274 // most likely couldn't move between filesystems
275 // unless write of tmp_ret failed
276 // so remove tmp file (if it exists)
284 // failed to write/rename tmp_ret so try writing direct
285 if (!bv_.buffer()->writeFile(fname_)) {
286 // It is dangerous to do this in the child,
287 // but safe in the parent, so...
289 // emit message signal.
290 bv_.buffer()->message(_("Autosave failed!"));
293 if (pid == 0) { // we are the child so...
303 void autoSave(BufferView * bv)
304 // should probably be moved into BufferList (Lgb)
305 // Perfect target for a thread...
310 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
311 // We don't save now, but we'll try again later
312 bv->buffer()->resetAutosaveTimers();
316 // emit message signal.
317 bv->buffer()->message(_("Autosaving current document..."));
319 // create autosave filename
320 string fname = bv->buffer()->filePath();
322 fname += onlyFilename(bv->buffer()->fileName());
325 AutoSaveBuffer autosave(*bv, fname);
328 bv->buffer()->markBakClean();
329 bv->buffer()->resetAutosaveTimers();
334 // Copyright CHT Software Service GmbH
337 // create new file with template
340 void newFile(BufferView * bv, string const & filename)
342 // Split argument by :
344 string tmpname = split(filename, name, ':');
345 lyxerr[Debug::INFO] << "Arg is " << filename
346 << "\nName is " << name
347 << "\nTemplate is " << tmpname << endl;
349 Buffer * const b = newFile(name, tmpname);
355 // Insert ascii file (if filename is empty, prompt for one)
356 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
361 // FIXME: We don't know the encoding of the file
362 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
366 // clear the selection
367 LyXText const & text = bv->buffer()->text();
368 if (&text == bv->getLyXText())
369 bv->cursor().clearSelection();
371 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
373 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
378 // Insert ascii file (if filename is empty, prompt for one)
379 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
384 FileDialog fileDlg(_("Select file to insert"),
385 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
387 FileDialog::Result result =
388 fileDlg.open(lyx::from_utf8(bv->buffer()->filePath()),
389 FileFilterList(), docstring());
391 if (result.first == FileDialog::Later)
394 fname = lyx::to_utf8(result.second);
400 if (!fs::is_readable(fname)) {
401 docstring const error = lyx::from_ascii(strerror(errno));
402 docstring const file = makeDisplayPath(fname, 50);
403 docstring 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 docstring const error = lyx::from_ascii(strerror(errno));
412 docstring const file = makeDisplayPath(fname, 50);
413 docstring 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 // emit message signal.
445 bv->buffer()->message(_("Running configure..."));
447 // Run configure in user lyx directory
448 lyx::support::Path p(package().user_support());
449 string const configure_command = package().configure_command();
451 one.startscript(Systemcall::Wait, configure_command);
453 // emit message signal.
454 bv->buffer()->message(_("Reloading configuration..."));
455 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
456 // Re-read packages.lst
457 LaTeXFeatures::getAvailable();
459 Alert::information(_("System reconfigured"),
460 _("The system has been reconfigured.\n"
461 "You need to restart LyX to make use of any\n"
462 "updated document class specifications."));