]> git.lyx.org Git - lyx.git/blob - src/lyx_cb.C
More 'standard conformant blurb' nonsense.
[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/path_defines.h"
39 #include "support/systemcall.h"
40 #include "support/lstrings.h"
41
42 #include <fstream>
43 #include <algorithm>
44 #include <utility>
45 #include <cerrno>
46
47 using namespace lyx::support;
48
49 using std::vector;
50 using std::ifstream;
51 using std::copy;
52 using std::endl;
53 using std::ios;
54 using std::back_inserter;
55 using std::istream_iterator;
56 using std::pair;
57 using std::make_pair;
58
59 extern BufferList bufferlist;
60 // this should be static, but I need it in buffer.C
61 bool quitting;  // flag, that we are quitting the program
62
63
64 //
65 // Menu callbacks
66 //
67
68 bool MenuWrite(Buffer * buffer)
69 {
70         if (buffer->save()) {
71                 lastfiles->newFile(buffer->fileName());
72                 return true;
73         }
74
75         // FIXME: we don't tell the user *WHY* the save failed !!
76
77         string const file = MakeDisplayPath(buffer->fileName(), 30);
78
79         string text = bformat(_("The document %1$s could not be saved.\n\n"
80                 "Do you want to rename the document and try again?"), file);
81         int const ret = Alert::prompt(_("Rename and save?"),
82                 text, 0, 1, _("&Rename"), _("&Cancel"));
83
84         if (ret == 0)
85                 return WriteAs(buffer);
86         return false;
87 }
88
89
90
91 bool WriteAs(Buffer * buffer, string const & filename)
92 {
93         string fname = buffer->fileName();
94         string const oldname = fname;
95
96         if (filename.empty()) {
97
98                 FileDialog fileDlg(_("Choose a filename to save document as"),
99                         LFUN_WRITEAS,
100                         make_pair(string(_("Documents|#o#O")),
101                                   string(lyxrc.document_path)),
102                         make_pair(string(_("Templates|#T#t")),
103                                   string(lyxrc.template_path)));
104
105                 if (!IsLyXFilename(fname))
106                         fname += ".lyx";
107
108                 FileDialog::Result result =
109                         fileDlg.save(OnlyPath(fname),
110                                        _("*.lyx| LyX Documents (*.lyx)"),
111                                        OnlyFilename(fname));
112
113                 if (result.first == FileDialog::Later)
114                         return false;
115
116                 fname = result.second;
117
118                 if (fname.empty())
119                         return false;
120
121                 // Make sure the absolute filename ends with appropriate suffix
122                 fname = MakeAbsPath(fname);
123                 if (!IsLyXFilename(fname))
124                         fname += ".lyx";
125         } else
126                 fname = filename;
127
128         FileInfo const myfile(fname);
129         if (myfile.isOK()) {
130                 string const file = MakeDisplayPath(fname, 30);
131                 string text = bformat(_("The document %1$s already exists.\n\n"
132                         "Do you want to over-write that document?"), file);
133                 int const ret = Alert::prompt(_("Over-write document?"),
134                         text, 0, 1, _("&Over-write"), _("&Cancel"));
135
136                 if (ret == 1)
137                         return false;
138         }
139
140         // Ok, change the name of the buffer
141         buffer->setFileName(fname);
142         buffer->markDirty();
143         bool unnamed = buffer->isUnnamed();
144         buffer->setUnnamed(false);
145
146         if (!MenuWrite(buffer)) {
147                 buffer->setFileName(oldname);
148                 buffer->setUnnamed(unnamed);
149                 return false;
150         }
151
152         removeAutosaveFile(oldname);
153         return true;
154 }
155
156
157 void QuitLyX()
158 {
159         lyxerr[Debug::INFO] << "Running QuitLyX." << endl;
160
161         if (lyx_gui::use_gui) {
162                 if (!bufferlist.quitWriteAll())
163                         return;
164
165                 lastfiles->writeFile(lyxrc.lastfiles);
166         }
167
168         // Set a flag that we do quitting from the program,
169         // so no refreshes are necessary.
170         quitting = true;
171
172         // close buffers first
173         bufferlist.closeAll();
174
175         // do any other cleanup procedures now
176         lyxerr[Debug::INFO] << "Deleting tmp dir " << os::getTmpDir() << endl;
177
178         if (destroyDir(os::getTmpDir()) != 0) {
179                 string msg = bformat(_("Could not remove the temporary directory %1$s"),
180                         os::getTmpDir());
181                 Alert::warning(_("Could not remove temporary directory"), msg);
182         }
183
184         lyx_gui::exit();
185 }
186
187
188 namespace {
189
190 class AutoSaveBuffer : public ForkedProcess {
191 public:
192         ///
193         AutoSaveBuffer(BufferView & bv, string const & fname)
194                 : bv_(bv), fname_(fname) {}
195         ///
196         virtual ForkedProcess * clone() const {
197                 return new AutoSaveBuffer(*this);
198         }
199         ///
200         int start();
201 private:
202         ///
203         virtual int generateChild();
204         ///
205         BufferView & bv_;
206         string fname_;
207 };
208
209
210 int AutoSaveBuffer::start()
211 {
212         command_ = bformat(_("Auto-saving %1$s"), fname_);
213         return runNonBlocking();
214 }
215
216
217 int AutoSaveBuffer::generateChild()
218 {
219         // tmp_ret will be located (usually) in /tmp
220         // will that be a problem?
221         pid_t const pid = fork(); // If you want to debug the autosave
222         // you should set pid to -1, and comment out the
223         // fork.
224         if (pid == 0 || pid == -1) {
225                 // pid = -1 signifies that lyx was unable
226                 // to fork. But we will do the save
227                 // anyway.
228                 bool failed = false;
229
230                 string const tmp_ret = tempName(string(), "lyxauto");
231                 if (!tmp_ret.empty()) {
232                         bv_.buffer()->writeFile(tmp_ret);
233                         // assume successful write of tmp_ret
234                         if (!rename(tmp_ret, fname_)) {
235                                 failed = true;
236                                 // most likely couldn't move between filesystems
237                                 // unless write of tmp_ret failed
238                                 // so remove tmp file (if it exists)
239                                 unlink(tmp_ret);
240                         }
241                 } else {
242                         failed = true;
243                 }
244
245                 if (failed) {
246                         // failed to write/rename tmp_ret so try writing direct
247                         if (!bv_.buffer()->writeFile(fname_)) {
248                                 // It is dangerous to do this in the child,
249                                 // but safe in the parent, so...
250                                 if (pid == -1)
251                                         bv_.owner()->message(_("Autosave failed!"));
252                         }
253                 }
254                 if (pid == 0) { // we are the child so...
255                         _exit(0);
256                 }
257         }
258         return pid;
259 }
260
261 } // namespace anon
262
263
264 void AutoSave(BufferView * bv)
265         // should probably be moved into BufferList (Lgb)
266         // Perfect target for a thread...
267 {
268         if (!bv->available())
269                 return;
270
271         if (bv->buffer()->isBakClean() || bv->buffer()->isReadonly()) {
272                 // We don't save now, but we'll try again later
273                 bv->owner()->resetAutosaveTimer();
274                 return;
275         }
276
277         bv->owner()->message(_("Autosaving current document..."));
278
279         // create autosave filename
280         string fname = bv->buffer()->filePath();
281         fname += '#';
282         fname += OnlyFilename(bv->buffer()->fileName());
283         fname += '#';
284
285         AutoSaveBuffer autosave(*bv, fname);
286         autosave.start();
287
288         bv->buffer()->markBakClean();
289         bv->owner()->resetAutosaveTimer();
290 }
291
292
293 //
294 // Copyright CHT Software Service GmbH
295 // Uwe C. Schroeder
296 //
297 // create new file with template
298 // SERVERCMD !
299 //
300 void NewFile(BufferView * bv, string const & filename)
301 {
302         // Split argument by :
303         string name;
304         string tmpname = split(filename, name, ':');
305 #ifdef __EMX__ // Fix me! lyx_cb.C may not be low level enough to allow this.
306         if (name.length() == 1
307             && isalpha(static_cast<unsigned char>(name[0]))
308             && (prefixIs(tmpname, "/") || prefixIs(tmpname, "\\"))) {
309                 name += ':';
310                 name += token(tmpname, ':', 0);
311                 tmpname = split(tmpname, ':');
312         }
313 #endif
314         lyxerr[Debug::INFO] << "Arg is " << filename
315                             << "\nName is " << name
316                             << "\nTemplate is " << tmpname << endl;
317
318         bv->newFile(name, tmpname);
319 }
320
321
322 // Insert ascii file (if filename is empty, prompt for one)
323 void InsertAsciiFile(BufferView * bv, string const & f, bool asParagraph)
324 {
325         if (!bv->available())
326                 return;
327
328         string const tmpstr = getContentsOfAsciiFile(bv, f, asParagraph);
329         if (tmpstr.empty())
330                 return;
331
332         // clear the selection
333         bool flag = (bv->text == bv->getLyXText());
334         if (flag)
335                 bv->beforeChange(bv->text);
336         if (!asParagraph)
337                 bv->getLyXText()->insertStringAsLines(tmpstr);
338         else
339                 bv->getLyXText()->insertStringAsParagraphs(tmpstr);
340         bv->update();
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 }