]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
Remove unused 'public slot: void slotEdit();'
[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/FileInfo.h"
40 #include "support/filetools.h"
41 #include "support/forkedcall.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
49 #include <cerrno>
50 #include <fstream>
51
52 using lyx::support::AddName;
53 using lyx::support::bformat;
54 using lyx::support::destroyDir;
55 using lyx::support::FileFilterList;
56 using lyx::support::FileInfo;
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 using std::back_inserter;
77 using std::copy;
78 using std::endl;
79 using std::make_pair;
80 using std::string;
81 using std::ifstream;
82 using std::ios;
83 using std::istream_iterator;
84
85
86 extern BufferList bufferlist;
87 // this should be static, but I need it in buffer.C
88 bool quitting;  // flag, that we are quitting the program
89
90
91 //
92 // Menu callbacks
93 //
94
95 bool MenuWrite(Buffer * buffer)
96 {
97         if (buffer->save()) {
98                 LyX::ref().lastfiles().newFile(buffer->fileName());
99                 return true;
100         }
101
102         // FIXME: we don't tell the user *WHY* the save failed !!
103
104         string const file = MakeDisplayPath(buffer->fileName(), 30);
105
106         string text = bformat(_("The document %1$s could not be saved.\n\n"
107                 "Do you want to rename the document and try again?"), file);
108         int const ret = Alert::prompt(_("Rename and save?"),
109                 text, 0, 1, _("&Rename"), _("&Cancel"));
110
111         if (ret == 0)
112                 return WriteAs(buffer);
113         return false;
114 }
115
116
117
118 bool WriteAs(Buffer * buffer, string const & filename)
119 {
120         string fname = buffer->fileName();
121         string const oldname = fname;
122
123         if (filename.empty()) {
124
125                 FileDialog fileDlg(_("Choose a filename to save document as"),
126                         LFUN_WRITEAS,
127                         make_pair(string(_("Documents|#o#O")),
128                                   string(lyxrc.document_path)),
129                         make_pair(string(_("Templates|#T#t")),
130                                   string(lyxrc.template_path)));
131
132                 if (!IsLyXFilename(fname))
133                         fname += ".lyx";
134
135                 FileFilterList const filter (_("LyX Documents (*.lyx)"));
136
137                 FileDialog::Result result =
138                         fileDlg.save(OnlyPath(fname),
139                                      filter,
140                                      OnlyFilename(fname));
141
142                 if (result.first == FileDialog::Later)
143                         return false;
144
145                 fname = result.second;
146
147                 if (fname.empty())
148                         return false;
149
150                 // Make sure the absolute filename ends with appropriate suffix
151                 fname = MakeAbsPath(fname);
152                 if (!IsLyXFilename(fname))
153                         fname += ".lyx";
154         } else
155                 fname = filename;
156
157         FileInfo const myfile(fname);
158         if (myfile.isOK()) {
159                 string const file = MakeDisplayPath(fname, 30);
160                 string text = bformat(_("The document %1$s already exists.\n\n"
161                         "Do you want to over-write that document?"), file);
162                 int const ret = Alert::prompt(_("Over-write document?"),
163                         text, 0, 1, _("&Over-write"), _("&Cancel"));
164
165                 if (ret == 1)
166                         return false;
167         }
168
169         // Ok, change the name of the buffer
170         buffer->setFileName(fname);
171         buffer->markDirty();
172         bool unnamed = buffer->isUnnamed();
173         buffer->setUnnamed(false);
174
175         if (!MenuWrite(buffer)) {
176                 buffer->setFileName(oldname);
177                 buffer->setUnnamed(unnamed);
178                 return false;
179         }
180
181         removeAutosaveFile(oldname);
182         return true;
183 }
184
185
186 void QuitLyX()
187 {
188         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
189
190         if (lyx_gui::use_gui) {
191                 if (!bufferlist.quitWriteAll())
192                         return;
193
194                 LyX::cref().lastfiles().writeFile(lyxrc.lastfiles);
195         }
196
197         // Set a flag that we do quitting from the program,
198         // so no refreshes are necessary.
199         quitting = true;
200
201         // close buffers first
202         bufferlist.closeAll();
203
204         // do any other cleanup procedures now
205         lyxerr[Debug::INFO] << "Deleting tmp dir " << package().temp_dir() << endl;
206
207         if (destroyDir(package().temp_dir()) != 0) {
208                 string msg = bformat(_("Could not remove the temporary directory %1$s"),
209                         package().temp_dir());
210                 Alert::warning(_("Could not remove temporary directory"), msg);
211         }
212
213         lyx_gui::exit();
214 }
215
216
217 namespace {
218
219 class AutoSaveBuffer : public ForkedProcess {
220 public:
221         ///
222         AutoSaveBuffer(BufferView & bv, string const & fname)
223                 : bv_(bv), fname_(fname) {}
224         ///
225         virtual shared_ptr<ForkedProcess> clone() const
226         {
227                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
228         }
229         ///
230         int start();
231 private:
232         ///
233         virtual int generateChild();
234         ///
235         BufferView & bv_;
236         string fname_;
237 };
238
239
240 int AutoSaveBuffer::start()
241 {
242         command_ = bformat(_("Auto-saving %1$s"), fname_);
243         return run(DontWait);
244 }
245
246
247 int AutoSaveBuffer::generateChild()
248 {
249         // tmp_ret will be located (usually) in /tmp
250         // will that be a problem?
251         pid_t const pid = fork(); // If you want to debug the autosave
252         // you should set pid to -1, and comment out the
253         // fork.
254         if (pid == 0 || pid == -1) {
255                 // pid = -1 signifies that lyx was unable
256                 // to fork. But we will do the save
257                 // anyway.
258                 bool failed = false;
259
260                 string const tmp_ret = tempName(string(), "lyxauto");
261                 if (!tmp_ret.empty()) {
262                         bv_.buffer()->writeFile(tmp_ret);
263                         // assume successful write of tmp_ret
264                         if (!rename(tmp_ret, fname_)) {
265                                 failed = true;
266                                 // most likely couldn't move between filesystems
267                                 // unless write of tmp_ret failed
268                                 // so remove tmp file (if it exists)
269                                 unlink(tmp_ret);
270                         }
271                 } else {
272                         failed = true;
273                 }
274
275                 if (failed) {
276                         // failed to write/rename tmp_ret so try writing direct
277                         if (!bv_.buffer()->writeFile(fname_)) {
278                                 // It is dangerous to do this in the child,
279                                 // but safe in the parent, so...
280                                 if (pid == -1)
281                                         bv_.owner()->message(_("Autosave failed!"));
282                         }
283                 }
284                 if (pid == 0) { // we are the child so...
285                         _exit(0);
286                 }
287         }
288         return pid;
289 }
290
291 } // namespace anon
292
293
294 void AutoSave(BufferView * bv)
295         // should probably be moved into BufferList (Lgb)
296         // Perfect target for a thread...
297 {
298         if (!bv->available())
299                 return;
300
301         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
302                 // We don't save now, but we'll try again later
303                 bv->owner()->resetAutosaveTimer();
304                 return;
305         }
306
307         bv->owner()->message(_("Autosaving current document..."));
308
309         // create autosave filename
310         string fname = bv->buffer()->filePath();
311         fname += '#';
312         fname += OnlyFilename(bv->buffer()->fileName());
313         fname += '#';
314
315         AutoSaveBuffer autosave(*bv, fname);
316         autosave.start();
317
318         bv->buffer()->markBakClean();
319         bv->owner()->resetAutosaveTimer();
320 }
321
322
323 //
324 // Copyright CHT Software Service GmbH
325 // Uwe C. Schroeder
326 //
327 // create new file with template
328 // SERVERCMD !
329 //
330 void NewFile(BufferView * bv, string const & filename)
331 {
332         // Split argument by :
333         string name;
334         string tmpname = split(filename, name, ':');
335 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
336         if (name.length() == 1
337             && isalpha(static_cast<unsigned char>(name[0]))
338             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
339                 name += ':';
340                 name += token(tmpname, ':', 0);
341                 tmpname = split(tmpname, ':');
342         }
343 #endif
344         lyxerr[Debug::INFO] << "Arg is " << filename
345                             << "\nName is " << name
346                             << "\nTemplate is " << tmpname << endl;
347
348         bv->newFile(name, tmpname);
349 }
350
351
352 // Insert ascii file (if filename is empty, prompt for one)
353 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
354 {
355         if (!bv->available())
356                 return;
357
358         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
359         if (tmpstr.empty())
360                 return;
361
362         // clear the selection
363         if (bv->text() == bv->getLyXText())
364                 bv->cursor().clearSelection();
365         if (asParagraph)
366                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
367         else
368                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
369         bv->update();
370 }
371
372
373 // Insert ascii file (if filename is empty, prompt for one)
374 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
375 {
376         string fname = f;
377
378         if (fname.empty()) {
379                 FileDialog fileDlg(_("Select file to insert"),
380                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
381
382                 FileDialog::Result result =
383                         fileDlg.open(bv->owner()->buffer()->filePath(),
384                                      FileFilterList(), string());
385
386                 if (result.first == FileDialog::Later)
387                         return string();
388
389                 fname = result.second;
390
391                 if (fname.empty())
392                         return string();
393         }
394
395         FileInfo fi(fname);
396
397         if (!fi.readable()) {
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 }