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