]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
aeaee83489a3ff5c0646ba461eb873d066dc467f
[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/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 fs = boost::filesystem;
81
82 using std::back_inserter;
83 using std::copy;
84 using std::endl;
85 using std::make_pair;
86 using std::string;
87 using std::ifstream;
88 using std::ios;
89 using std::istream_iterator;
90
91
92 // this should be static, but I need it in buffer.C
93 bool quitting;  // flag, that we are quitting the program
94
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                 FileDialog fileDlg(lyx::to_utf8(_("Choose a filename to save document as")),
131                         LFUN_BUFFER_WRITE_AS,
132                         make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
133                                   string(lyxrc.document_path)),
134                         make_pair(string(lyx::to_utf8(_("Templates|#T#t"))),
135                                   string(lyxrc.template_path)));
136
137                 if (!isLyXFilename(fname))
138                         fname += ".lyx";
139
140                 FileFilterList const filter (lyx::to_utf8(_("LyX Documents (*.lyx)")));
141
142                 FileDialog::Result result =
143                         fileDlg.save(onlyPath(fname),
144                                      filter,
145                                      onlyFilename(fname));
146
147                 if (result.first == FileDialog::Later)
148                         return false;
149
150                 fname = result.second;
151
152                 if (fname.empty())
153                         return false;
154
155                 // Make sure the absolute filename ends with appropriate suffix
156                 fname = makeAbsPath(fname);
157                 if (!isLyXFilename(fname))
158                         fname += ".lyx";
159         } else
160                 fname = filename;
161
162         if (fs::exists(fname)) {
163                 docstring const file = makeDisplayPath(fname, 30);
164                 docstring text = bformat(_("The document %1$s already exists.\n\n"
165                                                      "Do you want to over-write that document?"), file);
166                 int const ret = Alert::prompt(_("Over-write document?"),
167                         text, 0, 1, _("&Over-write"), _("&Cancel"));
168
169                 if (ret == 1)
170                         return false;
171         }
172
173         // Ok, change the name of the buffer
174         buffer->setFileName(fname);
175         buffer->markDirty();
176         bool unnamed = buffer->isUnnamed();
177         buffer->setUnnamed(false);
178
179         if (!menuWrite(buffer)) {
180                 buffer->setFileName(oldname);
181                 buffer->setUnnamed(unnamed);
182                 return false;
183         }
184
185         removeAutosaveFile(oldname);
186         return true;
187 }
188
189
190 void quitLyX(bool noask)
191 {
192         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
193
194         if (lyx_gui::use_gui) {
195                 if (!noask && !theApp->bufferList().quitWriteAll())
196                         return;
197
198                 LyX::cref().session().writeFile();
199         }
200
201         // Set a flag that we do quitting from the program,
202         // so no refreshes are necessary.
203         quitting = true;
204
205         // close buffers first
206         theApp->bufferList().closeAll();
207
208         // do any other cleanup procedures now
209         lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
210
211         if (!destroyDir(package().temp_dir())) {
212                 docstring const msg =
213                         bformat(_("Unable to remove the temporary directory %1$s"),
214                         lyx::from_utf8(package().temp_dir()));
215                 Alert::warning(_("Unable to remove temporary directory"), msg);
216         }
217
218         lyx_gui::exit(0);
219 }
220
221
222 namespace {
223
224 class AutoSaveBuffer : public ForkedProcess {
225 public:
226         ///
227         AutoSaveBuffer(BufferView & bv, string const & fname)
228                 : bv_(bv), fname_(fname) {}
229         ///
230         virtual shared_ptr<ForkedProcess> clone() const
231         {
232                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
233         }
234         ///
235         int start();
236 private:
237         ///
238         virtual int generateChild();
239         ///
240         BufferView & bv_;
241         string fname_;
242 };
243
244
245 int AutoSaveBuffer::start()
246 {
247         command_ = lyx::to_utf8(bformat(_("Auto-saving %1$s"), lyx::from_utf8(fname_)));
248         return run(DontWait);
249 }
250
251
252 int AutoSaveBuffer::generateChild()
253 {
254         // tmp_ret will be located (usually) in /tmp
255         // will that be a problem?
256         pid_t const pid = fork(); // If you want to debug the autosave
257         // you should set pid to -1, and comment out the
258         // fork.
259         if (pid == 0 || pid == -1) {
260                 // pid = -1 signifies that lyx was unable
261                 // to fork. But we will do the save
262                 // anyway.
263                 bool failed = false;
264
265                 string const tmp_ret = tempName(string(), "lyxauto");
266                 if (!tmp_ret.empty()) {
267                         bv_.buffer()->writeFile(tmp_ret);
268                         // assume successful write of tmp_ret
269                         if (!rename(tmp_ret, fname_)) {
270                                 failed = true;
271                                 // most likely couldn't move between filesystems
272                                 // unless write of tmp_ret failed
273                                 // so remove tmp file (if it exists)
274                                 unlink(tmp_ret);
275                         }
276                 } else {
277                         failed = true;
278                 }
279
280                 if (failed) {
281                         // failed to write/rename tmp_ret so try writing direct
282                         if (!bv_.buffer()->writeFile(fname_)) {
283                                 // It is dangerous to do this in the child,
284                                 // but safe in the parent, so...
285                                 if (pid == -1)
286                                         // emit message signal.
287                                         bv_.buffer()->message(_("Autosave failed!"));
288                         }
289                 }
290                 if (pid == 0) { // we are the child so...
291                         _exit(0);
292                 }
293         }
294         return pid;
295 }
296
297 } // namespace anon
298
299
300 void autoSave(BufferView * bv)
301         // should probably be moved into BufferList (Lgb)
302         // Perfect target for a thread...
303 {
304         if (!bv->buffer())
305                 return;
306
307         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
308                 // We don't save now, but we'll try again later
309                 bv->buffer()->resetAutosaveTimers();
310                 return;
311         }
312
313         // emit message signal.
314         bv->buffer()->message(_("Autosaving current document..."));
315
316         // create autosave filename
317         string fname = bv->buffer()->filePath();
318         fname += '#';
319         fname += onlyFilename(bv->buffer()->fileName());
320         fname += '#';
321
322         AutoSaveBuffer autosave(*bv, fname);
323         autosave.start();
324
325         bv->buffer()->markBakClean();
326         bv->buffer()->resetAutosaveTimers();
327 }
328
329
330 //
331 // Copyright CHT Software Service GmbH
332 // Uwe C. Schroeder
333 //
334 // create new file with template
335 // SERVERCMD !
336 //
337 void newFile(BufferView * bv, string const & filename)
338 {
339         // Split argument by :
340         string name;
341         string tmpname = split(filename, name, ':');
342         lyxerr[Debug::INFO] << "Arg is " << filename
343                             << "\nName is " << name
344                             << "\nTemplate is " << tmpname << endl;
345
346         Buffer * const b = newFile(name, tmpname);
347         if (b)
348                 bv->setBuffer(b);
349 }
350
351
352 // Insert ascii file (if filename is empty, prompt for one)
353 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
354 {
355         if (!bv->buffer())
356                 return;
357
358         // FIXME: We don't know the encoding of the file
359         docstring const tmpstr = lyx::from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
360         if (tmpstr.empty())
361                 return;
362
363         // clear the selection
364         LyXText const & text = bv->buffer()->text();
365         if (&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(lyx::to_utf8(_("Select file to insert")),
382                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
383
384                 FileDialog::Result result =
385                         fileDlg.open(bv->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                 docstring const error = lyx::from_ascii(strerror(errno));
399                 docstring const file = makeDisplayPath(fname, 50);
400                 docstring 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                 docstring const error = lyx::from_ascii(strerror(errno));
409                 docstring const file = makeDisplayPath(fname, 50);
410                 docstring 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         lyx::support::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 }