]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
65ce972af305a88ec083e5a5b79332aa66456195
[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), type_(UNKNOWN_INFO), name_(),
97         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         updateInfo();
153 }
154
155
156 void InsetInfo::write(ostream & os) const
157 {
158         os << "Info\ntype  \"" << infoType()
159            << "\"\narg   " << Lexer::quoteString(name_);
160 }
161
162
163 bool InsetInfo::validateModifyArgument(docstring const & arg) const
164 {
165         string type;
166         string const name = trim(split(to_utf8(arg), type, ' '));
167
168         switch (nameTranslator().find(type)) {
169         case UNKNOWN_INFO:
170                 return false;
171
172         case SHORTCUT_INFO:
173         case SHORTCUTS_INFO:
174         case MENU_INFO: {
175                 FuncRequest func = lyxaction.lookupFunc(name);
176                 return func.action() != LFUN_UNKNOWN_ACTION;
177         }
178
179         case ICON_INFO: {
180                 FuncCode const action = lyxaction.lookupFunc(name).action();
181                 if (action == LFUN_UNKNOWN_ACTION) {
182                         string dir = "images";
183                         return !imageLibFileSearch(dir, name, "svgz,png").empty();
184                 }
185                 return true;
186         }
187
188         case LYXRC_INFO: {
189                 ostringstream oss;
190                 lyxrc.write(oss, true, name);
191                 return !oss.str().empty();
192         }
193
194         case PACKAGE_INFO:
195         case TEXTCLASS_INFO:
196                 return true;
197
198         case BUFFER_INFO:
199                 if (name == "name" || name == "path" || name == "class")
200                         return true;
201                 if (name == "vcs-revision" || name == "vcs-tree-revision" ||
202                        name == "vcs-author" || name == "vcs-date" || name == "vcs-time")
203                         return buffer().lyxvc().inUse();
204                 return false;
205
206         case LYX_INFO:
207                 return name == "version";
208         }
209
210         return false;
211 }
212
213
214 bool InsetInfo::showInsetDialog(BufferView * bv) const
215 {
216         bv->showDialog("info");
217         return true;
218 }
219
220
221 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
222                 FuncStatus & flag) const
223 {
224         switch (cmd.action()) {
225         case LFUN_INSET_SETTINGS:
226                 return InsetCollapsible::getStatus(cur, cmd, flag);
227
228         case LFUN_INSET_DIALOG_UPDATE:
229         case LFUN_INSET_COPY_AS:
230                 flag.setEnabled(true);
231                 return true;
232
233         case LFUN_INSET_MODIFY:
234                 if (validateModifyArgument(cmd.argument())) {
235                         flag.setEnabled(true);
236                         return true;
237                 }
238                 //fall through
239
240         default:
241                 return false;
242         }
243 }
244
245
246 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
247 {
248         switch (cmd.action()) {
249         case LFUN_INSET_MODIFY:
250                 cur.recordUndo();
251                 setInfo(to_utf8(cmd.argument()));
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         updateInfo();
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::updateInfo()
307 {
308         BufferParams const & bp = buffer().params();
309
310         force_ltr_ = false;
311         switch (type_) {
312         case UNKNOWN_INFO:
313                 error("Unknown Info: %1$s");
314                 break;
315         case SHORTCUT_INFO:
316         case SHORTCUTS_INFO: {
317                 FuncRequest const func = lyxaction.lookupFunc(name_);
318                 if (func.action() == LFUN_UNKNOWN_ACTION) {
319                         error("Unknown action %1$s");
320                         break;
321                 }
322                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
323                 if (bindings.empty()) {
324                         // It is impropriate to use error() for undefined shortcut
325                         setText(_("undefined"));
326                         break;
327                 }
328                 docstring sequence;
329                 if (type_ == SHORTCUT_INFO)
330                         sequence = bindings.begin()->print(KeySequence::ForGui);
331                 else
332                         sequence = theTopLevelKeymap().printBindings(func, KeySequence::ForGui);
333                 // QKeySequence returns special characters for keys on the mac
334                 // Since these are not included in many fonts, we
335                 // re-translate them to textual names (see #10641)
336                 odocstringstream ods;
337                 docstring gui;
338                 string const lcode = bp.language->code();
339                 for (size_t n = 0; n < sequence.size(); ++n) {
340                         char_type const c = sequence[n];
341                         switch(c) {
342                         case 0x21b5://Return
343                                 gui = _("Return[[Key]]");
344                                 ods << translateIfPossible(from_ascii("Return[[Key]]"), lcode);
345                                 break;
346                         case 0x21b9://Tab both directions (Win)
347                                 gui = _("Tab[[Key]]");
348                                 ods << translateIfPossible(from_ascii("Tab[[Key]]"), lcode);
349                                 break;
350                         case 0x21de://Qt::Key_PageUp
351                                 gui = _("PgUp");
352                                 ods << translateIfPossible(from_ascii("PgUp"), lcode);
353                                 break;
354                         case 0x21df://Qt::Key_PageDown
355                                 gui = _("PgDown");
356                                 ods << translateIfPossible(from_ascii("PgDown"), lcode);
357                                 break;
358                         case 0x21e4://Qt::Key_Backtab
359                                 gui = _("Backtab");
360                                 ods << translateIfPossible(from_ascii("Backtab"), lcode);
361                                 break;
362                         case 0x21e5://Qt::Key_Tab
363                                 gui = _("Tab");
364                                 ods << translateIfPossible(from_ascii("Tab"), lcode);
365                                 break;
366                         case 0x21e7://Shift
367                                 gui = _("Shift");
368                                 ods << translateIfPossible(from_ascii("Shift"), lcode);
369                                 break;
370                         case 0x21ea://Qt::Key_CapsLock
371                                 gui = _("CapsLock");
372                                 ods << translateIfPossible(from_ascii("CapsLock"), lcode);
373                                 break;
374                         case 0x2318://CMD
375                                 gui = _("Command[[Key]]");
376                                 ods << translateIfPossible(from_ascii("Command[[Key]]"), lcode);
377                                 break;
378                         case 0x2324://Qt::Key_Enter
379                                 gui = _("Return[[Key]]");
380                                 ods << translateIfPossible(from_ascii("Return[[Key]]"), lcode);
381                                 break;
382                         case 0x2325://Option key
383                                 gui = _("Option[[Key]]");
384                                 ods << translateIfPossible(from_ascii("Option[[Key]]"), lcode);
385                                 break;
386                         case 0x2326://Qt::Key_Delete
387                                 gui = _("Delete[[Key]]");
388                                 ods << translateIfPossible(from_ascii("Delete[[Key]]"), lcode);
389                                 break;
390                         case 0x232b://Qt::Key_Backspace
391                                 gui = _("Fn+Del");
392                                 ods << translateIfPossible(from_ascii("Fn+Delete"), lcode);
393                                 break;
394                         case 0x238b://Qt::Key_Escape
395                                 gui = _("Esc");
396                                 ods << translateIfPossible(from_ascii("Esc"), lcode);
397                                 break;
398                         default:
399                                 ods.put(c);
400                         }
401                 }
402                 setText(ods.str());
403                 force_ltr_ = !bp.language->rightToLeft();
404                 break;
405         }
406         case LYXRC_INFO: {
407                 ostringstream oss;
408                 if (name_.empty()) {
409                         setText(_("undefined"));
410                         break;
411                 }
412                 lyxrc.write(oss, true, name_);
413                 string result = oss.str();
414                 if (result.size() < 2) {
415                         setText(_("undefined"));
416                         break;
417                 }
418                 string::size_type loc = result.rfind("\n", result.size() - 2);
419                 loc = loc == string::npos ? 0 : loc + 1;
420                 if (result.size() < loc + name_.size() + 1
421                           || result.substr(loc + 1, name_.size()) != name_) {
422                         setText(_("undefined"));
423                         break;
424                 }
425                 // remove leading comments and \\name and space
426                 result = result.substr(loc + name_.size() + 2);
427
428                 // remove \n and ""
429                 result = rtrim(result, "\n");
430                 result = trim(result, "\"");
431                 setText(from_utf8(result));
432                 break;
433         }
434         case PACKAGE_INFO:
435                 // check in packages.lst
436                 setText(LaTeXFeatures::isAvailable(name_) ? _("yes") : _("no"));
437                 break;
438
439         case TEXTCLASS_INFO: {
440                 // name_ is the class name
441                 LayoutFileList const & list = LayoutFileList::get();
442                 bool available = false;
443                 if (list.haveClass(name_))
444                         available = list[name_].isTeXClassAvailable();
445                 setText(available ? _("yes") : _("no"));
446                 break;
447         }
448         case MENU_INFO: {
449                 docstring_list names;
450                 FuncRequest const func = lyxaction.lookupFunc(name_);
451                 if (func.action() == LFUN_UNKNOWN_ACTION) {
452                         error("Unknown action %1$s");
453                         break;
454                 }
455                 // iterate through the menubackend to find it
456                 if (!theApp()) {
457                         error("Can't determine menu entry for action %1$s in batch mode");
458                         break;
459                 }
460                 if (!theApp()->searchMenu(func, names)) {
461                         error("No menu entry for action %1$s");
462                         break;
463                 }
464                 // if found, return its path.
465                 clear();
466                 Paragraph & par = paragraphs().front();
467                 Font const f(inherit_font, buffer().params().language);
468                 //Font fu = f;
469                 //fu.fontInfo().setUnderbar(FONT_ON);
470                 docstring_list::const_iterator beg = names.begin();
471                 docstring_list::const_iterator end = names.end();
472                 for (docstring_list::const_iterator it = beg ;
473                      it != end ; ++it) {
474                         // do not insert > for the top level menu item
475                         if (it != beg)
476                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
477                                                 f, Change(Change::UNCHANGED));
478                         //FIXME: add proper underlines here. This
479                         // involves rewriting searchMenu used above to
480                         // return a vector of menus. If we do not do
481                         // that, we might as well use below
482                         // Paragraph::insert on each string (JMarc)
483                         for (size_type i = 0; i != it->length(); ++i)
484                                 par.insertChar(par.size(), (*it)[i],
485                                                f, Change(Change::UNCHANGED));
486                 }
487                 break;
488         }
489         case ICON_INFO: {
490                 FuncRequest func = lyxaction.lookupFunc(name_);
491                 docstring icon_name = frontend::Application::iconName(func, true);
492                 // FIXME: We should use the icon directly instead of
493                 // going through FileName. The code below won't work
494                 // if the icon is embedded in the executable through
495                 // the Qt resource system.
496                 // This is only a negligible performance problem:
497                 // If the installed icon differs from the resource icon the
498                 // installed one is preferred anyway, and all icons that are
499                 // embedded in the resources are installed as well.
500                 FileName file(to_utf8(icon_name));
501                 if (file.onlyFileNameWithoutExt() == "unknown") {
502                         string dir = "images";
503                         FileName file2(imageLibFileSearch(dir, name_, "svgz,png"));
504                         if (!file2.empty())
505                                 file = file2;
506                 }
507                 if (!file.exists())
508                         break;
509                 int percent_scale = 100;
510                 if (use_gui) {
511                         // Compute the scale factor for the icon such that its
512                         // width on screen is equal to 1em in pixels.
513                         // The scale factor is rounded to the integer nearest
514                         // to the float value of the ratio 100*iconsize/imgsize.
515                         int imgsize = QImage(toqstr(file.absFileName())).width();
516                         if (imgsize > 0) {
517                                 int iconsize = Length(1, Length::EM).inPixels(1);
518                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
519                         }
520                 }
521                 InsetGraphics * inset = new InsetGraphics(buffer_);
522                 InsetGraphicsParams igp;
523                 igp.filename = file;
524                 igp.lyxscale = percent_scale;
525                 igp.scale = string();
526                 igp.width = Length(1, Length::EM);
527                 inset->setParams(igp);
528                 clear();
529                 Font const f(inherit_font, buffer().params().language);
530                 paragraphs().front().insertInset(0, inset, f,
531                                                  Change(Change::UNCHANGED));
532                 break;
533         }
534         case BUFFER_INFO: {
535                 if (name_ == "name") {
536                         setText(from_utf8(buffer().fileName().onlyFileName()));
537                         break;
538                 }
539                 if (name_ == "path") {
540                         setText(from_utf8(os::latex_path(buffer().filePath())));
541                         break;
542                 }
543                 if (name_ == "class") {
544                         setText(from_utf8(bp.documentClass().name()));
545                         break;
546                 }
547
548                 // everything that follows is for version control.
549                 // nothing that isn't version control should go below this line.
550                 if (!buffer().lyxvc().inUse()) {
551                         setText(_("No version control"));
552                         break;
553                 }
554                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
555                 if (name_ == "vcs-revision")
556                         itype = LyXVC::File;
557                 else if (name_ == "vcs-tree-revision")
558                         itype = LyXVC::Tree;
559                 else if (name_ == "vcs-author")
560                         itype = LyXVC::Author;
561                 else if (name_ == "vcs-time")
562                         itype = LyXVC::Time;
563                 else if (name_ == "vcs-date")
564                         itype = LyXVC::Date;
565                 string binfo = buffer().lyxvc().revisionInfo(itype);
566                 if (binfo.empty())
567                         setText(from_ascii(name_) + " unknown");
568                 else
569                         setText(from_utf8(binfo));
570                 break;
571         }
572         case LYX_INFO:
573                 if (name_ == "version")
574                         setText(from_ascii(lyx_version));
575                 break;
576         }
577 }
578
579
580 string InsetInfo::contextMenu(BufferView const &, int, int) const
581 {
582         //FIXME: We override the implementation of InsetCollapsible,
583         //because this inset is not a collapsible inset.
584         return contextMenuName();
585 }
586
587
588 string InsetInfo::contextMenuName() const
589 {
590         return "context-info";
591 }
592
593
594 } // namespace lyx