]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
* GuiApplication: explicitly clear out socket_callbacks_ in the destructor.
[lyx.git] / src / lyx_cb.C
1 /**
2  * \file lyx_cb.C
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 "lyx_cb.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 "debug.h"
25 #include "gettext.h"
26 #include "session.h"
27 #include "LaTeXFeatures.h"
28 #include "lyx_main.h"
29 #include "lyxlayout.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "paragraph.h"
33
34 #include "frontends/Alert.h"
35 #include "frontends/Application.h"
36 #include "frontends/FileDialog.h"
37
38 #include "support/filefilterlist.h"
39 #include "support/filetools.h"
40 #include "support/fontutils.h"
41 #include "support/forkedcall.h"
42 #include "support/fs_extras.h"
43 #include "support/lyxlib.h"
44 #include "support/package.h"
45 #include "support/path.h"
46 #include "support/systemcall.h"
47
48 #if !defined (HAVE_FORK)
49 # define fork() -1
50 #endif
51
52 #include <boost/shared_ptr.hpp>
53 #include <boost/filesystem/operations.hpp>
54
55 #include <cerrno>
56 #include <fstream>
57
58 using lyx::docstring;
59 using lyx::support::addName;
60 using lyx::support::bformat;
61 using lyx::support::destroyDir;
62 using lyx::support::FileFilterList;
63 using lyx::support::ForkedProcess;
64 using lyx::support::isLyXFilename;
65 using lyx::support::libFileSearch;
66 using lyx::support::makeAbsPath;
67 using lyx::support::makeDisplayPath;
68 using lyx::support::onlyFilename;
69 using lyx::support::onlyPath;
70 using lyx::support::package;
71 using lyx::support::removeAutosaveFile;
72 using lyx::support::rename;
73 using lyx::support::split;
74 using lyx::support::Systemcall;
75 using lyx::support::tempName;
76 using lyx::support::unlink;
77
78 using boost::shared_ptr;
79
80 namespace Alert = lyx::frontend::Alert;
81 namespace fs = boost::filesystem;
82
83 using std::back_inserter;
84 using std::copy;
85 using std::endl;
86 using std::make_pair;
87 using std::string;
88 using std::ifstream;
89 using std::ios;
90 using std::istream_iterator;
91
92
93 // this should be static, but I need it in buffer.C
94 bool quitting;  // flag, that we are quitting the program
95
96 namespace lyx {
97 extern bool use_gui;
98 }
99
100 //
101 // Menu callbacks
102 //
103
104 bool menuWrite(Buffer * buffer)
105 {
106         if (buffer->save()) {
107                 LyX::ref().session().addLastFile(buffer->fileName());
108                 return true;
109         }
110
111         // FIXME: we don't tell the user *WHY* the save failed !!
112
113         docstring const file = makeDisplayPath(buffer->fileName(), 30);
114
115         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
116                                              "Do you want to rename the document and try again?"), file);
117         int const ret = Alert::prompt(_("Rename and save?"),
118                 text, 0, 1, _("&Rename"), _("&Cancel"));
119
120         if (ret == 0)
121                 return writeAs(buffer);
122         return false;
123 }
124
125
126
127 bool writeAs(Buffer * buffer, string const & filename)
128 {
129         string fname = buffer->fileName();
130         string const oldname = fname;
131
132         if (filename.empty()) {
133
134                 // FIXME UNICODE
135                 FileDialog fileDlg(_("Choose a filename to save document as"),
136                         LFUN_BUFFER_WRITE_AS,
137                         make_pair(_("Documents|#o#O"), lyx::from_utf8(lyxrc.document_path)),
138                         make_pair(_("Templates|#T#t"), lyx::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(lyx::from_utf8(onlyPath(fname)),
147                                      filter,
148                                      lyx::from_utf8(onlyFilename(fname)));
149
150                 if (result.first == FileDialog::Later)
151                         return false;
152
153                 fname = lyx::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);
160                 if (!isLyXFilename(fname))
161                         fname += ".lyx";
162         } else
163                 fname = filename;
164
165         if (fs::exists(fname)) {
166                 docstring const file = makeDisplayPath(fname, 30);
167                 docstring text = bformat(_("The document %1$s already exists.\n\n"
168                                                      "Do you want to over-write that document?"), file);
169                 int const ret = Alert::prompt(_("Over-write document?"),
170                         text, 0, 1, _("&Over-write"), _("&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 void quitLyX(bool noask)
194 {
195         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
196
197         if (lyx::use_gui) {
198                 if (!noask && !theBufferList().quitWriteAll())
199                         return;
200
201                 LyX::cref().session().writeFile();
202         }
203
204         // Set a flag that we do quitting from the program,
205         // so no refreshes are necessary.
206         quitting = true;
207
208         // close buffers first
209         theBufferList().closeAll();
210
211         // do any other cleanup procedures now
212         lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
213
214         if (!destroyDir(package().temp_dir())) {
215                 docstring const msg =
216                         bformat(_("Unable to remove the temporary directory %1$s"),
217                         lyx::from_utf8(package().temp_dir()));
218                 Alert::warning(_("Unable to remove temporary directory"), msg);
219         }
220
221         if (lyx::use_gui) {
222                 theApp->exit(0);
223
224                 // Restore original font resources after Application is destroyed.
225                 lyx::support::restoreFontResources();
226         }
227 }
228
229
230 namespace {
231
232 class AutoSaveBuffer : public ForkedProcess {
233 public:
234         ///
235         AutoSaveBuffer(BufferView & bv, string const & fname)
236                 : bv_(bv), fname_(fname) {}
237         ///
238         virtual shared_ptr<ForkedProcess> clone() const
239         {
240                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
241         }
242         ///
243         int start();
244 private:
245         ///
246         virtual int generateChild();
247         ///
248         BufferView & bv_;
249         string fname_;
250 };
251
252
253 int AutoSaveBuffer::start()
254 {
255         command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
256         return run(DontWait);
257 }
258
259
260 int AutoSaveBuffer::generateChild()
261 {
262         // tmp_ret will be located (usually) in /tmp
263         // will that be a problem?
264         pid_t const pid = fork(); // If you want to debug the autosave
265         // you should set pid to -1, and comment out the
266         // fork.
267         if (pid == 0 || pid == -1) {
268                 // pid = -1 signifies that lyx was unable
269                 // to fork. But we will do the save
270                 // anyway.
271                 bool failed = false;
272
273                 string const tmp_ret = tempName(string(), "lyxauto");
274                 if (!tmp_ret.empty()) {
275                         bv_.buffer()->writeFile(tmp_ret);
276                         // assume successful write of tmp_ret
277                         if (!rename(tmp_ret, fname_)) {
278                                 failed = true;
279                                 // most likely couldn't move between filesystems
280                                 // unless write of tmp_ret failed
281                                 // so remove tmp file (if it exists)
282                                 unlink(tmp_ret);
283                         }
284                 } else {
285                         failed = true;
286                 }
287
288                 if (failed) {
289                         // failed to write/rename tmp_ret so try writing direct
290                         if (!bv_.buffer()->writeFile(fname_)) {
291                                 // It is dangerous to do this in the child,
292                                 // but safe in the parent, so...
293                                 if (pid == -1)
294                                         // emit message signal.
295                                         bv_.buffer()->message(_("Autosave failed!"));
296                         }
297                 }
298                 if (pid == 0) { // we are the child so...
299                         _exit(0);
300                 }
301         }
302         return pid;
303 }
304
305 } // namespace anon
306
307
308 void autoSave(BufferView * bv)
309         // should probably be moved into BufferList (Lgb)
310         // Perfect target for a thread...
311 {
312         if (!bv->buffer())
313                 return;
314
315         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
316                 // We don't save now, but we'll try again later
317                 bv->buffer()->resetAutosaveTimers();
318                 return;
319         }
320
321         // emit message signal.
322         bv->buffer()->message(_("Autosaving current document..."));
323
324         // create autosave filename
325         string fname = bv->buffer()->filePath();
326         fname += '#';
327         fname += onlyFilename(bv->buffer()->fileName());
328         fname += '#';
329
330         AutoSaveBuffer autosave(*bv, fname);
331         autosave.start();
332
333         bv->buffer()->markBakClean();
334         bv->buffer()->resetAutosaveTimers();
335 }
336
337
338 //
339 // Copyright CHT Software Service GmbH
340 // Uwe C. Schroeder
341 //
342 // create new file with template
343 // SERVERCMD !
344 //
345 void newFile(BufferView * bv, string const & filename)
346 {
347         // Split argument by :
348         string name;
349         string tmpname = split(filename, name, ':');
350         lyxerr[Debug::INFO] << "Arg is " << filename
351                             << "\nName is " << name
352                             << "\nTemplate is " << tmpname << endl;
353
354         Buffer * const b = newFile(name, tmpname);
355         if (b)
356                 bv->setBuffer(b);
357 }
358
359
360 // Insert ascii file (if filename is empty, prompt for one)
361 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
362 {
363         if (!bv->buffer())
364                 return;
365
366         // FIXME: We don't know the encoding of the file
367         docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
368         if (tmpstr.empty())
369                 return;
370
371         // clear the selection
372         LyXText const & text = bv->buffer()->text();
373         if (&text == bv->getLyXText())
374                 bv->cursor().clearSelection();
375         if (asParagraph)
376                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
377         else
378                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
379         bv->update();
380 }
381
382
383 // Insert ascii file (if filename is empty, prompt for one)
384 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
385 {
386         string fname = f;
387
388         if (fname.empty()) {
389                 FileDialog fileDlg(_("Select file to insert"),
390                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
391
392                 FileDialog::Result result =
393                         fileDlg.open(lyx::from_utf8(bv->buffer()->filePath()),
394                                      FileFilterList(), docstring());
395
396                 if (result.first == FileDialog::Later)
397                         return string();
398
399                 fname = lyx::to_utf8(result.second);
400
401                 if (fname.empty())
402                         return string();
403         }
404
405         if (!fs::is_readable(fname)) {
406                 docstring const error = lyx::from_ascii(strerror(errno));
407                 docstring const file = makeDisplayPath(fname, 50);
408                 docstring const text = bformat(_("Could not read the specified document\n"
409                                                            "%1$s\ndue to the error: %2$s"), file, error);
410                 Alert::error(_("Could not read file"), text);
411                 return string();
412         }
413
414         ifstream ifs(fname.c_str());
415         if (!ifs) {
416                 docstring const error = lyx::from_ascii(strerror(errno));
417                 docstring const file = makeDisplayPath(fname, 50);
418                 docstring const text = bformat(_("Could not open the specified document\n"
419                                                            "%1$s\ndue to the error: %2$s"), file, error);
420                 Alert::error(_("Could not open file"), text);
421                 return string();
422         }
423
424         ifs.unsetf(ios::skipws);
425         istream_iterator<char> ii(ifs);
426         istream_iterator<char> end;
427 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
428         // We use this until the compilers get better...
429         std::vector<char> tmp;
430         copy(ii, end, back_inserter(tmp));
431         string const tmpstr(tmp.begin(), tmp.end());
432 #else
433         // This is what we want to use and what we will use once the
434         // compilers get good enough.
435         //string tmpstr(ii, end); // yet a reason for using std::string
436         // alternate approach to get the file into a string:
437         string tmpstr;
438         copy(ii, end, back_inserter(tmpstr));
439 #endif
440
441         return tmpstr;
442 }
443
444
445 // This function runs "configure" and then rereads lyx.defaults to
446 // reconfigure the automatic settings.
447 void reconfigure(BufferView * bv)
448 {
449         // emit message signal.
450         bv->buffer()->message(_("Running configure..."));
451
452         // Run configure in user lyx directory
453         lyx::support::Path p(package().user_support());
454         string const configure_command = package().configure_command();
455         Systemcall one;
456         one.startscript(Systemcall::Wait, configure_command);
457         p.pop();
458         // emit message signal.
459         bv->buffer()->message(_("Reloading configuration..."));
460         lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
461         // Re-read packages.lst
462         LaTeXFeatures::getAvailable();
463
464         Alert::information(_("System reconfigured"),
465                            _("The system has been reconfigured.\n"
466                                           "You need to restart LyX to make use of any\n"
467                                           "updated document class specifications."));
468 }