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