]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Bulk cleanup/fix incorrect annotation at the end of namespaces.
[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         : InsetCollapsable(buf), type_(UNKNOWN_INFO), name_()
96 {
97         setInfo(name);
98         status_ = Collapsed;
99 }
100
101
102 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
103 {
104         // do not allow the cursor to be set in this Inset
105         return Inset::editXY(cur, x, y);
106 }
107
108
109 string InsetInfo::infoType() const
110 {
111         return nameTranslator().find(type_);
112 }
113
114
115 docstring InsetInfo::layoutName() const
116 {
117         return from_ascii("Info:" + infoType());
118 }
119
120
121 docstring InsetInfo::toolTip(BufferView const &, int, int) const
122 {
123         return bformat(_("Information regarding %1$s '%2$s'"),
124                         _(infoType()), from_utf8(name_));
125 }
126
127
128 void InsetInfo::read(Lexer & lex)
129 {
130         string token;
131         while (lex.isOK()) {
132                 lex.next();
133                 token = lex.getString();
134                 if (token == "type") {
135                         lex.next();
136                         token = lex.getString();
137                         type_ = nameTranslator().find(token);
138                 } else if (token == "arg") {
139                         lex.next(true);
140                         name_ = lex.getString();
141                 } else if (token == "\\end_inset")
142                         break;
143         }
144         if (token != "\\end_inset") {
145                 lex.printError("Missing \\end_inset at this point");
146                 throw ExceptionMessage(WarningException,
147                         _("Missing \\end_inset at this point."),
148                         from_utf8(token));
149         }
150         updateInfo();
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 InsetCollapsable::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                 break;
251
252         case LFUN_INSET_COPY_AS: {
253                 cap::clearSelection();
254                 Cursor copy(cur);
255                 copy.pushBackward(*this);
256                 copy.pit() = 0;
257                 copy.pos() = 0;
258                 copy.resetAnchor();
259                 copy.pit() = copy.lastpit();
260                 copy.pos() = copy.lastpos();
261                 copy.setSelection();
262                 cap::copySelection(copy);
263                 break;
264         }
265
266         default:
267                 InsetCollapsable::doDispatch(cur, cmd);
268                 break;
269         }
270 }
271
272
273 void InsetInfo::setInfo(string const & name)
274 {
275         if (name.empty())
276                 return;
277         // info_type name
278         string type;
279         name_ = trim(split(name, type, ' '));
280         type_ = nameTranslator().find(type);
281         updateInfo();
282 }
283
284
285 void InsetInfo::error(string const & err)
286 {
287         setText(bformat(_(err), from_utf8(name_)),
288                 Font(inherit_font, buffer().params().language), false);
289 }
290
291
292 void InsetInfo::setText(docstring const & str)
293 {
294         setText(str, Font(inherit_font, buffer().params().language), false);
295 }
296
297
298 void InsetInfo::updateInfo()
299 {
300         BufferParams const & bp = buffer().params();
301
302         switch (type_) {
303         case UNKNOWN_INFO:
304                 error("Unknown Info: %1$s");
305                 break;
306         case SHORTCUT_INFO:
307         case SHORTCUTS_INFO: {
308                 FuncRequest const func = lyxaction.lookupFunc(name_);
309                 if (func.action() == LFUN_UNKNOWN_ACTION) {
310                         error("Unknown action %1$s");
311                         break;
312                 }
313                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
314                 if (bindings.empty()) {
315                         // It is impropriate to use error() for undefined shortcut
316                         setText(_("undefined"));
317                         break;
318                 }
319                 if (type_ == SHORTCUT_INFO)
320                         setText(bindings.begin()->print(KeySequence::Portable));
321                 else
322                         setText(theTopLevelKeymap().printBindings(func, KeySequence::Portable));
323                 break;
324         }
325         case LYXRC_INFO: {
326                 ostringstream oss;
327                 if (name_.empty()) {
328                         setText(_("undefined"));
329                         break;
330                 }
331                 lyxrc.write(oss, true, name_);
332                 string result = oss.str();
333                 if (result.size() < 2) {
334                         setText(_("undefined"));
335                         break;
336                 }
337                 string::size_type loc = result.rfind("\n", result.size() - 2);
338                 loc = loc == string::npos ? 0 : loc + 1;
339                 if (result.size() < loc + name_.size() + 1
340                           || result.substr(loc + 1, name_.size()) != name_) {
341                         setText(_("undefined"));
342                         break;
343                 }
344                 // remove leading comments and \\name and space
345                 result = result.substr(loc + name_.size() + 2);
346
347                 // remove \n and ""
348                 result = rtrim(result, "\n");
349                 result = trim(result, "\"");
350                 setText(from_utf8(result));
351                 break;
352         }
353         case PACKAGE_INFO:
354                 // check in packages.lst
355                 setText(LaTeXFeatures::isAvailable(name_) ? _("yes") : _("no"));
356                 break;
357
358         case TEXTCLASS_INFO: {
359                 // name_ is the class name
360                 LayoutFileList const & list = LayoutFileList::get();
361                 bool available = false;
362                 if (list.haveClass(name_))
363                         available = list[name_].isTeXClassAvailable();
364                 setText(available ? _("yes") : _("no"));
365                 break;
366         }
367         case MENU_INFO: {
368                 docstring_list names;
369                 FuncRequest const func = lyxaction.lookupFunc(name_);
370                 if (func.action() == LFUN_UNKNOWN_ACTION) {
371                         error("Unknown action %1$s");
372                         break;
373                 }
374                 // iterate through the menubackend to find it
375                 if (!theApp()) {
376                         error("Can't determine menu entry for action %1$s in batch mode");
377                         break;
378                 }
379                 if (!theApp()->searchMenu(func, names)) {
380                         error("No menu entry for action %1$s");
381                         break;
382                 }
383                 // if found, return its path.
384                 clear();
385                 Paragraph & par = paragraphs().front();
386                 Font const f(inherit_font, buffer().params().language);
387                 //Font fu = f;
388                 //fu.fontInfo().setUnderbar(FONT_ON);
389                 docstring_list::const_iterator beg = names.begin();
390                 docstring_list::const_iterator end = names.end();
391                 for (docstring_list::const_iterator it = beg ;
392                      it != end ; ++it) {
393                         // do not insert > for the top level menu item
394                         if (it != beg)
395                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
396                                                 f, Change(Change::UNCHANGED));
397                         //FIXME: add proper underlines here. This
398                         // involves rewriting searchMenu used above to
399                         // return a vector of menus. If we do not do
400                         // that, we might as well use below
401                         // Paragraph::insert on each string (JMarc)
402                         for (size_type i = 0; i != it->length(); ++i)
403                                 par.insertChar(par.size(), (*it)[i],
404                                                f, Change(Change::UNCHANGED));
405                 }
406                 break;
407         }
408         case ICON_INFO: {
409                 FuncRequest func = lyxaction.lookupFunc(name_);
410                 docstring icon_name = frontend::Application::iconName(func, true);
411                 // FIXME: We should use the icon directly instead of
412                 // going through FileName. The code below won't work
413                 // if the icon is embedded in the executable through
414                 // the Qt resource system.
415                 // This is only a negligible performance problem:
416                 // If the installed icon differs from the resource icon the
417                 // installed one is preferred anyway, and all icons that are
418                 // embedded in the resources are installed as well.
419                 FileName file(to_utf8(icon_name));
420                 if (file.onlyFileNameWithoutExt() == "unknown") {
421                         string dir = "images";
422                         FileName file2(imageLibFileSearch(dir, name_, "svgz,png"));
423                         if (!file2.empty())
424                                 file = file2;
425                 }
426                 if (!file.exists())
427                         break;
428                 int percent_scale = 100;
429                 if (use_gui) {
430                         // Compute the scale factor for the icon such that its
431                         // width on screen is equal to 1em in pixels.
432                         // The scale factor is rounded to the integer nearest
433                         // to the float value of the ratio 100*iconsize/imgsize.
434                         int imgsize = QImage(toqstr(file.absFileName())).width();
435                         if (imgsize > 0) {
436                                 int iconsize = Length(1, Length::EM).inPixels(1);
437                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
438                         }
439                 }
440                 InsetGraphics * inset = new InsetGraphics(buffer_);
441                 InsetGraphicsParams igp;
442                 igp.filename = file;
443                 igp.lyxscale = percent_scale;
444                 igp.scale = string();
445                 igp.width = Length(1, Length::EM);
446                 inset->setParams(igp);
447                 clear();
448                 Font const f(inherit_font, buffer().params().language);
449                 paragraphs().front().insertInset(0, inset, f,
450                                                  Change(Change::UNCHANGED));
451                 break;
452         }
453         case BUFFER_INFO: {
454                 if (name_ == "name") {
455                         setText(from_utf8(buffer().fileName().onlyFileName()));
456                         break;
457                 }
458                 if (name_ == "path") {
459                         setText(from_utf8(os::latex_path(buffer().filePath())));
460                         break;
461                 }
462                 if (name_ == "class") {
463                         setText(from_utf8(bp.documentClass().name()));
464                         break;
465                 }
466
467                 // everything that follows is for version control.
468                 // nothing that isn't version control should go below this line.
469                 if (!buffer().lyxvc().inUse()) {
470                         setText(_("No version control"));
471                         break;
472                 }
473                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
474                 if (name_ == "vcs-revision")
475                         itype = LyXVC::File;
476                 else if (name_ == "vcs-tree-revision")
477                         itype = LyXVC::Tree;
478                 else if (name_ == "vcs-author")
479                         itype = LyXVC::Author;
480                 else if (name_ == "vcs-time")
481                         itype = LyXVC::Time;
482                 else if (name_ == "vcs-date")
483                         itype = LyXVC::Date;
484                 string binfo = buffer().lyxvc().revisionInfo(itype);
485                 if (binfo.empty())
486                         setText(from_ascii(name_) + " unknown");
487                 else
488                         setText(from_utf8(binfo));
489                 break;
490         }
491         case LYX_INFO:
492                 if (name_ == "version")
493                         setText(from_ascii(lyx_version));
494                 break;
495         }
496 }
497
498
499 string InsetInfo::contextMenu(BufferView const &, int, int) const
500 {
501         //FIXME: We override the implementation of InsetCollapsable,
502         //because this inset is not a collapsable inset.
503         return contextMenuName();
504 }
505
506
507 string InsetInfo::contextMenuName() const
508 {
509         return "context-info";
510 }
511
512
513 } // namespace lyx