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