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