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