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