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