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