]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
* Painter.h:
[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
38 #include "support/filefilterlist.h"
39 #include "support/filetools.h"
40 #include "support/fontutils.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
59 namespace lyx {
60
61 using support::addName;
62 using support::bformat;
63 using support::FileFilterList;
64 using support::ForkedProcess;
65 using support::isLyXFilename;
66 using support::libFileSearch;
67 using support::makeAbsPath;
68 using support::makeDisplayPath;
69 using support::onlyFilename;
70 using support::onlyPath;
71 using support::package;
72 using support::removeAutosaveFile;
73 using support::rename;
74 using support::split;
75 using support::Systemcall;
76 using support::tempName;
77 using support::unlink;
78
79 using boost::shared_ptr;
80
81 namespace Alert = 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 // Menu callbacks
99 //
100
101 bool menuWrite(Buffer * buffer)
102 {
103         if (buffer->save()) {
104                 LyX::ref().session().lastFiles().add(buffer->fileName());
105                 return true;
106         }
107
108         // FIXME: we don't tell the user *WHY* the save failed !!
109
110         docstring const file = makeDisplayPath(buffer->fileName(), 30);
111
112         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
113                                              "Do you want to rename the document and try again?"), file);
114         int const ret = Alert::prompt(_("Rename and save?"),
115                 text, 0, 1, _("&Rename"), _("&Cancel"));
116
117         if (ret == 0)
118                 return writeAs(buffer);
119         return false;
120 }
121
122
123
124 bool writeAs(Buffer * buffer, string const & filename)
125 {
126         string fname = buffer->fileName();
127         string const oldname = fname;
128
129         if (filename.empty()) {
130
131                 // FIXME UNICODE
132                 FileDialog fileDlg(_("Choose a filename to save document as"),
133                         LFUN_BUFFER_WRITE_AS,
134                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
135                         make_pair(_("Templates|#T#t"), from_utf8(lyxrc.template_path)));
136
137                 if (!isLyXFilename(fname))
138                         fname += ".lyx";
139
140                 FileFilterList const filter (_("LyX Documents (*.lyx)"));
141
142                 FileDialog::Result result =
143                         fileDlg.save(from_utf8(onlyPath(fname)),
144                                      filter,
145                                      from_utf8(onlyFilename(fname)));
146
147                 if (result.first == FileDialog::Later)
148                         return false;
149
150                 fname = to_utf8(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 namespace {
191
192 class AutoSaveBuffer : public ForkedProcess {
193 public:
194         ///
195         AutoSaveBuffer(BufferView & bv, string const & fname)
196                 : bv_(bv), fname_(fname) {}
197         ///
198         virtual shared_ptr<ForkedProcess> clone() const
199         {
200                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
201         }
202         ///
203         int start();
204 private:
205         ///
206         virtual int generateChild();
207         ///
208         BufferView & bv_;
209         string fname_;
210 };
211
212
213 int AutoSaveBuffer::start()
214 {
215         command_ = to_utf8(bformat(_("Auto-saving %1$s"), from_utf8(fname_)));
216         return run(DontWait);
217 }
218
219
220 int AutoSaveBuffer::generateChild()
221 {
222         // tmp_ret will be located (usually) in /tmp
223         // will that be a problem?
224         pid_t const pid = fork(); // If you want to debug the autosave
225         // you should set pid to -1, and comment out the
226         // fork.
227         if (pid == 0 || pid == -1) {
228                 // pid = -1 signifies that lyx was unable
229                 // to fork. But we will do the save
230                 // anyway.
231                 bool failed = false;
232
233                 string const tmp_ret = tempName(string(), "lyxauto");
234                 if (!tmp_ret.empty()) {
235                         bv_.buffer()->writeFile(tmp_ret);
236                         // assume successful write of tmp_ret
237                         if (!rename(tmp_ret, fname_)) {
238                                 failed = true;
239                                 // most likely couldn't move between filesystems
240                                 // unless write of tmp_ret failed
241                                 // so remove tmp file (if it exists)
242                                 unlink(tmp_ret);
243                         }
244                 } else {
245                         failed = true;
246                 }
247
248                 if (failed) {
249                         // failed to write/rename tmp_ret so try writing direct
250                         if (!bv_.buffer()->writeFile(fname_)) {
251                                 // It is dangerous to do this in the child,
252                                 // but safe in the parent, so...
253                                 if (pid == -1)
254                                         // emit message signal.
255                                         bv_.buffer()->message(_("Autosave failed!"));
256                         }
257                 }
258                 if (pid == 0) { // we are the child so...
259                         _exit(0);
260                 }
261         }
262         return pid;
263 }
264
265 } // namespace anon
266
267
268 void autoSave(BufferView * bv)
269         // should probably be moved into BufferList (Lgb)
270         // Perfect target for a thread...
271 {
272         if (!bv->buffer())
273                 return;
274
275         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
276                 // We don't save now, but we'll try again later
277                 bv->buffer()->resetAutosaveTimers();
278                 return;
279         }
280
281         // emit message signal.
282         bv->buffer()->message(_("Autosaving current document..."));
283
284         // create autosave filename
285         string fname = bv->buffer()->filePath();
286         fname += '#';
287         fname += onlyFilename(bv->buffer()->fileName());
288         fname += '#';
289
290         AutoSaveBuffer autosave(*bv, fname);
291         autosave.start();
292
293         bv->buffer()->markBakClean();
294         bv->buffer()->resetAutosaveTimers();
295 }
296
297
298 //
299 // Copyright CHT Software Service GmbH
300 // Uwe C. Schroeder
301 //
302 // create new file with template
303 // SERVERCMD !
304 //
305 void newFile(BufferView * bv, string const & filename)
306 {
307         // Split argument by :
308         string name;
309         string tmpname = split(filename, name, ':');
310         lyxerr[Debug::INFO] << "Arg is " << filename
311                             << "\nName is " << name
312                             << "\nTemplate is " << tmpname << endl;
313
314         Buffer * const b = newFile(name, tmpname);
315         if (b)
316                 bv->setBuffer(b);
317 }
318
319
320 // Insert ascii file (if filename is empty, prompt for one)
321 void insertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
322 {
323         if (!bv->buffer())
324                 return;
325
326         // FIXME: We don't know the encoding of the file
327         docstring const tmpstr = from_utf8(getContentsOfAsciiFile(bv, f, asParagraph));
328         if (tmpstr.empty())
329                 return;
330
331         // clear the selection
332         LyXText const & text = bv->buffer()->text();
333         if (&text == bv->getLyXText())
334                 bv->cursor().clearSelection();
335         if (asParagraph)
336                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
337         else
338                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
339         bv->update();
340 }
341
342
343 // Insert ascii file (if filename is empty, prompt for one)
344 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
345 {
346         string fname = f;
347
348         if (fname.empty()) {
349                 FileDialog fileDlg(_("Select file to insert"),
350                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
351
352                 FileDialog::Result result =
353                         fileDlg.open(from_utf8(bv->buffer()->filePath()),
354                                      FileFilterList(), docstring());
355
356                 if (result.first == FileDialog::Later)
357                         return string();
358
359                 fname = to_utf8(result.second);
360
361                 if (fname.empty())
362                         return string();
363         }
364
365         if (!fs::is_readable(fname)) {
366                 docstring const error = from_ascii(strerror(errno));
367                 docstring const file = makeDisplayPath(fname, 50);
368                 docstring const text = bformat(_("Could not read the specified document\n"
369                                                            "%1$s\ndue to the error: %2$s"), file, error);
370                 Alert::error(_("Could not read file"), text);
371                 return string();
372         }
373
374         ifstream ifs(fname.c_str());
375         if (!ifs) {
376                 docstring const error = from_ascii(strerror(errno));
377                 docstring const file = makeDisplayPath(fname, 50);
378                 docstring const text = bformat(_("Could not open the specified document\n"
379                                                            "%1$s\ndue to the error: %2$s"), file, error);
380                 Alert::error(_("Could not open file"), text);
381                 return string();
382         }
383
384         ifs.unsetf(ios::skipws);
385         istream_iterator<char> ii(ifs);
386         istream_iterator<char> end;
387 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
388         // We use this until the compilers get better...
389         std::vector<char> tmp;
390         copy(ii, end, back_inserter(tmp));
391         string const tmpstr(tmp.begin(), tmp.end());
392 #else
393         // This is what we want to use and what we will use once the
394         // compilers get good enough.
395         //string tmpstr(ii, end); // yet a reason for using std::string
396         // alternate approach to get the file into a string:
397         string tmpstr;
398         copy(ii, end, back_inserter(tmpstr));
399 #endif
400
401         return tmpstr;
402 }
403
404
405 // This function runs "configure" and then rereads lyx.defaults to
406 // reconfigure the automatic settings.
407 void reconfigure(BufferView * bv)
408 {
409         // emit message signal.
410         bv->buffer()->message(_("Running configure..."));
411
412         // Run configure in user lyx directory
413         support::Path p(package().user_support());
414         string const configure_command = package().configure_command();
415         Systemcall one;
416         one.startscript(Systemcall::Wait, configure_command);
417         p.pop();
418         // emit message signal.
419         bv->buffer()->message(_("Reloading configuration..."));
420         lyxrc.read(libFileSearch(string(), "lyxrc.defaults"));
421         // Re-read packages.lst
422         LaTeXFeatures::getAvailable();
423
424         Alert::information(_("System reconfigured"),
425                            _("The system has been reconfigured.\n"
426                                           "You need to restart LyX to make use of any\n"
427                                           "updated document class specifications."));
428 }
429
430
431 } // namespace lyx