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