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