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