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