]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
Fix bug 2195: Slowness in rendering inside insets, especially on the Mac
[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 #if !defined (HAVE_FORK)
48 # define fork() -1
49 #endif
50
51 #include <boost/shared_ptr.hpp>
52 #include <boost/filesystem/operations.hpp>
53
54 #include <cerrno>
55 #include <fstream>
56
57 using lyx::support::AddName;
58 using lyx::support::bformat;
59 using lyx::support::destroyDir;
60 using lyx::support::FileFilterList;
61 using lyx::support::ForkedProcess;
62 using lyx::support::IsLyXFilename;
63 using lyx::support::LibFileSearch;
64 using lyx::support::MakeAbsPath;
65 using lyx::support::MakeDisplayPath;
66 using lyx::support::OnlyFilename;
67 using lyx::support::OnlyPath;
68 using lyx::support::Path;
69 using lyx::support::package;
70 using lyx::support::QuoteName;
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().lastfiles().newFile(buffer->fileName());
105                 return true;
106         }
107
108         // FIXME: we don't tell the user *WHY* the save failed !!
109
110         string const file = MakeDisplayPath(buffer->fileName(), 30);
111
112         string 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(_("Choose a filename to save document as"),
132                         LFUN_WRITEAS,
133                         make_pair(string(_("Documents|#o#O")),
134                                   string(lyxrc.document_path)),
135                         make_pair(string(_("Templates|#T#t")),
136                                   string(lyxrc.template_path)));
137
138                 if (!IsLyXFilename(fname))
139                         fname += ".lyx";
140
141                 FileFilterList const filter (_("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                 string const file = MakeDisplayPath(fname, 30);
165                 string 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().lastfiles().writeFile(lyxrc.lastfiles);
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                 string const msg =
214                         bformat(_("Unable to remove the temporary directory %1$s"),
215                         package().temp_dir());
216                 Alert::warning(_("Unable to remove temporary directory"), msg);
217         }
218
219         lyx_gui::exit();
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_ = bformat(_("Auto-saving %1$s"), 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                                         bv_.owner()->message(_("Autosave failed!"));
288                         }
289                 }
290                 if (pid == 0) { // we are the child so...
291                         _exit(0);
292                 }
293         }
294         return pid;
295 }
296
297 } // namespace anon
298
299
300 void AutoSave(BufferView * bv)
301         // should probably be moved into BufferList (Lgb)
302         // Perfect target for a thread...
303 {
304         if (!bv->available())
305                 return;
306
307         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
308                 // We don't save now, but we'll try again later
309                 bv->owner()->resetAutosaveTimer();
310                 return;
311         }
312
313         bv->owner()->message(_("Autosaving current document..."));
314
315         // create autosave filename
316         string fname = bv->buffer()->filePath();
317         fname += '#';
318         fname += OnlyFilename(bv->buffer()->fileName());
319         fname += '#';
320
321         AutoSaveBuffer autosave(*bv, fname);
322         autosave.start();
323
324         bv->buffer()->markBakClean();
325         bv->owner()->resetAutosaveTimer();
326 }
327
328
329 //
330 // Copyright CHT Software Service GmbH
331 // Uwe C. Schroeder
332 //
333 // create new file with template
334 // SERVERCMD !
335 //
336 void NewFile(BufferView * bv, string const & filename)
337 {
338         // Split argument by :
339         string name;
340         string tmpname = split(filename, name, ':');
341 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
342         if (name.length() == 1
343             && isalpha(static_cast<unsigned char>(name[0]))
344             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
345                 name += ':';
346                 name += token(tmpname, ':', 0);
347                 tmpname = split(tmpname, ':');
348         }
349 #endif
350         lyxerr[Debug::INFO] << "Arg is " << filename
351                             << "\nName is " << name
352                             << "\nTemplate is " << tmpname << endl;
353
354         bv->newFile(name, tmpname);
355 }
356
357
358 // Insert ascii file (if filename is empty, prompt for one)
359 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
360 {
361         if (!bv->available())
362                 return;
363
364         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
365         if (tmpstr.empty())
366                 return;
367
368         // clear the selection
369         if (bv->text() == bv->getLyXText())
370                 bv->cursor().clearSelection();
371         if (asParagraph)
372                 bv->getLyXText()->insertStringAsParagraphs(bv->cursor(), tmpstr);
373         else
374                 bv->getLyXText()->insertStringAsLines(bv->cursor(), tmpstr);
375         bv->update();
376 }
377
378
379 // Insert ascii file (if filename is empty, prompt for one)
380 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
381 {
382         string fname = f;
383
384         if (fname.empty()) {
385                 FileDialog fileDlg(_("Select file to insert"),
386                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
387
388                 FileDialog::Result result =
389                         fileDlg.open(bv->owner()->buffer()->filePath(),
390                                      FileFilterList(), string());
391
392                 if (result.first == FileDialog::Later)
393                         return string();
394
395                 fname = result.second;
396
397                 if (fname.empty())
398                         return string();
399         }
400
401         if (!fs::is_readable(fname)) {
402                 string const error = strerror(errno);
403                 string const file = MakeDisplayPath(fname, 50);
404                 string const text = bformat(_("Could not read the specified document\n"
405                         "%1$s\ndue to the error: %2$s"), file, error);
406                 Alert::error(_("Could not read file"), text);
407                 return string();
408         }
409
410         ifstream ifs(fname.c_str());
411         if (!ifs) {
412                 string const error = strerror(errno);
413                 string const file = MakeDisplayPath(fname, 50);
414                 string const text = bformat(_("Could not open the specified document\n"
415                         "%1$s\ndue to the error: %2$s"), file, error);
416                 Alert::error(_("Could not open file"), text);
417                 return string();
418         }
419
420         ifs.unsetf(ios::skipws);
421         istream_iterator<char> ii(ifs);
422         istream_iterator<char> end;
423 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
424         // We use this until the compilers get better...
425         std::vector<char> tmp;
426         copy(ii, end, back_inserter(tmp));
427         string const tmpstr(tmp.begin(), tmp.end());
428 #else
429         // This is what we want to use and what we will use once the
430         // compilers get good enough.
431         //string tmpstr(ii, end); // yet a reason for using std::string
432         // alternate approach to get the file into a string:
433         string tmpstr;
434         copy(ii, end, back_inserter(tmpstr));
435 #endif
436
437         return tmpstr;
438 }
439
440
441 // This function runs "configure" and then rereads lyx.defaults to
442 // reconfigure the automatic settings.
443 void Reconfigure(BufferView * bv)
444 {
445         bv->owner()->message(_("Running configure..."));
446
447         // Run configure in user lyx directory
448         Path p(package().user_support());
449         string const configure_script =
450                 AddName(package().system_support(), "configure");
451         string const configure_command = "sh " + QuoteName(configure_script);
452         Systemcall one;
453         one.startscript(Systemcall::Wait, configure_command);
454         p.pop();
455         bv->owner()->message(_("Reloading configuration..."));
456         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
457         // Re-read packages.lst
458         LaTeXFeatures::getAvailable();
459
460         Alert::information(_("System reconfigured"),
461                 _("The system has been reconfigured.\n"
462                 "You need to restart LyX to make use of any\n"
463                 "updated document class specifications."));
464 }