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