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