]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
cc248424d9057155e14a5d073957e8e0ce4c678b
[lyx.git] / src / lyx_cb.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *          Copyright 1995 Matthias Ettrich,
7  *          Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "lyx_cb.h"
14 #include "lyx_main.h"
15 #include "buffer.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferview_funcs.h"
19 #include "debug.h"
20 #include "lastfiles.h"
21 #include "lyxrc.h"
22 #include "lyxtext.h"
23 #include "gettext.h"
24 #include "BufferView.h"
25 #include "Lsstream.h"
26
27 #include "insets/insetlabel.h"
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/path.h"
38 #include "support/systemcall.h"
39 #include "support/lstrings.h"
40
41 #include <fstream>
42 #include <algorithm>
43 #include <utility>
44 #include <cerrno>
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 " << system_tempdir << endl;
176
177         if (destroyDir(system_tempdir) != 0) {
178                 string msg = bformat(_("Could not remove the temporary directory %1$s"),
179                         system_tempdir);
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         if (flag)
340                 bv->update(BufferView::SELECT);
341 }
342
343
344 // Insert ascii file (if filename is empty, prompt for one)
345 string getContentsOfAsciiFile(BufferView * bv, string const & f, bool asParagraph)
346 {
347         string fname = f;
348
349         if (fname.empty()) {
350                 FileDialog fileDlg(_("Select file to insert"),
351                         (asParagraph) ? LFUN_FILE_INSERT_ASCII_PARA : LFUN_FILE_INSERT_ASCII);
352
353                 FileDialog::Result result = fileDlg.open(bv->owner()->buffer()->filePath());
354
355                 if (result.first == FileDialog::Later)
356                         return string();
357
358                 fname = result.second;
359
360                 if (fname.empty())
361                         return string();
362         }
363
364         FileInfo fi(fname);
365
366         if (!fi.readable()) {
367                 string const error = strerror(errno);
368                 string const file = MakeDisplayPath(fname, 50);
369                 string const text = bformat(_("Could not read the specified document\n"
370                         "%1$s\ndue to the error: %2$s"), file, error);
371                 Alert::error(_("Could not read file"), text);
372                 return string();
373         }
374
375         ifstream ifs(fname.c_str());
376         if (!ifs) {
377                 string const error = strerror(errno);
378                 string const file = MakeDisplayPath(fname, 50);
379                 string const text = bformat(_("Could not open the specified document\n"
380                         "%1$s\ndue to the error: %2$s"), file, error);
381                 Alert::error(_("Could not open file"), text);
382                 return string();
383         }
384
385         ifs.unsetf(ios::skipws);
386         istream_iterator<char> ii(ifs);
387         istream_iterator<char> end;
388 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
389         // We use this until the compilers get better...
390         vector<char> tmp;
391         copy(ii, end, back_inserter(tmp));
392         string const tmpstr(tmp.begin(), tmp.end());
393 #else
394         // This is what we want to use and what we will use once the
395         // compilers get good enough.
396         //string tmpstr(ii, end); // yet a reason for using std::string
397         // alternate approach to get the file into a string:
398         string tmpstr;
399         copy(ii, end, back_inserter(tmpstr));
400 #endif
401
402         return tmpstr;
403 }
404
405
406 string const getPossibleLabel(BufferView const & bv)
407 {
408         ParagraphList::iterator pit = bv.getLyXText()->cursor.par();
409         ParagraphList & plist = bv.getLyXText()->ownerParagraphs();
410
411         LyXLayout_ptr layout = pit->layout();
412
413         if (layout->latextype == LATEX_PARAGRAPH && pit != plist.begin()) {
414                 ParagraphList::iterator pit2 = boost::prior(pit);
415
416                 LyXLayout_ptr const & layout2 = pit2->layout();
417
418                 if (layout2->latextype != LATEX_PARAGRAPH) {
419                         pit = pit2;
420                         layout = layout2;
421                 }
422         }
423
424         string text = layout->latexname().substr(0, 3);
425         if (layout->latexname() == "theorem")
426                 text = "thm"; // Create a correct prefix for prettyref
427
428         text += ':';
429         if (layout->latextype == LATEX_PARAGRAPH ||
430             lyxrc.label_init_length < 0)
431                 text.erase();
432
433         string par_text = pit->asString(bv.buffer(), false);
434         for (int i = 0; i < lyxrc.label_init_length; ++i) {
435                 if (par_text.empty())
436                         break;
437                 string head;
438                 par_text = split(par_text, head, ' ');
439                 if (i > 0)
440                         text += '-'; // Is it legal to use spaces in
441                 // labels ?
442                 text += head;
443         }
444
445         return text;
446 }
447
448
449 // This function runs "configure" and then rereads lyx.defaults to
450 // reconfigure the automatic settings.
451 void Reconfigure(BufferView * bv)
452 {
453         bv->owner()->message(_("Running configure..."));
454
455         // Run configure in user lyx directory
456         Path p(user_lyxdir);
457         Systemcall one;
458         one.startscript(Systemcall::Wait,
459                         AddName(system_lyxdir, "configure"));
460         p.pop();
461         bv->owner()->message(_("Reloading configuration..."));
462         lyxrc.read(LibFileSearch(string(), "lyxrc.defaults"));
463
464         Alert::information(_("System reconfigured"),
465                 _("The system has been reconfigured.\n"
466                 "You need to restart LyX to make use of any \n"
467                 "updated document class specifications."));
468 }