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