]> git.lyx.org Git - lyx.git/blob - src/insets/InsetInfo.cpp
Add comment
[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 anon
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         setAutoBreakRows(true);
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         updateInfo();
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         case ICON_INFO: {
175                 FuncRequest func = lyxaction.lookupFunc(name);
176                 return func.action() != LFUN_UNKNOWN_ACTION;
177         }
178
179         case LYXRC_INFO: {
180                 ostringstream oss;
181                 lyxrc.write(oss, true, name);
182                 return !oss.str().empty();
183         }
184
185         case PACKAGE_INFO:
186         case TEXTCLASS_INFO:
187                 return true;
188
189         case BUFFER_INFO:
190                 if (name == "name" || name == "path" || name == "class")
191                         return true;
192                 if (name == "vcs-revision" || name == "vcs-tree-revision" ||
193                        name == "vcs-author" || name == "vcs-date" || name == "vcs-time")
194                         return buffer().lyxvc().inUse();
195                 return false;
196
197         case LYX_INFO:
198                 return name == "version";
199         }
200
201         return false;
202 }
203
204
205 bool InsetInfo::showInsetDialog(BufferView * bv) const
206 {
207         bv->showDialog("info");
208         return true;
209 }
210
211
212 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
213                 FuncStatus & flag) const
214 {
215         switch (cmd.action()) {
216         case LFUN_INSET_SETTINGS:
217                 return InsetCollapsable::getStatus(cur, cmd, flag);
218
219         case LFUN_INSET_DIALOG_UPDATE:
220         case LFUN_INSET_COPY_AS:
221                 flag.setEnabled(true);
222                 return true;
223
224         case LFUN_INSET_MODIFY:
225                 if (validateModifyArgument(cmd.argument())) {
226                         flag.setEnabled(true);
227                         return true;
228                 }
229                 //fall through
230
231         default:
232                 return false;
233         }
234 }
235
236
237 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
238 {
239         switch (cmd.action()) {
240         case LFUN_INSET_MODIFY:
241                 cur.recordUndo();
242                 setInfo(to_utf8(cmd.argument()));
243                 break;
244
245         case LFUN_INSET_COPY_AS: {
246                 cap::clearSelection();
247                 Cursor copy(cur);
248                 copy.pushBackward(*this);
249                 copy.pit() = 0;
250                 copy.pos() = 0;
251                 copy.resetAnchor();
252                 copy.pit() = copy.lastpit();
253                 copy.pos() = copy.lastpos();
254                 copy.setSelection();
255                 cap::copySelection(copy);
256                 break;
257         }
258
259         default:
260                 InsetCollapsable::doDispatch(cur, cmd);
261                 break;
262         }
263 }
264
265
266 void InsetInfo::setInfo(string const & name)
267 {
268         if (name.empty())
269                 return;
270         // info_type name
271         string type;
272         name_ = trim(split(name, type, ' '));
273         type_ = nameTranslator().find(type);
274         updateInfo();
275 }
276
277
278 void InsetInfo::error(string const & err)
279 {
280         setText(bformat(_(err), from_utf8(name_)), 
281                 Font(inherit_font, buffer().params().language), false);
282 }
283
284
285 void InsetInfo::setText(docstring const & str)
286 {
287         setText(str, Font(inherit_font, buffer().params().language), false);
288 }
289
290
291 void InsetInfo::updateInfo()
292 {
293         BufferParams const & bp = buffer().params();    
294
295         switch (type_) {
296         case UNKNOWN_INFO:
297                 error("Unknown Info: %1$s");
298                 break;
299         case SHORTCUT_INFO:
300         case SHORTCUTS_INFO: {
301                 FuncRequest const func = lyxaction.lookupFunc(name_);
302                 if (func.action() == LFUN_UNKNOWN_ACTION) {
303                         error("Unknown action %1$s");
304                         break;
305                 }
306                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
307                 if (bindings.empty()) {
308                         // It is impropriate to use error() for undefined shortcut
309                         setText(_("undefined"));
310                         break;
311                 }
312                 if (type_ == SHORTCUT_INFO)
313                         setText(bindings.begin()->print(KeySequence::Portable));
314                 else
315                         setText(theTopLevelKeymap().printBindings(func, KeySequence::Portable));
316                 break;
317         }
318         case LYXRC_INFO: {
319                 ostringstream oss;
320                 if (name_.empty()) {
321                         setText(_("undefined"));
322                         break;
323                 }
324                 lyxrc.write(oss, true, name_);
325                 string result = oss.str();
326                 if (result.size() < 2) {
327                         setText(_("undefined"));
328                         break;
329                 }
330                 string::size_type loc = result.rfind("\n", result.size() - 2);
331                 loc = loc == string::npos ? 0 : loc + 1;
332                 if (result.size() < loc + name_.size() + 1
333                           || result.substr(loc + 1, name_.size()) != name_) {
334                         setText(_("undefined"));
335                         break;
336                 }
337                 // remove leading comments and \\name and space
338                 result = result.substr(loc + name_.size() + 2);
339                 
340                 // remove \n and ""
341                 result = rtrim(result, "\n");
342                 result = trim(result, "\"");
343                 setText(from_utf8(result));
344                 break;
345         }
346         case PACKAGE_INFO:
347                 // check in packages.lst
348                 setText(LaTeXFeatures::isAvailable(name_) ? _("yes") : _("no"));
349                 break;
350
351         case TEXTCLASS_INFO: {
352                 // name_ is the class name
353                 LayoutFileList const & list = LayoutFileList::get();
354                 bool available = false;
355                 if (list.haveClass(name_))
356                         available = list[name_].isTeXClassAvailable();
357                 setText(available ? _("yes") : _("no"));
358                 break;
359         }
360         case MENU_INFO: {
361                 docstring_list names;
362                 FuncRequest const func = lyxaction.lookupFunc(name_);
363                 if (func.action() == LFUN_UNKNOWN_ACTION) {
364                         error("Unknown action %1$s");
365                         break;
366                 }
367                 // iterate through the menubackend to find it
368                 if (!theApp()) {
369                         error("Can't determine menu entry for action %1$s in batch mode");
370                         break;
371                 }
372                 if (!theApp()->searchMenu(func, names)) {
373                         error("No menu entry for action %1$s");
374                         break;
375                 }
376                 // if found, return its path.
377                 clear();
378                 Paragraph & par = paragraphs().front();
379                 Font const f(inherit_font, buffer().params().language);
380                 //Font fu = f;
381                 //fu.fontInfo().setUnderbar(FONT_ON);
382                 docstring_list::const_iterator beg = names.begin();
383                 docstring_list::const_iterator end = names.end();
384                 for (docstring_list::const_iterator it = beg ; 
385                      it != end ; ++it) {
386                         // do not insert > for the top level menu item
387                         if (it != beg)
388                                 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
389                                                 f, Change(Change::UNCHANGED));
390                         //FIXME: add proper underlines here. This
391                         // involves rewriting searchMenu used above to
392                         // return a vector of menus. If we do not do
393                         // that, we might as well use below
394                         // Paragraph::insert on each string (JMarc)
395                         for (size_type i = 0; i != it->length(); ++i)
396                                 par.insertChar(par.size(), (*it)[i], 
397                                                f, Change(Change::UNCHANGED));
398                 }
399                 break;
400         }
401         case ICON_INFO: {
402                 FuncRequest func = lyxaction.lookupFunc(name_);
403                 docstring icon_name = frontend::Application::iconName(func, true);
404                 // FIXME: We should use the icon directly instead of
405                 // going through FileName. The code below won't work
406                 // if the icon is embedded in the executable through
407                 // the Qt resource system.
408                 // This is only a negligible performance problem:
409                 // If the installed icon differs from the resource icon the
410                 // installed one is preferred anyway, and all icons that are
411                 // embedded in the resources are installed as well.
412                 FileName file(to_utf8(icon_name));
413                 if (file.onlyFileNameWithoutExt() == "unknown") {
414                         string dir = "images";
415                         FileName file2(imageLibFileSearch(dir, name_, "svgz,png"));
416                         if (!file2.empty())
417                                 file = file2;
418                 }
419                 if (!file.exists())
420                         break;
421                 int percent_scale = 100;
422                 if (use_gui) {
423                         // Compute the scale factor for the icon such its
424                         // width on screen is equal to 1em in pixels.
425                         // The scale factor is rounded to the integer nearest
426                         // to the float value of the ratio 100*iconsize/imgsize.
427                         int imgsize = QImage(toqstr(file.absFileName())).width();
428                         if (imgsize > 0) {
429                                 int iconsize = Length(1, Length::EM).inPixels(1);
430                                 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
431                         }
432                 }
433                 InsetGraphics * inset = new InsetGraphics(buffer_);
434                 InsetGraphicsParams igp;
435                 igp.filename = file;
436                 igp.lyxscale = percent_scale;
437                 igp.scale = string();
438                 igp.width = Length(1, Length::EM);
439                 inset->setParams(igp);
440                 clear();
441                 Font const f(inherit_font, buffer().params().language);
442                 paragraphs().front().insertInset(0, inset, f,
443                                                  Change(Change::UNCHANGED));
444                 break;
445         }
446         case BUFFER_INFO: {
447                 if (name_ == "name") {
448                         setText(from_utf8(buffer().fileName().onlyFileName()));
449                         break;
450                 }
451                 if (name_ == "path") {
452                         setText(from_utf8(os::latex_path(buffer().filePath())));
453                         break;
454                 }
455                 if (name_ == "class") {
456                         setText(from_utf8(bp.documentClass().name()));
457                         break;
458                 }
459                 
460                 // everything that follows is for version control.
461                 // nothing that isn't version control should go below this line.
462                 if (!buffer().lyxvc().inUse()) {
463                         setText(_("No version control"));
464                         break;
465                 }
466                 LyXVC::RevisionInfo itype = LyXVC::Unknown;
467                 if (name_ == "vcs-revision")
468                         itype = LyXVC::File;
469                 else if (name_ == "vcs-tree-revision")
470                         itype = LyXVC::Tree;
471                 else if (name_ == "vcs-author")
472                         itype = LyXVC::Author;
473                 else if (name_ == "vcs-time")
474                         itype = LyXVC::Time;
475                 else if (name_ == "vcs-date")
476                         itype = LyXVC::Date;
477                 string binfo = buffer().lyxvc().revisionInfo(itype);
478                 if (binfo.empty())
479                         setText(from_ascii(name_) + " unknown");
480                 else
481                         setText(from_utf8(binfo));
482                 break;
483         }
484         case LYX_INFO:
485                 if (name_ == "version")
486                         setText(from_ascii(lyx_version));
487                 break;
488         }
489 }
490
491
492 string InsetInfo::contextMenu(BufferView const &, int, int) const
493 {
494         //FIXME: We override the implementation of InsetCollapsable,
495         //because this inset is not a collapsable inset.
496         return contextMenuName();
497 }
498
499
500 string InsetInfo::contextMenuName() const
501 {
502         return "context-info";
503 }
504
505
506 } // namespace lyx