]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
af2f31c90f97b57b7d87a7a7a00fabe5956dba7a
[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                 FileDialog fileDlg(lyx::to_utf8(_("Choose a filename to save document as")),
133                         LFUN_BUFFER_WRITE_AS,
134                         make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
135                                   string(lyxrc.document_path)),
136                         make_pair(string(lyx::to_utf8(_("Templates|#T#t"))),
137                                   string(lyxrc.template_path)));
138
139                 if (!isLyXFilename(fname))
140                         fname += ".lyx";
141
142                 FileFilterList const filter (lyx::to_utf8(_("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                 docstring const file = makeDisplayPath(fname, 30);
166                 docstring 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 && !theApp->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         theApp->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                 docstring const msg =
215                         bformat(_("Unable to remove the temporary directory %1$s"),
216                         lyx::from_utf8(package().temp_dir()));
217                 Alert::warning(_("Unable to remove temporary directory"), msg);
218         }
219
220         theApp->exit(0);
221         // Restore original font resources after Application is destroyed.
222         lyx::support::restoreFontResources();
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(lyx::to_utf8(_("Select file to insert")),
386                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
387
388                 FileDialog::Result result =
389                         fileDlg.open(bv->buffer()->filePath(),
390                                      FileFilterList(), string());
391
392                 if (result.first == FileDialog::Later)
393                         return string();
394
395                 fname = 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 }