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