]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
6493b5002deffc2a303327664d0e1455911caa1a
[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 void QuitLyX()
181 {
182         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
183
184         if (lyxrc.use_gui) {
185                 if (!bufferlist.quitWriteAll())
186                         return;
187
188                 lastfiles->writeFile(lyxrc.lastfiles);
189         }
190
191         // Set a flag that we do quitting from the program,
192         // so no refreshes are necessary.
193         quitting = true;
194
195         // close buffers first
196         bufferlist.closeAll();
197
198         // do any other cleanup procedures now
199         lyxerr[Debug::INFO] << "Deleting tmp dir " << system_tempdir << endl;
200
201         if (destroyDir(system_tempdir) != 0) {
202 #if USE_BOOST_FORMAT
203                 boost::format fmt = _("Could not remove the temporary directory %1$s");
204                 fmt % system_tempdir;
205                 string msg = fmt.str();
206 #else
207                 string msg = _("Could not remove the temporary directory ") + system_tempdir;
208 #endif
209                 Alert::warning(_("Could not remove temporary directory"), msg);
210         }
211
212         lyx_gui::exit();
213 }
214
215
216 namespace {
217
218 class AutoSaveBuffer : public ForkedProcess {
219 public:
220         ///
221         AutoSaveBuffer(BufferView & bv, string const & fname)
222                 : bv_(bv), fname_(fname) {}
223         ///
224         virtual ForkedProcess * clone() const {
225                 return new AutoSaveBuffer(*this);
226         }
227         ///
228         int start();
229 private:
230         ///
231         virtual int generateChild();
232         ///
233         BufferView & bv_;
234         string fname_;
235 };
236
237
238 int AutoSaveBuffer::start()
239 {
240 #if USE_BOOST_FORMAT
241         command_ = boost::io::str(boost::format(_("Auto-saving %1$s")) % fname_);
242 #else
243         command_ = _("Auto-saving ") + fname_;
244 #endif
245         return runNonBlocking();
246 }
247
248
249 int AutoSaveBuffer::generateChild()
250 {
251         // tmp_ret will be located (usually) in /tmp
252         // will that be a problem?
253         pid_t const pid = fork(); // If you want to debug the autosave
254         // you should set pid to -1, and comment out the
255         // fork.
256         if (pid == 0 || pid == -1) {
257                 // pid = -1 signifies that lyx was unable
258                 // to fork. But we will do the save
259                 // anyway.
260                 bool failed = false;
261
262                 string const tmp_ret = lyx::tempName(string(), "lyxauto");
263                 if (!tmp_ret.empty()) {
264                         bv_.buffer()->writeFile(tmp_ret);
265                         // assume successful write of tmp_ret
266                         if (!lyx::rename(tmp_ret, fname_)) {
267                                 failed = true;
268                                 // most likely couldn't move between filesystems
269                                 // unless write of tmp_ret failed
270                                 // so remove tmp file (if it exists)
271                                 lyx::unlink(tmp_ret);
272                         }
273                 } else {
274                         failed = true;
275                 }
276
277                 if (failed) {
278                         // failed to write/rename tmp_ret so try writing direct
279                         if (!bv_.buffer()->writeFile(fname_)) {
280                                 // It is dangerous to do this in the child,
281                                 // but safe in the parent, so...
282                                 if (pid == -1)
283                                         bv_.owner()->message(_("Autosave failed!"));
284                         }
285                 }
286                 if (pid == 0) { // we are the child so...
287                         _exit(0);
288                 }
289         }
290         return pid;
291 }
292
293 } // namespace anon
294
295
296 void AutoSave(BufferView * bv)
297         // should probably be moved into BufferList (Lgb)
298         // Perfect target for a thread...
299 {
300         if (!bv->available())
301                 return;
302
303         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
304                 // We don't save now, but we'll try again later
305                 bv->owner()->resetAutosaveTimer();
306                 return;
307         }
308
309         bv->owner()->message(_("Autosaving current document..."));
310
311         // create autosave filename
312         string fname = bv->buffer()->filePath();
313         fname += '#';
314         fname += OnlyFilename(bv->buffer()->fileName());
315         fname += '#';
316
317         AutoSaveBuffer autosave(*bv, fname);
318         autosave.start();
319
320         bv->buffer()->markBakClean();
321         bv->owner()->resetAutosaveTimer();
322 }
323
324
325 //
326 // Copyright CHT Software Service GmbH
327 // Uwe C. Schroeder
328 //
329 // create new file with template
330 // SERVERCMD !
331 //
332 Buffer * NewFile(string const & filename)
333 {
334         // Split argument by :
335         string name;
336         string tmpname = split(filename, name, ':');
337 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
338         if (name.length() == 1
339             && isalpha(static_cast<unsigned char>(name[0]))
340             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
341                 name += ':';
342                 name += token(tmpname, ':', 0);
343                 tmpname = split(tmpname, ':');
344         }
345 #endif
346         lyxerr[Debug::INFO] << "Arg is " << filename
347                             << "\nName is " << name
348                             << "\nTemplate is " << tmpname << endl;
349
350         // find a free buffer
351         Buffer * tmpbuf = bufferlist.newFile(name, tmpname);
352         if (tmpbuf)
353                 lastfiles->newFile(tmpbuf->fileName());
354         return tmpbuf;
355 }
356
357
358 // Insert ascii file (if filename is empty, prompt for one)
359 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
360 {
361         if (!bv->available())
362                 return;
363
364         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
365         if (tmpstr.empty())
366                 return;
367
368         // insert the string
369         bv->hideCursor();
370
371         // clear the selection
372         bool flag = (bv->text == bv->getLyXText());
373         if (flag)
374                 bv->beforeChange(bv->text);
375         if (!asParagraph)
376                 bv->getLyXText()->insertStringAsLines(tmpstr);
377         else
378                 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
379         if (flag)
380                 bv->update(BufferView::SELECT);
381 }
382
383
384 // Insert ascii file (if filename is empty, prompt for one)
385 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
386 {
387         string fname = f;
388
389         if (fname.empty()) {
390                 FileDialog fileDlg(_("Select file to insert"),
391                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
392
393                 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
394
395                 if (result.first == FileDialog::Later)
396                         return string();
397
398                 fname = result.second;
399
400                 if (fname.empty())
401                         return string();
402         }
403
404         FileInfo fi(fname);
405
406         if (!fi.readable()) {
407                 string const error = strerror(errno);
408                 string const file = MakeDisplayPath(fname, 50);
409 #if USE_BOOST_FORMAT
410                 boost::format fmt(_("Could not read the specified document\n%1$s\ndue to the error: %2$s"));
411                 fmt % file;
412                 fmt % error;
413                 string text = fmt.str();
414 #else
415                 string text = _("Could not read the specified document\n");
416                 text += file + _(" due to the error: ");
417                 text += error;
418 #endif
419                 Alert::error(_("Could not read file"), text);
420                 return string();
421         }
422
423         ifstream ifs(fname.c_str());
424         if (!ifs) {
425                 string const error = strerror(errno);
426                 string const file = MakeDisplayPath(fname, 50);
427 #if USE_BOOST_FORMAT
428                 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
429                 fmt % file;
430                 fmt % error;
431                 string text = fmt.str();
432 #else
433                 string text = _("Could not open the specified document\n");
434                 text += file + _(" due to the error: ");
435                 text += error;
436 #endif
437                 Alert::error(_("Could not open file"), text);
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
517         Alert::information(_("System reconfigured"),
518                 _("The system has been reconfigured.\n"
519                 "You need to restart LyX to make use of any \n"
520                 "updated document class specifications."));
521 }