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