]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
341aa45c36dc145d54d6218cdb0ec120914ae4d3
[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 && !theApp->bufferList().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         theApp->bufferList().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         theApp->exit(0);
220         // Restore original font resources after Application is destroyed.
221         lyx::support::restoreFontResources();
222 }
223
224
225 namespace {
226
227 class AutoSaveBuffer : public ForkedProcess {
228 public:
229         ///
230         AutoSaveBuffer(BufferView & bv, string const & fname)
231                 : bv_(bv), fname_(fname) {}
232         ///
233         virtual shared_ptr<ForkedProcess> clone() const
234         {
235                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
236         }
237         ///
238         int start();
239 private:
240         ///
241         virtual int generateChild();
242         ///
243         BufferView & bv_;
244         string fname_;
245 };
246
247
248 int AutoSaveBuffer::start()
249 {
250         command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
251         return run(DontWait);
252 }
253
254
255 int AutoSaveBuffer::generateChild()
256 {
257         // tmp_ret will be located (usually) in /tmp
258         // will that be a problem?
259         pid_t const pid = fork(); // If you want to debug the autosave
260         // you should set pid to -1, and comment out the
261         // fork.
262         if (pid == 0 || pid == -1) {
263                 // pid = -1 signifies that lyx was unable
264                 // to fork. But we will do the save
265                 // anyway.
266                 bool failed = false;
267
268                 string const tmp_ret = tempName(string(), "lyxauto");
269                 if (!tmp_ret.empty()) {
270                         bv_.buffer()->writeFile(tmp_ret);
271                         // assume successful write of tmp_ret
272                         if (!rename(tmp_ret, fname_)) {
273                                 failed = true;
274                                 // most likely couldn't move between filesystems
275                                 // unless write of tmp_ret failed
276                                 // so remove tmp file (if it exists)
277                                 unlink(tmp_ret);
278                         }
279                 } else {
280                         failed = true;
281                 }
282
283                 if (failed) {
284                         // failed to write/rename tmp_ret so try writing direct
285                         if (!bv_.buffer()->writeFile(fname_)) {
286                                 // It is dangerous to do this in the child,
287                                 // but safe in the parent, so...
288                                 if (pid == -1)
289                                         // emit message signal.
290                                         bv_.buffer()->message(_("Autosave failed!"));
291                         }
292                 }
293                 if (pid == 0) { // we are the child so...
294                         _exit(0);
295                 }
296         }
297         return pid;
298 }
299
300 } // namespace anon
301
302
303 void autoSave(BufferView * bv)
304         // should probably be moved into BufferList (Lgb)
305         // Perfect target for a thread...
306 {
307         if (!bv->buffer())
308                 return;
309
310         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
311                 // We don't save now, but we'll try again later
312                 bv->buffer()->resetAutosaveTimers();
313                 return;
314         }
315
316         // emit message signal.
317         bv->buffer()->message(_("Autosaving current document..."));
318
319         // create autosave filename
320         string fname = bv->buffer()->filePath();
321         fname += '#';
322         fname += onlyFilename(bv->buffer()->fileName());
323         fname += '#';
324
325         AutoSaveBuffer autosave(*bv, fname);
326         autosave.start();
327
328         bv->buffer()->markBakClean();
329         bv->buffer()->resetAutosaveTimers();
330 }
331
332
333 //
334 // Copyright CHT Software Service GmbH
335 // Uwe C. Schroeder
336 //
337 // create new file with template
338 // SERVERCMD !
339 //
340 void newFile(BufferView * bv, string const & filename)
341 {
342         // Split argument by :
343         string name;
344         string tmpname = split(filename, name, ':');
345         lyxerr[Debug::INFO] << "Arg is " << filename
346                             << "\nName is " << name
347                             << "\nTemplate is " << tmpname << endl;
348
349         Buffer * const b = newFile(name, tmpname);
350         if (b)
351                 bv->setBuffer(b);
352 }
353
354
355 // Insert ascii file (if filename is empty, prompt for one)
356 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
357 {
358         if (!bv->buffer())
359                 return;
360
361         // FIXME: We don't know the encoding of the file
362         docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
363         if (tmpstr.empty())
364                 return;
365
366         // clear the selection
367         LyXText const & text = bv->buffer()->text();
368         if (&text == bv->getLyXText())
369                 bv->cursor().clearSelection();
370         if (asParagraph)
371                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
372         else
373                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
374         bv->update();
375 }
376
377
378 // Insert ascii file (if filename is empty, prompt for one)
379 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
380 {
381         string fname = f;
382
383         if (fname.empty()) {
384                 FileDialog fileDlg(_("Select file to insert"),
385                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
386
387                 FileDialog::Result result =
388                         fileDlg.open(lyx::from_utf8(bv->buffer()->filePath()),
389                                      FileFilterList(), docstring());
390
391                 if (result.first == FileDialog::Later)
392                         return string();
393
394                 fname = lyx::to_utf8(result.second);
395
396                 if (fname.empty())
397                         return string();
398         }
399
400         if (!fs::is_readable(fname)) {
401                 docstring const error = lyx::from_ascii(strerror(errno));
402                 docstring const file = makeDisplayPath(fname, 50);
403                 docstring const text = bformat(_("Could not read the specified document\n"
404                                                            "%1$s\ndue to the error: %2$s"), file, error);
405                 Alert::error(_("Could not read file"), text);
406                 return string();
407         }
408
409         ifstream ifs(fname.c_str());
410         if (!ifs) {
411                 docstring const error = lyx::from_ascii(strerror(errno));
412                 docstring const file = makeDisplayPath(fname, 50);
413                 docstring const text = bformat(_("Could not open the specified document\n"
414                                                            "%1$s\ndue to the error: %2$s"), file, error);
415                 Alert::error(_("Could not open file"), text);
416                 return string();
417         }
418
419         ifs.unsetf(ios::skipws);
420         istream_iterator<char> ii(ifs);
421         istream_iterator<char> end;
422 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
423         // We use this until the compilers get better...
424         std::vector<char> tmp;
425         copy(ii, end, back_inserter(tmp));
426         string const tmpstr(tmp.begin(), tmp.end());
427 #else
428         // This is what we want to use and what we will use once the
429         // compilers get good enough.
430         //string tmpstr(ii, end); // yet a reason for using std::string
431         // alternate approach to get the file into a string:
432         string tmpstr;
433         copy(ii, end, back_inserter(tmpstr));
434 #endif
435
436         return tmpstr;
437 }
438
439
440 // This function runs "configure" and then rereads lyx.defaults to
441 // reconfigure the automatic settings.
442 void reconfigure(BufferView * bv)
443 {
444         // emit message signal.
445         bv->buffer()->message(_("Running configure..."));
446
447         // Run configure in user lyx directory
448         lyx::support::Path p(package().user_support());
449         string const configure_command = package().configure_command();
450         Systemcall one;
451         one.startscript(Systemcall::Wait, configure_command);
452         p.pop();
453         // emit message signal.
454         bv->buffer()->message(_("Reloading configuration..."));
455         lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
456         // Re-read packages.lst
457         LaTeXFeatures::getAvailable();
458
459         Alert::information(_("System reconfigured"),
460                            _("The system has been reconfigured.\n"
461                                           "You need to restart LyX to make use of any\n"
462                                           "updated document class specifications."));
463 }