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