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