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