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"
38 #include "support/filefilterlist.h"
39 #include "support/filetools.h"
40 #include "support/fontutils.h"
41 #include "support/forkedcall.h"
42 #include "support/fs_extras.h"
43 #include "support/lyxlib.h"
44 #include "support/package.h"
45 #include "support/path.h"
46 #include "support/systemcall.h"
48 #if !defined (HAVE_FORK)
52 #include <boost/shared_ptr.hpp>
53 #include <boost/filesystem/operations.hpp>
59 using lyx::support::addName;
60 using lyx::support::bformat;
61 using lyx::support::destroyDir;
62 using lyx::support::FileFilterList;
63 using lyx::support::ForkedProcess;
64 using lyx::support::isLyXFilename;
65 using lyx::support::libFileSearch;
66 using lyx::support::makeAbsPath;
67 using lyx::support::makeDisplayPath;
68 using lyx::support::onlyFilename;
69 using lyx::support::onlyPath;
70 using lyx::support::package;
71 using lyx::support::removeAutosaveFile;
72 using lyx::support::rename;
73 using lyx::support::split;
74 using lyx::support::Systemcall;
75 using lyx::support::tempName;
76 using lyx::support::unlink;
78 using boost::shared_ptr;
80 namespace Alert = lyx::frontend::Alert;
81 namespace fs = boost::filesystem;
83 using std::back_inserter;
90 using std::istream_iterator;
93 // this should be static, but I need it in buffer.C
94 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()) {
131 FileDialog fileDlg(_("Choose a filename to save document as"),
132 LFUN_BUFFER_WRITE_AS,
133 make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
134 make_pair(_("Templates|#T#t"), lyx::from_utf8(lyxrc.template_path)));
136 if (!isLyXFilename(fname))
139 FileFilterList const filter (_("LyX Documents (*.lyx)"));
141 FileDialog::Result result =
142 fileDlg.save(lyx::from_utf8(onlyPath(fname)),
144 lyx::from_utf8(onlyFilename(fname)));
146 if (result.first == FileDialog::Later)
149 fname = lyx::to_utf8(result.second);
154 // Make sure the absolute filename ends with appropriate suffix
155 fname = makeAbsPath(fname);
156 if (!isLyXFilename(fname))
161 if (fs::exists(fname)) {
162 docstring const file = makeDisplayPath(fname, 30);
163 docstring 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);
189 void quitLyX(bool noask)
191 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
194 if (!noask && !theBufferList().quitWriteAll())
197 LyX::cref().session().writeFile();
200 // Set a flag that we do quitting from the program,
201 // so no refreshes are necessary.
204 // close buffers first
205 theBufferList().closeAll();
207 // do any other cleanup procedures now
208 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
210 if (!destroyDir(package().temp_dir())) {
211 docstring const msg =
212 bformat(_("Unable to remove the temporary directory %1$s"),
213 lyx::from_utf8(package().temp_dir()));
214 Alert::warning(_("Unable to remove temporary directory"), msg);
220 // Restore original font resources after Application is destroyed.
221 lyx::support::restoreFontResources();
228 class AutoSaveBuffer : public ForkedProcess {
231 AutoSaveBuffer(BufferView & bv, string const & fname)
232 : bv_(bv), fname_(fname) {}
234 virtual shared_ptr<ForkedProcess> clone() const
236 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
242 virtual int generateChild();
249 int AutoSaveBuffer::start()
251 command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
252 return run(DontWait);
256 int AutoSaveBuffer::generateChild()
258 // tmp_ret will be located (usually) in /tmp
259 // will that be a problem?
260 pid_t const pid = fork(); // If you want to debug the autosave
261 // you should set pid to -1, and comment out the
263 if (pid == 0 || pid == -1) {
264 // pid = -1 signifies that lyx was unable
265 // to fork. But we will do the save
269 string const tmp_ret = tempName(string(), "lyxauto");
270 if (!tmp_ret.empty()) {
271 bv_.buffer()->writeFile(tmp_ret);
272 // assume successful write of tmp_ret
273 if (!rename(tmp_ret, fname_)) {
275 // most likely couldn't move between filesystems
276 // unless write of tmp_ret failed
277 // so remove tmp file (if it exists)
285 // failed to write/rename tmp_ret so try writing direct
286 if (!bv_.buffer()->writeFile(fname_)) {
287 // It is dangerous to do this in the child,
288 // but safe in the parent, so...
290 // emit message signal.
291 bv_.buffer()->message(_("Autosave failed!"));
294 if (pid == 0) { // we are the child so...
304 void autoSave(BufferView * bv)
305 // should probably be moved into BufferList (Lgb)
306 // Perfect target for a thread...
311 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
312 // We don't save now, but we'll try again later
313 bv->buffer()->resetAutosaveTimers();
317 // emit message signal.
318 bv->buffer()->message(_("Autosaving current document..."));
320 // create autosave filename
321 string fname = bv->buffer()->filePath();
323 fname += onlyFilename(bv->buffer()->fileName());
326 AutoSaveBuffer autosave(*bv, fname);
329 bv->buffer()->markBakClean();
330 bv->buffer()->resetAutosaveTimers();
335 // Copyright CHT Software Service GmbH
338 // create new file with template
341 void newFile(BufferView * bv, string const & filename)
343 // Split argument by :
345 string tmpname = split(filename, name, ':');
346 lyxerr[Debug::INFO] << "Arg is " << filename
347 << "\nName is " << name
348 << "\nTemplate is " << tmpname << endl;
350 Buffer * const b = newFile(name, tmpname);
356 // Insert ascii file (if filename is empty, prompt for one)
357 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
362 // FIXME: We don't know the encoding of the file
363 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
367 // clear the selection
368 LyXText const & text = bv->buffer()->text();
369 if (&text == bv->getLyXText())
370 bv->cursor().clearSelection();
372 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
374 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
379 // Insert ascii file (if filename is empty, prompt for one)
380 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
385 FileDialog fileDlg(_("Select file to insert"),
386 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
388 FileDialog::Result result =
389 fileDlg.open(lyx::from_utf8(bv->buffer()->filePath()),
390 FileFilterList(), docstring());
392 if (result.first == FileDialog::Later)
395 fname = lyx::to_utf8(result.second);
401 if (!fs::is_readable(fname)) {
402 docstring const error = lyx::from_ascii(strerror(errno));
403 docstring const file = makeDisplayPath(fname, 50);
404 docstring const text = bformat(_("Could not read the specified document\n"
405 "%1$s\ndue to the error: %2$s"), file, error);
406 Alert::error(_("Could not read file"), text);
410 ifstream ifs(fname.c_str());
412 docstring const error = lyx::from_ascii(strerror(errno));
413 docstring const file = makeDisplayPath(fname, 50);
414 docstring const text = bformat(_("Could not open the specified document\n"
415 "%1$s\ndue to the error: %2$s"), file, error);
416 Alert::error(_("Could not open file"), text);
420 ifs.unsetf(ios::skipws);
421 istream_iterator<char> ii(ifs);
422 istream_iterator<char> end;
423 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
424 // We use this until the compilers get better...
425 std::vector<char> tmp;
426 copy(ii, end, back_inserter(tmp));
427 string const tmpstr(tmp.begin(), tmp.end());
429 // This is what we want to use and what we will use once the
430 // compilers get good enough.
431 //string tmpstr(ii, end); // yet a reason for using std::string
432 // alternate approach to get the file into a string:
434 copy(ii, end, back_inserter(tmpstr));
441 // This function runs "configure" and then rereads lyx.defaults to
442 // reconfigure the automatic settings.
443 void reconfigure(BufferView * bv)
445 // emit message signal.
446 bv->buffer()->message(_("Running configure..."));
448 // Run configure in user lyx directory
449 lyx::support::Path p(package().user_support());
450 string const configure_command = package().configure_command();
452 one.startscript(Systemcall::Wait, configure_command);
454 // emit message signal.
455 bv->buffer()->message(_("Reloading configuration..."));
456 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
457 // Re-read packages.lst
458 LaTeXFeatures::getAvailable();
460 Alert::information(_("System reconfigured"),
461 _("The system has been reconfigured.\n"
462 "You need to restart LyX to make use of any\n"
463 "updated document class specifications."));