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