]> git.lyx.org Git - lyx.git/blob - src/callback.cpp
7053831020a205a262a96af6323d165e376b8c03
[lyx.git] / src / callback.cpp
1 /**
2  * \file callback.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Angus Leeming
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "callback.h"
18
19 #include "Buffer.h"
20 #include "BufferList.h"
21 #include "BufferView.h"
22 #include "buffer_funcs.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "gettext.h"
27 #include "Session.h"
28 #include "LaTeXFeatures.h"
29 #include "LyX.h"
30 #include "Layout.h"
31 #include "LyXRC.h"
32 #include "Text.h"
33 #include "Undo.h"
34
35 #include "frontends/alert.h"
36 #include "frontends/Application.h"
37 #include "frontends/FileDialog.h"
38 #include "frontends/LyXView.h"
39
40 #include "support/FileFilterList.h"
41 #include "support/filetools.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"
48
49 #if !defined (HAVE_FORK)
50 # define fork() -1
51 #endif
52
53 #include <boost/shared_ptr.hpp>
54 #include <boost/filesystem/operations.hpp>
55
56 #include <cerrno>
57 #include <fstream>
58
59 using std::back_inserter;
60 using std::copy;
61 using std::endl;
62 using std::make_pair;
63 using std::string;
64 using std::ifstream;
65 using std::ios;
66 using std::istream_iterator;
67
68 using boost::shared_ptr;
69
70
71 namespace lyx {
72
73 using support::bformat;
74 using support::FileFilterList;
75 using support::FileName;
76 using support::ForkedProcess;
77 using support::isLyXFilename;
78 using support::libFileSearch;
79 using support::makeAbsPath;
80 using support::makeDisplayPath;
81 using support::onlyFilename;
82 using support::onlyPath;
83 using support::package;
84 using support::removeAutosaveFile;
85 using support::rename;
86 using support::split;
87 using support::Systemcall;
88 using support::tempName;
89 using support::unlink;
90
91 namespace Alert = frontend::Alert;
92 namespace fs = boost::filesystem;
93
94 // this should be static, but I need it in Buffer.cpp
95 bool quitting;  // flag, that we are quitting the program
96
97 //
98 // Menu callbacks
99 //
100
101 bool menuWrite(Buffer * buffer)
102 {
103         if (buffer->save()) {
104                 LyX::ref().session().lastFiles().add(FileName(buffer->fileName()));
105                 return true;
106         }
107
108         // FIXME: we don't tell the user *WHY* the save failed !!
109
110         docstring const file = makeDisplayPath(buffer->fileName(), 30);
111
112         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
113                                              "Do you want to rename the document and try again?"), file);
114         int const ret = Alert::prompt(_("Rename and save?"),
115                 text, 0, 1, _("&Rename"), _("&Cancel"));
116
117         if (ret == 0)
118                 return writeAs(buffer);
119         return false;
120 }
121
122
123
124 bool writeAs(Buffer * buffer, string const & newname)
125 {
126         string fname = buffer->fileName();
127         string const oldname = fname;
128
129         if (newname.empty()) {
130
131                 // FIXME UNICODE
132                 FileDialog fileDlg(_("Choose a filename to save document as"),
133                         LFUN_BUFFER_WRITE_AS,
134                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
135                         make_pair(_("Templates|#T#t"), from_utf8(lyxrc.template_path)));
136
137                 if (!isLyXFilename(fname))
138                         fname += ".lyx";
139
140                 FileFilterList const filter (_("LyX Documents (*.lyx)"));
141
142                 FileDialog::Result result =
143                         fileDlg.save(from_utf8(onlyPath(fname)),
144                                      filter,
145                                      from_utf8(onlyFilename(fname)));
146
147                 if (result.first == FileDialog::Later)
148                         return false;
149
150                 fname = to_utf8(result.second);
151
152                 if (fname.empty())
153                         return false;
154
155                 // Make sure the absolute filename ends with appropriate suffix
156                 fname = makeAbsPath(fname).absFilename();
157                 if (!isLyXFilename(fname))
158                         fname += ".lyx";
159         } else
160                 fname = newname;
161
162         FileName const filename(fname);
163         if (fs::exists(filename.toFilesystemEncoding())) {
164                 docstring const file = makeDisplayPath(fname, 30);
165                 docstring text = bformat(_("The document %1$s already exists.\n\n"
166                                            "Do you want to overwrite that document?"), file);
167                 int const ret = Alert::prompt(_("Overwrite document?"),
168                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
169
170                 if (ret == 1)
171                         return false;
172         }
173
174         // Ok, change the name of the buffer
175         buffer->setFileName(fname);
176         buffer->markDirty();
177         bool unnamed = buffer->isUnnamed();
178         buffer->setUnnamed(false);
179
180         if (!menuWrite(buffer)) {
181                 buffer->setFileName(oldname);
182                 buffer->setUnnamed(unnamed);
183                 return false;
184         }
185
186         removeAutosaveFile(oldname);
187         return true;
188 }
189
190
191 namespace {
192
193 class AutoSaveBuffer : public ForkedProcess {
194 public:
195         ///
196         AutoSaveBuffer(BufferView & bv, FileName const & fname)
197                 : bv_(bv), fname_(fname) {}
198         ///
199         virtual shared_ptr<ForkedProcess> clone() const
200         {
201                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
202         }
203         ///
204         int start();
205 private:
206         ///
207         virtual int generateChild();
208         ///
209         BufferView & bv_;
210         FileName fname_;
211 };
212
213
214 int AutoSaveBuffer::start()
215 {
216         command_ = to_utf8(bformat(_("Auto-saving %1$s"), from_utf8(fname_.absFilename())));
217         return run(DontWait);
218 }
219
220
221 int AutoSaveBuffer::generateChild()
222 {
223         // tmp_ret will be located (usually) in /tmp
224         // will that be a problem?
225         pid_t const pid = fork(); // If you want to debug the autosave
226         // you should set pid to -1, and comment out the
227         // fork.
228         if (pid == 0 || pid == -1) {
229                 // pid = -1 signifies that lyx was unable
230                 // to fork. But we will do the save
231                 // anyway.
232                 bool failed = false;
233
234                 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
235                 if (!tmp_ret.empty()) {
236                         bv_.buffer()->writeFile(tmp_ret);
237                         // assume successful write of tmp_ret
238                         if (!rename(tmp_ret, fname_)) {
239                                 failed = true;
240                                 // most likely couldn't move between filesystems
241                                 // unless write of tmp_ret failed
242                                 // so remove tmp file (if it exists)
243                                 unlink(tmp_ret);
244                         }
245                 } else {
246                         failed = true;
247                 }
248
249                 if (failed) {
250                         // failed to write/rename tmp_ret so try writing direct
251                         if (!bv_.buffer()->writeFile(fname_)) {
252                                 // It is dangerous to do this in the child,
253                                 // but safe in the parent, so...
254                                 if (pid == -1)
255                                         // emit message signal.
256                                         bv_.buffer()->message(_("Autosave failed!"));
257                         }
258                 }
259                 if (pid == 0) { // we are the child so...
260                         _exit(0);
261                 }
262         }
263         return pid;
264 }
265
266 } // namespace anon
267
268
269 void autoSave(BufferView * bv)
270         // should probably be moved into BufferList (Lgb)
271         // Perfect target for a thread...
272 {
273         if (!bv->buffer())
274                 return;
275
276         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
277                 // We don't save now, but we'll try again later
278                 bv->buffer()->resetAutosaveTimers();
279                 return;
280         }
281
282         // emit message signal.
283         bv->buffer()->message(_("Autosaving current document..."));
284
285         // create autosave filename
286         string fname = bv->buffer()->filePath();
287         fname += '#';
288         fname += onlyFilename(bv->buffer()->fileName());
289         fname += '#';
290
291         AutoSaveBuffer autosave(*bv, FileName(fname));
292         autosave.start();
293
294         bv->buffer()->markBakClean();
295         bv->buffer()->resetAutosaveTimers();
296 }
297
298
299 //
300 // Copyright CHT Software Service GmbH
301 // Uwe C. Schroeder
302 //
303 // create new file with template
304 // SERVERCMD !
305 //
306 void newFile(BufferView * bv, string const & filename)
307 {
308         // Split argument by :
309         string name;
310         string tmpname = split(filename, name, ':');
311         LYXERR(Debug::INFO) << "Arg is " << filename
312                             << "\nName is " << name
313                             << "\nTemplate is " << tmpname << endl;
314
315         Buffer * const b = newFile(name, tmpname);
316         if (b)
317                 bv->setBuffer(b);
318 }
319
320
321 // Insert plain text file (if filename is empty, prompt for one)
322 void insertPlaintextFile(BufferView * bv, string const & f, bool asParagraph)
323 {
324         if (!bv->buffer())
325                 return;
326
327         docstring const tmpstr = getContentsOfPlaintextFile(bv, f, asParagraph);
328         if (tmpstr.empty())
329                 return;
330
331         Cursor & cur = bv->cursor();
332         cap::replaceSelection(cur);
333         recordUndo(cur);
334         if (asParagraph)
335                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
336         else
337                 cur.innerText()->insertStringAsLines(cur, tmpstr);
338 }
339
340
341 docstring const getContentsOfPlaintextFile(BufferView * bv, string const & f,
342                 bool asParagraph)
343 {
344         FileName fname(f);
345
346         if (fname.empty()) {
347                 FileDialog fileDlg(_("Select file to insert"),
348                         (asParagraph) ? LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT);
349
350                 FileDialog::Result result =
351                         fileDlg.open(from_utf8(bv->buffer()->filePath()),
352                                      FileFilterList(), docstring());
353
354                 if (result.first == FileDialog::Later)
355                         return docstring();
356
357                 fname = makeAbsPath(to_utf8(result.second));
358
359                 if (fname.empty())
360                         return docstring();
361         }
362
363         if (!fs::is_readable(fname.toFilesystemEncoding())) {
364                 docstring const error = from_ascii(strerror(errno));
365                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
366                 docstring const text = bformat(_("Could not read the specified document\n"
367                                                            "%1$s\ndue to the error: %2$s"), file, error);
368                 Alert::error(_("Could not read file"), text);
369                 return docstring();
370         }
371
372         ifstream ifs(fname.toFilesystemEncoding().c_str());
373         if (!ifs) {
374                 docstring const error = from_ascii(strerror(errno));
375                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
376                 docstring const text = bformat(_("Could not open the specified document\n"
377                                                            "%1$s\ndue to the error: %2$s"), file, error);
378                 Alert::error(_("Could not open file"), text);
379                 return docstring();
380         }
381
382         ifs.unsetf(ios::skipws);
383         istream_iterator<char> ii(ifs);
384         istream_iterator<char> end;
385 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
386         // We use this until the compilers get better...
387         std::vector<char> tmp;
388         copy(ii, end, back_inserter(tmp));
389         string const tmpstr(tmp.begin(), tmp.end());
390 #else
391         // This is what we want to use and what we will use once the
392         // compilers get good enough.
393         //string tmpstr(ii, end); // yet a reason for using std::string
394         // alternate approach to get the file into a string:
395         string tmpstr;
396         copy(ii, end, back_inserter(tmpstr));
397 #endif
398
399         // FIXME UNICODE: We don't know the encoding of the file
400         docstring file_content = from_utf8(tmpstr);
401         if (file_content.empty()) {
402                 Alert::error(_("Reading not UTF-8 encoded file"),
403                                         _("The file is not UTF-8 encoded.\n"
404                                         "It will be read as local 8Bit-encoded.\n"
405                                         "If this does not give the correct result\n"
406                                         "then please change the encoding of the file\n"
407                                         "to UTF-8 with a program other than LyX.\n"));
408                 file_content = from_local8bit(tmpstr);
409         }
410
411         return normalize_c(file_content);
412 }
413
414
415 // This function runs "configure" and then rereads lyx.defaults to
416 // reconfigure the automatic settings.
417 void reconfigure(LyXView & lv)
418 {
419         // emit message signal.
420         lv.message(_("Running configure..."));
421
422         // Run configure in user lyx directory
423         support::Path p(package().user_support());
424         string const configure_command = package().configure_command();
425         Systemcall one;
426         one.startscript(Systemcall::Wait, configure_command);
427         p.pop();
428         // emit message signal.
429         lv.message(_("Reloading configuration..."));
430         lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
431         // Re-read packages.lst
432         LaTeXFeatures::getAvailable();
433
434         Alert::information(_("System reconfigured"),
435                            _("The system has been reconfigured.\n"
436                                           "You need to restart LyX to make use of any\n"
437                                           "updated document class specifications."));
438 }
439
440
441 } // namespace lyx