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