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/FileInfo.h"
38 #include "support/filetools.h"
39 #include "support/forkedcall.h"
40 #include "support/globbing.h"
41 #include "support/lyxlib.h"
42 #include "support/os.h"
43 #include "support/path.h"
44 #include "support/path_defines.h"
45 #include "support/systemcall.h"
47 #include <boost/shared_ptr.hpp>
52 using lyx::support::AddName;
53 using lyx::support::bformat;
54 using lyx::support::destroyDir;
55 using lyx::support::FileFilterList;
56 using lyx::support::FileInfo;
57 using lyx::support::ForkedProcess;
58 using lyx::support::IsLyXFilename;
59 using lyx::support::LibFileSearch;
60 using lyx::support::MakeAbsPath;
61 using lyx::support::MakeDisplayPath;
62 using lyx::support::OnlyFilename;
63 using lyx::support::OnlyPath;
64 using lyx::support::Path;
65 using lyx::support::removeAutosaveFile;
66 using lyx::support::rename;
67 using lyx::support::split;
68 using lyx::support::system_lyxdir;
69 using lyx::support::Systemcall;
70 using lyx::support::tempName;
71 using lyx::support::unlink;
72 using lyx::support::user_lyxdir;
74 namespace os = lyx::support::os;
76 using boost::shared_ptr;
78 using std::back_inserter;
85 using std::istream_iterator;
88 extern BufferList bufferlist;
89 // this should be static, but I need it in buffer.C
90 bool quitting; // flag, that we are quitting the program
97 bool MenuWrite(Buffer * buffer)
100 LyX::ref().lastfiles().newFile(buffer->fileName());
104 // FIXME: we don't tell the user *WHY* the save failed !!
106 string const file = MakeDisplayPath(buffer->fileName(), 30);
108 string text = bformat(_("The document %1$s could not be saved.\n\n"
109 "Do you want to rename the document and try again?"), file);
110 int const ret = Alert::prompt(_("Rename and save?"),
111 text, 0, 1, _("&Rename"), _("&Cancel"));
114 return WriteAs(buffer);
120 bool WriteAs(Buffer * buffer, string const & filename)
122 string fname = buffer->fileName();
123 string const oldname = fname;
125 if (filename.empty()) {
127 FileDialog fileDlg(_("Choose a filename to save document as"),
129 make_pair(string(_("Documents|#o#O")),
130 string(lyxrc.document_path)),
131 make_pair(string(_("Templates|#T#t")),
132 string(lyxrc.template_path)));
134 if (!IsLyXFilename(fname))
137 FileFilterList const filter (_("LyX Documents (*.lyx)"));
139 FileDialog::Result result =
140 fileDlg.save(OnlyPath(fname),
142 OnlyFilename(fname));
144 if (result.first == FileDialog::Later)
147 fname = result.second;
152 // Make sure the absolute filename ends with appropriate suffix
153 fname = MakeAbsPath(fname);
154 if (!IsLyXFilename(fname))
159 FileInfo const myfile(fname);
161 string const file = MakeDisplayPath(fname, 30);
162 string text = bformat(_("The document %1$s already exists.\n\n"
163 "Do you want to over-write that document?"), file);
164 int const ret = Alert::prompt(_("Over-write document?"),
165 text, 0, 1, _("&Over-write"), _("&Cancel"));
171 // Ok, change the name of the buffer
172 buffer->setFileName(fname);
174 bool unnamed = buffer->isUnnamed();
175 buffer->setUnnamed(false);
177 if (!MenuWrite(buffer)) {
178 buffer->setFileName(oldname);
179 buffer->setUnnamed(unnamed);
183 removeAutosaveFile(oldname);
190 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
192 if (lyx_gui::use_gui) {
193 if (!bufferlist.quitWriteAll())
196 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
199 // Set a flag that we do quitting from the program,
200 // so no refreshes are necessary.
203 // close buffers first
204 bufferlist.closeAll();
206 // do any other cleanup procedures now
207 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
209 if (destroyDir(os::getTmpDir()) != 0) {
210 string msg = bformat(_("Could not remove the temporary directory %1$s"),
212 Alert::warning(_("Could not remove temporary directory"), msg);
221 class AutoSaveBuffer : public ForkedProcess {
224 AutoSaveBuffer(BufferView & bv, string const & fname)
225 : bv_(bv), fname_(fname) {}
227 virtual shared_ptr<ForkedProcess> clone() const
229 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
235 virtual int generateChild();
242 int AutoSaveBuffer::start()
244 command_ = bformat(_("Auto-saving %1$s"), fname_);
245 return run(DontWait);
249 int AutoSaveBuffer::generateChild()
251 // tmp_ret will be located (usually) in /tmp
252 // will that be a problem?
253 pid_t const pid = fork(); // If you want to debug the autosave
254 // you should set pid to -1, and comment out the
256 if (pid == 0 || pid == -1) {
257 // pid = -1 signifies that lyx was unable
258 // to fork. But we will do the save
262 string const tmp_ret = tempName(string(), "lyxauto");
263 if (!tmp_ret.empty()) {
264 bv_.buffer()->writeFile(tmp_ret);
265 // assume successful write of tmp_ret
266 if (!rename(tmp_ret, fname_)) {
268 // most likely couldn't move between filesystems
269 // unless write of tmp_ret failed
270 // so remove tmp file (if it exists)
278 // failed to write/rename tmp_ret so try writing direct
279 if (!bv_.buffer()->writeFile(fname_)) {
280 // It is dangerous to do this in the child,
281 // but safe in the parent, so...
283 bv_.owner()->message(_("Autosave failed!"));
286 if (pid == 0) { // we are the child so...
296 void AutoSave(BufferView * bv)
297 // should probably be moved into BufferList (Lgb)
298 // Perfect target for a thread...
300 if (!bv->available())
303 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
304 // We don't save now, but we'll try again later
305 bv->owner()->resetAutosaveTimer();
309 bv->owner()->message(_("Autosaving current document..."));
311 // create autosave filename
312 string fname = bv->buffer()->filePath();
314 fname += OnlyFilename(bv->buffer()->fileName());
317 AutoSaveBuffer autosave(*bv, fname);
320 bv->buffer()->markBakClean();
321 bv->owner()->resetAutosaveTimer();
326 // Copyright CHT Software Service GmbH
329 // create new file with template
332 void NewFile(BufferView * bv, string const & filename)
334 // Split argument by :
336 string tmpname = split(filename, name, ':');
337 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
338 if (name.length() == 1
339 && isalpha(static_cast<unsigned char>(name[0]))
340 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
342 name += token(tmpname, ':', 0);
343 tmpname = split(tmpname, ':');
346 lyxerr[Debug::INFO] << "Arg is " << filename
347 << "\nName is " << name
348 << "\nTemplate is " << tmpname << endl;
350 bv->newFile(name, tmpname);
354 // Insert ascii file (if filename is empty, prompt for one)
355 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
357 if (!bv->available())
360 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
364 // clear the selection
365 if (bv->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(_("Select file to insert"),
382 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
384 FileDialog::Result result =
385 fileDlg.open(bv->owner()->buffer()->filePath(),
386 FileFilterList(), string());
388 if (result.first == FileDialog::Later)
391 fname = result.second;
399 if (!fi.readable()) {
400 string const error = strerror(errno);
401 string const file = MakeDisplayPath(fname, 50);
402 string const text = bformat(_("Could not read the specified document\n"
403 "%1$s\ndue to the error: %2$s"), file, error);
404 Alert::error(_("Could not read file"), text);
408 ifstream ifs(fname.c_str());
410 string const error = strerror(errno);
411 string const file = MakeDisplayPath(fname, 50);
412 string const text = bformat(_("Could not open the specified document\n"
413 "%1$s\ndue to the error: %2$s"), file, error);
414 Alert::error(_("Could not open file"), text);
418 ifs.unsetf(ios::skipws);
419 istream_iterator<char> ii(ifs);
420 istream_iterator<char> end;
421 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
422 // We use this until the compilers get better...
423 std::vector<char> tmp;
424 copy(ii, end, back_inserter(tmp));
425 string const tmpstr(tmp.begin(), tmp.end());
427 // This is what we want to use and what we will use once the
428 // compilers get good enough.
429 //string tmpstr(ii, end); // yet a reason for using std::string
430 // alternate approach to get the file into a string:
432 copy(ii, end, back_inserter(tmpstr));
439 // This function runs "configure" and then rereads lyx.defaults to
440 // reconfigure the automatic settings.
441 void Reconfigure(BufferView * bv)
443 bv->owner()->message(_("Running configure..."));
445 // Run configure in user lyx directory
446 Path p(user_lyxdir());
448 one.startscript(Systemcall::Wait,
449 AddName(system_lyxdir(), "configure"));
451 bv->owner()->message(_("Reloading configuration..."));
452 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
454 Alert::information(_("System reconfigured"),
455 _("The system has been reconfigured.\n"
456 "You need to restart LyX to make use of any \n"
457 "updated document class specifications."));