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