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
104 bool menuWrite(Buffer * buffer)
106 if (buffer->save()) {
107 LyX::ref().session().addLastFile(buffer->fileName());
111 // FIXME: we don't tell the user *WHY* the save failed !!
113 docstring const file = makeDisplayPath(buffer->fileName(), 30);
115 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
116 "Do you want to rename the document and try again?"), file);
117 int const ret = Alert::prompt(_("Rename and save?"),
118 text, 0, 1, _("&Rename"), _("&Cancel"));
121 return writeAs(buffer);
127 bool writeAs(Buffer * buffer, string const & filename)
129 string fname = buffer->fileName();
130 string const oldname = fname;
132 if (filename.empty()) {
135 FileDialog fileDlg(_("Choose a filename to save document as"),
136 LFUN_BUFFER_WRITE_AS,
137 make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
138 make_pair(_("Templates|#T#t"), lyx::from_utf8(lyxrc.template_path)));
140 if (!isLyXFilename(fname))
143 FileFilterList const filter (_("LyX Documents (*.lyx)"));
145 FileDialog::Result result =
146 fileDlg.save(lyx::from_utf8(onlyPath(fname)),
148 lyx::from_utf8(onlyFilename(fname)));
150 if (result.first == FileDialog::Later)
153 fname = lyx::to_utf8(result.second);
158 // Make sure the absolute filename ends with appropriate suffix
159 fname = makeAbsPath(fname);
160 if (!isLyXFilename(fname))
165 if (fs::exists(fname)) {
166 docstring const file = makeDisplayPath(fname, 30);
167 docstring text = bformat(_("The document %1$s already exists.\n\n"
168 "Do you want to over-write that document?"), file);
169 int const ret = Alert::prompt(_("Over-write document?"),
170 text, 0, 1, _("&Over-write"), _("&Cancel"));
176 // Ok, change the name of the buffer
177 buffer->setFileName(fname);
179 bool unnamed = buffer->isUnnamed();
180 buffer->setUnnamed(false);
182 if (!menuWrite(buffer)) {
183 buffer->setFileName(oldname);
184 buffer->setUnnamed(unnamed);
188 removeAutosaveFile(oldname);
193 void quitLyX(bool noask)
195 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
198 if (!noask && !theBufferList().quitWriteAll())
201 LyX::cref().session().writeFile();
204 // Set a flag that we do quitting from the program,
205 // so no refreshes are necessary.
208 // close buffers first
209 theBufferList().closeAll();
211 // do any other cleanup procedures now
212 lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
214 if (!destroyDir(package().temp_dir())) {
215 docstring const msg =
216 bformat(_("Unable to remove the temporary directory %1$s"),
217 lyx::from_utf8(package().temp_dir()));
218 Alert::warning(_("Unable to remove temporary directory"), msg);
224 // Restore original font resources after Application is destroyed.
225 lyx::support::restoreFontResources();
232 class AutoSaveBuffer : public ForkedProcess {
235 AutoSaveBuffer(BufferView & bv, string const & fname)
236 : bv_(bv), fname_(fname) {}
238 virtual shared_ptr<ForkedProcess> clone() const
240 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
246 virtual int generateChild();
253 int AutoSaveBuffer::start()
255 command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
256 return run(DontWait);
260 int AutoSaveBuffer::generateChild()
262 // tmp_ret will be located (usually) in /tmp
263 // will that be a problem?
264 pid_t const pid = fork(); // If you want to debug the autosave
265 // you should set pid to -1, and comment out the
267 if (pid == 0 || pid == -1) {
268 // pid = -1 signifies that lyx was unable
269 // to fork. But we will do the save
273 string const tmp_ret = tempName(string(), "lyxauto");
274 if (!tmp_ret.empty()) {
275 bv_.buffer()->writeFile(tmp_ret);
276 // assume successful write of tmp_ret
277 if (!rename(tmp_ret, fname_)) {
279 // most likely couldn't move between filesystems
280 // unless write of tmp_ret failed
281 // so remove tmp file (if it exists)
289 // failed to write/rename tmp_ret so try writing direct
290 if (!bv_.buffer()->writeFile(fname_)) {
291 // It is dangerous to do this in the child,
292 // but safe in the parent, so...
294 // emit message signal.
295 bv_.buffer()->message(_("Autosave failed!"));
298 if (pid == 0) { // we are the child so...
308 void autoSave(BufferView * bv)
309 // should probably be moved into BufferList (Lgb)
310 // Perfect target for a thread...
315 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
316 // We don't save now, but we'll try again later
317 bv->buffer()->resetAutosaveTimers();
321 // emit message signal.
322 bv->buffer()->message(_("Autosaving current document..."));
324 // create autosave filename
325 string fname = bv->buffer()->filePath();
327 fname += onlyFilename(bv->buffer()->fileName());
330 AutoSaveBuffer autosave(*bv, fname);
333 bv->buffer()->markBakClean();
334 bv->buffer()->resetAutosaveTimers();
339 // Copyright CHT Software Service GmbH
342 // create new file with template
345 void newFile(BufferView * bv, string const & filename)
347 // Split argument by :
349 string tmpname = split(filename, name, ':');
350 lyxerr[Debug::INFO] << "Arg is " << filename
351 << "\nName is " << name
352 << "\nTemplate is " << tmpname << endl;
354 Buffer * const b = newFile(name, tmpname);
360 // Insert ascii file (if filename is empty, prompt for one)
361 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
366 // FIXME: We don't know the encoding of the file
367 docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
371 // clear the selection
372 LyXText const & text = bv->buffer()->text();
373 if (&text == bv->getLyXText())
374 bv->cursor().clearSelection();
376 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
378 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
383 // Insert ascii file (if filename is empty, prompt for one)
384 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
389 FileDialog fileDlg(_("Select file to insert"),
390 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
392 FileDialog::Result result =
393 fileDlg.open(lyx::from_utf8(bv->buffer()->filePath()),
394 FileFilterList(), docstring());
396 if (result.first == FileDialog::Later)
399 fname = lyx::to_utf8(result.second);
405 if (!fs::is_readable(fname)) {
406 docstring const error = lyx::from_ascii(strerror(errno));
407 docstring const file = makeDisplayPath(fname, 50);
408 docstring const text = bformat(_("Could not read the specified document\n"
409 "%1$s\ndue to the error: %2$s"), file, error);
410 Alert::error(_("Could not read file"), text);
414 ifstream ifs(fname.c_str());
416 docstring const error = lyx::from_ascii(strerror(errno));
417 docstring const file = makeDisplayPath(fname, 50);
418 docstring const text = bformat(_("Could not open the specified document\n"
419 "%1$s\ndue to the error: %2$s"), file, error);
420 Alert::error(_("Could not open file"), text);
424 ifs.unsetf(ios::skipws);
425 istream_iterator<char> ii(ifs);
426 istream_iterator<char> end;
427 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
428 // We use this until the compilers get better...
429 std::vector<char> tmp;
430 copy(ii, end, back_inserter(tmp));
431 string const tmpstr(tmp.begin(), tmp.end());
433 // This is what we want to use and what we will use once the
434 // compilers get good enough.
435 //string tmpstr(ii, end); // yet a reason for using std::string
436 // alternate approach to get the file into a string:
438 copy(ii, end, back_inserter(tmpstr));
445 // This function runs "configure" and then rereads lyx.defaults to
446 // reconfigure the automatic settings.
447 void reconfigure(BufferView * bv)
449 // emit message signal.
450 bv->buffer()->message(_("Running configure..."));
452 // Run configure in user lyx directory
453 lyx::support::Path p(package().user_support());
454 string const configure_command = package().configure_command();
456 one.startscript(Systemcall::Wait, configure_command);
458 // emit message signal.
459 bv->buffer()->message(_("Reloading configuration..."));
460 lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
461 // Re-read packages.lst
462 LaTeXFeatures::getAvailable();
464 Alert::information(_("System reconfigured"),
465 _("The system has been reconfigured.\n"
466 "You need to restart LyX to make use of any\n"
467 "updated document class specifications."));