]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
ditch FileInfo -> use boost.filesystem
[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 "cursor.h"
23 #include "debug.h"
24 #include "gettext.h"
25 #include "lastfiles.h"
26 #include "LaTeXFeatures.h"
27 #include "lyx_main.h"
28 #include "lyxlayout.h"
29 #include "lyxrc.h"
30 #include "lyxtext.h"
31 #include "paragraph.h"
32
33 #include "frontends/Alert.h"
34 #include "frontends/FileDialog.h"
35 #include "frontends/lyx_gui.h"
36 #include "frontends/LyXView.h"
37
38 #include "support/filefilterlist.h"
39 #include "support/filetools.h"
40 #include "support/forkedcall.h"
41 #include "support/fs_extras.h"
42 #include "support/lyxlib.h"
43 #include "support/package.h"
44 #include "support/path.h"
45 #include "support/systemcall.h"
46
47 #include <boost/shared_ptr.hpp>
48 #include <boost/filesystem/operations.hpp>
49
50 #include <cerrno>
51 #include <fstream>
52
53 using lyx::support::AddName;
54 using lyx::support::bformat;
55 using lyx::support::destroyDir;
56 using lyx::support::FileFilterList;
57 using lyx::support::ForkedProcess;
58 using lyx::support::IsLyXFilename;
59 using lyx::support::LibFileSearch;
60 using lyx::support::MakeAbsPath;
61 using lyx::support::MakeDisplayPath;
62 using lyx::support::OnlyFilename;
63 using lyx::support::OnlyPath;
64 using lyx::support::Path;
65 using lyx::support::package;
66 using lyx::support::QuoteName;
67 using lyx::support::removeAutosaveFile;
68 using lyx::support::rename;
69 using lyx::support::split;
70 using lyx::support::Systemcall;
71 using lyx::support::tempName;
72 using lyx::support::unlink;
73
74 using boost::shared_ptr;
75
76 namespace fs = boost::filesystem;
77
78 using std::back_inserter;
79 using std::copy;
80 using std::endl;
81 using std::make_pair;
82 using std::string;
83 using std::ifstream;
84 using std::ios;
85 using std::istream_iterator;
86
87
88 extern BufferList bufferlist;
89 // this should be static, but I need it in buffer.C
90 bool quitting;  // flag, that we are quitting the program
91
92
93 //
94 // Menu callbacks
95 //
96
97 bool MenuWrite(Buffer * buffer)
98 {
99         if (buffer->save()) {
100                 LyX::ref().lastfiles().newFile(buffer->fileName());
101                 return true;
102         }
103
104         // FIXME: we don't tell the user *WHY* the save failed !!
105
106         string const file = MakeDisplayPath(buffer->fileName(), 30);
107
108         string text = bformat(_("The document %1$s could not be saved.\n\n"
109                 "Do you want to rename the document and try again?"), file);
110         int const ret = Alert::prompt(_("Rename and save?"),
111                 text, 0, 1, _("&Rename"), _("&Cancel"));
112
113         if (ret == 0)
114                 return WriteAs(buffer);
115         return false;
116 }
117
118
119
120 bool WriteAs(Buffer * buffer, string const & filename)
121 {
122         string fname = buffer->fileName();
123         string const oldname = fname;
124
125         if (filename.empty()) {
126
127                 FileDialog fileDlg(_("Choose a filename to save document as"),
128                         LFUN_WRITEAS,
129                         make_pair(string(_("Documents|#o#O")),
130                                   string(lyxrc.document_path)),
131                         make_pair(string(_("Templates|#T#t")),
132                                   string(lyxrc.template_path)));
133
134                 if (!IsLyXFilename(fname))
135                         fname += ".lyx";
136
137                 FileFilterList const filter (_("LyX Documents (*.lyx)"));
138
139                 FileDialog::Result result =
140                         fileDlg.save(OnlyPath(fname),
141                                      filter,
142                                      OnlyFilename(fname));
143
144                 if (result.first == FileDialog::Later)
145                         return false;
146
147                 fname = result.second;
148
149                 if (fname.empty())
150                         return false;
151
152                 // Make sure the absolute filename ends with appropriate suffix
153                 fname = MakeAbsPath(fname);
154                 if (!IsLyXFilename(fname))
155                         fname += ".lyx";
156         } else
157                 fname = filename;
158
159         if (fs::exists(fname)) {
160                 string const file = MakeDisplayPath(fname, 30);
161                 string text = bformat(_("The document %1$s already exists.\n\n"
162                         "Do you want to over-write that document?"), file);
163                 int const ret = Alert::prompt(_("Over-write document?"),
164                         text, 0, 1, _("&Over-write"), _("&Cancel"));
165
166                 if (ret == 1)
167                         return false;
168         }
169
170         // Ok, change the name of the buffer
171         buffer->setFileName(fname);
172         buffer->markDirty();
173         bool unnamed = buffer->isUnnamed();
174         buffer->setUnnamed(false);
175
176         if (!MenuWrite(buffer)) {
177                 buffer->setFileName(oldname);
178                 buffer->setUnnamed(unnamed);
179                 return false;
180         }
181
182         removeAutosaveFile(oldname);
183         return true;
184 }
185
186
187 void QuitLyX()
188 {
189         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
190
191         if (lyx_gui::use_gui) {
192                 if (!bufferlist.quitWriteAll())
193                         return;
194
195                 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
196         }
197
198         // Set a flag that we do quitting from the program,
199         // so no refreshes are necessary.
200         quitting = true;
201
202         // close buffers first
203         bufferlist.closeAll();
204
205         // do any other cleanup procedures now
206         lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
207
208         if (!destroyDir(package().temp_dir())) {
209                 string const msg =
210                         bformat(_("Unable to remove the temporary directory %1$s"),
211                         package().temp_dir());
212                 Alert::warning(_("Unable to remove temporary directory"), msg);
213         }
214
215         lyx_gui::exit();
216 }
217
218
219 namespace {
220
221 class AutoSaveBuffer : public ForkedProcess {
222 public:
223         ///
224         AutoSaveBuffer(BufferView & bv, string const & fname)
225                 : bv_(bv), fname_(fname) {}
226         ///
227         virtual shared_ptr<ForkedProcess> clone() const
228         {
229                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
230         }
231         ///
232         int start();
233 private:
234         ///
235         virtual int generateChild();
236         ///
237         BufferView & bv_;
238         string fname_;
239 };
240
241
242 int AutoSaveBuffer::start()
243 {
244         command_ = bformat(_("Auto-saving %1$s"), fname_);
245         return run(DontWait);
246 }
247
248
249 int AutoSaveBuffer::generateChild()
250 {
251         // tmp_ret will be located (usually) in /tmp
252         // will that be a problem?
253         pid_t const pid = fork(); // If you want to debug the autosave
254         // you should set pid to -1, and comment out the
255         // fork.
256         if (pid == 0 || pid == -1) {
257                 // pid = -1 signifies that lyx was unable
258                 // to fork. But we will do the save
259                 // anyway.
260                 bool failed = false;
261
262                 string const tmp_ret = tempName(string(), "lyxauto");
263                 if (!tmp_ret.empty()) {
264                         bv_.buffer()->writeFile(tmp_ret);
265                         // assume successful write of tmp_ret
266                         if (!rename(tmp_ret, fname_)) {
267                                 failed = true;
268                                 // most likely couldn't move between filesystems
269                                 // unless write of tmp_ret failed
270                                 // so remove tmp file (if it exists)
271                                 unlink(tmp_ret);
272                         }
273                 } else {
274                         failed = true;
275                 }
276
277                 if (failed) {
278                         // failed to write/rename tmp_ret so try writing direct
279                         if (!bv_.buffer()->writeFile(fname_)) {
280                                 // It is dangerous to do this in the child,
281                                 // but safe in the parent, so...
282                                 if (pid == -1)
283                                         bv_.owner()->message(_("Autosave failed!"));
284                         }
285                 }
286                 if (pid == 0) { // we are the child so...
287                         _exit(0);
288                 }
289         }
290         return pid;
291 }
292
293 } // namespace anon
294
295
296 void AutoSave(BufferView * bv)
297         // should probably be moved into BufferList (Lgb)
298         // Perfect target for a thread...
299 {
300         if (!bv->available())
301                 return;
302
303         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
304                 // We don't save now, but we'll try again later
305                 bv->owner()->resetAutosaveTimer();
306                 return;
307         }
308
309         bv->owner()->message(_("Autosaving current document..."));
310
311         // create autosave filename
312         string fname = bv->buffer()->filePath();
313         fname += '#';
314         fname += OnlyFilename(bv->buffer()->fileName());
315         fname += '#';
316
317         AutoSaveBuffer autosave(*bv, fname);
318         autosave.start();
319
320         bv->buffer()->markBakClean();
321         bv->owner()->resetAutosaveTimer();
322 }
323
324
325 //
326 // Copyright CHT Software Service GmbH
327 // Uwe C. Schroeder
328 //
329 // create new file with template
330 // SERVERCMD !
331 //
332 void NewFile(BufferView * bv, string const & filename)
333 {
334         // Split argument by :
335         string name;
336         string tmpname = split(filename, name, ':');
337 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
338         if (name.length() == 1
339             && isalpha(static_cast<unsigned char>(name[0]))
340             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
341                 name += ':';
342                 name += token(tmpname, ':', 0);
343                 tmpname = split(tmpname, ':');
344         }
345 #endif
346         lyxerr[Debug::INFO] << "Arg is " << filename
347                             << "\nName is " << name
348                             << "\nTemplate is " << tmpname << endl;
349
350         bv->newFile(name, tmpname);
351 }
352
353
354 // Insert ascii file (if filename is empty, prompt for one)
355 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
356 {
357         if (!bv->available())
358                 return;
359
360         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
361         if (tmpstr.empty())
362                 return;
363
364         // clear the selection
365         if (bv->text() == bv->getLyXText())
366                 bv->cursor().clearSelection();
367         if (asParagraph)
368                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
369         else
370                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
371         bv->update();
372 }
373
374
375 // Insert ascii file (if filename is empty, prompt for one)
376 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
377 {
378         string fname = f;
379
380         if (fname.empty()) {
381                 FileDialog fileDlg(_("Select file to insert"),
382                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
383
384                 FileDialog::Result result =
385                         fileDlg.open(bv->owner()->buffer()->filePath(),
386                                      FileFilterList(), string());
387
388                 if (result.first == FileDialog::Later)
389                         return string();
390
391                 fname = result.second;
392
393                 if (fname.empty())
394                         return string();
395         }
396
397         if (!fs::is_readable(fname)) {
398                 string const error = strerror(errno);
399                 string const file = MakeDisplayPath(fname, 50);
400                 string const text = bformat(_("Could not read the specified document\n"
401                         "%1$s\ndue to the error: %2$s"), file, error);
402                 Alert::error(_("Could not read file"), text);
403                 return string();
404         }
405
406         ifstream ifs(fname.c_str());
407         if (!ifs) {
408                 string const error = strerror(errno);
409                 string const file = MakeDisplayPath(fname, 50);
410                 string const text = bformat(_("Could not open the specified document\n"
411                         "%1$s\ndue to the error: %2$s"), file, error);
412                 Alert::error(_("Could not open file"), text);
413                 return string();
414         }
415
416         ifs.unsetf(ios::skipws);
417         istream_iterator<char> ii(ifs);
418         istream_iterator<char> end;
419 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
420         // We use this until the compilers get better...
421         std::vector<char> tmp;
422         copy(ii, end, back_inserter(tmp));
423         string const tmpstr(tmp.begin(), tmp.end());
424 #else
425         // This is what we want to use and what we will use once the
426         // compilers get good enough.
427         //string tmpstr(ii, end); // yet a reason for using std::string
428         // alternate approach to get the file into a string:
429         string tmpstr;
430         copy(ii, end, back_inserter(tmpstr));
431 #endif
432
433         return tmpstr;
434 }
435
436
437 // This function runs "configure" and then rereads lyx.defaults to
438 // reconfigure the automatic settings.
439 void Reconfigure(BufferView * bv)
440 {
441         bv->owner()->message(_("Running configure..."));
442
443         // Run configure in user lyx directory
444         Path p(package().user_support());
445         string const configure_script =
446                 AddName(package().system_support(), "configure");
447         string const configure_command = "sh " + QuoteName(configure_script);
448         Systemcall one;
449         one.startscript(Systemcall::Wait, configure_command);
450         p.pop();
451         bv->owner()->message(_("Reloading configuration..."));
452         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
453         // Re-read packages.lst
454         LaTeXFeatures::getAvailable();
455
456         Alert::information(_("System reconfigured"),
457                 _("The system has been reconfigured.\n"
458                 "You need to restart LyX to make use of any\n"
459                 "updated document class specifications."));
460 }