]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
replace LyXView::message() direct call with Buffer::message() boost signal emission.
[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/FileDialog.h"
36 #include "frontends/lyx_gui.h"
37 #include "frontends/LyXView.h"
38
39 #include "support/filefilterlist.h"
40 #include "support/filetools.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::support::addName;
59 using lyx::support::bformat;
60 using lyx::support::destroyDir;
61 using lyx::support::FileFilterList;
62 using lyx::support::ForkedProcess;
63 using lyx::support::isLyXFilename;
64 using lyx::support::libFileSearch;
65 using lyx::support::makeAbsPath;
66 using lyx::support::makeDisplayPath;
67 using lyx::support::onlyFilename;
68 using lyx::support::onlyPath;
69 using lyx::support::Path;
70 using lyx::support::package;
71 using lyx::support::quoteName;
72 using lyx::support::removeAutosaveFile;
73 using lyx::support::rename;
74 using lyx::support::split;
75 using lyx::support::Systemcall;
76 using lyx::support::tempName;
77 using lyx::support::unlink;
78
79 using boost::shared_ptr;
80
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 extern BufferList bufferlist;
94 // this should be static, but I need it in buffer.C
95 bool quitting;  // flag, that we are quitting the program
96
97
98 //
99 // Menu callbacks
100 //
101
102 bool menuWrite(Buffer * buffer)
103 {
104         if (buffer->save()) {
105                 LyX::ref().session().addLastFile(buffer->fileName());
106                 return true;
107         }
108
109         // FIXME: we don't tell the user *WHY* the save failed !!
110
111         string const file = makeDisplayPath(buffer->fileName(), 30);
112
113         string 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 & filename)
126 {
127         string fname = buffer->fileName();
128         string const oldname = fname;
129
130         if (filename.empty()) {
131
132                 FileDialog fileDlg(_("Choose a filename to save document as"),
133                         LFUN_BUFFER_WRITE_AS,
134                         make_pair(string(_("Documents|#o#O")),
135                                   string(lyxrc.document_path)),
136                         make_pair(string(_("Templates|#T#t")),
137                                   string(lyxrc.template_path)));
138
139                 if (!isLyXFilename(fname))
140                         fname += ".lyx";
141
142                 FileFilterList const filter (_("LyX Documents (*.lyx)"));
143
144                 FileDialog::Result result =
145                         fileDlg.save(onlyPath(fname),
146                                      filter,
147                                      onlyFilename(fname));
148
149                 if (result.first == FileDialog::Later)
150                         return false;
151
152                 fname = result.second;
153
154                 if (fname.empty())
155                         return false;
156
157                 // Make sure the absolute filename ends with appropriate suffix
158                 fname = makeAbsPath(fname);
159                 if (!isLyXFilename(fname))
160                         fname += ".lyx";
161         } else
162                 fname = filename;
163
164         if (fs::exists(fname)) {
165                 string const file = makeDisplayPath(fname, 30);
166                 string text = bformat(_("The document %1$s already exists.\n\n"
167                         "Do you want to over-write that document?"), file);
168                 int const ret = Alert::prompt(_("Over-write document?"),
169                         text, 0, 1, _("&Over-write"), _("&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 void quitLyX(bool noask)
193 {
194         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
195
196         if (lyx_gui::use_gui) {
197                 if (!noask && !bufferlist.quitWriteAll())
198                         return;
199
200                 LyX::cref().session().writeFile();
201         }
202
203         // Set a flag that we do quitting from the program,
204         // so no refreshes are necessary.
205         quitting = true;
206
207         // close buffers first
208         bufferlist.closeAll();
209
210         // do any other cleanup procedures now
211         lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
212
213         if (!destroyDir(package().temp_dir())) {
214                 string const msg =
215                         bformat(_("Unable to remove the temporary directory %1$s"),
216                         package().temp_dir());
217                 Alert::warning(_("Unable to remove temporary directory"), msg);
218         }
219
220         lyx_gui::exit(0);
221 }
222
223
224 namespace {
225
226 class AutoSaveBuffer : public ForkedProcess {
227 public:
228         ///
229         AutoSaveBuffer(BufferView & bv, string const & fname)
230                 : bv_(bv), fname_(fname) {}
231         ///
232         virtual shared_ptr<ForkedProcess> clone() const
233         {
234                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
235         }
236         ///
237         int start();
238 private:
239         ///
240         virtual int generateChild();
241         ///
242         BufferView & bv_;
243         string fname_;
244 };
245
246
247 int AutoSaveBuffer::start()
248 {
249         command_ = bformat(_("Auto-saving %1$s"), fname_);
250         return run(DontWait);
251 }
252
253
254 int AutoSaveBuffer::generateChild()
255 {
256         // tmp_ret will be located (usually) in /tmp
257         // will that be a problem?
258         pid_t const pid = fork(); // If you want to debug the autosave
259         // you should set pid to -1, and comment out the
260         // fork.
261         if (pid == 0 || pid == -1) {
262                 // pid = -1 signifies that lyx was unable
263                 // to fork. But we will do the save
264                 // anyway.
265                 bool failed = false;
266
267                 string const tmp_ret = tempName(string(), "lyxauto");
268                 if (!tmp_ret.empty()) {
269                         bv_.buffer()->writeFile(tmp_ret);
270                         // assume successful write of tmp_ret
271                         if (!rename(tmp_ret, fname_)) {
272                                 failed = true;
273                                 // most likely couldn't move between filesystems
274                                 // unless write of tmp_ret failed
275                                 // so remove tmp file (if it exists)
276                                 unlink(tmp_ret);
277                         }
278                 } else {
279                         failed = true;
280                 }
281
282                 if (failed) {
283                         // failed to write/rename tmp_ret so try writing direct
284                         if (!bv_.buffer()->writeFile(fname_)) {
285                                 // It is dangerous to do this in the child,
286                                 // but safe in the parent, so...
287                                 if (pid == -1)
288                                         // emit message signal.
289                                         bv_.buffer()->message(_("Autosave failed!"));
290                         }
291                 }
292                 if (pid == 0) { // we are the child so...
293                         _exit(0);
294                 }
295         }
296         return pid;
297 }
298
299 } // namespace anon
300
301
302 void autoSave(BufferView * bv)
303         // should probably be moved into BufferList (Lgb)
304         // Perfect target for a thread...
305 {
306         if (!bv->available())
307                 return;
308
309         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
310                 // We don't save now, but we'll try again later
311                 bv->owner()->resetAutosaveTimer();
312                 return;
313         }
314
315         // emit message signal.
316         bv->buffer()->message(_("Autosaving current document..."));
317
318         // create autosave filename
319         string fname = bv->buffer()->filePath();
320         fname += '#';
321         fname += onlyFilename(bv->buffer()->fileName());
322         fname += '#';
323
324         AutoSaveBuffer autosave(*bv, fname);
325         autosave.start();
326
327         bv->buffer()->markBakClean();
328         bv->owner()->resetAutosaveTimer();
329 }
330
331
332 //
333 // Copyright CHT Software Service GmbH
334 // Uwe C. Schroeder
335 //
336 // create new file with template
337 // SERVERCMD !
338 //
339 void newFile(BufferView * bv, string const & filename)
340 {
341         // Split argument by :
342         string name;
343         string tmpname = split(filename, name, ':');
344         lyxerr[Debug::INFO] << "Arg is " << filename
345                             << "\nName is " << name
346                             << "\nTemplate is " << tmpname << endl;
347
348         Buffer * const b = newFile(name, tmpname);
349         if (b)
350                 bv->setBuffer(b);
351 }
352
353
354 // Insert ascii file (if filename is empty, prompt for one)
355 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
356 {
357         if (!bv->available())
358                 return;
359
360         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
361         if (tmpstr.empty())
362                 return;
363
364         // clear the selection
365         if (bv->text() == bv->getLyXText())
366                 bv->cursor().clearSelection();
367         if (asParagraph)
368                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
369         else
370                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
371         bv->update();
372 }
373
374
375 // Insert ascii file (if filename is empty, prompt for one)
376 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
377 {
378         string fname = f;
379
380         if (fname.empty()) {
381                 FileDialog fileDlg(_("Select file to insert"),
382                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
383
384                 FileDialog::Result result =
385                         fileDlg.open(bv->owner()->buffer()->filePath(),
386                                      FileFilterList(), string());
387
388                 if (result.first == FileDialog::Later)
389                         return string();
390
391                 fname = result.second;
392
393                 if (fname.empty())
394                         return string();
395         }
396
397         if (!fs::is_readable(fname)) {
398                 string const error = strerror(errno);
399                 string const file = makeDisplayPath(fname, 50);
400                 string const text = bformat(_("Could not read the specified document\n"
401                         "%1$s\ndue to the error: %2$s"), file, error);
402                 Alert::error(_("Could not read file"), text);
403                 return string();
404         }
405
406         ifstream ifs(fname.c_str());
407         if (!ifs) {
408                 string const error = strerror(errno);
409                 string const file = makeDisplayPath(fname, 50);
410                 string const text = bformat(_("Could not open the specified document\n"
411                         "%1$s\ndue to the error: %2$s"), file, error);
412                 Alert::error(_("Could not open file"), text);
413                 return string();
414         }
415
416         ifs.unsetf(ios::skipws);
417         istream_iterator<char> ii(ifs);
418         istream_iterator<char> end;
419 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
420         // We use this until the compilers get better...
421         std::vector<char> tmp;
422         copy(ii, end, back_inserter(tmp));
423         string const tmpstr(tmp.begin(), tmp.end());
424 #else
425         // This is what we want to use and what we will use once the
426         // compilers get good enough.
427         //string tmpstr(ii, end); // yet a reason for using std::string
428         // alternate approach to get the file into a string:
429         string tmpstr;
430         copy(ii, end, back_inserter(tmpstr));
431 #endif
432
433         return tmpstr;
434 }
435
436
437 // This function runs "configure" and then rereads lyx.defaults to
438 // reconfigure the automatic settings.
439 void reconfigure(BufferView * bv)
440 {
441         // emit message signal.
442         bv->buffer()->message(_("Running configure..."));
443
444         // Run configure in user lyx directory
445         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         bv->buffer()->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 }