]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Refactor OutputParams
[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                         date = QDateTime::fromTime_t(buf->fileName().lastModified()).date();
301                 else if (itype == "fixdate" && !dt.empty()) {
302                         QDate const gdate = QDate::fromString(toqstr(dt), Qt::ISODate);
303                         date = (gdate.isValid()) ? gdate : QDate::currentDate();
304                 } else
305                         date = QDate::currentDate();
306                 result.push_back(make_pair("long",getDate("long", date)));
307                 result.push_back(make_pair("short", getDate("short", date)));
308                 result.push_back(make_pair("loclong", getDate("loclong", date)));
309                 result.push_back(make_pair("locmedium", getDate("locmedium", date)));
310                 result.push_back(make_pair("locshort", getDate("locshort", date)));
311                 result.push_back(make_pair("ISO", getDate("ISO", date)));
312                 result.push_back(make_pair("yyyy", getDate("yyyy", date)));
313                 result.push_back(make_pair("MMMM", getDate("MMMM", date)));
314                 result.push_back(make_pair("MMM", getDate("MMM", date)));
315                 result.push_back(make_pair("dddd", getDate("dddd", date)));
316                 result.push_back(make_pair("ddd", getDate("ddd", date)));
317                 result.push_back(make_pair("custom", _("Custom")));
318                 break;
319         }
320         case FIXTIME_INFO:
321         case TIME_INFO:
322         case MODTIME_INFO: {
323                 string const tt = split(name, '@');
324                 QTime time;
325                 if (itype == "modtime")
326                         time = QDateTime::fromTime_t(buf->fileName().lastModified()).time();
327                 else if (itype == "fixtime" && !tt.empty()) {
328                         QTime const gtime = QTime::fromString(toqstr(tt), Qt::ISODate);
329                         time = (gtime.isValid()) ? gtime : QTime::currentTime();
330                 } else
331                         time = QTime::currentTime();
332                 result.push_back(make_pair("long",getTime("long", time)));
333                 result.push_back(make_pair("short", getTime("short", time)));
334                 result.push_back(make_pair("ISO", getTime("ISO", time)));
335                 result.push_back(make_pair("custom", _("Custom")));
336                 break;
337         }
338         }
339
340         return result;
341 }
342
343
344 bool InsetInfoParams::validateArgument(Buffer const * buf, docstring const & arg,
345                                        bool const usedefaults) const
346 {
347         string type;
348         string name = trim(split(to_utf8(arg), type, ' '));
349         if (name.empty() && usedefaults)
350                 name = defaultValueTranslator().find(type);
351
352         switch (nameTranslator().find(type)) {
353         case UNKNOWN_INFO:
354                 return false;
355
356         case SHORTCUT_INFO:
357         case SHORTCUTS_INFO:
358         case MENU_INFO: {
359                 FuncRequest func = lyxaction.lookupFunc(name);
360                 return func.action() != LFUN_UNKNOWN_ACTION;
361         }
362
363         case L7N_INFO:
364                 return !name.empty();
365
366         case ICON_INFO: {
367                 FuncCode const action = lyxaction.lookupFunc(name).action();
368                 if (action == LFUN_UNKNOWN_ACTION) {
369                         string dir = "images";
370                         return !imageLibFileSearch(dir, name, "svgz,png").empty();
371                 }
372                 return true;
373         }
374
375         case LYXRC_INFO: {
376                 set<string> rcs = lyxrc.getRCs();
377                 return rcs.find(name) != rcs.end();
378         }
379
380         case PACKAGE_INFO:
381         case TEXTCLASS_INFO:
382                 return true;
383
384         case BUFFER_INFO:
385                 return (name == "name" || name == "name-noext"
386                         || name == "path" || name == "class");
387
388         case VCS_INFO:
389                 if (name == "revision" || name == "revision-abbrev" || name == "tree-revision"
390                     || name == "author" || name == "date" || name == "time")
391                         return buf->lyxvc().inUse();
392                 return false;
393
394         case LYX_INFO:
395                 return name == "version" || name == "layoutformat";
396
397         case FIXDATE_INFO: {
398                 string date;
399                 string piece;
400                 date = split(name, piece, '@');
401                 if (!date.empty() && !QDate::fromString(toqstr(date), Qt::ISODate).isValid())
402                         return false;
403                 if (!piece.empty())
404                         name = piece;
405         }
406         // fall through
407         case DATE_INFO:
408         case MODDATE_INFO: {
409                 if (name == "long" || name == "short" || name == "ISO")
410                         return true;
411                 else {
412                         QDate date = QDate::currentDate();
413                         return !date.toString(toqstr(name)).isEmpty();
414                 }
415         }
416         case FIXTIME_INFO: {
417                 string time;
418                 string piece;
419                 time = split(name, piece, '@');
420                 if (!time.empty() && !QTime::fromString(toqstr(time), Qt::ISODate).isValid())
421                         return false;
422                 if (!piece.empty())
423                         name = piece;
424         }
425         // fall through
426         case TIME_INFO:
427         case MODTIME_INFO: {
428                 if (name == "long" || name == "short" || name == "ISO")
429                         return true;
430                 else {
431                         QTime time = QTime::currentTime();
432                         return !time.toString(toqstr(name)).isEmpty();
433                 }
434         }
435         }
436
437         return false;
438 }
439
440
441
442
443 string InsetInfoParams::infoType() const
444 {
445         return nameTranslator().find(type);
446 }
447
448
449
450 /////////////////////////////////////////////////////////////////////////
451 //
452 // InsetInfo
453 //
454 /////////////////////////////////////////////////////////////////////////
455
456
457
458 InsetInfo::InsetInfo(Buffer * buf, string const & info)
459         : InsetCollapsible(buf), initialized_(false)
460 {
461         params_.type = InsetInfoParams::UNKNOWN_INFO;
462         params_.force_ltr = false;
463         setInfo(info);
464         status_ = Collapsed;
465 }
466
467
468 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
469 {
470         // do not allow the cursor to be set in this Inset
471         return Inset::editXY(cur, x, y);
472 }
473
474
475 docstring InsetInfo::layoutName() const
476 {
477         return from_ascii("Info:" + params_.infoType());
478 }
479
480
481 docstring InsetInfo::toolTip(BufferView const &, int, int) const
482 {
483         docstring result;
484         switch (nameTranslator().find(params_.infoType())) {
485         case InsetInfoParams::UNKNOWN_INFO:
486                 result = _("Invalid information inset");
487                 break;
488         case InsetInfoParams::SHORTCUT_INFO:
489                 result = bformat(_("The keybard shortcut for the function '%1$s'"),
490                                 from_utf8(params_.name));
491                 break;
492         case InsetInfoParams::SHORTCUTS_INFO:
493                 result = bformat(_("The keybard shortcuts for the function '%1$s'"),
494                                 from_utf8(params_.name));
495                 break;
496         case InsetInfoParams::MENU_INFO: 
497                 result = bformat(_("The menu location for the function '%1$s'"),
498                                 from_utf8(params_.name));
499                 break;
500         case InsetInfoParams::L7N_INFO: 
501                 result = bformat(_("The localization for the string '%1$s'"),
502                                 from_utf8(params_.name));
503                 break;
504         case InsetInfoParams::ICON_INFO:
505                 result = bformat(_("The toolbar icon for the function '%1$s'"),
506                                 from_utf8(params_.name));
507                 break;
508         case InsetInfoParams::LYXRC_INFO:
509                 result = bformat(_("The preference setting for the preference key '%1$s'"),
510                                 from_utf8(params_.name));
511                 break;
512         case InsetInfoParams::PACKAGE_INFO:
513                 result = bformat(_("Availability of the LaTeX package '%1$s'"),
514                                 from_utf8(params_.name));
515                 break;
516         case InsetInfoParams::TEXTCLASS_INFO:
517                 result = bformat(_("Availability of the LaTeX class '%1$s'"),
518                                 from_utf8(params_.name));
519                 break;
520         case InsetInfoParams::BUFFER_INFO:
521                 if (params_.name == "name")
522                         result = _("The name of this file (incl. extension)");
523                 else if (params_.name == "name-noext")
524                         result = _("The name of this file (without extension)");
525                 else if (params_.name == "path")
526                         result = _("The path where this file is saved");
527                 else if (params_.name == "class")
528                         result = _("The class this document uses");
529                 break;
530         case InsetInfoParams::VCS_INFO:
531                 if (params_.name == "revision")
532                         result = _("Version control revision");
533                 else if (params_.name == "revision-abbrev")
534                         result = _("Version control abbreviated revision");
535                 else if (params_.name == "tree-revision")
536                         result = _("Version control tree revision");
537                 else if (params_.name == "author")
538                          result = _("Version control author");
539                 else if (params_.name == "date")
540                         result = _("Version control date");
541                 else if (params_.name == "time")
542                         result = _("Version control time");
543                 break;
544         case InsetInfoParams::LYX_INFO:
545                 if (params_.name == "version")
546                         result = _("The current LyX version");
547                 else if (params_.name == "layoutformat")
548                         result = _("The current LyX layout format");
549                 break;
550         case InsetInfoParams::DATE_INFO:
551                 result = _("The current date");
552                 break;
553         case InsetInfoParams::MODDATE_INFO:
554                 result = _("The date of last save");
555                 break;
556         case InsetInfoParams::FIXDATE_INFO:
557                 result = _("A static date");
558                 break;
559         case InsetInfoParams::TIME_INFO:
560                 result = _("The current time");
561                 break;
562         case InsetInfoParams::MODTIME_INFO:
563                 result = _("The time of last save");
564                 break;
565         case InsetInfoParams::FIXTIME_INFO:
566                 result = _("A static time");
567                 break;
568         }
569
570         return result;
571 }
572
573
574 void InsetInfo::read(Lexer & lex)
575 {
576         string token;
577         while (lex.isOK()) {
578                 lex.next();
579                 token = lex.getString();
580                 if (token == "type") {
581                         lex.next();
582                         token = lex.getString();
583                         params_.type = nameTranslator().find(token);
584                 } else if (token == "arg") {
585                         lex.next(true);
586                         params_.name = lex.getString();
587                 } else if (token == "\\end_inset")
588                         break;
589         }
590         if (token != "\\end_inset") {
591                 lex.printError("Missing \\end_inset at this point");
592                 throw ExceptionMessage(WarningException,
593                         _("Missing \\end_inset at this point."),
594                         from_utf8(token));
595         }
596 }
597
598
599 void InsetInfo::write(ostream & os) const
600 {
601         os << "Info\ntype  \"" << params_.infoType()
602            << "\"\narg   " << Lexer::quoteString(params_.name);
603 }
604
605
606 bool InsetInfo::showInsetDialog(BufferView * bv) const
607 {
608         bv->showDialog("info");
609         return true;
610 }
611
612
613 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
614                 FuncStatus & flag) const
615 {
616         switch (cmd.action()) {
617         case LFUN_INSET_SETTINGS:
618                 return InsetCollapsible::getStatus(cur, cmd, flag);
619
620         case LFUN_INSET_DIALOG_UPDATE:
621         case LFUN_INSET_COPY_AS:
622         case LFUN_INSET_DISSOLVE:
623                 flag.setEnabled(true);
624                 return true;
625
626         case LFUN_INSET_MODIFY:
627                 if (nameTranslator().find(cmd.getArg(0)) == InsetInfoParams::UNKNOWN_INFO)
628                         return Inset::getStatus(cur, cmd, flag);
629                 if (params_.validateArgument(&buffer(), cmd.argument())) {
630                         flag.setEnabled(true);
631                         string typestr;
632                         string name = trim(split(to_utf8(cmd.argument()), typestr, ' '));
633                         InsetInfoParams::info_type type = nameTranslator().find(typestr);
634                         string origname = params_.name;
635                         if (type == InsetInfoParams::FIXDATE_INFO
636                             || type == InsetInfoParams::FIXTIME_INFO)
637                                 split(params_.name, origname, '@');
638                         flag.setOnOff(type == params_.type && name == origname);
639                         return true;
640                 }
641                 //fall through
642
643         default:
644                 return false;
645         }
646 }
647
648
649 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
650 {
651         switch (cmd.action()) {
652         case LFUN_INSET_MODIFY:
653                 if (nameTranslator().find(cmd.getArg(0)) == InsetInfoParams::UNKNOWN_INFO) {
654                         cur.undispatched();
655                         break;
656                 }
657                 cur.recordUndo();
658                 setInfo(to_utf8(cmd.argument()));
659                 cur.forceBufferUpdate();
660                 initialized_ = false;
661                 break;
662
663         case LFUN_INSET_COPY_AS: {
664                 cap::clearSelection();
665                 Cursor copy(cur);
666                 copy.pushBackward(*this);
667                 copy.pit() = 0;
668                 copy.pos() = 0;
669                 copy.resetAnchor();
670                 copy.pit() = copy.lastpit();
671                 copy.pos() = copy.lastpos();
672                 copy.setSelection();
673                 cap::copySelection(copy);
674                 break;
675         }
676
677         default:
678                 InsetCollapsible::doDispatch(cur, cmd);
679                 break;
680         }
681 }
682
683
684 void InsetInfo::setInfo(string const & info)
685 {
686         if (info.empty())
687                 return;
688
689         string saved_date_specifier;
690         // Store old date specifier for potential re-use
691         if (!params_.name.empty())
692                 saved_date_specifier = split(params_.name, '@');
693         // info_type name
694         string type;
695         params_.name = trim(split(info, type, ' '));
696         params_.type = nameTranslator().find(type);
697         if (params_.name.empty())
698                 params_.name = defaultValueTranslator().find(params_.type);
699         if (params_.type == InsetInfoParams::FIXDATE_INFO) {
700                 string const date_specifier = split(params_.name, '@');
701                 // If an explicit new fix date is specified, use that
702                 // Otherwise, use the old one or, if there is none,
703                 // the current date
704                 if (date_specifier.empty()) {
705                         if (saved_date_specifier.empty())
706                                 params_.name += "@" + fromqstr(QDate::currentDate().toString(Qt::ISODate));
707                         else
708                                 params_.name += "@" + saved_date_specifier;
709                 }
710         }
711         else if (params_.type == InsetInfoParams::FIXTIME_INFO) {
712                 string const time_specifier = split(params_.name, '@');
713                 // If an explicit new fix time is specified, use that
714                 // Otherwise, use the old one or, if there is none,
715                 // the current time
716                 if (time_specifier.empty()) {
717                         if (saved_date_specifier.empty())
718                                 params_.name += "@" + fromqstr(QTime::currentTime().toString(Qt::ISODate));
719                         else
720                                 params_.name += "@" + saved_date_specifier;
721                 }
722         }
723 }
724
725
726 void InsetInfo::error(docstring const & err, Language const * lang)
727 {
728         docstring const res = translateIfPossible(err, lang->code());
729         bool const translated = res != err;
730         // If the string is not translated, we use default lang (English)
731         Font const f = translated ? Font(inherit_font, lang) : Font(inherit_font);
732         setText(bformat(res, from_utf8(params_.name)), f, false);
733 }
734
735
736 void InsetInfo::info(docstring const & err, Language const * lang)
737 {
738         docstring const res = translateIfPossible(err, lang->code());
739         bool const translated = res != err;
740         // If the string is not translated, we use default lang (English)
741         Font const f = translated ? Font(inherit_font, lang) : Font(inherit_font);
742         setText(translateIfPossible(err, lang->code()), f, false);
743 }
744
745
746 void InsetInfo::setText(docstring const & str, Language const * lang)
747 {
748         setText(str, Font(inherit_font, lang), false);
749 }
750
751
752 bool InsetInfo::forceLTR(OutputParams const &) const
753 {
754         return params_.force_ltr;
755 }
756
757
758 bool InsetInfo::forceLocalFontSwitch() const
759 {
760         return params_.type == InsetInfoParams::MENU_INFO
761                 || params_.type == InsetInfoParams::SHORTCUTS_INFO
762                 || params_.type == InsetInfoParams::SHORTCUT_INFO
763                 || params_.type == InsetInfoParams::L7N_INFO;
764 }
765
766
767 void InsetInfo::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted) {
768         // If the Buffer is a clone, then we neither need nor want to do any
769         // of what follows. We want, rather, just to inherit how things were
770         // in the original Buffer. This is especially important for VCS.
771         // Otherwise, we could in principle have different settings here
772         // than in the Buffer we were exporting.
773         if (buffer().isClone())
774                 return;
775
776         BufferParams const & bp = buffer().params();
777         params_.lang = it.paragraph().getFontSettings(bp, it.pos()).language();
778         Language const * tryguilang = languages.getFromCode(Messages::guiLanguage());
779         // Some info insets use the language of the GUI (if available)
780         Language const * guilang = tryguilang ? tryguilang : params_.lang;
781
782         params_.force_ltr = !params_.lang->rightToLeft();
783         // This is just to get the string into the po files
784         docstring gui;
785         switch (params_.type) {
786         case InsetInfoParams::UNKNOWN_INFO:
787                 gui = _("Unknown Info!");
788                 info(from_ascii("Unknown Info!"), params_.lang);
789                 initialized_ = false;
790                 break;
791         case InsetInfoParams::SHORTCUT_INFO:
792         case InsetInfoParams::SHORTCUTS_INFO: {
793                 // shortcuts can change, so we need to re-do this each time
794                 FuncRequest const func = lyxaction.lookupFunc(params_.name);
795                 if (func.action() == LFUN_UNKNOWN_ACTION) {
796                         gui = _("Unknown action %1$s");
797                         error(from_ascii("Unknown action %1$s"), params_.lang);
798                         break;
799                 }
800                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
801                 if (bindings.empty()) {
802                         gui = _("undefined");
803                         info(from_ascii("undefined"), params_.lang);
804                         break;
805                 }
806                 docstring sequence;
807                 docstring seq_untranslated;
808                 if (params_.type == InsetInfoParams::SHORTCUT_INFO) {
809                         sequence = bindings.begin()->print(KeySequence::ForGui);
810                         seq_untranslated = bindings.begin()->print(KeySequence::ForGui, true);
811                 } else {
812                         sequence = theTopLevelKeymap().printBindings(func, KeySequence::ForGui);
813                         seq_untranslated = theTopLevelKeymap().printBindings(func, KeySequence::ForGui, true);
814                 }
815                 // QKeySequence returns special characters for keys on the mac
816                 // Since these are not included in many fonts, we
817                 // re-translate them to textual names (see #10641)
818                 odocstringstream ods;
819                 string const lcode = params_.lang->code();
820                 docstring trans;
821                 bool is_translated = sequence != seq_untranslated;
822                 for (char_type const c : sequence) {
823                         switch(c) {
824                         case 0x21b5://Return
825                                 gui = _("Return[[Key]]");
826                                 is_translated = translateString(from_ascii("Return[[Key]]"), trans, lcode);
827                                 ods << trans;
828                                 break;
829                         case 0x21b9://Tab both directions (Win)
830                                 gui = _("Tab[[Key]]");
831                                 is_translated = translateString(from_ascii("Tab[[Key]]"), trans, lcode);
832                                 ods << trans;
833                                 break;
834                         case 0x21de://Qt::Key_PageUp
835                                 gui = _("PgUp");
836                                 is_translated = translateString(from_ascii("PgUp"), trans, lcode);
837                                 ods << trans;
838                                 break;
839                         case 0x21df://Qt::Key_PageDown
840                                 gui = _("PgDown");
841                                 is_translated = translateString(from_ascii("PgDown"), trans, lcode);
842                                 ods << trans;
843                                 break;
844                         case 0x21e4://Qt::Key_Backtab
845                                 gui = _("Backtab");
846                                 is_translated = translateString(from_ascii("Backtab"), trans, lcode);
847                                 ods << trans;
848                                 break;
849                         case 0x21e5://Qt::Key_Tab
850                                 gui = _("Tab");
851                                 is_translated = translateString(from_ascii("Tab"), trans, lcode);
852                                 ods << trans;
853                                 break;
854                         case 0x21e7://Shift
855                                 gui = _("Shift");
856                                 is_translated = translateString(from_ascii("Shift"), trans, lcode);
857                                 ods << trans;
858                                 break;
859                         case 0x21ea://Qt::Key_CapsLock
860                                 gui = _("CapsLock");
861                                 is_translated = translateString(from_ascii("CapsLock"), trans, lcode);
862                                 ods << trans;
863                                 break;
864                         case 0x2303://Control
865                                 gui = _("Control[[Key]]");
866                                 is_translated = translateString(from_ascii("Control[[Key]]"), trans, lcode);
867                                 ods << trans;
868                                 break;
869                         case 0x2318://CMD
870                                 gui = _("Command[[Key]]");
871                                 is_translated = translateString(from_ascii("Command[[Key]]"), trans, lcode);
872                                 ods << trans;
873                                 break;
874                         case 0x2324://Qt::Key_Enter
875                                 gui = _("Return[[Key]]");
876                                 is_translated = translateString(from_ascii("Return[[Key]]"), trans, lcode);
877                                 ods << trans;
878                                 break;
879                         case 0x2325://Option key
880                                 gui = _("Option[[Key]]");
881                                 is_translated = translateString(from_ascii("Option[[Key]]"), trans, lcode);
882                                 ods << trans;
883                                 break;
884                         case 0x2326://Qt::Key_Delete
885                                 gui = _("Delete[[Key]]");
886                                 is_translated = translateString(from_ascii("Delete[[Key]]"), trans, lcode);
887                                 ods << trans;
888                                 break;
889                         case 0x232b://Qt::Key_Backspace
890                                 gui = _("Fn+Del");
891                                 is_translated = translateString(from_ascii("Fn+Del"), trans, lcode);
892                                 ods << trans;
893                                 break;
894                         case 0x238b://Qt::Key_Escape
895                                 gui = _("Esc");
896                                 is_translated = translateString(from_ascii("Esc"), trans, lcode);
897                                 ods << trans;
898                                 break;
899                         default:
900                                 ods.put(c);
901                         }
902                 }
903                 setText(ods.str(), is_translated ? guilang : nullptr);
904                 params_.force_ltr = !is_translated || (!guilang->rightToLeft() && !params_.lang->rightToLeft());
905                 break;
906         }
907         case InsetInfoParams::LYXRC_INFO: {
908                 // this information could change, if the preferences are changed,
909                 // so we will recalculate each time through.
910                 ostringstream oss;
911                 if (params_.name.empty()) {
912                         gui = _("undefined");
913                         info(from_ascii("undefined"), params_.lang);
914                         break;
915                 }
916                 // FIXME this uses the serialization mechanism to get the info
917                 // we want, which i guess works but is a bit strange.
918                 lyxrc.write(oss, true, params_.name);
919                 string result = oss.str();
920                 if (result.size() < 2) {
921                         gui = _("undefined");
922                         info(from_ascii("undefined"), params_.lang);
923                         break;
924                 }
925                 string::size_type loc = result.rfind("\n", result.size() - 2);
926                 loc = loc == string::npos ? 0 : loc + 1;
927                 if (result.size() < loc + params_.name.size() + 1
928                           || result.substr(loc + 1, params_.name.size()) != params_.name) {
929                         gui = _("undefined");
930                         info(from_ascii("undefined"), params_.lang);
931                         break;
932                 }
933                 // remove leading comments and \\name and space
934                 result = result.substr(loc + params_.name.size() + 2);
935
936                 // remove \n and ""
937                 result = rtrim(result, "\n");
938                 result = trim(result, "\"");
939                 gui = _("not set");
940                 if (result.empty())
941                         result = "not set";
942                 setText(from_utf8(result), params_.lang);
943                 break;
944         }
945         case InsetInfoParams::PACKAGE_INFO:
946                 // only need to do this once.
947                 if (initialized_)
948                         break;
949                 // check in packages.lst
950                 if (LaTeXFeatures::isAvailable(params_.name)) {
951                         gui = _("yes");
952                         info(from_ascii("yes"), params_.lang);
953                 } else {
954                         gui = _("no");
955                         info(from_ascii("no"), params_.lang);
956                 }
957                 initialized_ = true;
958                 break;
959
960         case InsetInfoParams::TEXTCLASS_INFO: {
961                 // the TextClass can change
962                 LayoutFileList const & list = LayoutFileList::get();
963                 bool available = false;
964                 // params_.name is the class name
965                 if (list.haveClass(params_.name))
966                         available = list[params_.name].isTeXClassAvailable();
967                 if (available) {
968                         gui = _("yes");
969                         info(from_ascii("yes"), params_.lang);
970                 } else {
971                         gui = _("no");
972                         info(from_ascii("no"), params_.lang);
973                 }
974                 break;
975         }
976         case InsetInfoParams::MENU_INFO: {
977                 // only need to do this once.
978                 if (initialized_)
979                         break;
980                 docstring_list names;
981                 FuncRequest func = lyxaction.lookupFunc(params_.name);
982                 if (func.action() == LFUN_UNKNOWN_ACTION) {
983                         gui = _("Unknown action %1$s");
984                         error(from_ascii("Unknown action %1$s"), params_.lang);
985                         break;
986                 }
987                 if (func.action() == LFUN_BUFFER_VIEW || func.action() == LFUN_BUFFER_UPDATE)
988                         // The default output format is in the menu without argument,
989                         // so strip it here.
990                         if (func.argument() == from_ascii(buffer().params().getDefaultOutputFormat()))
991                                 func = FuncRequest(func.action());
992                 // iterate through the menubackend to find it
993                 if (!theApp()) {
994                         gui = _("Can't determine menu entry for action %1$s in batch mode");
995                         error(from_ascii("Can't determine menu entry for action %1$s in batch mode"), params_.lang);
996                         initialized_ = true;
997                         break;
998                 }
999                 // and we will not keep trying if we fail
1000                 initialized_ = theApp()->hasBufferView();
1001                 if (!theApp()->searchMenu(func, names)) {
1002                         gui = _("No menu entry for action %1$s");
1003                         error(from_ascii("No menu entry for action %1$s"), params_.lang);
1004                         break;
1005                 }
1006                 // if found, return its path.
1007                 clear();
1008                 Paragraph & par = paragraphs().front();
1009                 Font const f(inherit_font, guilang);
1010                 params_.force_ltr = !guilang->rightToLeft();
1011                 //Font fu = f;
1012                 //fu.fontInfo().setUnderbar(FONT_ON);
1013                 for (docstring const & name : names) {
1014                         // do not insert > for the top level menu item
1015                         if (&name != &names.front())
1016                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
1017                                                 f, Change(Change::UNCHANGED));
1018                         //FIXME: add proper underlines here. This
1019                         // involves rewriting searchMenu used above to
1020                         // return a vector of menus. If we do not do
1021                         // that, we might as well use below
1022                         // Paragraph::insert on each string (JMarc)
1023                         for (char_type c : name)
1024                                 par.insertChar(par.size(), c, f, Change(Change::UNCHANGED));
1025                 }
1026                 break;
1027         }
1028         case InsetInfoParams::L7N_INFO: {
1029                 docstring locstring = _(params_.name);
1030                 // Remove trailing colons
1031                 locstring = rtrim(locstring, ":");
1032                 // Remove menu accelerators
1033                 if (contains(locstring, from_ascii("|"))) {
1034                         docstring nlocstring;
1035                         rsplit(locstring, nlocstring, '|');
1036                         locstring = nlocstring;
1037                 }
1038                 // Remove Qt accelerators, but keep literal ampersands
1039                 locstring = subst(locstring, from_ascii(" & "), from_ascii("</amp;>"));
1040                 locstring = subst(locstring, from_ascii("&"), docstring());
1041                 locstring = subst(locstring, from_ascii("</amp;>"), from_ascii(" & "));
1042                 setText(locstring, guilang);
1043                 params_.force_ltr = !guilang->rightToLeft() && !params_.lang->rightToLeft();
1044                 break;
1045         }
1046         case InsetInfoParams::ICON_INFO: {
1047                 // only need to do this once.
1048                 if (initialized_)
1049                         break;
1050                 // and we will not keep trying if we fail
1051                 initialized_ = true;
1052                 FuncRequest func = lyxaction.lookupFunc(params_.name);
1053                 docstring icon_name = frontend::Application::iconName(func, true);
1054                 FileName file(to_utf8(icon_name));
1055                 if (file.onlyFileNameWithoutExt() == "unknown") {
1056                         string dir = "images";
1057                         FileName file2(imageLibFileSearch(dir, params_.name, "svgz,png"));
1058                         if (!file2.empty())
1059                                 file = file2;
1060                 }
1061                 if (!file.exists())
1062                         break;
1063                 int percent_scale = 100;
1064                 if (use_gui) {
1065                         // Compute the scale factor for the icon such that its
1066                         // width on screen is equal to 1em in pixels.
1067                         // The scale factor is rounded to the integer nearest
1068                         // to the float value of the ratio 100*iconsize/imgsize.
1069                         int imgsize = QImage(toqstr(file.absFileName())).width();
1070                         if (imgsize > 0) {
1071                                 int iconsize = Length(1, Length::EM).inPixels(1);
1072                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
1073                         }
1074                 }
1075                 InsetGraphics * inset = new InsetGraphics(buffer_);
1076                 InsetGraphicsParams igp;
1077                 igp.filename = file;
1078                 igp.lyxscale = percent_scale;
1079                 igp.scale = string();
1080                 igp.width = Length(1, Length::EM);
1081                 inset->setParams(igp);
1082                 clear();
1083                 Font const f(inherit_font, params_.lang);
1084                 paragraphs().front().insertInset(0, inset, f,
1085                                                  Change(Change::UNCHANGED));
1086                 break;
1087         }
1088         case InsetInfoParams::BUFFER_INFO: {
1089                 // this could all change, so we will recalculate each time
1090                 if (params_.name == "name")
1091                         setText(from_utf8(buffer().fileName().onlyFileName()), params_.lang);
1092                 else if (params_.name == "name-noext")
1093                         setText(from_utf8(buffer().fileName().onlyFileNameWithoutExt()), params_.lang);
1094                 else if (params_.name == "path")
1095                         setText(from_utf8(os::latex_path(buffer().filePath())), params_.lang);
1096                 else if (params_.name == "class")
1097                         setText(from_utf8(bp.documentClass().name()), params_.lang);
1098                 break;
1099         }
1100         case InsetInfoParams::VCS_INFO: {
1101                 // this information could change, in principle, so we will 
1102                 // recalculate each time through
1103                 if (!buffer().lyxvc().inUse()) {
1104                         gui = _("No version control!");
1105                         info(from_ascii("No version control!"), params_.lang);
1106                         break;
1107                 }
1108                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
1109                 if (params_.name == "revision")
1110                         itype = LyXVC::File;
1111                 else if (params_.name == "revision-abbrev")
1112                         itype = LyXVC::FileAbbrev;
1113                 else if (params_.name == "tree-revision")
1114                         itype = LyXVC::Tree;
1115                 else if (params_.name == "author")
1116                         itype = LyXVC::Author;
1117                 else if (params_.name == "time")
1118                         itype = LyXVC::Time;
1119                 else if (params_.name == "date")
1120                         itype = LyXVC::Date;
1121                 string binfo = buffer().lyxvc().revisionInfo(itype);
1122                 if (binfo.empty()) {
1123                         gui = _("%1$s[[vcs data]] unknown");
1124                         error(from_ascii("%1$s[[vcs data]] unknown"), params_.lang);
1125                 } else
1126                         setText(from_utf8(binfo), params_.lang);
1127                 break;
1128         }
1129         case InsetInfoParams::LYX_INFO:
1130                 // only need to do this once.
1131                 if (initialized_)
1132                         break;
1133                 if (params_.name == "version")
1134                         setText(from_ascii(lyx_version), params_.lang);
1135                 else if (params_.name == "layoutformat")
1136                         setText(convert<docstring>(LAYOUT_FORMAT), params_.lang);
1137                 initialized_ = true;
1138                 break;
1139         case InsetInfoParams::DATE_INFO:
1140         case InsetInfoParams::MODDATE_INFO:
1141         case InsetInfoParams::FIXDATE_INFO: {
1142                 string date_format = params_.name;
1143                 string const date_specifier = (params_.type == InsetInfoParams::FIXDATE_INFO
1144                                                && contains(params_.name, '@'))
1145                                 ? split(params_.name, date_format, '@') : string();
1146                 QDate date;
1147                 if (params_.type == InsetInfoParams::MODDATE_INFO)
1148                         date = QDateTime::fromTime_t(buffer().fileName().lastModified()).date();
1149                 else if (params_.type == InsetInfoParams::FIXDATE_INFO && !date_specifier.empty())
1150                         date = QDate::fromString(toqstr(date_specifier), Qt::ISODate);
1151                 else
1152                         date = QDate::currentDate();
1153                 setText(params_.getDate(date_format, date), params_.lang);
1154                 break;
1155         }
1156         case InsetInfoParams::TIME_INFO:
1157         case InsetInfoParams::MODTIME_INFO:
1158         case InsetInfoParams::FIXTIME_INFO: {
1159                 string time_format = params_.name;
1160                 string const time_specifier = (params_.type == InsetInfoParams::FIXTIME_INFO
1161                                                && contains(params_.name, '@'))
1162                                 ? split(params_.name, time_format, '@') : string();
1163                 QTime time;
1164                 if (params_.type == InsetInfoParams::MODTIME_INFO)
1165                         time = QDateTime::fromTime_t(buffer().fileName().lastModified()).time();
1166                 else if (params_.type == InsetInfoParams::FIXTIME_INFO && !time_specifier.empty())
1167                         time = QTime::fromString(toqstr(time_specifier), Qt::ISODate);
1168                 else
1169                         time = QTime::currentTime();
1170                 setText(params_.getTime(time_format, time), params_.lang);
1171                 break;
1172         }
1173         }
1174
1175         // Just to do something with that string
1176         LYXERR(Debug::INFO, "info inset text: " << gui);
1177         InsetCollapsible::updateBuffer(it, utype, deleted);
1178 }
1179
1180
1181 string InsetInfo::contextMenu(BufferView const &, int, int) const
1182 {
1183         //FIXME: We override the implementation of InsetCollapsible,
1184         //because this inset is not a collapsible inset.
1185         return contextMenuName();
1186 }
1187
1188
1189 string InsetInfo::contextMenuName() const
1190 {
1191         return "context-info";
1192 }
1193
1194
1195 } // namespace lyx