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