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