]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Fix crash in lyx -e latex lib/doc/Shortcuts.lyx: theApp() is 0 in batch mode.
[lyx.git] / src / insets / InsetInfo.cpp
1 /**
2  * \file InsetInfo.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Bo Peng
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10 #include <config.h>
11
12 #include "InsetInfo.h"
13
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
18 #include "FuncRequest.h"
19 #include "FuncStatus.h"
20 #include "InsetGraphics.h"
21 #include "InsetSpecialChar.h"
22 #include "KeyMap.h"
23 #include "LaTeXFeatures.h"
24 #include "LayoutFile.h"
25 #include "LyXAction.h"
26 #include "LyXRC.h"
27 #include "LyXVC.h"
28 #include "Lexer.h"
29 #include "ParagraphParameters.h"
30
31 #include "frontends/Application.h"
32
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/docstring_list.h"
36 #include "support/ExceptionMessage.h"
37 #include "support/FileName.h"
38 #include "support/filetools.h"
39 #include "support/gettext.h"
40 #include "support/lstrings.h"
41
42 #include <sstream>
43
44 using namespace std;
45 using namespace lyx::support;
46
47 namespace lyx {
48
49 namespace {
50
51 typedef Translator<InsetInfo::info_type, string> NameTranslator;
52
53 NameTranslator const initTranslator()
54 {       
55         NameTranslator translator(InsetInfo::UNKNOWN_INFO, "unknown");
56
57         translator.addPair(InsetInfo::SHORTCUTS_INFO, "shortcuts");
58         translator.addPair(InsetInfo::SHORTCUT_INFO, "shortcut");
59         translator.addPair(InsetInfo::LYXRC_INFO, "lyxrc");
60         translator.addPair(InsetInfo::PACKAGE_INFO, "package");
61         translator.addPair(InsetInfo::TEXTCLASS_INFO, "textclass");
62         translator.addPair(InsetInfo::MENU_INFO, "menu");
63         translator.addPair(InsetInfo::ICON_INFO, "icon");
64         translator.addPair(InsetInfo::BUFFER_INFO, "buffer");
65         translator.addPair(InsetInfo::LYX_INFO, "lyxinfo");
66
67         return translator;
68 }
69
70 /// The translator between the information type enum and corresponding string.
71 NameTranslator const & nameTranslator()
72 {
73         static NameTranslator const translator = initTranslator();
74         return translator;
75 }
76
77 } // namespace anon
78
79 /////////////////////////////////////////////////////////////////////////
80 //
81 // InsetInfo
82 //
83 /////////////////////////////////////////////////////////////////////////
84
85
86         
87 InsetInfo::InsetInfo(Buffer * buf, string const & name) 
88         : InsetCollapsable(buf), type_(UNKNOWN_INFO), name_()
89 {
90         setAutoBreakRows(true);
91         setInfo(name);
92         status_ = Collapsed;
93 }
94
95
96 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
97 {
98         // do not allow the cursor to be set in this Inset
99         return Inset::editXY(cur, x, y);
100 }
101
102
103 string InsetInfo::infoType() const
104 {
105         return nameTranslator().find(type_);
106 }
107
108
109 docstring InsetInfo::name() const 
110 {
111         return from_ascii("Info:" + infoType());
112 }
113
114
115 docstring InsetInfo::toolTip(BufferView const &, int, int) const
116 {
117         return bformat(_("Information regarding %1$s '%2$s'"),
118                         _(infoType()), from_utf8(name_));
119 }
120
121
122 void InsetInfo::read(Lexer & lex)
123 {
124         string token;
125         while (lex.isOK()) {
126                 lex.next();
127                 token = lex.getString();
128                 if (token == "type") {
129                         lex.next();
130                         token = lex.getString();
131                         type_ = nameTranslator().find(token);
132                 } else if (token == "arg") {
133                         lex.next(true);
134                         name_ = lex.getString();
135                 } else if (token == "\\end_inset")
136                         break;
137         }       
138         if (token != "\\end_inset") {
139                 lex.printError("Missing \\end_inset at this point");
140                 throw ExceptionMessage(WarningException,
141                         _("Missing \\end_inset at this point."),
142                         from_utf8(token));
143         }
144         updateInfo();
145 }
146
147
148 void InsetInfo::write(ostream & os) const
149 {
150         os << "Info\ntype  \"" << infoType() 
151            << "\"\narg   " << Lexer::quoteString(name_);
152 }
153
154
155 bool InsetInfo::validateModifyArgument(docstring const & arg) const
156 {
157         string type;
158         string const name = trim(split(to_utf8(arg), type, ' '));
159
160         switch (nameTranslator().find(type)) {
161         case UNKNOWN_INFO:
162                 return false;
163
164         case SHORTCUT_INFO:
165         case SHORTCUTS_INFO:
166         case MENU_INFO:
167         case ICON_INFO: {
168                 FuncRequest func = lyxaction.lookupFunc(name);
169                 return func.action() != LFUN_UNKNOWN_ACTION;
170         }
171
172         case LYXRC_INFO: {
173                 ostringstream oss;
174                 lyxrc.write(oss, true, name);
175                 return !oss.str().empty();
176         }
177
178         case PACKAGE_INFO:
179         case TEXTCLASS_INFO:
180                 return true;
181
182         case BUFFER_INFO:
183                 if (name == "name" || name == "path" || name == "class")
184                         return true;
185                 if (name == "vcs-revision" || name == "vcs-tree-revision" ||
186                        name == "vcs-author" || name == "vcs-date" || name == "vcs-time")
187                         return buffer().lyxvc().inUse();
188                 return false;
189
190         case LYX_INFO:
191                 return name == "version";
192         }
193
194         return false;
195 }
196
197
198 bool InsetInfo::showInsetDialog(BufferView * bv) const
199 {
200         bv->showDialog("info");
201         return true;
202 }
203
204
205 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
206                 FuncStatus & flag) const
207 {
208         switch (cmd.action()) {
209         case LFUN_INSET_SETTINGS:
210                 return InsetCollapsable::getStatus(cur, cmd, flag);
211
212         case LFUN_INSET_DIALOG_UPDATE:
213         case LFUN_INSET_COPY_AS:
214                 flag.setEnabled(true);
215                 return true;
216
217         case LFUN_INSET_MODIFY:
218                 if (validateModifyArgument(cmd.argument())) {
219                         flag.setEnabled(true);
220                         return true;
221                 }
222                 //fall through
223
224         default:
225                 return false;
226         }
227 }
228
229
230 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
231 {
232         switch (cmd.action()) {
233         case LFUN_INSET_MODIFY:
234                 cur.recordUndo();
235                 setInfo(to_utf8(cmd.argument()));
236                 break;
237
238         case LFUN_INSET_COPY_AS: {
239                 cap::clearSelection();
240                 Cursor copy(cur);
241                 copy.pushBackward(*this);
242                 copy.pit() = 0;
243                 copy.pos() = 0;
244                 copy.resetAnchor();
245                 copy.pit() = copy.lastpit();
246                 copy.pos() = copy.lastpos();
247                 copy.setSelection();
248                 cap::copySelection(copy);
249                 break;
250         }
251
252         default:
253                 InsetCollapsable::doDispatch(cur, cmd);
254                 break;
255         }
256 }
257
258
259 void InsetInfo::setInfo(string const & name)
260 {
261         if (name.empty())
262                 return;
263         // info_type name
264         string type;
265         name_ = trim(split(name, type, ' '));
266         type_ = nameTranslator().find(type);
267         updateInfo();
268 }
269
270
271 void InsetInfo::error(string const & err)
272 {
273         setText(bformat(_(err), from_utf8(name_)), 
274                 Font(inherit_font, buffer().params().language), false);
275 }
276
277
278 void InsetInfo::setText(docstring const & str)
279 {
280         setText(str, Font(inherit_font, buffer().params().language), false);
281 }
282
283
284 void InsetInfo::updateInfo()
285 {
286         BufferParams const & bp = buffer().params();    
287
288         switch (type_) {
289         case UNKNOWN_INFO:
290                 error("Unknown Info: %1$s");
291                 break;
292         case SHORTCUT_INFO:
293         case SHORTCUTS_INFO: {
294                 FuncRequest const func = lyxaction.lookupFunc(name_);
295                 if (func.action() == LFUN_UNKNOWN_ACTION) {
296                         error("Unknown action %1$s");
297                         break;
298                 }
299                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
300                 if (bindings.empty()) {
301                         // It is impropriate to use error() for undefined shortcut
302                         setText(_("undefined"));
303                         break;
304                 }
305                 if (type_ == SHORTCUT_INFO)
306                         setText(bindings.begin()->print(KeySequence::Portable));
307                 else
308                         setText(theTopLevelKeymap().printBindings(func, KeySequence::Portable));
309                 break;
310         }
311         case LYXRC_INFO: {
312                 ostringstream oss;
313                 if (name_.empty()) {
314                         setText(_("undefined"));
315                         break;
316                 }
317                 lyxrc.write(oss, true, name_);
318                 string result = oss.str();
319                 if (result.size() < 2) {
320                         setText(_("undefined"));
321                         break;
322                 }
323                 string::size_type loc = result.rfind("\n", result.size() - 2);
324                 loc = loc == string::npos ? 0 : loc + 1;
325                 if (result.size() < loc + name_.size() + 1
326                           || result.substr(loc + 1, name_.size()) != name_) {
327                         setText(_("undefined"));
328                         break;
329                 }
330                 // remove leading comments and \\name and space
331                 result = result.substr(loc + name_.size() + 2);
332                 
333                 // remove \n and ""
334                 result = rtrim(result, "\n");
335                 result = trim(result, "\"");
336                 setText(from_utf8(result));
337                 break;
338         }
339         case PACKAGE_INFO:
340                 // check in packages.lst
341                 setText(LaTeXFeatures::isAvailable(name_) ? _("yes") : _("no"));
342                 break;
343
344         case TEXTCLASS_INFO: {
345                 // name_ is the class name
346                 LayoutFileList const & list = LayoutFileList::get();
347                 bool available = false;
348                 if (list.haveClass(name_))
349                         available = list[name_].isTeXClassAvailable();
350                 setText(available ? _("yes") : _("no"));
351                 break;
352         }
353         case MENU_INFO: {
354                 docstring_list names;
355                 FuncRequest const func = lyxaction.lookupFunc(name_);
356                 if (func.action() == LFUN_UNKNOWN_ACTION) {
357                         error("Unknown action %1$s");
358                         break;
359                 }
360                 // iterate through the menubackend to find it
361                 if (!theApp()) {
362                         error("Can't determine menu entry for action %1$s in batch mode");
363                         break;
364                 }
365                 if (!theApp()->searchMenu(func, names)) {
366                         error("No menu entry for action %1$s");
367                         break;
368                 }
369                 // if found, return its path.
370                 clear();
371                 Paragraph & par = paragraphs().front();
372                 Font const f(inherit_font, buffer().params().language);
373                 //Font fu = f;
374                 //fu.fontInfo().setUnderbar(FONT_ON);
375                 docstring_list::const_iterator beg = names.begin();
376                 docstring_list::const_iterator end = names.end();
377                 for (docstring_list::const_iterator it = beg ; 
378                      it != end ; ++it) {
379                         // do not insert > for the top level menu item
380                         if (it != beg)
381                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
382                                                 Change(Change::UNCHANGED));
383                         //FIXME: add proper underlines here. This
384                         // involves rewriting searchMenu used above to
385                         // return a vector of menus. If we do not do
386                         // that, we might as well use below
387                         // Paragraph::insert on each string (JMarc)
388                         for (size_type i = 0; i != it->length(); ++i)
389                                 par.insertChar(par.size(), (*it)[i], 
390                                                f, Change(Change::UNCHANGED));
391                 }
392                 break;
393         }
394         case ICON_INFO: {
395                 FuncRequest func = lyxaction.lookupFunc(name_);
396                 docstring icon_name = frontend::Application::iconName(func, true);
397                 //FIXME: We should use the icon directly instead of
398                 // going through FileName. The code below won't work
399                 // if the icon is embedded in the executable through
400                 // the Qt resource system.
401                 // This is only a negligible performance problem:
402                 // If the installed icon differs from the resource icon the
403                 // installed one is preferred anyway, and all icons that are
404                 // embedded in the resources are installed as well.
405                 FileName file(to_utf8(icon_name));
406                 if (!file.exists())
407                         break;
408                 InsetGraphics * inset = new InsetGraphics(buffer_);
409                 InsetGraphicsParams igp;
410                 igp.filename = file;
411                 inset->setParams(igp);
412                 clear();
413                 paragraphs().front().insertInset(0, inset, 
414                                                  Change(Change::UNCHANGED));
415                 break;
416         }
417         case BUFFER_INFO: {
418                 if (name_ == "name") {
419                         setText(from_utf8(buffer().fileName().onlyFileName()));
420                         break;
421                 }
422                 if (name_ == "path") {
423                         setText(from_utf8(buffer().filePath()));
424                         break;
425                 }
426                 if (name_ == "class") {
427                         setText(from_utf8(bp.documentClass().name()));
428                         break;
429                 }
430                 
431                 // everything that follows is for version control.
432                 // nothing that isn't version control should go below this line.
433                 if (!buffer().lyxvc().inUse()) {
434                         setText(_("No version control"));
435                         break;
436                 }
437                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
438                 if (name_ == "vcs-revision")
439                         itype = LyXVC::File;
440                 else if (name_ == "vcs-tree-revision")
441                         itype = LyXVC::Tree;
442                 else if (name_ == "vcs-author")
443                         itype = LyXVC::Author;
444                 else if (name_ == "vcs-time")
445                         itype = LyXVC::Time;
446                 else if (name_ == "vcs-date")
447                         itype = LyXVC::Date;
448                 string binfo = buffer().lyxvc().revisionInfo(itype);
449                 if (binfo.empty())
450                         setText(bformat(_("%1$s unknown"), from_ascii(name_)));
451                 else
452                         setText(from_utf8(binfo));
453                 break;
454         }
455         case LYX_INFO:
456                 if (name_ == "version")
457                         setText(from_ascii(PACKAGE_VERSION));
458                 break;
459         }
460 }
461
462
463 docstring InsetInfo::contextMenu(BufferView const &, int, int) const
464 {
465         //FIXME: We override the implementation of InsetCollapsable,
466         //because this inset is not a collapsable inset.
467         return contextMenuName();
468 }
469
470
471 docstring InsetInfo::contextMenuName() const
472 {
473         return from_ascii("context-info");
474 }
475
476
477 } // namespace lyx