]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Fix bug #10835.
[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  *
8  * Full author contact details are available in file CREDITS.
9  */
10 #include <config.h>
11
12 #include "InsetInfo.h"
13 #include "LyX.h"
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
18 #include "FuncRequest.h"
19 #include "FuncStatus.h"
20 #include "InsetGraphics.h"
21 #include "InsetSpecialChar.h"
22 #include "KeyMap.h"
23 #include "LaTeXFeatures.h"
24 #include "LayoutFile.h"
25 #include "Length.h"
26 #include "LyXAction.h"
27 #include "LyXRC.h"
28 #include "LyXVC.h"
29 #include "Lexer.h"
30 #include "ParagraphParameters.h"
31 #include "version.h"
32
33 #include "frontends/Application.h"
34
35 #include "support/convert.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/docstring_list.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/FileName.h"
41 #include "support/filetools.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/qstring_helpers.h"
45 #include "support/Translator.h"
46
47 #include <sstream>
48
49 #include <QtGui/QImage>
50
51 using namespace std;
52 using namespace lyx::support;
53
54 namespace lyx {
55
56 namespace {
57
58 typedef Translator<InsetInfo::info_type, string> NameTranslator;
59
60 NameTranslator const initTranslator()
61 {
62         NameTranslator translator(InsetInfo::UNKNOWN_INFO, "unknown");
63
64         translator.addPair(InsetInfo::SHORTCUTS_INFO, "shortcuts");
65         translator.addPair(InsetInfo::SHORTCUT_INFO, "shortcut");
66         translator.addPair(InsetInfo::LYXRC_INFO, "lyxrc");
67         translator.addPair(InsetInfo::PACKAGE_INFO, "package");
68         translator.addPair(InsetInfo::TEXTCLASS_INFO, "textclass");
69         translator.addPair(InsetInfo::MENU_INFO, "menu");
70         translator.addPair(InsetInfo::ICON_INFO, "icon");
71         translator.addPair(InsetInfo::BUFFER_INFO, "buffer");
72         translator.addPair(InsetInfo::LYX_INFO, "lyxinfo");
73
74         return translator;
75 }
76
77 /// The translator between the information type enum and corresponding string.
78 NameTranslator const & nameTranslator()
79 {
80         static NameTranslator const translator = initTranslator();
81         return translator;
82 }
83
84 } // namespace
85
86 /////////////////////////////////////////////////////////////////////////
87 //
88 // InsetInfo
89 //
90 /////////////////////////////////////////////////////////////////////////
91
92
93
94 InsetInfo::InsetInfo(Buffer * buf, string const & name)
95         : InsetCollapsible(buf), initialized_(false), 
96           type_(UNKNOWN_INFO), name_()
97 {
98         setInfo(name);
99         status_ = Collapsed;
100 }
101
102
103 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
104 {
105         // do not allow the cursor to be set in this Inset
106         return Inset::editXY(cur, x, y);
107 }
108
109
110 string InsetInfo::infoType() const
111 {
112         return nameTranslator().find(type_);
113 }
114
115
116 docstring InsetInfo::layoutName() const
117 {
118         return from_ascii("Info:" + infoType());
119 }
120
121
122 docstring InsetInfo::toolTip(BufferView const &, int, int) const
123 {
124         return bformat(_("Information regarding %1$s '%2$s'"),
125                         _(infoType()), from_utf8(name_));
126 }
127
128
129 void InsetInfo::read(Lexer & lex)
130 {
131         string token;
132         while (lex.isOK()) {
133                 lex.next();
134                 token = lex.getString();
135                 if (token == "type") {
136                         lex.next();
137                         token = lex.getString();
138                         type_ = nameTranslator().find(token);
139                 } else if (token == "arg") {
140                         lex.next(true);
141                         name_ = lex.getString();
142                 } else if (token == "\\end_inset")
143                         break;
144         }
145         if (token != "\\end_inset") {
146                 lex.printError("Missing \\end_inset at this point");
147                 throw ExceptionMessage(WarningException,
148                         _("Missing \\end_inset at this point."),
149                         from_utf8(token));
150         }
151 }
152
153
154 void InsetInfo::write(ostream & os) const
155 {
156         os << "Info\ntype  \"" << infoType()
157            << "\"\narg   " << Lexer::quoteString(name_);
158 }
159
160
161 bool InsetInfo::validateModifyArgument(docstring const & arg) const
162 {
163         string type;
164         string const name = trim(split(to_utf8(arg), type, ' '));
165
166         switch (nameTranslator().find(type)) {
167         case UNKNOWN_INFO:
168                 return false;
169
170         case SHORTCUT_INFO:
171         case SHORTCUTS_INFO:
172         case MENU_INFO: {
173                 FuncRequest func = lyxaction.lookupFunc(name);
174                 return func.action() != LFUN_UNKNOWN_ACTION;
175         }
176
177         case ICON_INFO: {
178                 FuncCode const action = lyxaction.lookupFunc(name).action();
179                 if (action == LFUN_UNKNOWN_ACTION) {
180                         string dir = "images";
181                         return !imageLibFileSearch(dir, name, "svgz,png").empty();
182                 }
183                 return true;
184         }
185
186         case LYXRC_INFO: {
187                 ostringstream oss;
188                 lyxrc.write(oss, true, name);
189                 return !oss.str().empty();
190         }
191
192         case PACKAGE_INFO:
193         case TEXTCLASS_INFO:
194                 return true;
195
196         case BUFFER_INFO:
197                 if (name == "name" || name == "path" || name == "class")
198                         return true;
199                 if (name == "vcs-revision" || name == "vcs-tree-revision" ||
200                        name == "vcs-author" || name == "vcs-date" || name == "vcs-time")
201                         return buffer().lyxvc().inUse();
202                 return false;
203
204         case LYX_INFO:
205                 return name == "version";
206         }
207
208         return false;
209 }
210
211
212 bool InsetInfo::showInsetDialog(BufferView * bv) const
213 {
214         bv->showDialog("info");
215         return true;
216 }
217
218
219 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
220                 FuncStatus & flag) const
221 {
222         switch (cmd.action()) {
223         case LFUN_INSET_SETTINGS:
224                 return InsetCollapsible::getStatus(cur, cmd, flag);
225
226         case LFUN_INSET_DIALOG_UPDATE:
227         case LFUN_INSET_COPY_AS:
228                 flag.setEnabled(true);
229                 return true;
230
231         case LFUN_INSET_MODIFY:
232                 if (validateModifyArgument(cmd.argument())) {
233                         flag.setEnabled(true);
234                         return true;
235                 }
236                 //fall through
237
238         default:
239                 return false;
240         }
241 }
242
243
244 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
245 {
246         switch (cmd.action()) {
247         case LFUN_INSET_MODIFY:
248                 cur.recordUndo();
249                 setInfo(to_utf8(cmd.argument()));
250                 cur.forceBufferUpdate();
251                 initialized_ = false;
252                 break;
253
254         case LFUN_INSET_COPY_AS: {
255                 cap::clearSelection();
256                 Cursor copy(cur);
257                 copy.pushBackward(*this);
258                 copy.pit() = 0;
259                 copy.pos() = 0;
260                 copy.resetAnchor();
261                 copy.pit() = copy.lastpit();
262                 copy.pos() = copy.lastpos();
263                 copy.setSelection();
264                 cap::copySelection(copy);
265                 break;
266         }
267
268         default:
269                 InsetCollapsible::doDispatch(cur, cmd);
270                 break;
271         }
272 }
273
274
275 void InsetInfo::setInfo(string const & name)
276 {
277         if (name.empty())
278                 return;
279         // info_type name
280         string type;
281         name_ = trim(split(name, type, ' '));
282         type_ = nameTranslator().find(type);
283 }
284
285
286 void InsetInfo::error(string const & err)
287 {
288         setText(bformat(_(err), from_utf8(name_)),
289                 Font(inherit_font, buffer().params().language), false);
290 }
291
292
293 void InsetInfo::setText(docstring const & str)
294 {
295         setText(str, Font(inherit_font, buffer().params().language), false);
296 }
297
298
299 void InsetInfo::updateBuffer(ParIterator const & it, UpdateType utype) {
300         // If the Buffer is a clone, then we neither need nor want to do any
301         // of what follows. We want, rather, just to inherit how things were
302         // in the original Buffer. This is especially important for VCS.
303         // Otherwise, we could in principle have different settings here
304         // than in the Buffer we were exporting.
305         if (buffer().isClone())
306                 return;
307
308         BufferParams const & bp = buffer().params();
309
310         switch (type_) {
311         case UNKNOWN_INFO:
312                 error("Unknown Info: %1$s");
313                 initialized_ = false;
314                 break;
315         case SHORTCUT_INFO:
316         case SHORTCUTS_INFO: {
317                 // shortcuts can change, so we need to re-do this each time
318                 FuncRequest const func = lyxaction.lookupFunc(name_);
319                 if (func.action() == LFUN_UNKNOWN_ACTION) {
320                         error("Unknown action %1$s");
321                         break;
322                 }
323                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
324                 if (bindings.empty()) {
325                         // It is impropriate to use error() for undefined shortcut
326                         setText(_("undefined"));
327                         break;
328                 }
329                 if (type_ == SHORTCUT_INFO)
330                         setText(bindings.begin()->print(KeySequence::Portable));
331                 else
332                         setText(theTopLevelKeymap().printBindings(func, KeySequence::Portable));
333                 break;
334         }
335         case LYXRC_INFO: {
336                 // this information could change, if the preferences are changed,
337                 // so we will recalculate each time through.
338                 ostringstream oss;
339                 if (name_.empty()) {
340                         setText(_("undefined"));
341                         break;
342                 }
343                 // FIXME this uses the serialization mechanism to get the info
344                 // we want, which i guess works but is a bit strange.
345                 lyxrc.write(oss, true, name_);
346                 string result = oss.str();
347                 if (result.size() < 2) {
348                         setText(_("undefined"));
349                         break;
350                 }
351                 string::size_type loc = result.rfind("\n", result.size() - 2);
352                 loc = loc == string::npos ? 0 : loc + 1;
353                 if (result.size() < loc + name_.size() + 1
354                           || result.substr(loc + 1, name_.size()) != name_) {
355                         setText(_("undefined"));
356                         break;
357                 }
358                 // remove leading comments and \\name and space
359                 result = result.substr(loc + name_.size() + 2);
360
361                 // remove \n and ""
362                 result = rtrim(result, "\n");
363                 result = trim(result, "\"");
364                 setText(from_utf8(result));
365                 break;
366         }
367         case PACKAGE_INFO:
368                 // only need to do this once.
369                 if (initialized_)
370                         break;
371                 // check in packages.lst
372                 setText(LaTeXFeatures::isAvailable(name_) ? _("yes") : _("no"));
373                 initialized_ = true;
374                 break;
375
376         case TEXTCLASS_INFO: {
377                 // the TextClass can change
378                 LayoutFileList const & list = LayoutFileList::get();
379                 bool available = false;
380                 // name_ is the class name
381                 if (list.haveClass(name_))
382                         available = list[name_].isTeXClassAvailable();
383                 setText(available ? _("yes") : _("no"));
384                 break;
385         }
386         case MENU_INFO: {
387                 // only need to do this once.
388                 if (initialized_)
389                         break;
390                 // and we will not keep trying if we fail
391                 initialized_ = true;
392                 docstring_list names;
393                 FuncRequest const func = lyxaction.lookupFunc(name_);
394                 if (func.action() == LFUN_UNKNOWN_ACTION) {
395                         error("Unknown action %1$s");
396                         break;
397                 }
398                 // iterate through the menubackend to find it
399                 if (!theApp()) {
400                         error("Can't determine menu entry for action %1$s in batch mode");
401                         break;
402                 }
403                 if (!theApp()->searchMenu(func, names)) {
404                         error("No menu entry for action %1$s");
405                         break;
406                 }
407                 // if found, return its path.
408                 clear();
409                 Paragraph & par = paragraphs().front();
410                 Font const f(inherit_font, buffer().params().language);
411                 //Font fu = f;
412                 //fu.fontInfo().setUnderbar(FONT_ON);
413                 for (docstring const & name : names) {
414                         // do not insert > for the top level menu item
415                         if (&name != &names.front())
416                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
417                                                 f, Change(Change::UNCHANGED));
418                         //FIXME: add proper underlines here. This
419                         // involves rewriting searchMenu used above to
420                         // return a vector of menus. If we do not do
421                         // that, we might as well use below
422                         // Paragraph::insert on each string (JMarc)
423                         for (char_type c : name)
424                                 par.insertChar(par.size(), c, f, Change(Change::UNCHANGED));
425                 }
426                 break;
427         }
428         case ICON_INFO: {
429                 // only need to do this once.
430                 if (initialized_)
431                         break;
432                 // and we will not keep trying if we fail
433                 initialized_ = true;
434                 FuncRequest func = lyxaction.lookupFunc(name_);
435                 docstring icon_name = frontend::Application::iconName(func, true);
436                 // FIXME: We should use the icon directly instead of
437                 // going through FileName. The code below won't work
438                 // if the icon is embedded in the executable through
439                 // the Qt resource system.
440                 // This is only a negligible performance problem:
441                 // If the installed icon differs from the resource icon the
442                 // installed one is preferred anyway, and all icons that are
443                 // embedded in the resources are installed as well.
444                 FileName file(to_utf8(icon_name));
445                 if (file.onlyFileNameWithoutExt() == "unknown") {
446                         string dir = "images";
447                         FileName file2(imageLibFileSearch(dir, name_, "svgz,png"));
448                         if (!file2.empty())
449                                 file = file2;
450                 }
451                 if (!file.exists())
452                         break;
453                 int percent_scale = 100;
454                 if (use_gui) {
455                         // Compute the scale factor for the icon such that its
456                         // width on screen is equal to 1em in pixels.
457                         // The scale factor is rounded to the integer nearest
458                         // to the float value of the ratio 100*iconsize/imgsize.
459                         int imgsize = QImage(toqstr(file.absFileName())).width();
460                         if (imgsize > 0) {
461                                 int iconsize = Length(1, Length::EM).inPixels(1);
462                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
463                         }
464                 }
465                 InsetGraphics * inset = new InsetGraphics(buffer_);
466                 InsetGraphicsParams igp;
467                 igp.filename = file;
468                 igp.lyxscale = percent_scale;
469                 igp.scale = string();
470                 igp.width = Length(1, Length::EM);
471                 inset->setParams(igp);
472                 clear();
473                 Font const f(inherit_font, buffer().params().language);
474                 paragraphs().front().insertInset(0, inset, f,
475                                                  Change(Change::UNCHANGED));
476                 break;
477         }
478         case BUFFER_INFO: {
479                 // this could all change, so we will recalculate each time
480                 if (name_ == "name") {
481                         setText(from_utf8(buffer().fileName().onlyFileName()));
482                         break;
483                 }
484                 if (name_ == "path") {
485                         setText(from_utf8(os::latex_path(buffer().filePath())));
486                         break;
487                 }
488                 if (name_ == "class") {
489                         setText(from_utf8(bp.documentClass().name()));
490                         break;
491                 }
492
493                 ////////////////////////////////////////////////////////////////
494                 // everything that follows is for version control.
495                 // nothing that isn't version control should go below this line.
496                 
497                 // this information could change, in principle, so we will 
498                 // recalculate each time through
499                 if (!buffer().lyxvc().inUse()) {
500                         setText(_("No version control"));
501                         break;
502                 }
503                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
504                 if (name_ == "vcs-revision")
505                         itype = LyXVC::File;
506                 else if (name_ == "vcs-tree-revision")
507                         itype = LyXVC::Tree;
508                 else if (name_ == "vcs-author")
509                         itype = LyXVC::Author;
510                 else if (name_ == "vcs-time")
511                         itype = LyXVC::Time;
512                 else if (name_ == "vcs-date")
513                         itype = LyXVC::Date;
514                 string binfo = buffer().lyxvc().revisionInfo(itype);
515                 if (binfo.empty())
516                         setText(from_ascii(name_) + " unknown");
517                 else
518                         setText(from_utf8(binfo));
519                 break;
520         }
521         case LYX_INFO:
522                 // only need to do this once.
523                 if (initialized_)
524                         break;
525                 if (name_ == "version")
526                         setText(from_ascii(lyx_version));
527                 initialized_ = true;
528                 break;
529         }
530         InsetCollapsible::updateBuffer(it, utype);
531 }
532
533
534 string InsetInfo::contextMenu(BufferView const &, int, int) const
535 {
536         //FIXME: We override the implementation of InsetCollapsible,
537         //because this inset is not a collapsible inset.
538         return contextMenuName();
539 }
540
541
542 string InsetInfo::contextMenuName() const
543 {
544         return "context-info";
545 }
546
547
548 } // namespace lyx