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