3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Asger Alstrup
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Martin Vermeer
14 * Full author contact details are available in file CREDITS.
22 #include "GuiApplication.h"
24 #include "qt_helpers.h"
26 #include "BiblioInfo.h"
27 #include "BranchList.h"
29 #include "BufferList.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "Converter.h"
33 #include "CutAndPaste.h"
35 #include "FloatList.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
41 #include "LyXAction.h"
42 #include "LyX.h" // for lastfiles
44 #include "Paragraph.h"
46 #include "TextClass.h"
47 #include "TocBackend.h"
48 #include "ToolbarBackend.h"
50 #include "insets/Inset.h"
51 #include "insets/InsetCitation.h"
52 #include "insets/InsetGraphics.h"
54 #include "support/lassert.h"
55 #include "support/convert.h"
56 #include "support/debug.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
67 #include <boost/shared_ptr.hpp>
73 using namespace lyx::support;
81 // MacOSX specific stuff is at the end.
88 /// The type of elements that can be in a menu
96 /** This is the list of last opened file,
97 typically for the File menu. */
99 /** This is the list of opened Documents,
100 typically for the Documents menu. */
102 /** This is the bookmarks */
106 /** This is a list of viewable formats
107 typically for the File->View menu. */
109 /** This is a list of updatable formats
110 typically for the File->Update menu. */
112 /** This is a list of exportable formats
113 typically for the File->Export menu. */
115 /** This is a list of importable formats
116 typically for the File->Export menu. */
118 /** This is the list of elements available
119 * for insertion into document. */
121 /** This is the list of user-configurable
122 insets to insert into document */
124 /** This is the list of XML elements to
125 insert into the document */
127 /** This is the list of floats that we can
128 insert a list for. */
130 /** This is the list of floats that we can
133 /** This is the list of selections that can
138 /** Available branches in document */
140 /** Available citation styles for a given citation */
142 /** Available graphics groups */
146 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
149 QString const & label,
150 QString const & submenu = QString(),
151 bool optional = false)
152 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
154 LASSERT(kind == Submenu, /**/);
158 QString const & label,
159 FuncRequest const & func,
160 bool optional = false)
161 : kind_(kind), label_(label), func_(func), optional_(optional)
163 func_.origin = FuncRequest::MENU;
166 // boost::shared_ptr<MenuDefinition> needs this apprently...
169 /// The label of a given menuitem
170 QString label() const { return label_.split('|')[0]; }
172 /// The keyboard shortcut (usually underlined in the entry)
173 QString shortcut() const
175 return label_.contains('|') ? label_.split('|')[1] : QString();
177 /// The complete label, with label and shortcut separated by a '|'
178 QString fulllabel() const { return label_;}
179 /// The kind of entry
180 Kind kind() const { return kind_; }
181 /// the action (if relevant)
182 FuncRequest const & func() const { return func_; }
183 /// returns true if the entry should be ommited when disabled
184 bool optional() const { return optional_; }
185 /// returns the status of the lfun associated with this entry
186 FuncStatus const & status() const { return status_; }
187 /// returns the status of the lfun associated with this entry
188 FuncStatus & status() { return status_; }
189 /// returns the status of the lfun associated with this entry
190 void status(FuncStatus const & status) { status_ = status; }
192 ///returns the binding associated to this action.
193 QString binding() const
195 if (kind_ != Command)
197 // Get the keys bound to this action, but keep only the
199 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
201 return toqstr(bindings.begin()->print(KeySequence::ForGui));
203 LYXERR(Debug::KBMAP, "No binding for "
204 << lyxaction.getActionName(func_.action)
205 << '(' << func_.argument() << ')');
209 /// the description of the submenu (if relevant)
210 QString const & submenuname() const { return submenuname_; }
211 /// set the description of the submenu
212 void submenuname(QString const & name) { submenuname_ = name; }
214 bool hasSubmenu() const { return !submenu_.isEmpty(); }
216 MenuDefinition const & submenu() const { return submenu_.at(0); }
217 MenuDefinition & submenu() { return submenu_[0]; }
219 void setSubmenu(MenuDefinition const & menu)
222 submenu_.append(menu);
233 QString submenuname_;
238 /// contains 0 or 1 item.
239 QList<MenuDefinition> submenu_;
243 class MenuDefinition {
246 typedef std::vector<MenuItem> ItemList;
248 typedef ItemList::const_iterator const_iterator;
250 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
255 QString const & name() const { return name_; }
257 bool empty() const { return items_.empty(); }
258 /// Clear the menu content.
259 void clear() { items_.clear(); }
261 size_t size() const { return items_.size(); }
263 MenuItem const & operator[](size_t) const;
265 const_iterator begin() const { return items_.begin(); }
267 const_iterator end() const { return items_.end(); }
269 // search for func in this menu iteratively, and put menu
271 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
274 bool hasFunc(FuncRequest const &) const;
275 /// Add the menu item unconditionally
276 void add(MenuItem const & item) { items_.push_back(item); }
277 /// Checks the associated FuncRequest status before adding the
279 void addWithStatusCheck(MenuItem const &);
280 // Check whether the menu shortcuts are unique
281 void checkShortcuts() const;
283 void expandLastfiles();
284 void expandDocuments();
285 void expandBookmarks();
286 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
287 void expandFloatListInsert(Buffer const * buf);
288 void expandFloatInsert(Buffer const * buf);
289 void expandFlexInsert(Buffer const * buf, std::string s);
290 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
291 void expandToc(Buffer const * buf);
292 void expandPasteRecent();
293 void expandToolbars();
294 void expandBranches(Buffer const * buf);
295 void expandCiteStyles(BufferView const *);
296 void expandGraphicsGroups(Buffer const * buf);
304 /// Helper for std::find_if
308 MenuNamesEqual(QString const & name) : name_(name) {}
309 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
316 typedef std::vector<MenuDefinition> MenuList;
318 typedef MenuList::const_iterator const_iterator;
320 typedef MenuList::iterator iterator;
322 /////////////////////////////////////////////////////////////////////
323 // MenuDefinition implementation
324 /////////////////////////////////////////////////////////////////////
326 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
330 case MenuItem::Command: {
331 FuncStatus status = lyx::getStatus(i.func());
332 if (status.unknown() || (!status.enabled() && i.optional()))
335 items_.back().status(status);
339 case MenuItem::Submenu: {
340 if (i.hasSubmenu()) {
341 bool enabled = false;
342 for (const_iterator cit = i.submenu().begin();
343 cit != i.submenu().end(); ++cit) {
344 if ((cit->kind() == MenuItem::Command
345 || cit->kind() == MenuItem::Submenu)
346 && cit->status().enabled()) {
351 if (enabled || !i.optional()) {
353 items_.back().status().enabled(enabled);
361 case MenuItem::Separator:
362 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
372 void MenuDefinition::read(Lexer & lex)
401 LexerKeyword menutags[] = {
402 { "bookmarks", md_bookmarks },
403 { "branches", md_branches },
404 { "charstyles", md_charstyles },
405 { "citestyles", md_citestyles },
406 { "custom", md_custom },
407 { "documents", md_documents },
408 { "elements", md_elements },
409 { "end", md_endmenu },
410 { "exportformats", md_exportformats },
411 { "floatinsert", md_floatinsert },
412 { "floatlistinsert", md_floatlistinsert },
413 { "graphicsgroups", md_graphicsgroups },
414 { "importformats", md_importformats },
416 { "lastfiles", md_lastfiles },
417 { "optitem", md_optitem },
418 { "optsubmenu", md_optsubmenu },
419 { "pasterecent", md_pasterecent },
420 { "separator", md_separator },
421 { "submenu", md_submenu },
423 { "toolbars", md_toolbars },
424 { "updateformats", md_updateformats },
425 { "viewformats", md_viewformats }
428 lex.pushTable(menutags);
429 lex.setContext("MenuDefinition::read: ");
432 bool optional = false;
434 while (lex.isOK() && !quit) {
438 // fallback to md_item
441 docstring const name = translateIfPossible(lex.getDocString());
443 string const command = lex.getString();
444 FuncRequest func = lyxaction.lookupFunc(command);
445 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
451 add(MenuItem(MenuItem::Separator));
455 add(MenuItem(MenuItem::Lastfiles));
459 add(MenuItem(MenuItem::CharStyles));
463 add(MenuItem(MenuItem::Custom));
467 add(MenuItem(MenuItem::Elements));
471 add(MenuItem(MenuItem::Documents));
475 add(MenuItem(MenuItem::Bookmarks));
479 add(MenuItem(MenuItem::Toc));
483 add(MenuItem(MenuItem::ViewFormats));
486 case md_updateformats:
487 add(MenuItem(MenuItem::UpdateFormats));
490 case md_exportformats:
491 add(MenuItem(MenuItem::ExportFormats));
494 case md_importformats:
495 add(MenuItem(MenuItem::ImportFormats));
498 case md_floatlistinsert:
499 add(MenuItem(MenuItem::FloatListInsert));
503 add(MenuItem(MenuItem::FloatInsert));
507 add(MenuItem(MenuItem::PasteRecent));
511 add(MenuItem(MenuItem::Toolbars));
515 add(MenuItem(MenuItem::Branches));
519 add(MenuItem(MenuItem::CiteStyles));
522 case md_graphicsgroups:
523 add(MenuItem(MenuItem::GraphicsGroups));
528 // fallback to md_submenu
531 docstring const mlabel = translateIfPossible(lex.getDocString());
533 docstring const mname = lex.getDocString();
534 add(MenuItem(MenuItem::Submenu,
535 toqstr(mlabel), toqstr(mname), optional));
545 lex.printError("Unknown menu tag");
553 MenuItem const & MenuDefinition::operator[](size_type i) const
559 bool MenuDefinition::hasFunc(FuncRequest const & func) const
561 for (const_iterator it = begin(), et = end(); it != et; ++it)
562 if (it->func() == func)
568 void MenuDefinition::checkShortcuts() const
570 // This is a quadratic algorithm, but we do not care because
571 // menus are short enough
572 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
573 QString shortcut = it1->shortcut();
574 if (shortcut.isEmpty())
576 if (!it1->label().contains(shortcut))
577 LYXERR0("Menu warning: menu entry \""
579 << "\" does not contain shortcut `"
580 << shortcut << "'.");
581 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
582 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
583 LYXERR0("Menu warning: menu entries "
584 << '"' << it1->fulllabel()
585 << "\" and \"" << it2->fulllabel()
586 << "\" share the same shortcut.");
593 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
595 const_iterator m = begin();
596 const_iterator m_end = end();
597 for (; m != m_end; ++m) {
598 if (m->kind() == MenuItem::Command && m->func() == func) {
599 names.push_back(qstring_to_ucs4(m->label()));
602 if (m->kind() == MenuItem::Submenu) {
603 names.push_back(qstring_to_ucs4(m->label()));
604 if (!m->hasSubmenu()) {
605 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
606 << m->label() << " name=" << m->submenuname());
610 if (m->submenu().searchMenu(func, names))
619 bool compareFormat(Format const * p1, Format const * p2)
625 QString limitStringLength(docstring const & str)
627 size_t const max_item_length = 45;
629 if (str.size() > max_item_length)
630 return toqstr(str.substr(0, max_item_length - 3) + "...");
636 void MenuDefinition::expandGraphicsGroups(Buffer const * buf)
639 InsetGraphics::getGraphicsGroups(*buf, grp);
640 set<string>::const_iterator it = grp.begin();
641 set<string>::const_iterator end = grp.end();
642 if (grp.empty()) return;
644 add(MenuItem(MenuItem::Separator));
645 add(MenuItem(MenuItem::Command, qt_("Clear group"), FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
646 for (; it != end; it++) {
647 add(MenuItem(MenuItem::Command, toqstr(*it), FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
651 void MenuDefinition::expandLastfiles()
653 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
654 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
658 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
659 string const file = lfit->absFilename();
660 QString const label = QString("%1. %2|%3").arg(ii)
661 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
662 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
667 void MenuDefinition::expandDocuments()
669 Buffer * first = theBufferList().first();
674 // We cannot use a for loop as the buffer list cycles.
676 QString label = toqstr(b->fileName().displayName(20));
680 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
681 add(MenuItem(MenuItem::Command, label,
682 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
684 b = theBufferList().next(b);
686 } while (b != first);
688 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
689 FuncRequest(LFUN_NOACTION)));
694 void MenuDefinition::expandBookmarks()
696 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
698 for (size_t i = 1; i <= bm.size(); ++i) {
700 string const file = bm.bookmark(i).filename.absFilename();
701 QString const label = QString("%1. %2|%3").arg(i)
702 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
703 add(MenuItem(MenuItem::Command, label,
704 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
710 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
712 if (!buf && kind != MenuItem::ImportFormats) {
713 add(MenuItem(MenuItem::Command,
714 qt_("No Document Open!"),
715 FuncRequest(LFUN_NOACTION)));
719 typedef vector<Format const *> Formats;
724 case MenuItem::ImportFormats:
725 formats = theConverters().importableFormats();
726 action = LFUN_BUFFER_IMPORT;
728 case MenuItem::ViewFormats:
729 formats = buf->exportableFormats(true);
730 action = LFUN_BUFFER_VIEW;
732 case MenuItem::UpdateFormats:
733 formats = buf->exportableFormats(true);
734 action = LFUN_BUFFER_UPDATE;
737 formats = buf->exportableFormats(false);
738 action = LFUN_BUFFER_EXPORT;
740 sort(formats.begin(), formats.end(), &compareFormat);
742 Formats::const_iterator fit = formats.begin();
743 Formats::const_iterator end = formats.end();
744 for (; fit != end ; ++fit) {
747 QString label = toqstr((*fit)->prettyname());
748 QString const shortcut = toqstr((*fit)->shortcut());
751 case MenuItem::ImportFormats:
752 // FIXME: This is a hack, we should rather solve
753 // FIXME: bug 2488 instead.
754 if ((*fit)->name() == "text")
755 label = qt_("Plain Text");
756 else if ((*fit)->name() == "textparagraph")
757 label = qt_("Plain Text, Join Lines");
760 case MenuItem::ViewFormats:
761 case MenuItem::ExportFormats:
762 case MenuItem::UpdateFormats:
763 if (!(*fit)->documentFormat())
767 LASSERT(false, /**/);
770 // FIXME: if we had proper support for translating the
771 // format names defined in configure.py, there would
772 // not be a need to check whether the shortcut is
773 // correct. If we add it uncondiitonally, it would
774 // create useless warnings on bad shortcuts
775 if (!shortcut.isEmpty() && label.contains(shortcut))
776 label += '|' + shortcut;
779 addWithStatusCheck(MenuItem(MenuItem::Command, label,
780 FuncRequest(action, (*fit)->name())));
782 add(MenuItem(MenuItem::Command, label,
783 FuncRequest(action, (*fit)->name())));
788 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
791 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
792 FuncRequest(LFUN_NOACTION)));
796 FloatList const & floats = buf->params().documentClass().floats();
797 FloatList::const_iterator cit = floats.begin();
798 FloatList::const_iterator end = floats.end();
799 for (; cit != end; ++cit) {
800 addWithStatusCheck(MenuItem(MenuItem::Command,
801 qt_(cit->second.listName()),
802 FuncRequest(LFUN_FLOAT_LIST,
803 cit->second.type())));
808 void MenuDefinition::expandFloatInsert(Buffer const * buf)
811 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
812 FuncRequest(LFUN_NOACTION)));
816 FloatList const & floats = buf->params().documentClass().floats();
817 FloatList::const_iterator cit = floats.begin();
818 FloatList::const_iterator end = floats.end();
819 for (; cit != end; ++cit) {
821 QString const label = qt_(cit->second.name());
822 addWithStatusCheck(MenuItem(MenuItem::Command, label,
823 FuncRequest(LFUN_FLOAT_INSERT,
824 cit->second.type())));
829 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
832 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
833 FuncRequest(LFUN_NOACTION)));
836 TextClass::InsetLayouts const & insetLayouts =
837 buf->params().documentClass().insetLayouts();
838 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
839 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
840 for (; cit != end; ++cit) {
841 docstring const label = cit->first;
842 if (cit->second.lyxtype() == s)
843 addWithStatusCheck(MenuItem(MenuItem::Command,
844 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
850 size_t const max_number_of_items = 25;
852 void MenuDefinition::expandToc2(Toc const & toc_list,
853 size_t from, size_t to, int depth)
855 int shortcut_count = 0;
857 // check whether depth is smaller than the smallest depth in toc.
858 int min_depth = 1000;
859 for (size_t i = from; i < to; ++i)
860 min_depth = min(min_depth, toc_list[i].depth());
861 if (min_depth > depth)
864 if (to - from <= max_number_of_items) {
865 for (size_t i = from; i < to; ++i) {
866 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
867 label += limitStringLength(toc_list[i].str());
868 if (toc_list[i].depth() == depth
869 && shortcut_count < 9) {
870 if (label.contains(QString::number(shortcut_count + 1)))
871 label += '|' + QString::number(++shortcut_count);
873 add(MenuItem(MenuItem::Command, label,
874 FuncRequest(toc_list[i].action())));
879 size_t new_pos = pos + 1;
880 while (new_pos < to && toc_list[new_pos].depth() > depth)
883 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
884 label += limitStringLength(toc_list[pos].str());
885 if (toc_list[pos].depth() == depth &&
886 shortcut_count < 9) {
887 if (label.contains(QString::number(shortcut_count + 1)))
888 label += '|' + QString::number(++shortcut_count);
890 if (new_pos == pos + 1) {
891 add(MenuItem(MenuItem::Command,
892 label, FuncRequest(toc_list[pos].action())));
895 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
896 MenuItem item(MenuItem::Submenu, label);
897 item.setSubmenu(sub);
906 void MenuDefinition::expandToc(Buffer const * buf)
908 // To make things very cleanly, we would have to pass buf to
909 // all MenuItem constructors and to expandToc2. However, we
910 // know that all the entries in a TOC will be have status_ ==
911 // OK, so we avoid this unnecessary overhead (JMarc)
914 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
915 FuncRequest(LFUN_NOACTION)));
919 Buffer* cbuf = const_cast<Buffer*>(buf);
920 cbuf->tocBackend().update();
921 cbuf->structureChanged();
923 // Add an entry for the master doc if this is a child doc
924 Buffer const * const master = buf->masterBuffer();
926 ParIterator const pit = par_iterator_begin(master->inset());
927 string const arg = convert<string>(pit->id());
928 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
929 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
932 MenuDefinition other_lists;
934 FloatList const & floatlist = buf->params().documentClass().floats();
935 TocList const & toc_list = buf->tocBackend().tocs();
936 TocList::const_iterator cit = toc_list.begin();
937 TocList::const_iterator end = toc_list.end();
938 for (; cit != end; ++cit) {
940 if (cit->first == "tableofcontents")
943 string const & floatName = floatlist.getType(cit->first).listName();
945 bool in_other_list = true;
946 if (!floatName.empty()) {
947 label = qt_(floatName);
948 in_other_list = false;
950 else if (cit->first == "child") {
951 label = qt_("Child Documents");
952 in_other_list = false;
953 } else if (cit->first == "graphics")
954 label = qt_("List of Graphics");
955 else if (cit->first == "equation")
956 label = qt_("List of Equations");
957 else if (cit->first == "index")
958 label = qt_("List of Indexes");
959 else if (cit->first == "listing") {
960 // FIXME: the listing navigate menu causes a crash for unknown
961 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
962 // This is a temporary fix:
963 //label = qt_("List of Listings");
966 else if (cit->first == "marginalnote")
967 label = qt_("List of Marginal notes");
968 else if (cit->first == "note")
969 label = qt_("List of Notes");
970 else if (cit->first == "footnote")
971 label = qt_("List of Footnotes");
972 else if (cit->first == "label")
973 label = qt_("Labels and References");
974 else if (cit->first == "citation")
975 label = qt_("List of Citations");
977 // This should not happen unless the entry is missing above.
978 label = qt_("Other floats: ") + toqstr(cit->first);
980 MenuDefinition submenu;
982 if (cit->second.size() >= 30) {
983 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
984 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
986 TocIterator ccit = cit->second.begin();
987 TocIterator eend = cit->second.end();
988 for (; ccit != eend; ++ccit) {
989 QString const label = limitStringLength(ccit->str());
990 submenu.add(MenuItem(MenuItem::Command, label,
991 FuncRequest(ccit->action())));
995 MenuItem item(MenuItem::Submenu, label);
996 item.setSubmenu(submenu);
998 other_lists.add(item);
1000 item.setSubmenu(submenu);
1004 if (!other_lists.empty()) {
1005 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1006 item.setSubmenu(other_lists);
1011 // Handle normal TOC
1012 cit = toc_list.find("tableofcontents");
1014 addWithStatusCheck(MenuItem(MenuItem::Command,
1015 qt_("No Table of contents"),
1018 expandToc2(cit->second, 0, cit->second.size(), 0);
1023 void MenuDefinition::expandPasteRecent()
1025 vector<docstring> const sel = cap::availableSelections();
1027 vector<docstring>::const_iterator cit = sel.begin();
1028 vector<docstring>::const_iterator end = sel.end();
1030 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1031 add(MenuItem(MenuItem::Command, toqstr(*cit),
1032 FuncRequest(LFUN_PASTE, convert<string>(index))));
1037 void MenuDefinition::expandToolbars()
1040 // extracts the toolbars from the backend
1041 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1042 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1044 for (; cit != end; ++cit) {
1045 QString label = qt_(cit->gui_name);
1046 // frontends are not supposed to turn on/off toolbars,
1047 // if they cannot update ToolbarBackend::flags. That
1048 // is to say, ToolbarsBackend::flags should reflect
1049 // the true state of toolbars.
1051 // menu is displayed as
1055 // in the case of auto.
1056 if (cit->flags & ToolbarInfo::AUTO)
1057 label += qt_(" (auto)");
1058 add(MenuItem(MenuItem::Command, label,
1059 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1064 void MenuDefinition::expandBranches(Buffer const * buf)
1067 add(MenuItem(MenuItem::Command,
1068 qt_("No Document Open!"),
1069 FuncRequest(LFUN_NOACTION)));
1073 BufferParams const & params = buf->masterBuffer()->params();
1074 if (params.branchlist().empty()) {
1075 add(MenuItem(MenuItem::Command,
1076 qt_("No Branch in Document!"),
1077 FuncRequest(LFUN_NOACTION)));
1081 BranchList::const_iterator cit = params.branchlist().begin();
1082 BranchList::const_iterator end = params.branchlist().end();
1084 for (int ii = 1; cit != end; ++cit, ++ii) {
1085 docstring label = cit->getBranch();
1087 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1088 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1089 FuncRequest(LFUN_BRANCH_INSERT,
1090 cit->getBranch())));
1095 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1098 add(MenuItem(MenuItem::Command,
1099 qt_("No Document Open!"),
1100 FuncRequest(LFUN_NOACTION)));
1104 Inset const * inset = bv->cursor().nextInset();
1105 if (!inset || inset->lyxCode() != CITE_CODE) {
1106 add(MenuItem(MenuItem::Command,
1107 qt_("No Citation in Scope!"),
1108 FuncRequest(LFUN_NOACTION)));
1111 InsetCommand const * citinset =
1112 static_cast<InsetCommand const *>(inset);
1114 Buffer const * buf = &bv->buffer();
1115 docstring key = citinset->getParam("key");
1116 // we can only handle one key currently
1117 if (contains(key, ','))
1118 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1120 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1121 vector<docstring> citeStrings =
1122 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1124 vector<docstring>::const_iterator cit = citeStrings.begin();
1125 vector<docstring>::const_iterator end = citeStrings.end();
1127 for (int ii = 1; cit != end; ++cit, ++ii) {
1128 docstring label = *cit;
1130 CiteStyle cst = citeStyleList[ii - 1];
1132 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1133 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1134 "changetype " + from_utf8(citationStyleToString(cs)))));
1141 /////////////////////////////////////////////////////////////////////
1142 // Menu::Impl definition and implementation
1143 /////////////////////////////////////////////////////////////////////
1147 /// populates the menu or one of its submenu
1148 /// This is used as a recursive function
1149 void populate(QMenu & qMenu, MenuDefinition const & menu);
1151 /// Only needed for top level menus.
1152 MenuDefinition * top_level_menu;
1155 /// the name of this menu
1161 /// Get a MenuDefinition item label from the menu backend
1162 static QString label(MenuItem const & mi)
1164 QString label = mi.label();
1165 label.replace("&", "&&");
1167 QString shortcut = mi.shortcut();
1168 if (!shortcut.isEmpty()) {
1169 int pos = label.indexOf(shortcut);
1171 //label.insert(pos, 1, char_type('&'));
1172 label.replace(pos, 0, "&");
1175 QString const binding = mi.binding();
1176 if (!binding.isEmpty())
1177 label += '\t' + binding;
1182 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1184 LYXERR(Debug::GUI, "populating menu " << menu.name());
1185 if (menu.size() == 0) {
1186 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1189 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1190 MenuDefinition::const_iterator m = menu.begin();
1191 MenuDefinition::const_iterator end = menu.end();
1192 for (; m != end; ++m) {
1193 if (m->kind() == MenuItem::Separator)
1194 qMenu.addSeparator();
1195 else if (m->kind() == MenuItem::Submenu) {
1196 QMenu * subMenu = qMenu.addMenu(label(*m));
1197 populate(*subMenu, m->submenu());
1199 // we have a MenuItem::Command
1200 qMenu.addAction(new Action(view, QIcon(), label(*m),
1201 m->func(), QString(), &qMenu));
1206 /////////////////////////////////////////////////////////////////////
1207 // Menu implementation
1208 /////////////////////////////////////////////////////////////////////
1210 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1211 : QMenu(gv), d(new Menu::Impl)
1213 d->top_level_menu = top_level? new MenuDefinition : 0;
1217 if (d->top_level_menu)
1218 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1224 delete d->top_level_menu;
1229 void Menu::updateView()
1231 guiApp->menus().updateMenu(this);
1235 /////////////////////////////////////////////////////////////////////
1236 // Menus::Impl definition and implementation
1237 /////////////////////////////////////////////////////////////////////
1239 struct Menus::Impl {
1241 bool hasMenu(QString const &) const;
1243 MenuDefinition & getMenu(QString const &);
1245 MenuDefinition const & getMenu(QString const &) const;
1247 /// Expands some special entries of the menu
1248 /** The entries with the following kind are expanded to a
1249 sequence of Command MenuItems: Lastfiles, Documents,
1250 ViewFormats, ExportFormats, UpdateFormats, Branches
1252 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1253 BufferView const *) const;
1255 /// Initialize specific MACOS X menubar
1256 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1258 /// Mac special menu.
1259 /** This defines a menu whose entries list the FuncRequests
1260 that will be removed by expand() in other menus. This is
1261 used by the Qt/Mac code
1263 MenuDefinition specialmenu_;
1268 MenuDefinition menubar_;
1270 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1272 /// name to menu for \c menu() method.
1277 Here is what the Qt documentation says about how a menubar is chosen:
1279 1) If the window has a QMenuBar then it is used. 2) If the window
1280 is a modal then its menubar is used. If no menubar is specified
1281 then a default menubar is used (as documented below) 3) If the
1282 window has no parent then the default menubar is used (as
1285 The above 3 steps are applied all the way up the parent window
1286 chain until one of the above are satisifed. If all else fails a
1287 default menubar will be created, the default menubar on Qt/Mac is
1288 an empty menubar, however you can create a different default
1289 menubar by creating a parentless QMenuBar, the first one created
1290 will thus be designated the default menubar, and will be used
1291 whenever a default menubar is needed.
1293 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1294 that this menubar will be used also when one of LyX' dialogs has
1297 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1299 /* Since Qt 4.2, the qt/mac menu code has special code for
1300 specifying the role of a menu entry. However, it does not
1301 work very well with our scheme of creating menus on demand,
1302 and therefore we need to put these entries in a special
1303 invisible menu. (JMarc)
1306 /* The entries of our special mac menu. If we add support for
1307 * special entries in Menus, we could imagine something
1309 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1310 * and therefore avoid hardcoding. I am not sure it is worth
1311 * the hassle, though. (JMarc)
1313 struct MacMenuEntry {
1317 QAction::MenuRole role;
1320 MacMenuEntry entries[] = {
1321 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1322 QAction::AboutRole},
1323 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1324 QAction::PreferencesRole},
1325 {LFUN_RECONFIGURE, "", "Reconfigure",
1326 QAction::ApplicationSpecificRole},
1327 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1329 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1331 // the special menu for Menus. Fill it up only once.
1332 if (specialmenu_.size() == 0) {
1333 for (size_t i = 0 ; i < num_entries ; ++i) {
1334 FuncRequest const func(entries[i].action,
1335 from_utf8(entries[i].arg));
1336 specialmenu_.add(MenuItem(MenuItem::Command,
1337 entries[i].label, func));
1341 // add the entries to a QMenu that will eventually be empty
1342 // and therefore invisible.
1343 QMenu * qMenu = qmb->addMenu("special");
1344 MenuDefinition::const_iterator cit = specialmenu_.begin();
1345 MenuDefinition::const_iterator end = specialmenu_.end();
1346 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1347 Action * action = new Action(view, QIcon(), cit->label(),
1348 cit->func(), QString(), qMenu);
1349 action->setMenuRole(entries[i].role);
1350 qMenu->addAction(action);
1355 void Menus::Impl::expand(MenuDefinition const & frommenu,
1356 MenuDefinition & tomenu, BufferView const * bv) const
1358 if (!tomenu.empty())
1361 for (MenuDefinition::const_iterator cit = frommenu.begin();
1362 cit != frommenu.end() ; ++cit) {
1363 Buffer const * buf = bv ? &bv->buffer() : 0;
1364 switch (cit->kind()) {
1365 case MenuItem::Lastfiles:
1366 tomenu.expandLastfiles();
1369 case MenuItem::Documents:
1370 tomenu.expandDocuments();
1373 case MenuItem::Bookmarks:
1374 tomenu.expandBookmarks();
1377 case MenuItem::ImportFormats:
1378 case MenuItem::ViewFormats:
1379 case MenuItem::UpdateFormats:
1380 case MenuItem::ExportFormats:
1381 tomenu.expandFormats(cit->kind(), buf);
1384 case MenuItem::CharStyles:
1385 tomenu.expandFlexInsert(buf, "charstyle");
1388 case MenuItem::Custom:
1389 tomenu.expandFlexInsert(buf, "custom");
1392 case MenuItem::Elements:
1393 tomenu.expandFlexInsert(buf, "element");
1396 case MenuItem::FloatListInsert:
1397 tomenu.expandFloatListInsert(buf);
1400 case MenuItem::FloatInsert:
1401 tomenu.expandFloatInsert(buf);
1404 case MenuItem::PasteRecent:
1405 tomenu.expandPasteRecent();
1408 case MenuItem::Toolbars:
1409 tomenu.expandToolbars();
1412 case MenuItem::Branches:
1413 tomenu.expandBranches(buf);
1416 case MenuItem::CiteStyles:
1417 tomenu.expandCiteStyles(bv);
1421 tomenu.expandToc(buf);
1424 case MenuItem::GraphicsGroups:
1425 tomenu.expandGraphicsGroups(buf);
1428 case MenuItem::Submenu: {
1429 MenuItem item(*cit);
1430 item.setSubmenu(MenuDefinition(cit->submenuname()));
1431 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1432 tomenu.addWithStatusCheck(item);
1436 case MenuItem::Separator:
1437 tomenu.addWithStatusCheck(*cit);
1440 case MenuItem::Command:
1441 if (!specialmenu_.hasFunc(cit->func()))
1442 tomenu.addWithStatusCheck(*cit);
1446 // we do not want the menu to end with a separator
1447 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1448 tomenu.items_.pop_back();
1450 // Check whether the shortcuts are unique
1451 tomenu.checkShortcuts();
1455 bool Menus::Impl::hasMenu(QString const & name) const
1457 return find_if(menulist_.begin(), menulist_.end(),
1458 MenuNamesEqual(name)) != menulist_.end();
1462 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1464 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1465 MenuNamesEqual(name));
1466 if (cit == menulist_.end())
1467 LYXERR0("No submenu named " << name);
1468 LASSERT(cit != menulist_.end(), /**/);
1473 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1475 iterator it = find_if(menulist_.begin(), menulist_.end(),
1476 MenuNamesEqual(name));
1477 if (it == menulist_.end())
1478 LYXERR0("No submenu named " << name);
1479 LASSERT(it != menulist_.end(), /**/);
1484 /////////////////////////////////////////////////////////////////////
1488 /////////////////////////////////////////////////////////////////////
1490 Menus::Menus() : d(new Impl) {}
1497 void Menus::read(Lexer & lex)
1505 LexerKeyword menutags[] = {
1506 { "end", md_endmenuset },
1507 { "menu", md_menu },
1508 { "menubar", md_menubar }
1511 // consistency check
1512 if (compare_ascii_no_case(lex.getString(), "menuset"))
1513 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1515 lex.pushTable(menutags);
1516 lex.setContext("Menus::read");
1520 while (lex.isOK() && !quit) {
1521 switch (lex.lex()) {
1523 d->menubar_.read(lex);
1527 QString const name = toqstr(lex.getDocString());
1528 if (d->hasMenu(name))
1529 d->getMenu(name).read(lex);
1531 MenuDefinition menu(name);
1533 d->menulist_.push_back(menu);
1541 lex.printError("Unknown menu tag");
1549 bool Menus::searchMenu(FuncRequest const & func,
1550 vector<docstring> & names) const
1552 MenuDefinition menu;
1553 d->expand(d->menubar_, menu, 0);
1554 return menu.searchMenu(func, names);
1558 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1562 // setup special mac specific menu item
1563 d->macxMenuBarInit(view, qmb);
1566 // Clear all menubar contents before filling it.
1570 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1572 if (d->menubar_.size() == 0) {
1573 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1574 << d->menubar_.name());
1577 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1579 MenuDefinition menu;
1580 BufferView * bv = 0;
1583 d->expand(d->menubar_, menu, bv);
1585 MenuDefinition::const_iterator m = menu.begin();
1586 MenuDefinition::const_iterator end = menu.end();
1588 for (; m != end; ++m) {
1590 if (m->kind() != MenuItem::Submenu) {
1591 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1595 LYXERR(Debug::GUI, "menu bar item " << m->label()
1596 << " is a submenu named " << m->submenuname());
1598 QString name = m->submenuname();
1599 if (!d->hasMenu(name)) {
1600 LYXERR(Debug::GUI, "\tERROR: " << name
1601 << " submenu has no menu!");
1605 Menu * menu = new Menu(view, m->submenuname(), true);
1606 menu->setTitle(label(*m));
1609 d->name_map_[view][name] = menu;
1614 void Menus::updateMenu(Menu * qmenu)
1616 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1619 if (qmenu->d->name.isEmpty())
1622 // Here, We make sure that theLyXFunc points to the correct LyXView.
1623 theLyXFunc().setLyXView(qmenu->d->view);
1625 if (!d->hasMenu(qmenu->d->name)) {
1626 qmenu->addAction(qt_("No action defined!"));
1627 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1632 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1633 BufferView * bv = 0;
1635 bv = qmenu->d->view->view();
1636 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1637 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1641 Menu * Menus::menu(QString const & name, GuiView & view)
1643 LYXERR(Debug::GUI, "Context menu requested: " << name);
1644 Menu * menu = d->name_map_[&view].value(name, 0);
1645 if (!menu && !name.startsWith("context-")) {
1646 LYXERR0("requested context menu not found: " << name);
1650 menu = new Menu(&view, name, true);
1651 d->name_map_[&view][name] = menu;
1655 } // namespace frontend
1658 #include "Menus_moc.cpp"