]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
InsetInfo: add useful shortcuts.
[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 #include "LyX.h"
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
18 #include "Font.h"
19 #include "FuncRequest.h"
20 #include "FuncStatus.h"
21 #include "InsetGraphics.h"
22 #include "InsetSpecialChar.h"
23 #include "KeyMap.h"
24 #include "LaTeXFeatures.h"
25 #include "Language.h"
26 #include "LayoutFile.h"
27 #include "Length.h"
28 #include "LyXAction.h"
29 #include "LyXRC.h"
30 #include "LyXVC.h"
31 #include "Lexer.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
34 #include "ParagraphParameters.h"
35 #include "version.h"
36
37 #include "frontends/Application.h"
38
39 #include "support/convert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/docstring_list.h"
43 #include "support/ExceptionMessage.h"
44 #include "support/FileName.h"
45 #include "support/filetools.h"
46 #include "support/gettext.h"
47 #include "support/Messages.h"
48 #include "support/lstrings.h"
49 #include "support/qstring_helpers.h"
50 #include "support/Translator.h"
51
52 #include <sstream>
53
54 #include <QtGui/QImage>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60
61 namespace {
62
63 typedef Translator<InsetInfo::info_type, string> NameTranslator;
64
65 NameTranslator const initTranslator()
66 {
67         NameTranslator translator(InsetInfo::UNKNOWN_INFO, "unknown");
68
69         translator.addPair(InsetInfo::SHORTCUTS_INFO, "shortcuts");
70         translator.addPair(InsetInfo::SHORTCUT_INFO, "shortcut");
71         translator.addPair(InsetInfo::LYXRC_INFO, "lyxrc");
72         translator.addPair(InsetInfo::PACKAGE_INFO, "package");
73         translator.addPair(InsetInfo::TEXTCLASS_INFO, "textclass");
74         translator.addPair(InsetInfo::MENU_INFO, "menu");
75         translator.addPair(InsetInfo::ICON_INFO, "icon");
76         translator.addPair(InsetInfo::BUFFER_INFO, "buffer");
77         translator.addPair(InsetInfo::LYX_INFO, "lyxinfo");
78
79         return translator;
80 }
81
82 /// The translator between the information type enum and corresponding string.
83 NameTranslator const & nameTranslator()
84 {
85         static NameTranslator const translator = initTranslator();
86         return translator;
87 }
88
89 } // namespace
90
91 /////////////////////////////////////////////////////////////////////////
92 //
93 // InsetInfo
94 //
95 /////////////////////////////////////////////////////////////////////////
96
97
98
99 InsetInfo::InsetInfo(Buffer * buf, string const & name)
100         : InsetCollapsible(buf), initialized_(false), 
101           type_(UNKNOWN_INFO), name_(), force_ltr_(false)
102 {
103         setInfo(name);
104         status_ = Collapsed;
105 }
106
107
108 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
109 {
110         // do not allow the cursor to be set in this Inset
111         return Inset::editXY(cur, x, y);
112 }
113
114
115 string InsetInfo::infoType() const
116 {
117         return nameTranslator().find(type_);
118 }
119
120
121 docstring InsetInfo::layoutName() const
122 {
123         return from_ascii("Info:" + infoType());
124 }
125
126
127 docstring InsetInfo::toolTip(BufferView const &, int, int) const
128 {
129         docstring result;
130         switch (nameTranslator().find(infoType())) {
131         case UNKNOWN_INFO:
132                 result = _("Invalid information inset");
133                 break;
134         case SHORTCUT_INFO:
135                 result = bformat(_("The keybard shortcut for the function '%1$s'"),
136                                 from_utf8(name_));
137                 break;
138         case SHORTCUTS_INFO:
139                 result = bformat(_("The keybard shortcuts for the function '%1$s'"),
140                                 from_utf8(name_));
141                 break;
142         case MENU_INFO: 
143                 result = bformat(_("The menu location for the function '%1$s'"),
144                                 from_utf8(name_));
145                 break;
146         case ICON_INFO:
147                 result = bformat(_("The toolbar icon for the function '%1$s'"),
148                                 from_utf8(name_));
149                 break;
150         case LYXRC_INFO:
151                 result = bformat(_("The preference setting for the preference key '%1$s'"),
152                                 from_utf8(name_));
153                 break;
154         case PACKAGE_INFO:
155                 result = bformat(_("Availability of the LaTeX package '%1$s'"),
156                                 from_utf8(name_));
157                 break;
158         case TEXTCLASS_INFO:
159                 result = bformat(_("Availability of the LaTeX class '%1$s'"),
160                                 from_utf8(name_));
161                 break;
162         case BUFFER_INFO:
163                 if (name_ == "name")
164                         result = _("The name of this file");
165                 else if (name_ == "path")
166                         result = _("The path were this file is saved");
167                 else if (name_ == "class")
168                         result = _("The class this document uses");
169                 else if (name_ == "vcs-revision")
170                         result = _("Version control revision");
171                 else if (name_ == "vcs-tree-revision")
172                         result = _("Version control tree revision");
173                 else if (name_ == "vcs-author")
174                          result = _("Version control author");
175                  else if (name_ == "vcs-date")
176                         result = _("Version control date");
177                 else if (name_ == "vcs-time")
178                         result = _("Version control time");
179                 break;
180         case LYX_INFO:
181                 result = _("The current LyX version");
182                 break;
183         }
184
185         return result;
186 }
187
188
189 void InsetInfo::read(Lexer & lex)
190 {
191         string token;
192         while (lex.isOK()) {
193                 lex.next();
194                 token = lex.getString();
195                 if (token == "type") {
196                         lex.next();
197                         token = lex.getString();
198                         type_ = nameTranslator().find(token);
199                 } else if (token == "arg") {
200                         lex.next(true);
201                         name_ = lex.getString();
202                 } else if (token == "\\end_inset")
203                         break;
204         }
205         if (token != "\\end_inset") {
206                 lex.printError("Missing \\end_inset at this point");
207                 throw ExceptionMessage(WarningException,
208                         _("Missing \\end_inset at this point."),
209                         from_utf8(token));
210         }
211 }
212
213
214 void InsetInfo::write(ostream & os) const
215 {
216         os << "Info\ntype  \"" << infoType()
217            << "\"\narg   " << Lexer::quoteString(name_);
218 }
219
220
221 bool InsetInfo::validateModifyArgument(docstring const & arg) const
222 {
223         string type;
224         string const name = trim(split(to_utf8(arg), type, ' '));
225
226         switch (nameTranslator().find(type)) {
227         case UNKNOWN_INFO:
228                 return false;
229
230         case SHORTCUT_INFO:
231         case SHORTCUTS_INFO:
232         case MENU_INFO: {
233                 FuncRequest func = lyxaction.lookupFunc(name);
234                 return func.action() != LFUN_UNKNOWN_ACTION;
235         }
236
237         case ICON_INFO: {
238                 FuncCode const action = lyxaction.lookupFunc(name).action();
239                 if (action == LFUN_UNKNOWN_ACTION) {
240                         string dir = "images";
241                         return !imageLibFileSearch(dir, name, "svgz,png").empty();
242                 }
243                 return true;
244         }
245
246         case LYXRC_INFO: {
247                 ostringstream oss;
248                 lyxrc.write(oss, true, name);
249                 return !oss.str().empty();
250         }
251
252         case PACKAGE_INFO:
253         case TEXTCLASS_INFO:
254                 return true;
255
256         case BUFFER_INFO:
257                 if (name == "name" || name == "path" || name == "class")
258                         return true;
259                 if (name == "vcs-revision" || name == "vcs-tree-revision" ||
260                        name == "vcs-author" || name == "vcs-date" || name == "vcs-time")
261                         return buffer().lyxvc().inUse();
262                 return false;
263
264         case LYX_INFO:
265                 return name == "version";
266         }
267
268         return false;
269 }
270
271
272 bool InsetInfo::showInsetDialog(BufferView * bv) const
273 {
274         bv->showDialog("info");
275         return true;
276 }
277
278
279 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
280                 FuncStatus & flag) const
281 {
282         switch (cmd.action()) {
283         case LFUN_INSET_SETTINGS:
284                 return InsetCollapsible::getStatus(cur, cmd, flag);
285
286         case LFUN_INSET_DIALOG_UPDATE:
287         case LFUN_INSET_COPY_AS:
288                 flag.setEnabled(true);
289                 return true;
290
291         case LFUN_INSET_MODIFY:
292                 if (validateModifyArgument(cmd.argument())) {
293                         flag.setEnabled(true);
294                         return true;
295                 }
296                 //fall through
297
298         default:
299                 return false;
300         }
301 }
302
303
304 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
305 {
306         switch (cmd.action()) {
307         case LFUN_INSET_MODIFY:
308                 cur.recordUndo();
309                 setInfo(to_utf8(cmd.argument()));
310                 cur.forceBufferUpdate();
311                 initialized_ = false;
312                 break;
313
314         case LFUN_INSET_COPY_AS: {
315                 cap::clearSelection();
316                 Cursor copy(cur);
317                 copy.pushBackward(*this);
318                 copy.pit() = 0;
319                 copy.pos() = 0;
320                 copy.resetAnchor();
321                 copy.pit() = copy.lastpit();
322                 copy.pos() = copy.lastpos();
323                 copy.setSelection();
324                 cap::copySelection(copy);
325                 break;
326         }
327
328         default:
329                 InsetCollapsible::doDispatch(cur, cmd);
330                 break;
331         }
332 }
333
334
335 void InsetInfo::setInfo(string const & name)
336 {
337         if (name.empty())
338                 return;
339         // info_type name
340         string type;
341         name_ = trim(split(name, type, ' '));
342         type_ = nameTranslator().find(type);
343 }
344
345
346 void InsetInfo::error(docstring const & err, Language const * lang)
347 {
348         setText(bformat(translateIfPossible(err, lang->code()), from_utf8(name_)),
349                 Font(inherit_font, lang), false);
350 }
351
352
353 void InsetInfo::info(docstring const & err, Language const * lang)
354 {
355         setText(translateIfPossible(err, lang->code()),
356                         Font(inherit_font, lang), false);
357 }
358
359
360 void InsetInfo::setText(docstring const & str, Language const * lang)
361 {
362         setText(str, Font(inherit_font, lang), false);
363 }
364
365
366 bool InsetInfo::forceLTR() const
367 {
368         return force_ltr_;
369 }
370
371
372 void InsetInfo::updateBuffer(ParIterator const & it, UpdateType utype) {
373         // If the Buffer is a clone, then we neither need nor want to do any
374         // of what follows. We want, rather, just to inherit how things were
375         // in the original Buffer. This is especially important for VCS.
376         // Otherwise, we could in principle have different settings here
377         // than in the Buffer we were exporting.
378         if (buffer().isClone())
379                 return;
380
381         BufferParams const & bp = buffer().params();
382         Language const * lang = it.paragraph().getFontSettings(bp, it.pos()).language();
383         Language const * tryguilang = languages.getFromCode(Messages::guiLanguage());
384         // Some info insets use the language of the GUI (if available)
385         Language const * guilang = tryguilang ? tryguilang : lang;
386
387         force_ltr_ = !lang->rightToLeft();
388         // This is just to get the string into the po files
389         docstring gui;
390         switch (type_) {
391         case UNKNOWN_INFO:
392                 gui = _("Unknown Info!");
393                 info(from_ascii("Unknown Info!"), lang);
394                 initialized_ = false;
395                 break;
396         case SHORTCUT_INFO:
397         case SHORTCUTS_INFO: {
398                 // shortcuts can change, so we need to re-do this each time
399                 FuncRequest const func = lyxaction.lookupFunc(name_);
400                 if (func.action() == LFUN_UNKNOWN_ACTION) {
401                         gui = _("Unknown action %1$s");
402                         error(from_ascii("Unknown action %1$s"), lang);
403                         break;
404                 }
405                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
406                 if (bindings.empty()) {
407                         gui = _("undefined");
408                         info(from_ascii("undefined"), lang);
409                         break;
410                 }
411                 if (type_ == SHORTCUT_INFO)
412                         setText(bindings.begin()->print(KeySequence::Portable), guilang);
413                 else
414                         setText(theTopLevelKeymap().printBindings(func, KeySequence::Portable), guilang);
415                 force_ltr_ = !guilang->rightToLeft() && !lang->rightToLeft();
416                 break;
417         }
418         case LYXRC_INFO: {
419                 // this information could change, if the preferences are changed,
420                 // so we will recalculate each time through.
421                 ostringstream oss;
422                 if (name_.empty()) {
423                         gui = _("undefined");
424                         info(from_ascii("undefined"), lang);
425                         break;
426                 }
427                 // FIXME this uses the serialization mechanism to get the info
428                 // we want, which i guess works but is a bit strange.
429                 lyxrc.write(oss, true, name_);
430                 string result = oss.str();
431                 if (result.size() < 2) {
432                         gui = _("undefined");
433                         info(from_ascii("undefined"), lang);
434                         break;
435                 }
436                 string::size_type loc = result.rfind("\n", result.size() - 2);
437                 loc = loc == string::npos ? 0 : loc + 1;
438                 if (result.size() < loc + name_.size() + 1
439                           || result.substr(loc + 1, name_.size()) != name_) {
440                         gui = _("undefined");
441                         info(from_ascii("undefined"), lang);
442                         break;
443                 }
444                 // remove leading comments and \\name and space
445                 result = result.substr(loc + name_.size() + 2);
446
447                 // remove \n and ""
448                 result = rtrim(result, "\n");
449                 result = trim(result, "\"");
450                 setText(from_utf8(result), lang);
451                 break;
452         }
453         case PACKAGE_INFO:
454                 // only need to do this once.
455                 if (initialized_)
456                         break;
457                 // check in packages.lst
458                 if (LaTeXFeatures::isAvailable(name_)) {
459                         gui = _("yes");
460                         info(from_ascii("yes"), lang);
461                 } else {
462                         gui = _("no");
463                         info(from_ascii("no"), lang);
464                 }
465                 initialized_ = true;
466                 break;
467
468         case TEXTCLASS_INFO: {
469                 // the TextClass can change
470                 LayoutFileList const & list = LayoutFileList::get();
471                 bool available = false;
472                 // name_ is the class name
473                 if (list.haveClass(name_))
474                         available = list[name_].isTeXClassAvailable();
475                 if (available) {
476                         gui = _("yes");
477                         info(from_ascii("yes"), lang);
478                 } else {
479                         gui = _("no");
480                         info(from_ascii("no"), lang);
481                 }
482                 break;
483         }
484         case MENU_INFO: {
485                 // only need to do this once.
486                 if (initialized_)
487                         break;
488                 // and we will not keep trying if we fail
489                 initialized_ = true;
490                 docstring_list names;
491                 FuncRequest const func = lyxaction.lookupFunc(name_);
492                 if (func.action() == LFUN_UNKNOWN_ACTION) {
493                         gui = _("Unknown action %1$s");
494                         error(from_ascii("Unknown action %1$s"), lang);
495                         break;
496                 }
497                 // iterate through the menubackend to find it
498                 if (!theApp()) {
499                         gui = _("Can't determine menu entry for action %1$s in batch mode");
500                         error(from_ascii("Can't determine menu entry for action %1$s in batch mode"), lang);
501                         break;
502                 }
503                 if (!theApp()->searchMenu(func, names)) {
504                         gui = _("No menu entry for action %1$s");
505                         error(from_ascii("No menu entry for action %1$s"), lang);
506                         break;
507                 }
508                 // if found, return its path.
509                 clear();
510                 Paragraph & par = paragraphs().front();
511                 Font const f(inherit_font, guilang);
512                 force_ltr_ = !guilang->rightToLeft();
513                 //Font fu = f;
514                 //fu.fontInfo().setUnderbar(FONT_ON);
515                 for (docstring const & name : names) {
516                         // do not insert > for the top level menu item
517                         if (&name != &names.front())
518                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
519                                                 f, Change(Change::UNCHANGED));
520                         //FIXME: add proper underlines here. This
521                         // involves rewriting searchMenu used above to
522                         // return a vector of menus. If we do not do
523                         // that, we might as well use below
524                         // Paragraph::insert on each string (JMarc)
525                         for (char_type c : name)
526                                 par.insertChar(par.size(), c, f, Change(Change::UNCHANGED));
527                 }
528                 break;
529         }
530         case ICON_INFO: {
531                 // only need to do this once.
532                 if (initialized_)
533                         break;
534                 // and we will not keep trying if we fail
535                 initialized_ = true;
536                 FuncRequest func = lyxaction.lookupFunc(name_);
537                 docstring icon_name = frontend::Application::iconName(func, true);
538                 // FIXME: We should use the icon directly instead of
539                 // going through FileName. The code below won't work
540                 // if the icon is embedded in the executable through
541                 // the Qt resource system.
542                 // This is only a negligible performance problem:
543                 // If the installed icon differs from the resource icon the
544                 // installed one is preferred anyway, and all icons that are
545                 // embedded in the resources are installed as well.
546                 FileName file(to_utf8(icon_name));
547                 if (file.onlyFileNameWithoutExt() == "unknown") {
548                         string dir = "images";
549                         FileName file2(imageLibFileSearch(dir, name_, "svgz,png"));
550                         if (!file2.empty())
551                                 file = file2;
552                 }
553                 if (!file.exists())
554                         break;
555                 int percent_scale = 100;
556                 if (use_gui) {
557                         // Compute the scale factor for the icon such that its
558                         // width on screen is equal to 1em in pixels.
559                         // The scale factor is rounded to the integer nearest
560                         // to the float value of the ratio 100*iconsize/imgsize.
561                         int imgsize = QImage(toqstr(file.absFileName())).width();
562                         if (imgsize > 0) {
563                                 int iconsize = Length(1, Length::EM).inPixels(1);
564                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
565                         }
566                 }
567                 InsetGraphics * inset = new InsetGraphics(buffer_);
568                 InsetGraphicsParams igp;
569                 igp.filename = file;
570                 igp.lyxscale = percent_scale;
571                 igp.scale = string();
572                 igp.width = Length(1, Length::EM);
573                 inset->setParams(igp);
574                 clear();
575                 Font const f(inherit_font, lang);
576                 paragraphs().front().insertInset(0, inset, f,
577                                                  Change(Change::UNCHANGED));
578                 break;
579         }
580         case BUFFER_INFO: {
581                 // this could all change, so we will recalculate each time
582                 if (name_ == "name") {
583                         setText(from_utf8(buffer().fileName().onlyFileName()), lang);
584                         break;
585                 }
586                 if (name_ == "path") {
587                         setText(from_utf8(os::latex_path(buffer().filePath())), lang);
588                         break;
589                 }
590                 if (name_ == "class") {
591                         setText(from_utf8(bp.documentClass().name()), lang);
592                         break;
593                 }
594
595                 ////////////////////////////////////////////////////////////////
596                 // everything that follows is for version control.
597                 // nothing that isn't version control should go below this line.
598                 
599                 // this information could change, in principle, so we will 
600                 // recalculate each time through
601                 if (!buffer().lyxvc().inUse()) {
602                         gui = _("No version control");
603                         info(from_ascii("No version control"), lang);
604                         break;
605                 }
606                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
607                 if (name_ == "vcs-revision")
608                         itype = LyXVC::File;
609                 else if (name_ == "vcs-tree-revision")
610                         itype = LyXVC::Tree;
611                 else if (name_ == "vcs-author")
612                         itype = LyXVC::Author;
613                 else if (name_ == "vcs-time")
614                         itype = LyXVC::Time;
615                 else if (name_ == "vcs-date")
616                         itype = LyXVC::Date;
617                 string binfo = buffer().lyxvc().revisionInfo(itype);
618                 if (binfo.empty()) {
619                         gui = _("%1$s[[vcs data]] unknown");
620                         error(from_ascii("%1$s[[vcs data]] unknown"), lang);
621                 } else
622                         setText(from_utf8(binfo), lang);
623                 break;
624         }
625         case LYX_INFO:
626                 // only need to do this once.
627                 if (initialized_)
628                         break;
629                 if (name_ == "version")
630                         setText(from_ascii(lyx_version), lang);
631                 initialized_ = true;
632                 break;
633         }
634         // Just to do something with that string
635         LYXERR(Debug::INFO, "info inset text: " << gui);
636         InsetCollapsible::updateBuffer(it, utype);
637 }
638
639
640 string InsetInfo::contextMenu(BufferView const &, int, int) const
641 {
642         //FIXME: We override the implementation of InsetCollapsible,
643         //because this inset is not a collapsible inset.
644         return contextMenuName();
645 }
646
647
648 string InsetInfo::contextMenuName() const
649 {
650         return "context-info";
651 }
652
653
654 } // namespace lyx