]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
Painter and scrollbar API patches
[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 "frontends/LyXView.h"
21 #include "lyxrc.h"
22 #include "lyxtext.h"
23 #include "gettext.h"
24 #include "BufferView.h"
25 #include "lyxtextclasslist.h"
26
27 #include "insets/insetlabel.h"
28
29 #include "frontends/Alert.h"
30 #include "frontends/FileDialog.h"
31 #include <X11/Xlib.h>
32
33 #include "support/FileInfo.h"
34 #include "support/filetools.h"
35 #include "support/path.h"
36 #include "support/systemcall.h"
37 #include "support/lstrings.h"
38
39 #include <fstream>
40 #include <algorithm>
41 #include <utility>
42 #include <iostream>
43
44 using std::vector;
45 using std::ifstream;
46 using std::copy;
47 using std::endl;
48 using std::ios;
49 using std::back_inserter;
50 using std::istream_iterator;
51 using std::pair;
52 using std::make_pair;
53
54 extern BufferList bufferlist;
55 // this should be static, but I need it in buffer.C
56 bool quitting;  // flag, that we are quitting the program
57 extern bool finished; // all cleanup done just let it run through now.
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.Select(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         finished = true;
245 }
246
247
248
249 void AutoSave(BufferView * bv)
250         // should probably be moved into BufferList (Lgb)
251         // Perfect target for a thread...
252 {
253         if (!bv->available())
254                 return;
255
256         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
257                 // We don't save now, but we'll try again later
258                 bv->owner()->resetAutosaveTimer();
259                 return;
260         }
261
262         bv->owner()->message(_("Autosaving current document..."));
263
264         // create autosave filename
265         string fname =  bv->buffer()->filePath();
266         fname += "#";
267         fname += OnlyFilename(bv->buffer()->fileName());
268         fname += "#";
269
270         // tmp_ret will be located (usually) in /tmp
271         // will that be a problem?
272         pid_t const pid = fork(); // If you want to debug the autosave
273         // you should set pid to -1, and comment out the
274         // fork.
275         if (pid == 0 || pid == -1) {
276                 // pid = -1 signifies that lyx was unable
277                 // to fork. But we will do the save
278                 // anyway.
279                 bool failed = false;
280
281                 string const tmp_ret = lyx::tempName(string(), "lyxauto");
282                 if (!tmp_ret.empty()) {
283                         bv->buffer()->writeFile(tmp_ret, 1);
284                         // assume successful write of tmp_ret
285                         if (!lyx::rename(tmp_ret, fname)) {
286                                 failed = true;
287                                 // most likely couldn't move between filesystems
288                                 // unless write of tmp_ret failed
289                                 // so remove tmp file (if it exists)
290                                 lyx::unlink(tmp_ret);
291                         }
292                 } else {
293                         failed = true;
294                 }
295
296                 if (failed) {
297                         // failed to write/rename tmp_ret so try writing direct
298                         if (!bv->buffer()->writeFile(fname, 1)) {
299                                 // It is dangerous to do this in the child,
300                                 // but safe in the parent, so...
301                                 if (pid == -1)
302                                         bv->owner()->message(_("Autosave failed!"));
303                         }
304                 }
305                 if (pid == 0) { // we are the child so...
306                         _exit(0);
307                 }
308         }
309
310         bv->buffer()->markBakClean();
311         bv->owner()->resetAutosaveTimer();
312 }
313
314
315 //
316 // Copyright CHT Software Service GmbH
317 // Uwe C. Schroeder
318 //
319 // create new file with template
320 // SERVERCMD !
321 //
322 Buffer * NewLyxFile(string const & filename)
323 {
324         // Split argument by :
325         string name;
326         string tmpname = split(filename, name, ':');
327 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
328         if (name.length() == 1
329             && isalpha(static_cast<unsigned char>(name[0]))
330             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
331                 name += ':';
332                 name += token(tmpname, ':', 0);
333                 tmpname = split(tmpname, ':');
334         }
335 #endif
336         lyxerr[Debug::INFO] << "Arg is " << filename
337                             << "\nName is " << name
338                             << "\nTemplate is " << tmpname << endl;
339
340         // find a free buffer
341         Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
342         if (tmpbuf)
343                 lastfiles->newFile(tmpbuf->fileName());
344         return tmpbuf;
345 }
346
347
348 // Insert ascii file (if filename is empty, prompt for one)
349 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
350 {
351         if (!bv->available())
352                 return;
353
354         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
355         if (tmpstr.empty())
356                 return;
357
358         // insert the string
359         bv->hideCursor();
360
361         // clear the selection
362         bool flag = (bv->text == bv->getLyXText());
363         if (flag)
364                 bv->beforeChange(bv->text);
365         if (!asParagraph)
366                 bv->getLyXText()->insertStringAsLines(bv, tmpstr);
367         else
368                 bv->getLyXText()->insertStringAsParagraphs(bv, tmpstr);
369         if (flag)
370                 bv->update(bv->text,
371                            BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
372 }
373
374
375 // Insert ascii file (if filename is empty, prompt for one)
376 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
377 {
378         string fname = f;
379
380         if (fname.empty()) {
381                 FileDialog fileDlg(bv->owner(), _("Select file to insert"),
382                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
383
384                 FileDialog::Result result = fileDlg.Select(bv->owner()->buffer()->filePath());
385
386                 if (result.first == FileDialog::Later)
387                         return string();
388
389                 fname = result.second;
390
391                 if (fname.empty())
392                         return string();
393         }
394
395         FileInfo fi(fname);
396
397         if (!fi.readable()) {
398                 Alert::err_alert(_("Error! Specified file is unreadable: "),
399                              MakeDisplayPath(fname, 50));
400                 return string();
401         }
402
403         ifstream ifs(fname.c_str());
404         if (!ifs) {
405                 Alert::err_alert(_("Error! Cannot open specified file: "),
406                              MakeDisplayPath(fname, 50));
407                 return string();
408         }
409
410         ifs.unsetf(ios::skipws);
411         istream_iterator<char> ii(ifs);
412         istream_iterator<char> end;
413 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
414         // We use this until the compilers get better...
415         vector<char> tmp;
416         copy(ii, end, back_inserter(tmp));
417         string const tmpstr(tmp.begin(), tmp.end());
418 #else
419         // This is what we want to use and what we will use once the
420         // compilers get good enough.
421         //string tmpstr(ii, end); // yet a reason for using std::string
422         // alternate approach to get the file into a string:
423         string tmpstr;
424         copy(ii, end, back_inserter(tmpstr));
425 #endif
426
427         return tmpstr;
428 }
429
430
431 void MenuInsertLabel(BufferView * bv, string const & arg)
432 {
433         string label(arg);
434         bv->owner()->prohibitInput();
435         if (label.empty()) {
436                 Paragraph * par = bv->getLyXText()->cursor.par();
437                 LyXTextClass const & tclass =
438                         textclasslist[bv->buffer()->params.textclass];
439                 LyXLayout const * layout = &tclass[par->layout()];
440
441                 if (layout->latextype == LATEX_PARAGRAPH && par->previous()) {
442                         Paragraph * par2 = par->previous();
443                         LyXLayout const * layout2 = &tclass[par2->layout()];
444                         if (layout2->latextype != LATEX_PARAGRAPH) {
445                                 par = par2;
446                                 layout = layout2;
447                         }
448                 }
449                 string text = layout->latexname().substr(0, 3);
450                 if (layout->latexname() == "theorem")
451                         text = "thm"; // Create a correct prefix for prettyref
452
453                 text += ":";
454                 if (layout->latextype == LATEX_PARAGRAPH ||
455                     lyxrc.label_init_length < 0)
456                         text.erase();
457                 string par_text = par->asString(bv->buffer(), false);
458                 for (int i = 0; i < lyxrc.label_init_length; ++i) {
459                         if (par_text.empty())
460                                 break;
461                         string head;
462                         par_text = split(par_text, head, ' ');
463                         if (i > 0)
464                                 text += '-'; // Is it legal to use spaces in
465                                              // labels ?
466                         text += head;
467                 }
468
469                 pair<bool, string> result =
470                         Alert::askForText(_("Enter new label to insert:"), text);
471                 if (result.first) {
472                         label = frontStrip(strip(result.second));
473                 }
474         }
475         if (!label.empty()) {
476                 InsetCommandParams p("label", label);
477                 InsetLabel * inset = new InsetLabel(p);
478                 bv->insertInset(inset);
479         }
480         bv->owner()->allowInput();
481 }
482
483
484 // This function runs "configure" and then rereads lyx.defaults to
485 // reconfigure the automatic settings.
486 void Reconfigure(BufferView * bv)
487 {
488         bv->owner()->message(_("Running configure..."));
489
490         // Run configure in user lyx directory
491         Path p(user_lyxdir);
492         Systemcall one;
493         one.startscript(Systemcall::Wait,
494                         AddName(system_lyxdir, "configure"));
495         p.pop();
496         bv->owner()->message(_("Reloading configuration..."));
497         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
498         Alert::alert(_("The system has been reconfigured."),
499                    _("You need to restart LyX to make use of any"),
500                    _("updated document class specifications."));
501 }