]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
s/errno.h/cerrno/
[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/FileDialog.h"
36 #include "frontends/lyx_gui.h"
37 #include "frontends/LyXView.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::Path;
71 using lyx::support::package;
72 using lyx::support::quoteName;
73 using lyx::support::removeAutosaveFile;
74 using lyx::support::rename;
75 using lyx::support::split;
76 using lyx::support::Systemcall;
77 using lyx::support::tempName;
78 using lyx::support::unlink;
79
80 using boost::shared_ptr;
81
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 extern BufferList bufferlist;
95 // this should be static, but I need it in buffer.C
96 bool quitting;  // flag, that we are quitting the program
97
98
99 //
100 // Menu callbacks
101 //
102
103 bool menuWrite(Buffer * buffer)
104 {
105         if (buffer->save()) {
106                 LyX::ref().session().addLastFile(buffer->fileName());
107                 return true;
108         }
109
110         // FIXME: we don't tell the user *WHY* the save failed !!
111
112         string const file = makeDisplayPath(buffer->fileName(), 30);
113
114         string text = bformat(_("The document %1$s could not be saved.\n\n"
115                 "Do you want to rename the document and try again?"), file);
116         int const ret = Alert::prompt(_("Rename and save?"),
117                 text, 0, 1, _("&Rename"), _("&Cancel"));
118
119         if (ret == 0)
120                 return writeAs(buffer);
121         return false;
122 }
123
124
125
126 bool writeAs(Buffer * buffer, string const & filename)
127 {
128         string fname = buffer->fileName();
129         string const oldname = fname;
130
131         if (filename.empty()) {
132
133                 FileDialog fileDlg(_("Choose a filename to save document as"),
134                         LFUN_BUFFER_WRITE_AS,
135                         make_pair(string(_("Documents|#o#O")),
136                                   string(lyxrc.document_path)),
137                         make_pair(string(_("Templates|#T#t")),
138                                   string(lyxrc.template_path)));
139
140                 if (!isLyXFilename(fname))
141                         fname += ".lyx";
142
143                 FileFilterList const filter (_("LyX Documents (*.lyx)"));
144
145                 FileDialog::Result result =
146                         fileDlg.save(onlyPath(fname),
147                                      filter,
148                                      onlyFilename(fname));
149
150                 if (result.first == FileDialog::Later)
151                         return false;
152
153                 fname = result.second;
154
155                 if (fname.empty())
156                         return false;
157
158                 // Make sure the absolute filename ends with appropriate suffix
159                 fname = makeAbsPath(fname);
160                 if (!isLyXFilename(fname))
161                         fname += ".lyx";
162         } else
163                 fname = filename;
164
165         if (fs::exists(fname)) {
166                 string const file = makeDisplayPath(fname, 30);
167                 string text = bformat(_("The document %1$s already exists.\n\n"
168                         "Do you want to over-write that document?"), file);
169                 int const ret = Alert::prompt(_("Over-write document?"),
170                         text, 0, 1, _("&Over-write"), _("&Cancel"));
171
172                 if (ret == 1)
173                         return false;
174         }
175
176         // Ok, change the name of the buffer
177         buffer->setFileName(fname);
178         buffer->markDirty();
179         bool unnamed = buffer->isUnnamed();
180         buffer->setUnnamed(false);
181
182         if (!menuWrite(buffer)) {
183                 buffer->setFileName(oldname);
184                 buffer->setUnnamed(unnamed);
185                 return false;
186         }
187
188         removeAutosaveFile(oldname);
189         return true;
190 }
191
192
193 void quitLyX(bool noask)
194 {
195         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
196
197         if (lyx_gui::use_gui) {
198                 if (!noask && !bufferlist.quitWriteAll())
199                         return;
200
201                 LyX::cref().session().writeFile();
202         }
203
204         // Set a flag that we do quitting from the program,
205         // so no refreshes are necessary.
206         quitting = true;
207
208         // close buffers first
209         bufferlist.closeAll();
210
211         // do any other cleanup procedures now
212         lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
213
214         if (!destroyDir(package().temp_dir())) {
215                 string const msg =
216                         bformat(_("Unable to remove the temporary directory %1$s"),
217                         package().temp_dir());
218                 Alert::warning(_("Unable to remove temporary directory"), msg);
219         }
220
221         lyx_gui::exit(0);
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_ = bformat(_("Auto-saving %1$s"), 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->available())
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->owner()->resetAutosaveTimer();
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->owner()->resetAutosaveTimer();
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->available())
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         if (bv->text() == bv->getLyXText())
368                 bv->cursor().clearSelection();
369         if (asParagraph)
370                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
371         else
372                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
373         bv->update();
374 }
375
376
377 // Insert ascii file (if filename is empty, prompt for one)
378 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
379 {
380         string fname = f;
381
382         if (fname.empty()) {
383                 FileDialog fileDlg(_("Select file to insert"),
384                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
385
386                 FileDialog::Result result =
387                         fileDlg.open(bv->owner()->buffer()->filePath(),
388                                      FileFilterList(), string());
389
390                 if (result.first == FileDialog::Later)
391                         return string();
392
393                 fname = result.second;
394
395                 if (fname.empty())
396                         return string();
397         }
398
399         if (!fs::is_readable(fname)) {
400                 string const error = strerror(errno);
401                 string const file = makeDisplayPath(fname, 50);
402                 string const text = bformat(_("Could not read the specified document\n"
403                         "%1$s\ndue to the error: %2$s"), file, error);
404                 Alert::error(_("Could not read file"), text);
405                 return string();
406         }
407
408         ifstream ifs(fname.c_str());
409         if (!ifs) {
410                 string const error = strerror(errno);
411                 string const file = makeDisplayPath(fname, 50);
412                 string const text = bformat(_("Could not open the specified document\n"
413                         "%1$s\ndue to the error: %2$s"), file, error);
414                 Alert::error(_("Could not open file"), text);
415                 return string();
416         }
417
418         ifs.unsetf(ios::skipws);
419         istream_iterator<char> ii(ifs);
420         istream_iterator<char> end;
421 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
422         // We use this until the compilers get better...
423         std::vector<char> tmp;
424         copy(ii, end, back_inserter(tmp));
425         string const tmpstr(tmp.begin(), tmp.end());
426 #else
427         // This is what we want to use and what we will use once the
428         // compilers get good enough.
429         //string tmpstr(ii, end); // yet a reason for using std::string
430         // alternate approach to get the file into a string:
431         string tmpstr;
432         copy(ii, end, back_inserter(tmpstr));
433 #endif
434
435         return tmpstr;
436 }
437
438
439 // This function runs "configure" and then rereads lyx.defaults to
440 // reconfigure the automatic settings.
441 void reconfigure(BufferView * bv)
442 {
443         // emit message signal.
444         bv->buffer()->message(_("Running configure..."));
445
446         // Run configure in user lyx directory
447         Path p(package().user_support());
448         string const configure_command = package().configure_command();
449         Systemcall one;
450         one.startscript(Systemcall::Wait, configure_command);
451         p.pop();
452         // emit message signal.
453         bv->buffer()->message(_("Reloading configuration..."));
454         lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
455         // Re-read packages.lst
456         LaTeXFeatures::getAvailable();
457
458         Alert::information(_("System reconfigured"),
459                 _("The system has been reconfigured.\n"
460                 "You need to restart LyX to make use of any\n"
461                 "updated document class specifications."));
462 }