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