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"
50 using lyx::support::AddName;
51 using lyx::support::bformat;
52 using lyx::support::destroyDir;
53 using lyx::support::FileFilterList;
54 using lyx::support::FileInfo;
55 using lyx::support::ForkedProcess;
56 using lyx::support::IsLyXFilename;
57 using lyx::support::LibFileSearch;
58 using lyx::support::MakeAbsPath;
59 using lyx::support::MakeDisplayPath;
60 using lyx::support::OnlyFilename;
61 using lyx::support::OnlyPath;
62 using lyx::support::Path;
63 using lyx::support::removeAutosaveFile;
64 using lyx::support::rename;
65 using lyx::support::split;
66 using lyx::support::system_lyxdir;
67 using lyx::support::Systemcall;
68 using lyx::support::tempName;
69 using lyx::support::unlink;
70 using lyx::support::user_lyxdir;
72 namespace os = lyx::support::os;
75 using std::back_inserter;
82 using std::istream_iterator;
85 extern BufferList bufferlist;
86 // this should be static, but I need it in buffer.C
87 bool quitting; // flag, that we are quitting the program
94 bool MenuWrite(Buffer * buffer)
97 LyX::ref().lastfiles().newFile(buffer->fileName());
101 // FIXME: we don't tell the user *WHY* the save failed !!
103 string const file = MakeDisplayPath(buffer->fileName(), 30);
105 string text = bformat(_("The document %1$s could not be saved.\n\n"
106 "Do you want to rename the document and try again?"), file);
107 int const ret = Alert::prompt(_("Rename and save?"),
108 text, 0, 1, _("&Rename"), _("&Cancel"));
111 return WriteAs(buffer);
117 bool WriteAs(Buffer * buffer, string const & filename)
119 string fname = buffer->fileName();
120 string const oldname = fname;
122 if (filename.empty()) {
124 FileDialog fileDlg(_("Choose a filename to save document as"),
126 make_pair(string(_("Documents|#o#O")),
127 string(lyxrc.document_path)),
128 make_pair(string(_("Templates|#T#t")),
129 string(lyxrc.template_path)));
131 if (!IsLyXFilename(fname))
134 FileFilterList const filter (_("LyX Documents (*.lyx)"));
136 FileDialog::Result result =
137 fileDlg.save(OnlyPath(fname),
139 OnlyFilename(fname));
141 if (result.first == FileDialog::Later)
144 fname = result.second;
149 // Make sure the absolute filename ends with appropriate suffix
150 fname = MakeAbsPath(fname);
151 if (!IsLyXFilename(fname))
156 FileInfo const myfile(fname);
158 string const file = MakeDisplayPath(fname, 30);
159 string text = bformat(_("The document %1$s already exists.\n\n"
160 "Do you want to over-write that document?"), file);
161 int const ret = Alert::prompt(_("Over-write document?"),
162 text, 0, 1, _("&Over-write"), _("&Cancel"));
168 // Ok, change the name of the buffer
169 buffer->setFileName(fname);
171 bool unnamed = buffer->isUnnamed();
172 buffer->setUnnamed(false);
174 if (!MenuWrite(buffer)) {
175 buffer->setFileName(oldname);
176 buffer->setUnnamed(unnamed);
180 removeAutosaveFile(oldname);
187 lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
189 if (lyx_gui::use_gui) {
190 if (!bufferlist.quitWriteAll())
193 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
196 // Set a flag that we do quitting from the program,
197 // so no refreshes are necessary.
200 // close buffers first
201 bufferlist.closeAll();
203 // do any other cleanup procedures now
204 lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
206 if (destroyDir(os::getTmpDir()) != 0) {
207 string msg = bformat(_("Could not remove the temporary directory %1$s"),
209 Alert::warning(_("Could not remove temporary directory"), msg);
218 class AutoSaveBuffer : public ForkedProcess {
221 AutoSaveBuffer(BufferView & bv, string const & fname)
222 : bv_(bv), fname_(fname) {}
224 virtual auto_ptr<ForkedProcess> clone() const {
225 return auto_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
231 virtual int generateChild();
238 int AutoSaveBuffer::start()
240 command_ = bformat(_("Auto-saving %1$s"), fname_);
241 return runNonBlocking();
245 int AutoSaveBuffer::generateChild()
247 // tmp_ret will be located (usually) in /tmp
248 // will that be a problem?
249 pid_t const pid = fork(); // If you want to debug the autosave
250 // you should set pid to -1, and comment out the
252 if (pid == 0 || pid == -1) {
253 // pid = -1 signifies that lyx was unable
254 // to fork. But we will do the save
258 string const tmp_ret = tempName(string(), "lyxauto");
259 if (!tmp_ret.empty()) {
260 bv_.buffer()->writeFile(tmp_ret);
261 // assume successful write of tmp_ret
262 if (!rename(tmp_ret, fname_)) {
264 // most likely couldn't move between filesystems
265 // unless write of tmp_ret failed
266 // so remove tmp file (if it exists)
274 // failed to write/rename tmp_ret so try writing direct
275 if (!bv_.buffer()->writeFile(fname_)) {
276 // It is dangerous to do this in the child,
277 // but safe in the parent, so...
279 bv_.owner()->message(_("Autosave failed!"));
282 if (pid == 0) { // we are the child so...
292 void AutoSave(BufferView * bv)
293 // should probably be moved into BufferList (Lgb)
294 // Perfect target for a thread...
296 if (!bv->available())
299 if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
300 // We don't save now, but we'll try again later
301 bv->owner()->resetAutosaveTimer();
305 bv->owner()->message(_("Autosaving current document..."));
307 // create autosave filename
308 string fname = bv->buffer()->filePath();
310 fname += OnlyFilename(bv->buffer()->fileName());
313 AutoSaveBuffer autosave(*bv, fname);
316 bv->buffer()->markBakClean();
317 bv->owner()->resetAutosaveTimer();
322 // Copyright CHT Software Service GmbH
325 // create new file with template
328 void NewFile(BufferView * bv, string const & filename)
330 // Split argument by :
332 string tmpname = split(filename, name, ':');
333 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
334 if (name.length() == 1
335 && isalpha(static_cast<unsigned char>(name[0]))
336 && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
338 name += token(tmpname, ':', 0);
339 tmpname = split(tmpname, ':');
342 lyxerr[Debug::INFO] << "Arg is " << filename
343 << "\nName is " << name
344 << "\nTemplate is " << tmpname << endl;
346 bv->newFile(name, tmpname);
350 // Insert ascii file (if filename is empty, prompt for one)
351 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
353 if (!bv->available())
356 string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
360 // clear the selection
361 if (bv->text() == bv->getLyXText())
362 bv->cursor().clearSelection();
364 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
366 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
371 // Insert ascii file (if filename is empty, prompt for one)
372 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
377 FileDialog fileDlg(_("Select file to insert"),
378 (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
380 FileDialog::Result result =
381 fileDlg.open(bv->owner()->buffer()->filePath(),
382 FileFilterList(), string());
384 if (result.first == FileDialog::Later)
387 fname = result.second;
395 if (!fi.readable()) {
396 string const error = strerror(errno);
397 string const file = MakeDisplayPath(fname, 50);
398 string const text = bformat(_("Could not read the specified document\n"
399 "%1$s\ndue to the error: %2$s"), file, error);
400 Alert::error(_("Could not read file"), text);
404 ifstream ifs(fname.c_str());
406 string const error = strerror(errno);
407 string const file = MakeDisplayPath(fname, 50);
408 string const text = bformat(_("Could not open the specified document\n"
409 "%1$s\ndue to the error: %2$s"), file, error);
410 Alert::error(_("Could not open file"), text);
414 ifs.unsetf(ios::skipws);
415 istream_iterator<char> ii(ifs);
416 istream_iterator<char> end;
417 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
418 // We use this until the compilers get better...
419 std::vector<char> tmp;
420 copy(ii, end, back_inserter(tmp));
421 string const tmpstr(tmp.begin(), tmp.end());
423 // This is what we want to use and what we will use once the
424 // compilers get good enough.
425 //string tmpstr(ii, end); // yet a reason for using std::string
426 // alternate approach to get the file into a string:
428 copy(ii, end, back_inserter(tmpstr));
435 // This function runs "configure" and then rereads lyx.defaults to
436 // reconfigure the automatic settings.
437 void Reconfigure(BufferView * bv)
439 bv->owner()->message(_("Running configure..."));
441 // Run configure in user lyx directory
442 Path p(user_lyxdir());
444 one.startscript(Systemcall::Wait,
445 AddName(system_lyxdir(), "configure"));
447 bv->owner()->message(_("Reloading configuration..."));
448 lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
450 Alert::information(_("System reconfigured"),
451 _("The system has been reconfigured.\n"
452 "You need to restart LyX to make use of any \n"
453 "updated document class specifications."));