]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
6149734b948a24dd498f59c7680051d51bb7be5c
[lyx.git] / src / lyx_cb.C
1 /**
2  * \file lyx_cb.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Angus Leeming
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyx_cb.h"
18
19 #include "buffer.h"
20 #include "bufferlist.h"
21 #include "BufferView.h"
22 #include "debug.h"
23 #include "gettext.h"
24 #include "lastfiles.h"
25 #include "lyx_main.h"
26 #include "lyxlayout.h"
27 #include "lyxrc.h"
28 #include "lyxtext.h"
29 #include "paragraph.h"
30
31 #include "frontends/Alert.h"
32 #include "frontends/FileDialog.h"
33 #include "frontends/lyx_gui.h"
34 #include "frontends/LyXView.h"
35
36 #include "support/FileInfo.h"
37 #include "support/filetools.h"
38 #include "support/forkedcall.h"
39 #include "support/lyxlib.h"
40 #include "support/os.h"
41 #include "support/path.h"
42 #include "support/path_defines.h"
43 #include "support/systemcall.h"
44
45 #include <cerrno>
46 #include <fstream>
47
48 using lyx::support::AddName;
49 using lyx::support::bformat;
50 using lyx::support::destroyDir;
51 using lyx::support::FileInfo;
52 using lyx::support::ForkedProcess;
53 using lyx::support::IsLyXFilename;
54 using lyx::support::LibFileSearch;
55 using lyx::support::MakeAbsPath;
56 using lyx::support::MakeDisplayPath;
57 using lyx::support::OnlyFilename;
58 using lyx::support::OnlyPath;
59 using lyx::support::os;
60 using lyx::support::Path;
61 using lyx::support::removeAutosaveFile;
62 using lyx::support::rename;
63 using lyx::support::split;
64 using lyx::support::system_lyxdir;
65 using lyx::support::Systemcall;
66 using lyx::support::tempName;
67 using lyx::support::unlink;
68 using lyx::support::user_lyxdir;
69
70 using std::back_inserter;
71 using std::copy;
72 using std::endl;
73 using std::make_pair;
74
75 using std::ifstream;
76 using std::ios;
77 using std::istream_iterator;
78
79
80 extern BufferList bufferlist;
81 // this should be static, but I need it in buffer.C
82 bool quitting;  // flag, that we are quitting the program
83
84
85 //
86 // Menu callbacks
87 //
88
89 bool MenuWrite(Buffer * buffer)
90 {
91         if (buffer->save()) {
92                 lastfiles->newFile(buffer->fileName());
93                 return true;
94         }
95
96         // FIXME: we don't tell the user *WHY* the save failed !!
97
98         string const file = MakeDisplayPath(buffer->fileName(), 30);
99
100         string text = bformat(_("The document %1$s could not be saved.\n\n"
101                 "Do you want to rename the document and try again?"), file);
102         int const ret = Alert::prompt(_("Rename and save?"),
103                 text, 0, 1, _("&Rename"), _("&Cancel"));
104
105         if (ret == 0)
106                 return WriteAs(buffer);
107         return false;
108 }
109
110
111
112 bool WriteAs(Buffer * buffer, string const & filename)
113 {
114         string fname = buffer->fileName();
115         string const oldname = fname;
116
117         if (filename.empty()) {
118
119                 FileDialog fileDlg(_("Choose a filename to save document as"),
120                         LFUN_WRITEAS,
121                         make_pair(string(_("Documents|#o#O")),
122                                   string(lyxrc.document_path)),
123                         make_pair(string(_("Templates|#T#t")),
124                                   string(lyxrc.template_path)));
125
126                 if (!IsLyXFilename(fname))
127                         fname += ".lyx";
128
129                 FileDialog::Result result =
130                         fileDlg.save(OnlyPath(fname),
131                                        _("*.lyx| LyX Documents (*.lyx)"),
132                                        OnlyFilename(fname));
133
134                 if (result.first == FileDialog::Later)
135                         return false;
136
137                 fname = result.second;
138
139                 if (fname.empty())
140                         return false;
141
142                 // Make sure the absolute filename ends with appropriate suffix
143                 fname = MakeAbsPath(fname);
144                 if (!IsLyXFilename(fname))
145                         fname += ".lyx";
146         } else
147                 fname = filename;
148
149         FileInfo const myfile(fname);
150         if (myfile.isOK()) {
151                 string const file = MakeDisplayPath(fname, 30);
152                 string text = bformat(_("The document %1$s already exists.\n\n"
153                         "Do you want to over-write that document?"), file);
154                 int const ret = Alert::prompt(_("Over-write document?"),
155                         text, 0, 1, _("&Over-write"), _("&Cancel"));
156
157                 if (ret == 1)
158                         return false;
159         }
160
161         // Ok, change the name of the buffer
162         buffer->setFileName(fname);
163         buffer->markDirty();
164         bool unnamed = buffer->isUnnamed();
165         buffer->setUnnamed(false);
166
167         if (!MenuWrite(buffer)) {
168                 buffer->setFileName(oldname);
169                 buffer->setUnnamed(unnamed);
170                 return false;
171         }
172
173         removeAutosaveFile(oldname);
174         return true;
175 }
176
177
178 void QuitLyX()
179 {
180         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
181
182         if (lyx_gui::use_gui) {
183                 if (!bufferlist.quitWriteAll())
184                         return;
185
186                 lastfiles->writeFile(lyxrc.lastfiles);
187         }
188
189         // Set a flag that we do quitting from the program,
190         // so no refreshes are necessary.
191         quitting = true;
192
193         // close buffers first
194         bufferlist.closeAll();
195
196         // do any other cleanup procedures now
197         lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
198
199         if (destroyDir(os::getTmpDir()) != 0) {
200                 string msg = bformat(_("Could not remove the temporary directory %1$s"),
201                         os::getTmpDir());
202                 Alert::warning(_("Could not remove temporary directory"), msg);
203         }
204
205         lyx_gui::exit();
206 }
207
208
209 namespace {
210
211 class AutoSaveBuffer : public ForkedProcess {
212 public:
213         ///
214         AutoSaveBuffer(BufferView & bv, string const & fname)
215                 : bv_(bv), fname_(fname) {}
216         ///
217         virtual ForkedProcess * clone() const {
218                 return new AutoSaveBuffer(*this);
219         }
220         ///
221         int start();
222 private:
223         ///
224         virtual int generateChild();
225         ///
226         BufferView & bv_;
227         string fname_;
228 };
229
230
231 int AutoSaveBuffer::start()
232 {
233         command_ = bformat(_("Auto-saving %1$s"), fname_);
234         return runNonBlocking();
235 }
236
237
238 int AutoSaveBuffer::generateChild()
239 {
240         // tmp_ret will be located (usually) in /tmp
241         // will that be a problem?
242         pid_t const pid = fork(); // If you want to debug the autosave
243         // you should set pid to -1, and comment out the
244         // fork.
245         if (pid == 0 || pid == -1) {
246                 // pid = -1 signifies that lyx was unable
247                 // to fork. But we will do the save
248                 // anyway.
249                 bool failed = false;
250
251                 string const tmp_ret = tempName(string(), "lyxauto");
252                 if (!tmp_ret.empty()) {
253                         bv_.buffer()->writeFile(tmp_ret);
254                         // assume successful write of tmp_ret
255                         if (!rename(tmp_ret, fname_)) {
256                                 failed = true;
257                                 // most likely couldn't move between filesystems
258                                 // unless write of tmp_ret failed
259                                 // so remove tmp file (if it exists)
260                                 unlink(tmp_ret);
261                         }
262                 } else {
263                         failed = true;
264                 }
265
266                 if (failed) {
267                         // failed to write/rename tmp_ret so try writing direct
268                         if (!bv_.buffer()->writeFile(fname_)) {
269                                 // It is dangerous to do this in the child,
270                                 // but safe in the parent, so...
271                                 if (pid == -1)
272                                         bv_.owner()->message(_("Autosave failed!"));
273                         }
274                 }
275                 if (pid == 0) { // we are the child so...
276                         _exit(0);
277                 }
278         }
279         return pid;
280 }
281
282 } // namespace anon
283
284
285 void AutoSave(BufferView * bv)
286         // should probably be moved into BufferList (Lgb)
287         // Perfect target for a thread...
288 {
289         if (!bv->available())
290                 return;
291
292         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
293                 // We don't save now, but we'll try again later
294                 bv->owner()->resetAutosaveTimer();
295                 return;
296         }
297
298         bv->owner()->message(_("Autosaving current document..."));
299
300         // create autosave filename
301         string fname = bv->buffer()->filePath();
302         fname += '#';
303         fname += OnlyFilename(bv->buffer()->fileName());
304         fname += '#';
305
306         AutoSaveBuffer autosave(*bv, fname);
307         autosave.start();
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 void NewFile(BufferView * bv, 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         bv->newFile(name, tmpname);
340 }
341
342
343 // Insert ascii file (if filename is empty, prompt for one)
344 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
345 {
346         if (!bv->available())
347                 return;
348
349         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
350         if (tmpstr.empty())
351                 return;
352
353         // clear the selection
354         bool flag = (bv->text == bv->getLyXText());
355         if (flag)
356                 bv->beforeChange(bv->text);
357         if (!asParagraph)
358                 bv->getLyXText()->insertStringAsLines(tmpstr);
359         else
360                 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
361         bv->update();
362 }
363
364
365 // Insert ascii file (if filename is empty, prompt for one)
366 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
367 {
368         string fname = f;
369
370         if (fname.empty()) {
371                 FileDialog fileDlg(_("Select file to insert"),
372                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
373
374                 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
375
376                 if (result.first == FileDialog::Later)
377                         return string();
378
379                 fname = result.second;
380
381                 if (fname.empty())
382                         return string();
383         }
384
385         FileInfo fi(fname);
386
387         if (!fi.readable()) {
388                 string const error = strerror(errno);
389                 string const file = MakeDisplayPath(fname, 50);
390                 string const text = bformat(_("Could not read the specified document\n"
391                         "%1$s\ndue to the error: %2$s"), file, error);
392                 Alert::error(_("Could not read file"), text);
393                 return string();
394         }
395
396         ifstream ifs(fname.c_str());
397         if (!ifs) {
398                 string const error = strerror(errno);
399                 string const file = MakeDisplayPath(fname, 50);
400                 string const text = bformat(_("Could not open the specified document\n"
401                         "%1$s\ndue to the error: %2$s"), file, error);
402                 Alert::error(_("Could not open file"), text);
403                 return string();
404         }
405
406         ifs.unsetf(ios::skipws);
407         istream_iterator<char> ii(ifs);
408         istream_iterator<char> end;
409 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
410         // We use this until the compilers get better...
411         std::vector<char> tmp;
412         copy(ii, end, back_inserter(tmp));
413         string const tmpstr(tmp.begin(), tmp.end());
414 #else
415         // This is what we want to use and what we will use once the
416         // compilers get good enough.
417         //string tmpstr(ii, end); // yet a reason for using std::string
418         // alternate approach to get the file into a string:
419         string tmpstr;
420         copy(ii, end, back_inserter(tmpstr));
421 #endif
422
423         return tmpstr;
424 }
425
426
427 string const getPossibleLabel(BufferView const & bv)
428 {
429         ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
430         ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
431
432         LyXLayout_ptr layout = pit->layout();
433
434         if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
435                 ParagraphList::iterator pit2 = boost::prior(pit);
436
437                 LyXLayout_ptr const & layout2 = pit2->layout();
438
439                 if (layout2->latextype != LATEX_PARAGRAPH) {
440                         pit = pit2;
441                         layout = layout2;
442                 }
443         }
444
445         string text = layout->latexname().substr(0, 3);
446         if (layout->latexname() == "theorem")
447                 text = "thm"; // Create a correct prefix for prettyref
448
449         text += ':';
450         if (layout->latextype == LATEX_PARAGRAPH ||
451             lyxrc.label_init_length < 0)
452                 text.erase();
453
454         string par_text = pit->asString(*bv.buffer(), false);
455         for (int i = 0; i < lyxrc.label_init_length; ++i) {
456                 if (par_text.empty())
457                         break;
458                 string head;
459                 par_text = split(par_text, head, ' ');
460                 if (i > 0)
461                         text += '-'; // Is it legal to use spaces in
462                 // labels ?
463                 text += head;
464         }
465
466         return text;
467 }
468
469
470 // This function runs "configure" and then rereads lyx.defaults to
471 // reconfigure the automatic settings.
472 void Reconfigure(BufferView * bv)
473 {
474         bv->owner()->message(_("Running configure..."));
475
476         // Run configure in user lyx directory
477         Path p(user_lyxdir());
478         Systemcall one;
479         one.startscript(Systemcall::Wait,
480                         AddName(system_lyxdir(), "configure"));
481         p.pop();
482         bv->owner()->message(_("Reloading configuration..."));
483         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
484
485         Alert::information(_("System reconfigured"),
486                 _("The system has been reconfigured.\n"
487                 "You need to restart LyX to make use of any \n"
488                 "updated document class specifications."));
489 }