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