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