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