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