]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Fix crash in InsetInfo when bindings change
[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  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetInfo.h"
14 #include "LyX.h"
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "Changes.h"
19 #include "Cursor.h"
20 #include "CutAndPaste.h"
21 #include "Font.h"
22 #include "FuncRequest.h"
23 #include "FuncStatus.h"
24 #include "InsetGraphics.h"
25 #include "InsetSpecialChar.h"
26 #include "KeyMap.h"
27 #include "LaTeXFeatures.h"
28 #include "Language.h"
29 #include "LayoutFile.h"
30 #include "LyXAction.h"
31 #include "LyXRC.h"
32 #include "LyXVC.h"
33 #include "Lexer.h"
34 #include "Paragraph.h"
35 #include "ParIterator.h"
36 #include "ParagraphParameters.h"
37 #include "version.h"
38
39 #include "frontends/Application.h"
40
41 #include "support/convert.h"
42 #include "support/debug.h"
43 #include "support/docstream.h"
44 #include "support/docstring_list.h"
45 #include "support/ExceptionMessage.h"
46 #include "support/FileName.h"
47 #include "support/filetools.h"
48 #include "support/gettext.h"
49 #include "support/Length.h"
50 #include "support/Messages.h"
51 #include "support/lstrings.h"
52 #include "support/qstring_helpers.h"
53 #include "support/Translator.h"
54
55 #include <sstream>
56
57 #include <QtGui/QImage>
58 #include <QDate>
59 #include <QLocale>
60
61 using namespace std;
62 using namespace lyx::support;
63
64 namespace lyx {
65
66 namespace {
67
68 typedef Translator<InsetInfoParams::info_type, string> NameTranslator;
69
70 NameTranslator const initTranslator()
71 {
72         NameTranslator translator(InsetInfoParams::UNKNOWN_INFO, "unknown");
73
74         translator.addPair(InsetInfoParams::SHORTCUTS_INFO, "shortcuts");
75         translator.addPair(InsetInfoParams::SHORTCUT_INFO, "shortcut");
76         translator.addPair(InsetInfoParams::LYXRC_INFO, "lyxrc");
77         translator.addPair(InsetInfoParams::PACKAGE_INFO, "package");
78         translator.addPair(InsetInfoParams::TEXTCLASS_INFO, "textclass");
79         translator.addPair(InsetInfoParams::MENU_INFO, "menu");
80         translator.addPair(InsetInfoParams::L7N_INFO, "l7n");
81         translator.addPair(InsetInfoParams::ICON_INFO, "icon");
82         translator.addPair(InsetInfoParams::BUFFER_INFO, "buffer");
83         translator.addPair(InsetInfoParams::LYX_INFO, "lyxinfo");
84         translator.addPair(InsetInfoParams::VCS_INFO, "vcs");
85         translator.addPair(InsetInfoParams::DATE_INFO, "date");
86         translator.addPair(InsetInfoParams::MODDATE_INFO, "moddate");
87         translator.addPair(InsetInfoParams::FIXDATE_INFO, "fixdate");
88         translator.addPair(InsetInfoParams::TIME_INFO, "time");
89         translator.addPair(InsetInfoParams::MODTIME_INFO, "modtime");
90         translator.addPair(InsetInfoParams::FIXTIME_INFO, "fixtime");
91
92         return translator;
93 }
94
95 /// The translator between the information type enum and corresponding string.
96 NameTranslator const & nameTranslator()
97 {
98         static NameTranslator const translator = initTranslator();
99         return translator;
100 }
101
102
103 typedef Translator<InsetInfoParams::info_type, string> DefaultValueTranslator;
104
105 DefaultValueTranslator const initDVTranslator()
106 {
107         DefaultValueTranslator translator(InsetInfoParams::UNKNOWN_INFO, "");
108
109         translator.addPair(InsetInfoParams::SHORTCUTS_INFO, "info-insert");
110         translator.addPair(InsetInfoParams::SHORTCUT_INFO, "info-insert");
111         translator.addPair(InsetInfoParams::LYXRC_INFO, "user_name");
112         translator.addPair(InsetInfoParams::PACKAGE_INFO, "graphics");
113         translator.addPair(InsetInfoParams::TEXTCLASS_INFO, "article");
114         translator.addPair(InsetInfoParams::MENU_INFO, "info-insert");
115         translator.addPair(InsetInfoParams::L7N_INFO, "");
116         translator.addPair(InsetInfoParams::ICON_INFO, "info-insert");
117         translator.addPair(InsetInfoParams::BUFFER_INFO, "name-noext");
118         translator.addPair(InsetInfoParams::LYX_INFO, "version");
119         translator.addPair(InsetInfoParams::VCS_INFO, "revision");
120         translator.addPair(InsetInfoParams::DATE_INFO, "loclong");
121         translator.addPair(InsetInfoParams::MODDATE_INFO, "loclong");
122         translator.addPair(InsetInfoParams::FIXDATE_INFO, "loclong");
123         translator.addPair(InsetInfoParams::TIME_INFO, "long");
124         translator.addPair(InsetInfoParams::MODTIME_INFO, "long");
125         translator.addPair(InsetInfoParams::FIXTIME_INFO, "long");
126
127         return translator;
128 }
129
130 /// The translator between the information type enum and some sensible default value.
131 DefaultValueTranslator const & defaultValueTranslator()
132 {
133         static DefaultValueTranslator const translator = initDVTranslator();
134         return translator;
135 }
136
137 } // namespace
138
139
140 /////////////////////////////////////////////////////////////////////
141 //
142 // InsetInfoParams
143 //
144 ///////////////////////////////////////////////////////////////////////
145
146 InsetInfoParams infoparams;
147
148 namespace{
149 set<string> getTexFileList(string const & filename)
150 {
151         set<string> list;
152         FileName const file = libFileSearch(string(), filename);
153         if (file.empty())
154                 return list;
155
156         // FIXME Unicode.
157         vector<docstring> doclist =
158                 getVectorFromString(file.fileContents("UTF-8"), from_ascii("\n"));
159
160         // Normalise paths like /foo//bar ==> /foo/bar
161         for (auto doc : doclist) {
162                 doc = subst(doc, from_ascii("\r"), docstring());
163                 while (contains(doc, from_ascii("//")))
164                         doc = subst(doc, from_ascii("//"), from_ascii("/"));
165                 if (!doc.empty())
166                         list.insert(removeExtension(onlyFileName(to_utf8(doc))));
167         }
168
169         // remove duplicates
170         return list;
171 }
172
173 bool translateString(docstring const & in, docstring & out, string const & lcode)
174 {
175         out = translateIfPossible(in, lcode);
176         return in != out;
177 }
178 } // namespace anon
179
180
181 docstring InsetInfoParams::getDate(string const & iname, QDate const date) const
182 {
183         QLocale loc;
184         if (lang)
185                 loc = QLocale(toqstr(lang->code()));
186         if (iname == "long")
187                 return qstring_to_ucs4(loc.toString(date, QLocale::LongFormat));
188         else if (iname == "short")
189                 return qstring_to_ucs4(loc.toString(date, QLocale::ShortFormat));
190         else if (iname == "ISO")
191                 return qstring_to_ucs4(date.toString(Qt::ISODate));
192         else if (iname == "loclong")
193                 return lang ? qstring_to_ucs4(loc.toString(date, toqstr(lang->dateFormat(0))))
194                             : _("No long date format (language unknown)!");
195         else if (iname == "locmedium")
196                 return lang ? qstring_to_ucs4(loc.toString(date, toqstr(lang->dateFormat(1))))
197                             : _("No medium date format (language unknown)!");
198         else if (iname == "locshort")
199                 return lang ? qstring_to_ucs4(loc.toString(date, toqstr(lang->dateFormat(2))))
200                                 : _("No short date format (language unknown)!");
201         else
202                 return qstring_to_ucs4(loc.toString(date, toqstr(iname)));
203 }
204
205
206 docstring InsetInfoParams::getTime(string const & iname, QTime const time) const
207 {
208         QLocale loc;
209         if (lang)
210                 loc = QLocale(toqstr(lang->code()));
211         if (iname == "long")
212                 return qstring_to_ucs4(loc.toString(time, QLocale::LongFormat));
213         else if (iname == "short")
214                 return qstring_to_ucs4(loc.toString(time, QLocale::ShortFormat));
215         else if (iname == "ISO")
216                 return qstring_to_ucs4(time.toString(Qt::ISODate));
217         else
218                 return qstring_to_ucs4(loc.toString(time, toqstr(iname)));
219 }
220
221
222 vector<pair<string,docstring>> InsetInfoParams::getArguments(Buffer const * buf,
223                                                              string const & itype) const
224 {
225         vector<pair<string,docstring>> result;
226
227         switch (nameTranslator().find(itype)) {
228         case UNKNOWN_INFO:
229                 result.push_back(make_pair("invalid", _("Please select a valid type!")));
230                 break;
231
232         case SHORTCUT_INFO:
233         case SHORTCUTS_INFO:
234         case MENU_INFO:
235         case ICON_INFO: {
236                 result.push_back(make_pair("custom", _("Custom")));
237                 for (auto const & name_code : lyxaction) {
238                         string const lfun = name_code.first;
239                         if (!lfun.empty())
240                                 result.push_back(make_pair(lfun, from_ascii(lfun)));
241                 }
242                 break;
243         }
244
245         case L7N_INFO:
246                 result.push_back(make_pair("custom", _("Custom")));
247                 break;
248
249         case LYXRC_INFO: {
250                 result.push_back(make_pair("custom", _("Custom")));
251                 set<string> rcs = lyxrc.getRCs();
252                 for (auto const & rc : rcs)
253                         result.push_back(make_pair(rc, from_ascii(rc)));
254                 break;
255         }
256
257         case PACKAGE_INFO:
258         case TEXTCLASS_INFO: {
259                 result.push_back(make_pair("custom", _("Custom")));
260                 string const filename = (itype == "package") ? "styFiles.lst"
261                                                             : "clsFiles.lst";
262                 set<string> flist = getTexFileList(filename);
263                 for (auto const & f : flist)
264                         result.push_back(make_pair(f, from_utf8(f)));
265                 break;
266         }
267
268         case BUFFER_INFO:
269                 result.push_back(make_pair("name", _("File name (with extension)")));
270                 result.push_back(make_pair("name-noext", _("File name (without extension)")));
271                 result.push_back(make_pair("path", _("File path")));
272                 result.push_back(make_pair("class", _("Used text class")));
273                 break;
274
275         case VCS_INFO: {
276                 if (!buf->lyxvc().inUse()) {
277                         result.push_back(make_pair("invalid", _("No version control!")));
278                         break;
279                 }
280                 result.push_back(make_pair("revision", _("Revision[[Version Control]]")));
281                 result.push_back(make_pair("revision-abbrev", _("Abbreviated revision[[Version Control]]")));
282                 result.push_back(make_pair("tree-revision", _("Tree revision")));
283                 result.push_back(make_pair("author", _("Author")));
284                 result.push_back(make_pair("date", _("Date")));
285                 result.push_back(make_pair("time", _("Time[[of day]]")));
286                 break;
287         }
288
289         case LYX_INFO:
290                 result.push_back(make_pair("version", _("LyX version")));
291                 result.push_back(make_pair("layoutformat", _("LyX layout format")));
292                 break;
293
294         case FIXDATE_INFO:
295         case DATE_INFO:
296         case MODDATE_INFO: {
297                 string const dt = split(name, '@');
298                 QDate date;
299                 if (itype == "moddate")
300 #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
301                         date = QDateTime::fromSecsSinceEpoch(buf->fileName().lastModified()).date();
302 #else
303                         date = QDateTime::fromTime_t(buf->fileName().lastModified()).date();
304 #endif
305                 else if (itype == "fixdate" && !dt.empty()) {
306                         QDate const gdate = QDate::fromString(toqstr(dt), Qt::ISODate);
307                         date = (gdate.isValid()) ? gdate : QDate::currentDate();
308                 } else
309                         date = QDate::currentDate();
310                 result.push_back(make_pair("long",getDate("long", date)));
311                 result.push_back(make_pair("short", getDate("short", date)));
312                 result.push_back(make_pair("loclong", getDate("loclong", date)));
313                 result.push_back(make_pair("locmedium", getDate("locmedium", date)));
314                 result.push_back(make_pair("locshort", getDate("locshort", date)));
315                 result.push_back(make_pair("ISO", getDate("ISO", date)));
316                 result.push_back(make_pair("yyyy", getDate("yyyy", date)));
317                 result.push_back(make_pair("MMMM", getDate("MMMM", date)));
318                 result.push_back(make_pair("MMM", getDate("MMM", date)));
319                 result.push_back(make_pair("dddd", getDate("dddd", date)));
320                 result.push_back(make_pair("ddd", getDate("ddd", date)));
321                 result.push_back(make_pair("custom", _("Custom")));
322                 break;
323         }
324         case FIXTIME_INFO:
325         case TIME_INFO:
326         case MODTIME_INFO: {
327                 string const tt = split(name, '@');
328                 QTime time;
329                 if (itype == "modtime")
330 #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
331                         time = QDateTime::fromSecsSinceEpoch(buf->fileName().lastModified()).time();
332 #else
333                         time = QDateTime::fromTime_t(buf->fileName().lastModified()).time();
334 #endif
335                 else if (itype == "fixtime" && !tt.empty()) {
336                         QTime const gtime = QTime::fromString(toqstr(tt), Qt::ISODate);
337                         time = (gtime.isValid()) ? gtime : QTime::currentTime();
338                 } else
339                         time = QTime::currentTime();
340                 result.push_back(make_pair("long",getTime("long", time)));
341                 result.push_back(make_pair("short", getTime("short", time)));
342                 result.push_back(make_pair("ISO", getTime("ISO", time)));
343                 result.push_back(make_pair("custom", _("Custom")));
344                 break;
345         }
346         }
347
348         return result;
349 }
350
351
352 bool InsetInfoParams::validateArgument(Buffer const * buf, docstring const & arg,
353                                        bool const usedefaults) const
354 {
355         string type;
356         string name = trim(split(to_utf8(arg), type, ' '));
357         if (name.empty() && usedefaults)
358                 name = defaultValueTranslator().find(type);
359
360         switch (nameTranslator().find(type)) {
361         case UNKNOWN_INFO:
362                 return false;
363
364         case SHORTCUT_INFO:
365         case SHORTCUTS_INFO:
366         case MENU_INFO: {
367                 FuncRequest func = lyxaction.lookupFunc(name);
368                 return func.action() != LFUN_UNKNOWN_ACTION;
369         }
370
371         case L7N_INFO:
372                 return !name.empty();
373
374         case ICON_INFO: {
375                 FuncCode const action = lyxaction.lookupFunc(name).action();
376                 if (action == LFUN_UNKNOWN_ACTION) {
377                         string dir = "images";
378                         return !imageLibFileSearch(dir, name, "svgz,png").empty();
379                 }
380                 return true;
381         }
382
383         case LYXRC_INFO: {
384                 set<string> rcs = lyxrc.getRCs();
385                 return rcs.find(name) != rcs.end();
386         }
387
388         case PACKAGE_INFO:
389         case TEXTCLASS_INFO:
390                 return true;
391
392         case BUFFER_INFO:
393                 return (name == "name" || name == "name-noext"
394                         || name == "path" || name == "class");
395
396         case VCS_INFO:
397                 if (name == "revision" || name == "revision-abbrev" || name == "tree-revision"
398                     || name == "author" || name == "date" || name == "time")
399                         return buf->lyxvc().inUse();
400                 return false;
401
402         case LYX_INFO:
403                 return name == "version" || name == "layoutformat";
404
405         case FIXDATE_INFO: {
406                 string date;
407                 string piece;
408                 date = split(name, piece, '@');
409                 if (!date.empty() && !QDate::fromString(toqstr(date), Qt::ISODate).isValid())
410                         return false;
411                 if (!piece.empty())
412                         name = piece;
413         }
414         // fall through
415         case DATE_INFO:
416         case MODDATE_INFO: {
417                 if (name == "long" || name == "short" || name == "ISO")
418                         return true;
419                 else {
420                         QDate date = QDate::currentDate();
421                         return !date.toString(toqstr(name)).isEmpty();
422                 }
423         }
424         case FIXTIME_INFO: {
425                 string time;
426                 string piece;
427                 time = split(name, piece, '@');
428                 if (!time.empty() && !QTime::fromString(toqstr(time), Qt::ISODate).isValid())
429                         return false;
430                 if (!piece.empty())
431                         name = piece;
432         }
433         // fall through
434         case TIME_INFO:
435         case MODTIME_INFO: {
436                 if (name == "long" || name == "short" || name == "ISO")
437                         return true;
438                 else {
439                         QTime time = QTime::currentTime();
440                         return !time.toString(toqstr(name)).isEmpty();
441                 }
442         }
443         }
444
445         return false;
446 }
447
448
449
450
451 string InsetInfoParams::infoType() const
452 {
453         return nameTranslator().find(type);
454 }
455
456
457
458 /////////////////////////////////////////////////////////////////////////
459 //
460 // InsetInfo
461 //
462 /////////////////////////////////////////////////////////////////////////
463
464
465
466 InsetInfo::InsetInfo(Buffer * buf, string const & info)
467         : InsetCollapsible(buf), initialized_(false)
468 {
469         params_.type = InsetInfoParams::UNKNOWN_INFO;
470         params_.force_ltr = false;
471         setInfo(info);
472         status_ = Collapsed;
473 }
474
475
476 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
477 {
478         // do not allow the cursor to be set in this Inset
479         return Inset::editXY(cur, x, y);
480 }
481
482
483 docstring InsetInfo::layoutName() const
484 {
485         return from_ascii("Info:" + params_.infoType());
486 }
487
488
489 docstring InsetInfo::toolTip(BufferView const &, int, int) const
490 {
491         docstring result;
492         switch (nameTranslator().find(params_.infoType())) {
493         case InsetInfoParams::UNKNOWN_INFO:
494                 result = _("Invalid information inset");
495                 break;
496         case InsetInfoParams::SHORTCUT_INFO:
497                 result = bformat(_("The keybard shortcut for the function '%1$s'"),
498                                 from_utf8(params_.name));
499                 break;
500         case InsetInfoParams::SHORTCUTS_INFO:
501                 result = bformat(_("The keybard shortcuts for the function '%1$s'"),
502                                 from_utf8(params_.name));
503                 break;
504         case InsetInfoParams::MENU_INFO: 
505                 result = bformat(_("The menu location for the function '%1$s'"),
506                                 from_utf8(params_.name));
507                 break;
508         case InsetInfoParams::L7N_INFO: 
509                 result = bformat(_("The localization for the string '%1$s'"),
510                                 from_utf8(params_.name));
511                 break;
512         case InsetInfoParams::ICON_INFO:
513                 result = bformat(_("The toolbar icon for the function '%1$s'"),
514                                 from_utf8(params_.name));
515                 break;
516         case InsetInfoParams::LYXRC_INFO:
517                 result = bformat(_("The preference setting for the preference key '%1$s'"),
518                                 from_utf8(params_.name));
519                 break;
520         case InsetInfoParams::PACKAGE_INFO:
521                 result = bformat(_("Availability of the LaTeX package '%1$s'"),
522                                 from_utf8(params_.name));
523                 break;
524         case InsetInfoParams::TEXTCLASS_INFO:
525                 result = bformat(_("Availability of the LaTeX class '%1$s'"),
526                                 from_utf8(params_.name));
527                 break;
528         case InsetInfoParams::BUFFER_INFO:
529                 if (params_.name == "name")
530                         result = _("The name of this file (incl. extension)");
531                 else if (params_.name == "name-noext")
532                         result = _("The name of this file (without extension)");
533                 else if (params_.name == "path")
534                         result = _("The path where this file is saved");
535                 else if (params_.name == "class")
536                         result = _("The class this document uses");
537                 break;
538         case InsetInfoParams::VCS_INFO:
539                 if (params_.name == "revision")
540                         result = _("Version control revision");
541                 else if (params_.name == "revision-abbrev")
542                         result = _("Version control abbreviated revision");
543                 else if (params_.name == "tree-revision")
544                         result = _("Version control tree revision");
545                 else if (params_.name == "author")
546                          result = _("Version control author");
547                 else if (params_.name == "date")
548                         result = _("Version control date");
549                 else if (params_.name == "time")
550                         result = _("Version control time");
551                 break;
552         case InsetInfoParams::LYX_INFO:
553                 if (params_.name == "version")
554                         result = _("The current LyX version");
555                 else if (params_.name == "layoutformat")
556                         result = _("The current LyX layout format");
557                 break;
558         case InsetInfoParams::DATE_INFO:
559                 result = _("The current date");
560                 break;
561         case InsetInfoParams::MODDATE_INFO:
562                 result = _("The date of last save");
563                 break;
564         case InsetInfoParams::FIXDATE_INFO:
565                 result = _("A static date");
566                 break;
567         case InsetInfoParams::TIME_INFO:
568                 result = _("The current time");
569                 break;
570         case InsetInfoParams::MODTIME_INFO:
571                 result = _("The time of last save");
572                 break;
573         case InsetInfoParams::FIXTIME_INFO:
574                 result = _("A static time");
575                 break;
576         }
577
578         return result;
579 }
580
581
582 void InsetInfo::read(Lexer & lex)
583 {
584         string token;
585         while (lex.isOK()) {
586                 lex.next();
587                 token = lex.getString();
588                 if (token == "type") {
589                         lex.next();
590                         token = lex.getString();
591                         params_.type = nameTranslator().find(token);
592                 } else if (token == "arg") {
593                         lex.next(true);
594                         params_.name = lex.getString();
595                 } else if (token == "\\end_inset")
596                         break;
597         }
598         if (token != "\\end_inset") {
599                 lex.printError("Missing \\end_inset at this point");
600                 throw ExceptionMessage(WarningException,
601                         _("Missing \\end_inset at this point."),
602                         from_utf8(token));
603         }
604 }
605
606
607 void InsetInfo::write(ostream & os) const
608 {
609         os << "Info\ntype  \"" << params_.infoType()
610            << "\"\narg   " << Lexer::quoteString(params_.name);
611 }
612
613
614 bool InsetInfo::showInsetDialog(BufferView * bv) const
615 {
616         bv->showDialog("info");
617         return true;
618 }
619
620
621 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
622                 FuncStatus & flag) const
623 {
624         switch (cmd.action()) {
625         case LFUN_INSET_SETTINGS:
626                 return InsetCollapsible::getStatus(cur, cmd, flag);
627
628         case LFUN_INSET_DIALOG_UPDATE:
629         case LFUN_INSET_COPY_AS:
630         case LFUN_INSET_DISSOLVE:
631                 flag.setEnabled(true);
632                 return true;
633
634         case LFUN_INSET_MODIFY:
635                 if (nameTranslator().find(cmd.getArg(0)) == InsetInfoParams::UNKNOWN_INFO)
636                         return Inset::getStatus(cur, cmd, flag);
637                 if (params_.validateArgument(&buffer(), cmd.argument())) {
638                         flag.setEnabled(true);
639                         string typestr;
640                         string name = trim(split(to_utf8(cmd.argument()), typestr, ' '));
641                         InsetInfoParams::info_type type = nameTranslator().find(typestr);
642                         string origname = params_.name;
643                         if (type == InsetInfoParams::FIXDATE_INFO
644                             || type == InsetInfoParams::FIXTIME_INFO)
645                                 split(params_.name, origname, '@');
646                         flag.setOnOff(type == params_.type && name == origname);
647                         return true;
648                 }
649                 //fall through
650
651         default:
652                 return false;
653         }
654 }
655
656
657 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
658 {
659         switch (cmd.action()) {
660         case LFUN_INSET_MODIFY:
661                 if (nameTranslator().find(cmd.getArg(0)) == InsetInfoParams::UNKNOWN_INFO) {
662                         cur.undispatched();
663                         break;
664                 }
665                 cur.recordUndo();
666                 setInfo(to_utf8(cmd.argument()));
667                 cur.forceBufferUpdate();
668                 initialized_ = false;
669                 break;
670
671         case LFUN_INSET_COPY_AS: {
672                 cap::clearSelection();
673                 Cursor copy(cur);
674                 copy.pushBackward(*this);
675                 copy.pit() = 0;
676                 copy.pos() = 0;
677                 copy.resetAnchor();
678                 copy.pit() = copy.lastpit();
679                 copy.pos() = copy.lastpos();
680                 copy.setSelection();
681                 cap::copySelection(copy);
682                 break;
683         }
684
685         default:
686                 InsetCollapsible::doDispatch(cur, cmd);
687                 break;
688         }
689 }
690
691
692 void InsetInfo::setInfo(string const & info)
693 {
694         if (info.empty())
695                 return;
696
697         string saved_date_specifier;
698         // Store old date specifier for potential re-use
699         if (!params_.name.empty())
700                 saved_date_specifier = split(params_.name, '@');
701         // info_type name
702         string type;
703         params_.name = trim(split(info, type, ' '));
704         params_.type = nameTranslator().find(type);
705         if (params_.name.empty())
706                 params_.name = defaultValueTranslator().find(params_.type);
707         if (params_.type == InsetInfoParams::FIXDATE_INFO) {
708                 string const date_specifier = split(params_.name, '@');
709                 // If an explicit new fix date is specified, use that
710                 // Otherwise, use the old one or, if there is none,
711                 // the current date
712                 if (date_specifier.empty()) {
713                         if (saved_date_specifier.empty())
714                                 params_.name += "@" + fromqstr(QDate::currentDate().toString(Qt::ISODate));
715                         else
716                                 params_.name += "@" + saved_date_specifier;
717                 }
718         }
719         else if (params_.type == InsetInfoParams::FIXTIME_INFO) {
720                 string const time_specifier = split(params_.name, '@');
721                 // If an explicit new fix time is specified, use that
722                 // Otherwise, use the old one or, if there is none,
723                 // the current time
724                 if (time_specifier.empty()) {
725                         if (saved_date_specifier.empty())
726                                 params_.name += "@" + fromqstr(QTime::currentTime().toString(Qt::ISODate));
727                         else
728                                 params_.name += "@" + saved_date_specifier;
729                 }
730         }
731 }
732
733
734 void InsetInfo::error(docstring const & err, Language const * lang)
735 {
736         docstring const res = translateIfPossible(err, lang->code());
737         bool const translated = res != err;
738         // If the string is not translated, we use default lang (English)
739         Font const f = translated ? Font(inherit_font, lang) : Font(inherit_font);
740         setText(bformat(res, from_utf8(params_.name)), f, false);
741 }
742
743
744 void InsetInfo::info(docstring const & err, Language const * lang)
745 {
746         docstring const res = translateIfPossible(err, lang->code());
747         bool const translated = res != err;
748         // If the string is not translated, we use default lang (English)
749         Font const f = translated ? Font(inherit_font, lang) : Font(inherit_font);
750         setText(translateIfPossible(err, lang->code()), f, false);
751 }
752
753
754 void InsetInfo::setText(docstring const & str, Language const * lang)
755 {
756         setText(str, Font(inherit_font, lang), false);
757 }
758
759
760 bool InsetInfo::forceLTR(OutputParams const &) const
761 {
762         return params_.force_ltr;
763 }
764
765
766 bool InsetInfo::forceLocalFontSwitch() const
767 {
768         return params_.type == InsetInfoParams::MENU_INFO
769                 || params_.type == InsetInfoParams::SHORTCUTS_INFO
770                 || params_.type == InsetInfoParams::SHORTCUT_INFO
771                 || params_.type == InsetInfoParams::L7N_INFO;
772 }
773
774
775 void InsetInfo::metrics(MetricsInfo & mi, Dimension & dim) const
776 {
777         const_cast<InsetInfo *>(this)->build();
778         InsetCollapsible::metrics(mi, dim);
779 }
780
781
782 void InsetInfo::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
783
784 {
785         // If the Buffer is a clone, then we neither need nor want to do any
786         // of what follows. We want, rather, just to inherit how things were
787         // in the original Buffer. This is especially important for VCS.
788         // Otherwise, we could in principle have different settings here
789         // than in the Buffer we were exporting.
790         if (buffer().isClone())
791                 return;
792         BufferParams const & bp = buffer().params();
793         params_.lang = it.paragraph().getFontSettings(bp, it.pos()).language();
794         InsetCollapsible::updateBuffer(it, utype, deleted);
795 }
796
797
798 void InsetInfo::build()
799 {
800         // If the Buffer is a clone, then we neither need nor want to do any
801         // of what follows. We want, rather, just to inherit how things were
802         // in the original Buffer. This is especially important for VCS.
803         // Otherwise, we could in principle have different settings here
804         // than in the Buffer we were exporting.
805         if (buffer().isClone())
806                 return;
807
808         Language const * tryguilang = languages.getFromCode(Messages::guiLanguage());
809         // Some info insets use the language of the GUI (if available)
810         Language const * guilang = tryguilang ? tryguilang : params_.lang;
811
812         params_.force_ltr = !params_.lang->rightToLeft();
813         // This is just to get the string into the po files
814         docstring gui;
815         switch (params_.type) {
816         case InsetInfoParams::UNKNOWN_INFO:
817                 gui = _("Unknown Info!");
818                 info(from_ascii("Unknown Info!"), params_.lang);
819                 initialized_ = false;
820                 break;
821         case InsetInfoParams::SHORTCUT_INFO:
822         case InsetInfoParams::SHORTCUTS_INFO: {
823                 // shortcuts can change, so we need to re-do this each time
824                 FuncRequest const func = lyxaction.lookupFunc(params_.name);
825                 if (func.action() == LFUN_UNKNOWN_ACTION) {
826                         gui = _("Unknown action %1$s");
827                         error(from_ascii("Unknown action %1$s"), params_.lang);
828                         break;
829                 }
830                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
831                 if (bindings.empty()) {
832                         gui = _("undefined");
833                         info(from_ascii("undefined"), params_.lang);
834                         break;
835                 }
836                 docstring sequence;
837                 docstring seq_untranslated;
838                 if (params_.type == InsetInfoParams::SHORTCUT_INFO) {
839                         sequence = bindings.begin()->print(KeySequence::ForGui);
840                         seq_untranslated = bindings.begin()->print(KeySequence::ForGui, true);
841                 } else {
842                         sequence = theTopLevelKeymap().printBindings(func, KeySequence::ForGui);
843                         seq_untranslated = theTopLevelKeymap().printBindings(func, KeySequence::ForGui, true);
844                 }
845                 // QKeySequence returns special characters for keys on the mac
846                 // Since these are not included in many fonts, we
847                 // re-translate them to textual names (see #10641)
848                 odocstringstream ods;
849                 string const lcode = params_.lang->code();
850                 docstring trans;
851                 bool is_translated = sequence != seq_untranslated;
852                 for (char_type const c : sequence) {
853                         switch(c) {
854                         case 0x21b5://Return
855                                 gui = _("Return[[Key]]");
856                                 is_translated = translateString(from_ascii("Return[[Key]]"), trans, lcode);
857                                 ods << trans;
858                                 break;
859                         case 0x21b9://Tab both directions (Win)
860                                 gui = _("Tab[[Key]]");
861                                 is_translated = translateString(from_ascii("Tab[[Key]]"), trans, lcode);
862                                 ods << trans;
863                                 break;
864                         case 0x21de://Qt::Key_PageUp
865                                 gui = _("PgUp");
866                                 is_translated = translateString(from_ascii("PgUp"), trans, lcode);
867                                 ods << trans;
868                                 break;
869                         case 0x21df://Qt::Key_PageDown
870                                 gui = _("PgDown");
871                                 is_translated = translateString(from_ascii("PgDown"), trans, lcode);
872                                 ods << trans;
873                                 break;
874                         case 0x21e4://Qt::Key_Backtab
875                                 gui = _("Backtab");
876                                 is_translated = translateString(from_ascii("Backtab"), trans, lcode);
877                                 ods << trans;
878                                 break;
879                         case 0x21e5://Qt::Key_Tab
880                                 gui = _("Tab");
881                                 is_translated = translateString(from_ascii("Tab"), trans, lcode);
882                                 ods << trans;
883                                 break;
884                         case 0x21e7://Shift
885                                 gui = _("Shift");
886                                 is_translated = translateString(from_ascii("Shift"), trans, lcode);
887                                 ods << trans;
888                                 break;
889                         case 0x21ea://Qt::Key_CapsLock
890                                 gui = _("CapsLock");
891                                 is_translated = translateString(from_ascii("CapsLock"), trans, lcode);
892                                 ods << trans;
893                                 break;
894                         case 0x2303://Control
895                                 gui = _("Control[[Key]]");
896                                 is_translated = translateString(from_ascii("Control[[Key]]"), trans, lcode);
897                                 ods << trans;
898                                 break;
899                         case 0x2318://CMD
900                                 gui = _("Command[[Key]]");
901                                 is_translated = translateString(from_ascii("Command[[Key]]"), trans, lcode);
902                                 ods << trans;
903                                 break;
904                         case 0x2324://Qt::Key_Enter
905                                 gui = _("Return[[Key]]");
906                                 is_translated = translateString(from_ascii("Return[[Key]]"), trans, lcode);
907                                 ods << trans;
908                                 break;
909                         case 0x2325://Option key
910                                 gui = _("Option[[Key]]");
911                                 is_translated = translateString(from_ascii("Option[[Key]]"), trans, lcode);
912                                 ods << trans;
913                                 break;
914                         case 0x2326://Qt::Key_Delete
915                                 gui = _("Delete[[Key]]");
916                                 is_translated = translateString(from_ascii("Delete[[Key]]"), trans, lcode);
917                                 ods << trans;
918                                 break;
919                         case 0x232b://Qt::Key_Backspace
920                                 gui = _("Fn+Del");
921                                 is_translated = translateString(from_ascii("Fn+Del"), trans, lcode);
922                                 ods << trans;
923                                 break;
924                         case 0x238b://Qt::Key_Escape
925                                 gui = _("Esc");
926                                 is_translated = translateString(from_ascii("Esc"), trans, lcode);
927                                 ods << trans;
928                                 break;
929                         default:
930                                 ods.put(c);
931                         }
932                 }
933                 setText(ods.str(), is_translated ? guilang : nullptr);
934                 params_.force_ltr = !is_translated || (!guilang->rightToLeft() && !params_.lang->rightToLeft());
935                 break;
936         }
937         case InsetInfoParams::LYXRC_INFO: {
938                 // this information could change, if the preferences are changed,
939                 // so we will recalculate each time through.
940                 ostringstream oss;
941                 if (params_.name.empty()) {
942                         gui = _("undefined");
943                         info(from_ascii("undefined"), params_.lang);
944                         break;
945                 }
946                 // FIXME this uses the serialization mechanism to get the info
947                 // we want, which i guess works but is a bit strange.
948                 lyxrc.write(oss, true, params_.name);
949                 string result = oss.str();
950                 if (result.size() < 2) {
951                         gui = _("undefined");
952                         info(from_ascii("undefined"), params_.lang);
953                         break;
954                 }
955                 string::size_type loc = result.rfind("\n", result.size() - 2);
956                 loc = loc == string::npos ? 0 : loc + 1;
957                 if (result.size() < loc + params_.name.size() + 1
958                           || result.substr(loc + 1, params_.name.size()) != params_.name) {
959                         gui = _("undefined");
960                         info(from_ascii("undefined"), params_.lang);
961                         break;
962                 }
963                 // remove leading comments and \\name and space
964                 result = result.substr(loc + params_.name.size() + 2);
965
966                 // remove \n and ""
967                 result = rtrim(result, "\n");
968                 result = trim(result, "\"");
969                 gui = _("not set");
970                 if (result.empty())
971                         result = "not set";
972                 setText(from_utf8(result), params_.lang);
973                 break;
974         }
975         case InsetInfoParams::PACKAGE_INFO:
976                 // only need to do this once.
977                 if (initialized_)
978                         break;
979                 // check in packages.lst
980                 if (LaTeXFeatures::isAvailable(params_.name)) {
981                         gui = _("yes");
982                         info(from_ascii("yes"), params_.lang);
983                 } else {
984                         gui = _("no");
985                         info(from_ascii("no"), params_.lang);
986                 }
987                 initialized_ = true;
988                 break;
989
990         case InsetInfoParams::TEXTCLASS_INFO: {
991                 // the TextClass can change
992                 LayoutFileList const & list = LayoutFileList::get();
993                 bool available = false;
994                 // params_.name is the class name
995                 if (list.haveClass(params_.name))
996                         available = list[params_.name].isTeXClassAvailable();
997                 if (available) {
998                         gui = _("yes");
999                         info(from_ascii("yes"), params_.lang);
1000                 } else {
1001                         gui = _("no");
1002                         info(from_ascii("no"), params_.lang);
1003                 }
1004                 break;
1005         }
1006         case InsetInfoParams::MENU_INFO: {
1007                 // only need to do this once.
1008                 if (initialized_)
1009                         break;
1010                 docstring_list names;
1011                 FuncRequest func = lyxaction.lookupFunc(params_.name);
1012                 if (func.action() == LFUN_UNKNOWN_ACTION) {
1013                         gui = _("Unknown action %1$s");
1014                         error(from_ascii("Unknown action %1$s"), params_.lang);
1015                         break;
1016                 }
1017                 if (func.action() == LFUN_BUFFER_VIEW || func.action() == LFUN_BUFFER_UPDATE)
1018                         // The default output format is in the menu without argument,
1019                         // so strip it here.
1020                         if (func.argument() == from_ascii(buffer().params().getDefaultOutputFormat()))
1021                                 func = FuncRequest(func.action());
1022                 // iterate through the menubackend to find it
1023                 if (!theApp()) {
1024                         gui = _("Can't determine menu entry for action %1$s in batch mode");
1025                         error(from_ascii("Can't determine menu entry for action %1$s in batch mode"), params_.lang);
1026                         initialized_ = true;
1027                         break;
1028                 }
1029                 // and we will not keep trying if we fail
1030                 initialized_ = theApp()->hasBufferView();
1031                 if (!theApp()->searchMenu(func, names)) {
1032                         gui = _("No menu entry for action %1$s");
1033                         error(from_ascii("No menu entry for action %1$s"), params_.lang);
1034                         break;
1035                 }
1036                 // if found, return its path.
1037                 clear();
1038                 Paragraph & par = paragraphs().front();
1039                 Font const f(inherit_font, guilang);
1040                 params_.force_ltr = !guilang->rightToLeft();
1041                 //Font fu = f;
1042                 //fu.fontInfo().setUnderbar(FONT_ON);
1043                 for (docstring const & name : names) {
1044                         // do not insert > for the top level menu item
1045                         if (&name != &names.front())
1046                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
1047                                                 f, Change(Change::UNCHANGED));
1048                         //FIXME: add proper underlines here. This
1049                         // involves rewriting searchMenu used above to
1050                         // return a vector of menus. If we do not do
1051                         // that, we might as well use below
1052                         // Paragraph::insert on each string (JMarc)
1053                         for (char_type c : name)
1054                                 par.insertChar(par.size(), c, f, Change(Change::UNCHANGED));
1055                 }
1056                 break;
1057         }
1058         case InsetInfoParams::L7N_INFO: {
1059                 docstring locstring = _(params_.name);
1060                 // Remove trailing colons
1061                 locstring = rtrim(locstring, ":");
1062                 // Remove menu accelerators
1063                 if (contains(locstring, from_ascii("|"))) {
1064                         docstring nlocstring;
1065                         rsplit(locstring, nlocstring, '|');
1066                         locstring = nlocstring;
1067                 }
1068                 // Remove Qt accelerators, but keep literal ampersands
1069                 locstring = subst(locstring, from_ascii(" & "), from_ascii("</amp;>"));
1070                 locstring = subst(locstring, from_ascii("&"), docstring());
1071                 locstring = subst(locstring, from_ascii("</amp;>"), from_ascii(" & "));
1072                 setText(locstring, guilang);
1073                 params_.force_ltr = !guilang->rightToLeft() && !params_.lang->rightToLeft();
1074                 break;
1075         }
1076         case InsetInfoParams::ICON_INFO: {
1077                 // only need to do this once.
1078                 if (initialized_)
1079                         break;
1080                 // and we will not keep trying if we fail
1081                 initialized_ = true;
1082                 FuncRequest func = lyxaction.lookupFunc(params_.name);
1083                 docstring icon_name = frontend::Application::iconName(func, true);
1084                 FileName file(to_utf8(icon_name));
1085                 if (file.onlyFileNameWithoutExt() == "unknown") {
1086                         string dir = "images";
1087                         FileName file2(imageLibFileSearch(dir, params_.name, "svgz,png"));
1088                         if (!file2.empty())
1089                                 file = file2;
1090                 }
1091                 if (!file.exists())
1092                         break;
1093                 int percent_scale = 100;
1094                 if (use_gui) {
1095                         // Compute the scale factor for the icon such that its
1096                         // width on screen is equal to 1em in pixels.
1097                         // The scale factor is rounded to the integer nearest
1098                         // to the float value of the ratio 100*iconsize/imgsize.
1099                         int imgsize = QImage(toqstr(file.absFileName())).width();
1100                         if (imgsize > 0) {
1101                                 int iconsize = Length(1, Length::EM).inPixels(1);
1102                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
1103                         }
1104                 }
1105                 InsetGraphics * inset = new InsetGraphics(buffer_);
1106                 InsetGraphicsParams igp;
1107                 igp.filename = file;
1108                 igp.lyxscale = percent_scale;
1109                 igp.scale = string();
1110                 igp.width = Length(1, Length::EM);
1111                 if (contains(file.absoluteFilePath(), from_ascii("math"))
1112                     || contains(file.absoluteFilePath(), from_ascii("ert-insert"))
1113                     || suffixIs(file.onlyPath().absoluteFilePath(), from_ascii("ipa")))
1114                         igp.darkModeSensitive = true;
1115                 inset->setParams(igp);
1116                 clear();
1117                 Font const f(inherit_font, params_.lang);
1118                 paragraphs().front().insertInset(0, inset, f,
1119                                                  Change(Change::UNCHANGED));
1120                 break;
1121         }
1122         case InsetInfoParams::BUFFER_INFO: {
1123                 // this could all change, so we will recalculate each time
1124                 if (params_.name == "name")
1125                         setText(from_utf8(buffer().fileName().onlyFileName()), params_.lang);
1126                 else if (params_.name == "name-noext")
1127                         setText(from_utf8(buffer().fileName().onlyFileNameWithoutExt()), params_.lang);
1128                 else if (params_.name == "path")
1129                         setText(from_utf8(os::latex_path(buffer().filePath())), params_.lang);
1130                 else if (params_.name == "class")
1131                         setText(from_utf8(buffer().params().documentClass().name()), params_.lang);
1132                 break;
1133         }
1134         case InsetInfoParams::VCS_INFO: {
1135                 // this information could change, in principle, so we will 
1136                 // recalculate each time through
1137                 if (!buffer().lyxvc().inUse()) {
1138                         gui = _("No version control!");
1139                         info(from_ascii("No version control!"), params_.lang);
1140                         break;
1141                 }
1142                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
1143                 if (params_.name == "revision")
1144                         itype = LyXVC::File;
1145                 else if (params_.name == "revision-abbrev")
1146                         itype = LyXVC::FileAbbrev;
1147                 else if (params_.name == "tree-revision")
1148                         itype = LyXVC::Tree;
1149                 else if (params_.name == "author")
1150                         itype = LyXVC::Author;
1151                 else if (params_.name == "time")
1152                         itype = LyXVC::Time;
1153                 else if (params_.name == "date")
1154                         itype = LyXVC::Date;
1155                 string binfo = buffer().lyxvc().revisionInfo(itype);
1156                 if (binfo.empty()) {
1157                         gui = _("%1$s[[vcs data]] unknown");
1158                         error(from_ascii("%1$s[[vcs data]] unknown"), params_.lang);
1159                 } else
1160                         setText(from_utf8(binfo), params_.lang);
1161                 break;
1162         }
1163         case InsetInfoParams::LYX_INFO:
1164                 // only need to do this once.
1165                 if (initialized_)
1166                         break;
1167                 if (params_.name == "version")
1168                         setText(from_ascii(lyx_version), params_.lang);
1169                 else if (params_.name == "layoutformat")
1170                         setText(convert<docstring>(LAYOUT_FORMAT), params_.lang);
1171                 initialized_ = true;
1172                 break;
1173         case InsetInfoParams::DATE_INFO:
1174         case InsetInfoParams::MODDATE_INFO:
1175         case InsetInfoParams::FIXDATE_INFO: {
1176                 string date_format = params_.name;
1177                 string const date_specifier = (params_.type == InsetInfoParams::FIXDATE_INFO
1178                                                && contains(params_.name, '@'))
1179                                 ? split(params_.name, date_format, '@') : string();
1180                 QDate date;
1181                 if (params_.type == InsetInfoParams::MODDATE_INFO)
1182 #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
1183                         date = QDateTime::fromSecsSinceEpoch(buffer().fileName().lastModified()).date();
1184 #else
1185                         date = QDateTime::fromTime_t(buffer().fileName().lastModified()).date();
1186 #endif
1187                 else if (params_.type == InsetInfoParams::FIXDATE_INFO && !date_specifier.empty())
1188                         date = QDate::fromString(toqstr(date_specifier), Qt::ISODate);
1189                 else
1190                         date = QDate::currentDate();
1191                 setText(params_.getDate(date_format, date), params_.lang);
1192                 break;
1193         }
1194         case InsetInfoParams::TIME_INFO:
1195         case InsetInfoParams::MODTIME_INFO:
1196         case InsetInfoParams::FIXTIME_INFO: {
1197                 string time_format = params_.name;
1198                 string const time_specifier = (params_.type == InsetInfoParams::FIXTIME_INFO
1199                                                && contains(params_.name, '@'))
1200                                 ? split(params_.name, time_format, '@') : string();
1201                 QTime time;
1202                 if (params_.type == InsetInfoParams::MODTIME_INFO)
1203 #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
1204                         time = QDateTime::fromSecsSinceEpoch(buffer().fileName().lastModified()).time();
1205 #else
1206                         time = QDateTime::fromTime_t(buffer().fileName().lastModified()).time();
1207 #endif
1208                 else if (params_.type == InsetInfoParams::FIXTIME_INFO && !time_specifier.empty())
1209                         time = QTime::fromString(toqstr(time_specifier), Qt::ISODate);
1210                 else
1211                         time = QTime::currentTime();
1212                 setText(params_.getTime(time_format, time), params_.lang);
1213                 break;
1214         }
1215         }
1216
1217         // Just to do something with that string
1218         LYXERR(Debug::INFO, "info inset text: " << gui);
1219 }
1220
1221
1222 void InsetInfo::latex(otexstream & os, OutputParams const & runparams) const
1223 {
1224         const_cast<InsetInfo *>(this)->build();
1225         InsetCollapsible::latex(os, runparams);
1226 }
1227
1228
1229 string InsetInfo::contextMenu(BufferView const &, int, int) const
1230 {
1231         //FIXME: We override the implementation of InsetCollapsible,
1232         //because this inset is not a collapsible inset.
1233         return contextMenuName();
1234 }
1235
1236
1237 string InsetInfo::contextMenuName() const
1238 {
1239         return "context-info";
1240 }
1241
1242
1243 } // namespace lyx