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