]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
more cursor dispatch
[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 <cerrno>
48 #include <fstream>
49
50 using lyx::support::AddName;
51 using lyx::support::bformat;
52 using lyx::support::destroyDir;
53 using lyx::support::FileFilterList;
54 using lyx::support::FileInfo;
55 using lyx::support::ForkedProcess;
56 using lyx::support::IsLyXFilename;
57 using lyx::support::LibFileSearch;
58 using lyx::support::MakeAbsPath;
59 using lyx::support::MakeDisplayPath;
60 using lyx::support::OnlyFilename;
61 using lyx::support::OnlyPath;
62 using lyx::support::Path;
63 using lyx::support::removeAutosaveFile;
64 using lyx::support::rename;
65 using lyx::support::split;
66 using lyx::support::system_lyxdir;
67 using lyx::support::Systemcall;
68 using lyx::support::tempName;
69 using lyx::support::unlink;
70 using lyx::support::user_lyxdir;
71
72 namespace os = lyx::support::os;
73
74 using std::auto_ptr;
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 " << os::getTmpDir() << endl;
205
206         if (destroyDir(os::getTmpDir()) != 0) {
207                 string msg = bformat(_("Could not remove the temporary directory %1$s"),
208                         os::getTmpDir());
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 auto_ptr<ForkedProcess> clone() const {
225                 return auto_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
226         }
227         ///
228         int start();
229 private:
230         ///
231         virtual int generateChild();
232         ///
233         BufferView & bv_;
234         string fname_;
235 };
236
237
238 int AutoSaveBuffer::start()
239 {
240         command_ = bformat(_("Auto-saving %1$s"), fname_);
241         return runNonBlocking();
242 }
243
244
245 int AutoSaveBuffer::generateChild()
246 {
247         // tmp_ret will be located (usually) in /tmp
248         // will that be a problem?
249         pid_t const pid = fork(); // If you want to debug the autosave
250         // you should set pid to -1, and comment out the
251         // fork.
252         if (pid == 0 || pid == -1) {
253                 // pid = -1 signifies that lyx was unable
254                 // to fork. But we will do the save
255                 // anyway.
256                 bool failed = false;
257
258                 string const tmp_ret = tempName(string(), "lyxauto");
259                 if (!tmp_ret.empty()) {
260                         bv_.buffer()->writeFile(tmp_ret);
261                         // assume successful write of tmp_ret
262                         if (!rename(tmp_ret, fname_)) {
263                                 failed = true;
264                                 // most likely couldn't move between filesystems
265                                 // unless write of tmp_ret failed
266                                 // so remove tmp file (if it exists)
267                                 unlink(tmp_ret);
268                         }
269                 } else {
270                         failed = true;
271                 }
272
273                 if (failed) {
274                         // failed to write/rename tmp_ret so try writing direct
275                         if (!bv_.buffer()->writeFile(fname_)) {
276                                 // It is dangerous to do this in the child,
277                                 // but safe in the parent, so...
278                                 if (pid == -1)
279                                         bv_.owner()->message(_("Autosave failed!"));
280                         }
281                 }
282                 if (pid == 0) { // we are the child so...
283                         _exit(0);
284                 }
285         }
286         return pid;
287 }
288
289 } // namespace anon
290
291
292 void AutoSave(BufferView * bv)
293         // should probably be moved into BufferList (Lgb)
294         // Perfect target for a thread...
295 {
296         if (!bv->available())
297                 return;
298
299         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
300                 // We don't save now, but we'll try again later
301                 bv->owner()->resetAutosaveTimer();
302                 return;
303         }
304
305         bv->owner()->message(_("Autosaving current document..."));
306
307         // create autosave filename
308         string fname = bv->buffer()->filePath();
309         fname += '#';
310         fname += OnlyFilename(bv->buffer()->fileName());
311         fname += '#';
312
313         AutoSaveBuffer autosave(*bv, fname);
314         autosave.start();
315
316         bv->buffer()->markBakClean();
317         bv->owner()->resetAutosaveTimer();
318 }
319
320
321 //
322 // Copyright CHT Software Service GmbH
323 // Uwe C. Schroeder
324 //
325 // create new file with template
326 // SERVERCMD !
327 //
328 void NewFile(BufferView * bv, string const & filename)
329 {
330         // Split argument by :
331         string name;
332         string tmpname = split(filename, name, ':');
333 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
334         if (name.length() == 1
335             && isalpha(static_cast<unsigned char>(name[0]))
336             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
337                 name += ':';
338                 name += token(tmpname, ':', 0);
339                 tmpname = split(tmpname, ':');
340         }
341 #endif
342         lyxerr[Debug::INFO] << "Arg is " << filename
343                             << "\nName is " << name
344                             << "\nTemplate is " << tmpname << endl;
345
346         bv->newFile(name, tmpname);
347 }
348
349
350 // Insert ascii file (if filename is empty, prompt for one)
351 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
352 {
353         if (!bv->available())
354                 return;
355
356         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
357         if (tmpstr.empty())
358                 return;
359
360         // clear the selection
361         if (bv->text() == bv->getLyXText())
362                 bv->cursor().clearSelection();
363         if (asParagraph)
364                 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
365         else
366                 bv->getLyXText()->insertStringAsLines(tmpstr);
367         bv->update();
368 }
369
370
371 // Insert ascii file (if filename is empty, prompt for one)
372 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
373 {
374         string fname = f;
375
376         if (fname.empty()) {
377                 FileDialog fileDlg(_("Select file to insert"),
378                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
379
380                 FileDialog::Result result =
381                         fileDlg.open(bv->owner()->buffer()->filePath(),
382                                      FileFilterList(), string());
383
384                 if (result.first == FileDialog::Later)
385                         return string();
386
387                 fname = result.second;
388
389                 if (fname.empty())
390                         return string();
391         }
392
393         FileInfo fi(fname);
394
395         if (!fi.readable()) {
396                 string const error = strerror(errno);
397                 string const file = MakeDisplayPath(fname, 50);
398                 string const text = bformat(_("Could not read the specified document\n"
399                         "%1$s\ndue to the error: %2$s"), file, error);
400                 Alert::error(_("Could not read file"), text);
401                 return string();
402         }
403
404         ifstream ifs(fname.c_str());
405         if (!ifs) {
406                 string const error = strerror(errno);
407                 string const file = MakeDisplayPath(fname, 50);
408                 string const text = bformat(_("Could not open the specified document\n"
409                         "%1$s\ndue to the error: %2$s"), file, error);
410                 Alert::error(_("Could not open file"), text);
411                 return string();
412         }
413
414         ifs.unsetf(ios::skipws);
415         istream_iterator<char> ii(ifs);
416         istream_iterator<char> end;
417 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
418         // We use this until the compilers get better...
419         std::vector<char> tmp;
420         copy(ii, end, back_inserter(tmp));
421         string const tmpstr(tmp.begin(), tmp.end());
422 #else
423         // This is what we want to use and what we will use once the
424         // compilers get good enough.
425         //string tmpstr(ii, end); // yet a reason for using std::string
426         // alternate approach to get the file into a string:
427         string tmpstr;
428         copy(ii, end, back_inserter(tmpstr));
429 #endif
430
431         return tmpstr;
432 }
433
434
435 string const getPossibleLabel(BufferView const & bv)
436 {
437         ParagraphList::iterator pit = bv.getLyXText()->cursorPar();
438         ParagraphList & plist = bv.getLyXText()->paragraphs();
439
440         LyXLayout_ptr layout = pit->layout();
441
442         if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
443                 ParagraphList::iterator pit2 = boost::prior(pit);
444
445                 LyXLayout_ptr const & layout2 = pit2->layout();
446
447                 if (layout2->latextype != LATEX_PARAGRAPH) {
448                         pit = pit2;
449                         layout = layout2;
450                 }
451         }
452
453         string text = layout->latexname().substr(0, 3);
454         if (layout->latexname() == "theorem")
455                 text = "thm"; // Create a correct prefix for prettyref
456
457         text += ':';
458         if (layout->latextype == LATEX_PARAGRAPH ||
459             lyxrc.label_init_length < 0)
460                 text.erase();
461
462         string par_text = pit->asString(*bv.buffer(), false);
463         for (int i = 0; i < lyxrc.label_init_length; ++i) {
464                 if (par_text.empty())
465                         break;
466                 string head;
467                 par_text = split(par_text, head, ' ');
468                 // Is it legal to use spaces in labels ?
469                 if (i > 0)
470                         text += '-';
471                 text += head;
472         }
473
474         return text;
475 }
476
477
478 // This function runs "configure" and then rereads lyx.defaults to
479 // reconfigure the automatic settings.
480 void Reconfigure(BufferView * bv)
481 {
482         bv->owner()->message(_("Running configure..."));
483
484         // Run configure in user lyx directory
485         Path p(user_lyxdir());
486         Systemcall one;
487         one.startscript(Systemcall::Wait,
488                         AddName(system_lyxdir(), "configure"));
489         p.pop();
490         bv->owner()->message(_("Reloading configuration..."));
491         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
492
493         Alert::information(_("System reconfigured"),
494                 _("The system has been reconfigured.\n"
495                 "You need to restart LyX to make use of any \n"
496                 "updated document class specifications."));
497 }