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