]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Fix deprecation warning (from|toTime_t)
[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::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted) {
776         // If the Buffer is a clone, then we neither need nor want to do any
777         // of what follows. We want, rather, just to inherit how things were
778         // in the original Buffer. This is especially important for VCS.
779         // Otherwise, we could in principle have different settings here
780         // than in the Buffer we were exporting.
781         if (buffer().isClone())
782                 return;
783
784         BufferParams const & bp = buffer().params();
785         params_.lang = it.paragraph().getFontSettings(bp, it.pos()).language();
786         Language const * tryguilang = languages.getFromCode(Messages::guiLanguage());
787         // Some info insets use the language of the GUI (if available)
788         Language const * guilang = tryguilang ? tryguilang : params_.lang;
789
790         params_.force_ltr = !params_.lang->rightToLeft();
791         // This is just to get the string into the po files
792         docstring gui;
793         switch (params_.type) {
794         case InsetInfoParams::UNKNOWN_INFO:
795                 gui = _("Unknown Info!");
796                 info(from_ascii("Unknown Info!"), params_.lang);
797                 initialized_ = false;
798                 break;
799         case InsetInfoParams::SHORTCUT_INFO:
800         case InsetInfoParams::SHORTCUTS_INFO: {
801                 // shortcuts can change, so we need to re-do this each time
802                 FuncRequest const func = lyxaction.lookupFunc(params_.name);
803                 if (func.action() == LFUN_UNKNOWN_ACTION) {
804                         gui = _("Unknown action %1$s");
805                         error(from_ascii("Unknown action %1$s"), params_.lang);
806                         break;
807                 }
808                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
809                 if (bindings.empty()) {
810                         gui = _("undefined");
811                         info(from_ascii("undefined"), params_.lang);
812                         break;
813                 }
814                 docstring sequence;
815                 docstring seq_untranslated;
816                 if (params_.type == InsetInfoParams::SHORTCUT_INFO) {
817                         sequence = bindings.begin()->print(KeySequence::ForGui);
818                         seq_untranslated = bindings.begin()->print(KeySequence::ForGui, true);
819                 } else {
820                         sequence = theTopLevelKeymap().printBindings(func, KeySequence::ForGui);
821                         seq_untranslated = theTopLevelKeymap().printBindings(func, KeySequence::ForGui, true);
822                 }
823                 // QKeySequence returns special characters for keys on the mac
824                 // Since these are not included in many fonts, we
825                 // re-translate them to textual names (see #10641)
826                 odocstringstream ods;
827                 string const lcode = params_.lang->code();
828                 docstring trans;
829                 bool is_translated = sequence != seq_untranslated;
830                 for (char_type const c : sequence) {
831                         switch(c) {
832                         case 0x21b5://Return
833                                 gui = _("Return[[Key]]");
834                                 is_translated = translateString(from_ascii("Return[[Key]]"), trans, lcode);
835                                 ods << trans;
836                                 break;
837                         case 0x21b9://Tab both directions (Win)
838                                 gui = _("Tab[[Key]]");
839                                 is_translated = translateString(from_ascii("Tab[[Key]]"), trans, lcode);
840                                 ods << trans;
841                                 break;
842                         case 0x21de://Qt::Key_PageUp
843                                 gui = _("PgUp");
844                                 is_translated = translateString(from_ascii("PgUp"), trans, lcode);
845                                 ods << trans;
846                                 break;
847                         case 0x21df://Qt::Key_PageDown
848                                 gui = _("PgDown");
849                                 is_translated = translateString(from_ascii("PgDown"), trans, lcode);
850                                 ods << trans;
851                                 break;
852                         case 0x21e4://Qt::Key_Backtab
853                                 gui = _("Backtab");
854                                 is_translated = translateString(from_ascii("Backtab"), trans, lcode);
855                                 ods << trans;
856                                 break;
857                         case 0x21e5://Qt::Key_Tab
858                                 gui = _("Tab");
859                                 is_translated = translateString(from_ascii("Tab"), trans, lcode);
860                                 ods << trans;
861                                 break;
862                         case 0x21e7://Shift
863                                 gui = _("Shift");
864                                 is_translated = translateString(from_ascii("Shift"), trans, lcode);
865                                 ods << trans;
866                                 break;
867                         case 0x21ea://Qt::Key_CapsLock
868                                 gui = _("CapsLock");
869                                 is_translated = translateString(from_ascii("CapsLock"), trans, lcode);
870                                 ods << trans;
871                                 break;
872                         case 0x2303://Control
873                                 gui = _("Control[[Key]]");
874                                 is_translated = translateString(from_ascii("Control[[Key]]"), trans, lcode);
875                                 ods << trans;
876                                 break;
877                         case 0x2318://CMD
878                                 gui = _("Command[[Key]]");
879                                 is_translated = translateString(from_ascii("Command[[Key]]"), trans, lcode);
880                                 ods << trans;
881                                 break;
882                         case 0x2324://Qt::Key_Enter
883                                 gui = _("Return[[Key]]");
884                                 is_translated = translateString(from_ascii("Return[[Key]]"), trans, lcode);
885                                 ods << trans;
886                                 break;
887                         case 0x2325://Option key
888                                 gui = _("Option[[Key]]");
889                                 is_translated = translateString(from_ascii("Option[[Key]]"), trans, lcode);
890                                 ods << trans;
891                                 break;
892                         case 0x2326://Qt::Key_Delete
893                                 gui = _("Delete[[Key]]");
894                                 is_translated = translateString(from_ascii("Delete[[Key]]"), trans, lcode);
895                                 ods << trans;
896                                 break;
897                         case 0x232b://Qt::Key_Backspace
898                                 gui = _("Fn+Del");
899                                 is_translated = translateString(from_ascii("Fn+Del"), trans, lcode);
900                                 ods << trans;
901                                 break;
902                         case 0x238b://Qt::Key_Escape
903                                 gui = _("Esc");
904                                 is_translated = translateString(from_ascii("Esc"), trans, lcode);
905                                 ods << trans;
906                                 break;
907                         default:
908                                 ods.put(c);
909                         }
910                 }
911                 setText(ods.str(), is_translated ? guilang : nullptr);
912                 params_.force_ltr = !is_translated || (!guilang->rightToLeft() && !params_.lang->rightToLeft());
913                 break;
914         }
915         case InsetInfoParams::LYXRC_INFO: {
916                 // this information could change, if the preferences are changed,
917                 // so we will recalculate each time through.
918                 ostringstream oss;
919                 if (params_.name.empty()) {
920                         gui = _("undefined");
921                         info(from_ascii("undefined"), params_.lang);
922                         break;
923                 }
924                 // FIXME this uses the serialization mechanism to get the info
925                 // we want, which i guess works but is a bit strange.
926                 lyxrc.write(oss, true, params_.name);
927                 string result = oss.str();
928                 if (result.size() < 2) {
929                         gui = _("undefined");
930                         info(from_ascii("undefined"), params_.lang);
931                         break;
932                 }
933                 string::size_type loc = result.rfind("\n", result.size() - 2);
934                 loc = loc == string::npos ? 0 : loc + 1;
935                 if (result.size() < loc + params_.name.size() + 1
936                           || result.substr(loc + 1, params_.name.size()) != params_.name) {
937                         gui = _("undefined");
938                         info(from_ascii("undefined"), params_.lang);
939                         break;
940                 }
941                 // remove leading comments and \\name and space
942                 result = result.substr(loc + params_.name.size() + 2);
943
944                 // remove \n and ""
945                 result = rtrim(result, "\n");
946                 result = trim(result, "\"");
947                 gui = _("not set");
948                 if (result.empty())
949                         result = "not set";
950                 setText(from_utf8(result), params_.lang);
951                 break;
952         }
953         case InsetInfoParams::PACKAGE_INFO:
954                 // only need to do this once.
955                 if (initialized_)
956                         break;
957                 // check in packages.lst
958                 if (LaTeXFeatures::isAvailable(params_.name)) {
959                         gui = _("yes");
960                         info(from_ascii("yes"), params_.lang);
961                 } else {
962                         gui = _("no");
963                         info(from_ascii("no"), params_.lang);
964                 }
965                 initialized_ = true;
966                 break;
967
968         case InsetInfoParams::TEXTCLASS_INFO: {
969                 // the TextClass can change
970                 LayoutFileList const & list = LayoutFileList::get();
971                 bool available = false;
972                 // params_.name is the class name
973                 if (list.haveClass(params_.name))
974                         available = list[params_.name].isTeXClassAvailable();
975                 if (available) {
976                         gui = _("yes");
977                         info(from_ascii("yes"), params_.lang);
978                 } else {
979                         gui = _("no");
980                         info(from_ascii("no"), params_.lang);
981                 }
982                 break;
983         }
984         case InsetInfoParams::MENU_INFO: {
985                 // only need to do this once.
986                 if (initialized_)
987                         break;
988                 docstring_list names;
989                 FuncRequest func = lyxaction.lookupFunc(params_.name);
990                 if (func.action() == LFUN_UNKNOWN_ACTION) {
991                         gui = _("Unknown action %1$s");
992                         error(from_ascii("Unknown action %1$s"), params_.lang);
993                         break;
994                 }
995                 if (func.action() == LFUN_BUFFER_VIEW || func.action() == LFUN_BUFFER_UPDATE)
996                         // The default output format is in the menu without argument,
997                         // so strip it here.
998                         if (func.argument() == from_ascii(buffer().params().getDefaultOutputFormat()))
999                                 func = FuncRequest(func.action());
1000                 // iterate through the menubackend to find it
1001                 if (!theApp()) {
1002                         gui = _("Can't determine menu entry for action %1$s in batch mode");
1003                         error(from_ascii("Can't determine menu entry for action %1$s in batch mode"), params_.lang);
1004                         initialized_ = true;
1005                         break;
1006                 }
1007                 // and we will not keep trying if we fail
1008                 initialized_ = theApp()->hasBufferView();
1009                 if (!theApp()->searchMenu(func, names)) {
1010                         gui = _("No menu entry for action %1$s");
1011                         error(from_ascii("No menu entry for action %1$s"), params_.lang);
1012                         break;
1013                 }
1014                 // if found, return its path.
1015                 clear();
1016                 Paragraph & par = paragraphs().front();
1017                 Font const f(inherit_font, guilang);
1018                 params_.force_ltr = !guilang->rightToLeft();
1019                 //Font fu = f;
1020                 //fu.fontInfo().setUnderbar(FONT_ON);
1021                 for (docstring const & name : names) {
1022                         // do not insert > for the top level menu item
1023                         if (&name != &names.front())
1024                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
1025                                                 f, Change(Change::UNCHANGED));
1026                         //FIXME: add proper underlines here. This
1027                         // involves rewriting searchMenu used above to
1028                         // return a vector of menus. If we do not do
1029                         // that, we might as well use below
1030                         // Paragraph::insert on each string (JMarc)
1031                         for (char_type c : name)
1032                                 par.insertChar(par.size(), c, f, Change(Change::UNCHANGED));
1033                 }
1034                 break;
1035         }
1036         case InsetInfoParams::L7N_INFO: {
1037                 docstring locstring = _(params_.name);
1038                 // Remove trailing colons
1039                 locstring = rtrim(locstring, ":");
1040                 // Remove menu accelerators
1041                 if (contains(locstring, from_ascii("|"))) {
1042                         docstring nlocstring;
1043                         rsplit(locstring, nlocstring, '|');
1044                         locstring = nlocstring;
1045                 }
1046                 // Remove Qt accelerators, but keep literal ampersands
1047                 locstring = subst(locstring, from_ascii(" & "), from_ascii("</amp;>"));
1048                 locstring = subst(locstring, from_ascii("&"), docstring());
1049                 locstring = subst(locstring, from_ascii("</amp;>"), from_ascii(" & "));
1050                 setText(locstring, guilang);
1051                 params_.force_ltr = !guilang->rightToLeft() && !params_.lang->rightToLeft();
1052                 break;
1053         }
1054         case InsetInfoParams::ICON_INFO: {
1055                 // only need to do this once.
1056                 if (initialized_)
1057                         break;
1058                 // and we will not keep trying if we fail
1059                 initialized_ = true;
1060                 FuncRequest func = lyxaction.lookupFunc(params_.name);
1061                 docstring icon_name = frontend::Application::iconName(func, true);
1062                 FileName file(to_utf8(icon_name));
1063                 if (file.onlyFileNameWithoutExt() == "unknown") {
1064                         string dir = "images";
1065                         FileName file2(imageLibFileSearch(dir, params_.name, "svgz,png"));
1066                         if (!file2.empty())
1067                                 file = file2;
1068                 }
1069                 if (!file.exists())
1070                         break;
1071                 int percent_scale = 100;
1072                 if (use_gui) {
1073                         // Compute the scale factor for the icon such that its
1074                         // width on screen is equal to 1em in pixels.
1075                         // The scale factor is rounded to the integer nearest
1076                         // to the float value of the ratio 100*iconsize/imgsize.
1077                         int imgsize = QImage(toqstr(file.absFileName())).width();
1078                         if (imgsize > 0) {
1079                                 int iconsize = Length(1, Length::EM).inPixels(1);
1080                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
1081                         }
1082                 }
1083                 InsetGraphics * inset = new InsetGraphics(buffer_);
1084                 InsetGraphicsParams igp;
1085                 igp.filename = file;
1086                 igp.lyxscale = percent_scale;
1087                 igp.scale = string();
1088                 igp.width = Length(1, Length::EM);
1089                 if (contains(file.absoluteFilePath(), from_ascii("math"))
1090                     || contains(file.absoluteFilePath(), from_ascii("ert-insert"))
1091                     || suffixIs(file.onlyPath().absoluteFilePath(), from_ascii("ipa")))
1092                         igp.darkModeSensitive = true;
1093                 inset->setParams(igp);
1094                 clear();
1095                 Font const f(inherit_font, params_.lang);
1096                 paragraphs().front().insertInset(0, inset, f,
1097                                                  Change(Change::UNCHANGED));
1098                 break;
1099         }
1100         case InsetInfoParams::BUFFER_INFO: {
1101                 // this could all change, so we will recalculate each time
1102                 if (params_.name == "name")
1103                         setText(from_utf8(buffer().fileName().onlyFileName()), params_.lang);
1104                 else if (params_.name == "name-noext")
1105                         setText(from_utf8(buffer().fileName().onlyFileNameWithoutExt()), params_.lang);
1106                 else if (params_.name == "path")
1107                         setText(from_utf8(os::latex_path(buffer().filePath())), params_.lang);
1108                 else if (params_.name == "class")
1109                         setText(from_utf8(bp.documentClass().name()), params_.lang);
1110                 break;
1111         }
1112         case InsetInfoParams::VCS_INFO: {
1113                 // this information could change, in principle, so we will 
1114                 // recalculate each time through
1115                 if (!buffer().lyxvc().inUse()) {
1116                         gui = _("No version control!");
1117                         info(from_ascii("No version control!"), params_.lang);
1118                         break;
1119                 }
1120                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
1121                 if (params_.name == "revision")
1122                         itype = LyXVC::File;
1123                 else if (params_.name == "revision-abbrev")
1124                         itype = LyXVC::FileAbbrev;
1125                 else if (params_.name == "tree-revision")
1126                         itype = LyXVC::Tree;
1127                 else if (params_.name == "author")
1128                         itype = LyXVC::Author;
1129                 else if (params_.name == "time")
1130                         itype = LyXVC::Time;
1131                 else if (params_.name == "date")
1132                         itype = LyXVC::Date;
1133                 string binfo = buffer().lyxvc().revisionInfo(itype);
1134                 if (binfo.empty()) {
1135                         gui = _("%1$s[[vcs data]] unknown");
1136                         error(from_ascii("%1$s[[vcs data]] unknown"), params_.lang);
1137                 } else
1138                         setText(from_utf8(binfo), params_.lang);
1139                 break;
1140         }
1141         case InsetInfoParams::LYX_INFO:
1142                 // only need to do this once.
1143                 if (initialized_)
1144                         break;
1145                 if (params_.name == "version")
1146                         setText(from_ascii(lyx_version), params_.lang);
1147                 else if (params_.name == "layoutformat")
1148                         setText(convert<docstring>(LAYOUT_FORMAT), params_.lang);
1149                 initialized_ = true;
1150                 break;
1151         case InsetInfoParams::DATE_INFO:
1152         case InsetInfoParams::MODDATE_INFO:
1153         case InsetInfoParams::FIXDATE_INFO: {
1154                 string date_format = params_.name;
1155                 string const date_specifier = (params_.type == InsetInfoParams::FIXDATE_INFO
1156                                                && contains(params_.name, '@'))
1157                                 ? split(params_.name, date_format, '@') : string();
1158                 QDate date;
1159                 if (params_.type == InsetInfoParams::MODDATE_INFO)
1160 #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
1161                         date = QDateTime::fromSecsSinceEpoch(buffer().fileName().lastModified()).date();
1162 #else
1163                         date = QDateTime::fromTime_t(buffer().fileName().lastModified()).date();
1164 #endif
1165                 else if (params_.type == InsetInfoParams::FIXDATE_INFO && !date_specifier.empty())
1166                         date = QDate::fromString(toqstr(date_specifier), Qt::ISODate);
1167                 else
1168                         date = QDate::currentDate();
1169                 setText(params_.getDate(date_format, date), params_.lang);
1170                 break;
1171         }
1172         case InsetInfoParams::TIME_INFO:
1173         case InsetInfoParams::MODTIME_INFO:
1174         case InsetInfoParams::FIXTIME_INFO: {
1175                 string time_format = params_.name;
1176                 string const time_specifier = (params_.type == InsetInfoParams::FIXTIME_INFO
1177                                                && contains(params_.name, '@'))
1178                                 ? split(params_.name, time_format, '@') : string();
1179                 QTime time;
1180                 if (params_.type == InsetInfoParams::MODTIME_INFO)
1181 #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
1182                         time = QDateTime::fromSecsSinceEpoch(buffer().fileName().lastModified()).time();
1183 #else
1184                         time = QDateTime::fromTime_t(buffer().fileName().lastModified()).time();
1185 #endif
1186                 else if (params_.type == InsetInfoParams::FIXTIME_INFO && !time_specifier.empty())
1187                         time = QTime::fromString(toqstr(time_specifier), Qt::ISODate);
1188                 else
1189                         time = QTime::currentTime();
1190                 setText(params_.getTime(time_format, time), params_.lang);
1191                 break;
1192         }
1193         }
1194
1195         // Just to do something with that string
1196         LYXERR(Debug::INFO, "info inset text: " << gui);
1197         InsetCollapsible::updateBuffer(it, utype, deleted);
1198 }
1199
1200
1201 string InsetInfo::contextMenu(BufferView const &, int, int) const
1202 {
1203         //FIXME: We override the implementation of InsetCollapsible,
1204         //because this inset is not a collapsible inset.
1205         return contextMenuName();
1206 }
1207
1208
1209 string InsetInfo::contextMenuName() const
1210 {
1211         return "context-info";
1212 }
1213
1214
1215 } // namespace lyx