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"
53 #include "support/lassert.h"
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/filetools.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
66 #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 */
144 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
147 QString const & label,
148 QString const & submenu = QString(),
149 bool optional = false)
150 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
152 LASSERT(kind == Submenu, /**/);
156 QString const & label,
157 FuncRequest const & func,
158 bool optional = false)
159 : kind_(kind), label_(label), func_(func), optional_(optional)
161 func_.origin = FuncRequest::MENU;
164 // boost::shared_ptr<MenuDefinition> needs this apprently...
167 /// The label of a given menuitem
168 QString label() const { return label_.split('|')[0]; }
170 /// The keyboard shortcut (usually underlined in the entry)
171 QString shortcut() const
173 return label_.contains('|') ? label_.split('|')[1] : QString();
175 /// The complete label, with label and shortcut separated by a '|'
176 QString fulllabel() const { return label_;}
177 /// The kind of entry
178 Kind kind() const { return kind_; }
179 /// the action (if relevant)
180 FuncRequest const & func() const { return func_; }
181 /// returns true if the entry should be ommited when disabled
182 bool optional() const { return optional_; }
183 /// returns the status of the lfun associated with this entry
184 FuncStatus const & status() const { return status_; }
185 /// returns the status of the lfun associated with this entry
186 FuncStatus & status() { return status_; }
187 /// returns the status of the lfun associated with this entry
188 void status(FuncStatus const & status) { status_ = status; }
190 ///returns the binding associated to this action.
191 QString binding() const
193 if (kind_ != Command)
195 // Get the keys bound to this action, but keep only the
197 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
199 return toqstr(bindings.begin()->print(KeySequence::ForGui));
201 LYXERR(Debug::KBMAP, "No binding for "
202 << lyxaction.getActionName(func_.action)
203 << '(' << func_.argument() << ')');
207 /// the description of the submenu (if relevant)
208 QString const & submenuname() const { return submenuname_; }
209 /// set the description of the submenu
210 void submenuname(QString const & name) { submenuname_ = name; }
212 bool hasSubmenu() const { return !submenu_.isEmpty(); }
214 MenuDefinition const & submenu() const { return submenu_.at(0); }
215 MenuDefinition & submenu() { return submenu_[0]; }
217 void setSubmenu(MenuDefinition const & menu)
220 submenu_.append(menu);
231 QString submenuname_;
236 /// contains 0 or 1 item.
237 QList<MenuDefinition> submenu_;
241 class MenuDefinition {
244 typedef std::vector<MenuItem> ItemList;
246 typedef ItemList::const_iterator const_iterator;
248 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
253 QString const & name() const { return name_; }
255 bool empty() const { return items_.empty(); }
256 /// Clear the menu content.
257 void clear() { items_.clear(); }
259 size_t size() const { return items_.size(); }
261 MenuItem const & operator[](size_t) const;
263 const_iterator begin() const { return items_.begin(); }
265 const_iterator end() const { return items_.end(); }
267 // search for func in this menu iteratively, and put menu
269 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
272 bool hasFunc(FuncRequest const &) const;
273 /// Add the menu item unconditionally
274 void add(MenuItem const & item) { items_.push_back(item); }
275 /// Checks the associated FuncRequest status before adding the
277 void addWithStatusCheck(MenuItem const &);
278 // Check whether the menu shortcuts are unique
279 void checkShortcuts() const;
281 void expandLastfiles();
282 void expandDocuments();
283 void expandBookmarks();
284 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
285 void expandFloatListInsert(Buffer const * buf);
286 void expandFloatInsert(Buffer const * buf);
287 void expandFlexInsert(Buffer const * buf, std::string s);
288 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
289 void expandToc(Buffer const * buf);
290 void expandPasteRecent();
291 void expandToolbars();
292 void expandBranches(Buffer const * buf);
293 void expandCiteStyles(BufferView const *);
301 /// Helper for std::find_if
305 MenuNamesEqual(QString const & name) : name_(name) {}
306 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
313 typedef std::vector<MenuDefinition> MenuList;
315 typedef MenuList::const_iterator const_iterator;
317 typedef MenuList::iterator iterator;
319 /////////////////////////////////////////////////////////////////////
320 // MenuDefinition implementation
321 /////////////////////////////////////////////////////////////////////
323 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
327 case MenuItem::Command: {
328 FuncStatus status = lyx::getStatus(i.func());
329 if (status.unknown() || (!status.enabled() && i.optional()))
332 items_.back().status(status);
336 case MenuItem::Submenu: {
337 if (i.hasSubmenu()) {
338 bool enabled = false;
339 for (const_iterator cit = i.submenu().begin();
340 cit != i.submenu().end(); ++cit) {
341 if ((cit->kind() == MenuItem::Command
342 || cit->kind() == MenuItem::Submenu)
343 && cit->status().enabled()) {
348 if (enabled || !i.optional()) {
350 items_.back().status().enabled(enabled);
358 case MenuItem::Separator:
359 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
369 void MenuDefinition::read(Lexer & lex)
397 LexerKeyword menutags[] = {
398 { "bookmarks", md_bookmarks },
399 { "branches", md_branches },
400 { "charstyles", md_charstyles },
401 { "citestyles", md_citestyles },
402 { "custom", md_custom },
403 { "documents", md_documents },
404 { "elements", md_elements },
405 { "end", md_endmenu },
406 { "exportformats", md_exportformats },
407 { "floatinsert", md_floatinsert },
408 { "floatlistinsert", md_floatlistinsert },
409 { "importformats", md_importformats },
411 { "lastfiles", md_lastfiles },
412 { "optitem", md_optitem },
413 { "optsubmenu", md_optsubmenu },
414 { "pasterecent", md_pasterecent },
415 { "separator", md_separator },
416 { "submenu", md_submenu },
418 { "toolbars", md_toolbars },
419 { "updateformats", md_updateformats },
420 { "viewformats", md_viewformats }
423 lex.pushTable(menutags);
424 lex.setContext("MenuDefinition::read: ");
427 bool optional = false;
429 while (lex.isOK() && !quit) {
433 // fallback to md_item
436 docstring const name = translateIfPossible(lex.getDocString());
438 string const command = lex.getString();
439 FuncRequest func = lyxaction.lookupFunc(command);
440 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
446 add(MenuItem(MenuItem::Separator));
450 add(MenuItem(MenuItem::Lastfiles));
454 add(MenuItem(MenuItem::CharStyles));
458 add(MenuItem(MenuItem::Custom));
462 add(MenuItem(MenuItem::Elements));
466 add(MenuItem(MenuItem::Documents));
470 add(MenuItem(MenuItem::Bookmarks));
474 add(MenuItem(MenuItem::Toc));
478 add(MenuItem(MenuItem::ViewFormats));
481 case md_updateformats:
482 add(MenuItem(MenuItem::UpdateFormats));
485 case md_exportformats:
486 add(MenuItem(MenuItem::ExportFormats));
489 case md_importformats:
490 add(MenuItem(MenuItem::ImportFormats));
493 case md_floatlistinsert:
494 add(MenuItem(MenuItem::FloatListInsert));
498 add(MenuItem(MenuItem::FloatInsert));
502 add(MenuItem(MenuItem::PasteRecent));
506 add(MenuItem(MenuItem::Toolbars));
510 add(MenuItem(MenuItem::Branches));
514 add(MenuItem(MenuItem::CiteStyles));
519 // fallback to md_submenu
522 docstring const mlabel = translateIfPossible(lex.getDocString());
524 docstring const mname = lex.getDocString();
525 add(MenuItem(MenuItem::Submenu,
526 toqstr(mlabel), toqstr(mname), optional));
536 lex.printError("Unknown menu tag");
544 MenuItem const & MenuDefinition::operator[](size_type i) const
550 bool MenuDefinition::hasFunc(FuncRequest const & func) const
552 for (const_iterator it = begin(), et = end(); it != et; ++it)
553 if (it->func() == func)
559 void MenuDefinition::checkShortcuts() const
561 // This is a quadratic algorithm, but we do not care because
562 // menus are short enough
563 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
564 QString shortcut = it1->shortcut();
565 if (shortcut.isEmpty())
567 if (!it1->label().contains(shortcut))
568 LYXERR0("Menu warning: menu entry \""
570 << "\" does not contain shortcut `"
571 << shortcut << "'." << endl);
572 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
573 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
574 LYXERR0("Menu warning: menu entries "
575 << '"' << it1->fulllabel()
576 << "\" and \"" << it2->fulllabel()
577 << "\" share the same shortcut."
585 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
587 const_iterator m = begin();
588 const_iterator m_end = end();
589 for (; m != m_end; ++m) {
590 if (m->kind() == MenuItem::Command && m->func() == func) {
591 names.push_back(qstring_to_ucs4(m->label()));
594 if (m->kind() == MenuItem::Submenu) {
595 names.push_back(qstring_to_ucs4(m->label()));
596 if (!m->hasSubmenu()) {
597 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
598 << m->label() << " name=" << m->submenuname());
602 if (m->submenu().searchMenu(func, names))
611 bool compareFormat(Format const * p1, Format const * p2)
617 QString limitStringLength(docstring const & str)
619 size_t const max_item_length = 45;
621 if (str.size() > max_item_length)
622 return toqstr(str.substr(0, max_item_length - 3) + "...");
628 void MenuDefinition::expandLastfiles()
630 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
631 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
635 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
636 string const file = lfit->absFilename();
637 QString const label = QString("%1. %2|%3").arg(ii)
638 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
639 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
644 void MenuDefinition::expandDocuments()
646 Buffer * first = theBufferList().first();
651 // We cannot use a for loop as the buffer list cycles.
653 QString label = toqstr(b->fileName().displayName(20));
657 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
658 add(MenuItem(MenuItem::Command, label,
659 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
661 b = theBufferList().next(b);
663 } while (b != first);
665 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
666 FuncRequest(LFUN_NOACTION)));
671 void MenuDefinition::expandBookmarks()
673 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
675 for (size_t i = 1; i <= bm.size(); ++i) {
677 string const file = bm.bookmark(i).filename.absFilename();
678 QString const label = QString("%1. %2|%3").arg(i)
679 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
680 add(MenuItem(MenuItem::Command, label,
681 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
687 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
689 if (!buf && kind != MenuItem::ImportFormats) {
690 add(MenuItem(MenuItem::Command,
691 qt_("No Document Open!"),
692 FuncRequest(LFUN_NOACTION)));
696 typedef vector<Format const *> Formats;
701 case MenuItem::ImportFormats:
702 formats = theConverters().importableFormats();
703 action = LFUN_BUFFER_IMPORT;
705 case MenuItem::ViewFormats:
706 formats = buf->exportableFormats(true);
707 action = LFUN_BUFFER_VIEW;
709 case MenuItem::UpdateFormats:
710 formats = buf->exportableFormats(true);
711 action = LFUN_BUFFER_UPDATE;
714 formats = buf->exportableFormats(false);
715 action = LFUN_BUFFER_EXPORT;
717 sort(formats.begin(), formats.end(), &compareFormat);
719 Formats::const_iterator fit = formats.begin();
720 Formats::const_iterator end = formats.end();
721 for (; fit != end ; ++fit) {
724 QString label = toqstr((*fit)->prettyname());
725 QString const shortcut = toqstr((*fit)->shortcut());
728 case MenuItem::ImportFormats:
729 // FIXME: This is a hack, we should rather solve
730 // FIXME: bug 2488 instead.
731 if ((*fit)->name() == "text")
732 label = qt_("Plain Text");
733 else if ((*fit)->name() == "textparagraph")
734 label = qt_("Plain Text, Join Lines");
737 case MenuItem::ViewFormats:
738 case MenuItem::ExportFormats:
739 case MenuItem::UpdateFormats:
740 if (!(*fit)->documentFormat())
744 LASSERT(false, /**/);
747 // FIXME: if we had proper support for translating the
748 // format names defined in configure.py, there would
749 // not be a need to check whether the shortcut is
750 // correct. If we add it uncondiitonally, it would
751 // create useless warnings on bad shortcuts
752 if (!shortcut.isEmpty() && label.contains(shortcut))
753 label += '|' + shortcut;
756 addWithStatusCheck(MenuItem(MenuItem::Command, label,
757 FuncRequest(action, (*fit)->name())));
759 add(MenuItem(MenuItem::Command, label,
760 FuncRequest(action, (*fit)->name())));
765 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
768 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
769 FuncRequest(LFUN_NOACTION)));
773 FloatList const & floats = buf->params().documentClass().floats();
774 FloatList::const_iterator cit = floats.begin();
775 FloatList::const_iterator end = floats.end();
776 for (; cit != end; ++cit) {
777 addWithStatusCheck(MenuItem(MenuItem::Command,
778 qt_(cit->second.listName()),
779 FuncRequest(LFUN_FLOAT_LIST,
780 cit->second.type())));
785 void MenuDefinition::expandFloatInsert(Buffer const * buf)
788 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
789 FuncRequest(LFUN_NOACTION)));
793 FloatList const & floats = buf->params().documentClass().floats();
794 FloatList::const_iterator cit = floats.begin();
795 FloatList::const_iterator end = floats.end();
796 for (; cit != end; ++cit) {
798 QString const label = qt_(cit->second.name());
799 addWithStatusCheck(MenuItem(MenuItem::Command, label,
800 FuncRequest(LFUN_FLOAT_INSERT,
801 cit->second.type())));
806 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
809 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
810 FuncRequest(LFUN_NOACTION)));
813 TextClass::InsetLayouts const & insetLayouts =
814 buf->params().documentClass().insetLayouts();
815 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
816 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
817 for (; cit != end; ++cit) {
818 docstring const label = cit->first;
819 if (cit->second.lyxtype() == s)
820 addWithStatusCheck(MenuItem(MenuItem::Command,
821 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
827 size_t const max_number_of_items = 25;
829 void MenuDefinition::expandToc2(Toc const & toc_list,
830 size_t from, size_t to, int depth)
832 int shortcut_count = 0;
834 // check whether depth is smaller than the smallest depth in toc.
835 int min_depth = 1000;
836 for (size_t i = from; i < to; ++i)
837 min_depth = min(min_depth, toc_list[i].depth());
838 if (min_depth > depth)
841 if (to - from <= max_number_of_items) {
842 for (size_t i = from; i < to; ++i) {
843 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
844 label += limitStringLength(toc_list[i].str());
845 if (toc_list[i].depth() == depth
846 && shortcut_count < 9) {
847 if (label.contains(QString::number(shortcut_count + 1)))
848 label += '|' + QString::number(++shortcut_count);
850 add(MenuItem(MenuItem::Command, label,
851 FuncRequest(toc_list[i].action())));
856 size_t new_pos = pos + 1;
857 while (new_pos < to && toc_list[new_pos].depth() > depth)
860 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
861 label += limitStringLength(toc_list[pos].str());
862 if (toc_list[pos].depth() == depth &&
863 shortcut_count < 9) {
864 if (label.contains(QString::number(shortcut_count + 1)))
865 label += '|' + QString::number(++shortcut_count);
867 if (new_pos == pos + 1) {
868 add(MenuItem(MenuItem::Command,
869 label, FuncRequest(toc_list[pos].action())));
872 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
873 MenuItem item(MenuItem::Submenu, label);
874 item.setSubmenu(sub);
883 void MenuDefinition::expandToc(Buffer const * buf)
885 // To make things very cleanly, we would have to pass buf to
886 // all MenuItem constructors and to expandToc2. However, we
887 // know that all the entries in a TOC will be have status_ ==
888 // OK, so we avoid this unnecessary overhead (JMarc)
891 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
892 FuncRequest(LFUN_NOACTION)));
896 Buffer* cbuf = const_cast<Buffer*>(buf);
897 cbuf->tocBackend().update();
898 cbuf->structureChanged();
900 // Add an entry for the master doc if this is a child doc
901 Buffer const * const master = buf->masterBuffer();
903 ParIterator const pit = par_iterator_begin(master->inset());
904 string const arg = convert<string>(pit->id());
905 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
906 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
909 MenuDefinition other_lists;
911 FloatList const & floatlist = buf->params().documentClass().floats();
912 TocList const & toc_list = buf->tocBackend().tocs();
913 TocList::const_iterator cit = toc_list.begin();
914 TocList::const_iterator end = toc_list.end();
915 for (; cit != end; ++cit) {
917 if (cit->first == "tableofcontents")
920 string const & floatName = floatlist.getType(cit->first).listName();
922 bool in_other_list = true;
923 if (!floatName.empty()) {
924 label = qt_(floatName);
925 in_other_list = false;
927 else if (cit->first == "child") {
928 label = qt_("Child Documents");
929 in_other_list = false;
930 } else if (cit->first == "graphics")
931 label = qt_("List of Graphics");
932 else if (cit->first == "equation")
933 label = qt_("List of Equations");
934 else if (cit->first == "index")
935 label = qt_("List of Indexes");
936 else if (cit->first == "listing") {
937 // FIXME: the listing navigate menu causes a crash for unknown
938 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
939 // This is a temporary fix:
940 //label = qt_("List of Listings");
943 else if (cit->first == "marginalnote")
944 label = qt_("List of Marginal notes");
945 else if (cit->first == "note")
946 label = qt_("List of Notes");
947 else if (cit->first == "footnote")
948 label = qt_("List of Footnotes");
949 else if (cit->first == "label")
950 label = qt_("Labels and References");
951 else if (cit->first == "citation")
952 label = qt_("List of Citations");
954 // This should not happen unless the entry is missing above.
955 label = qt_("Other floats: ") + toqstr(cit->first);
957 MenuDefinition submenu;
959 if (cit->second.size() >= 30) {
960 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
961 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
963 TocIterator ccit = cit->second.begin();
964 TocIterator eend = cit->second.end();
965 for (; ccit != eend; ++ccit) {
966 QString const label = limitStringLength(ccit->str());
967 submenu.add(MenuItem(MenuItem::Command, label,
968 FuncRequest(ccit->action())));
972 MenuItem item(MenuItem::Submenu, label);
973 item.setSubmenu(submenu);
975 other_lists.add(item);
977 item.setSubmenu(submenu);
981 if (!other_lists.empty()) {
982 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
983 item.setSubmenu(other_lists);
989 cit = toc_list.find("tableofcontents");
991 addWithStatusCheck(MenuItem(MenuItem::Command,
992 qt_("No Table of contents"),
995 expandToc2(cit->second, 0, cit->second.size(), 0);
1000 void MenuDefinition::expandPasteRecent()
1002 vector<docstring> const sel = cap::availableSelections();
1004 vector<docstring>::const_iterator cit = sel.begin();
1005 vector<docstring>::const_iterator end = sel.end();
1007 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1008 add(MenuItem(MenuItem::Command, toqstr(*cit),
1009 FuncRequest(LFUN_PASTE, convert<string>(index))));
1014 void MenuDefinition::expandToolbars()
1017 // extracts the toolbars from the backend
1018 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1019 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1021 for (; cit != end; ++cit) {
1022 QString label = qt_(cit->gui_name);
1023 // frontends are not supposed to turn on/off toolbars,
1024 // if they cannot update ToolbarBackend::flags. That
1025 // is to say, ToolbarsBackend::flags should reflect
1026 // the true state of toolbars.
1028 // menu is displayed as
1032 // in the case of auto.
1033 if (cit->flags & ToolbarInfo::AUTO)
1034 label += qt_(" (auto)");
1035 add(MenuItem(MenuItem::Command, label,
1036 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1041 void MenuDefinition::expandBranches(Buffer const * buf)
1044 add(MenuItem(MenuItem::Command,
1045 qt_("No Document Open!"),
1046 FuncRequest(LFUN_NOACTION)));
1050 BufferParams const & params = buf->masterBuffer()->params();
1051 if (params.branchlist().empty()) {
1052 add(MenuItem(MenuItem::Command,
1053 qt_("No Branch in Document!"),
1054 FuncRequest(LFUN_NOACTION)));
1058 BranchList::const_iterator cit = params.branchlist().begin();
1059 BranchList::const_iterator end = params.branchlist().end();
1061 for (int ii = 1; cit != end; ++cit, ++ii) {
1062 docstring label = cit->getBranch();
1064 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1065 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1066 FuncRequest(LFUN_BRANCH_INSERT,
1067 cit->getBranch())));
1072 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1075 add(MenuItem(MenuItem::Command,
1076 qt_("No Document Open!"),
1077 FuncRequest(LFUN_NOACTION)));
1081 Inset const * inset = bv->cursor().nextInset();
1082 if (!inset || inset->lyxCode() != CITE_CODE) {
1083 add(MenuItem(MenuItem::Command,
1084 qt_("No Citation in Scope!"),
1085 FuncRequest(LFUN_NOACTION)));
1088 InsetCommand const * citinset =
1089 static_cast<InsetCommand const *>(inset);
1091 Buffer const * buf = &bv->buffer();
1092 docstring key = citinset->getParam("key");
1093 // we can only handle one key currently
1094 if (contains(key, ','))
1095 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1097 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1098 vector<docstring> citeStrings =
1099 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1101 vector<docstring>::const_iterator cit = citeStrings.begin();
1102 vector<docstring>::const_iterator end = citeStrings.end();
1104 for (int ii = 1; cit != end; ++cit, ++ii) {
1105 docstring label = *cit;
1107 CiteStyle cst = citeStyleList[ii - 1];
1109 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1110 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1111 "changetype " + from_utf8(citationStyleToString(cs)))));
1118 /////////////////////////////////////////////////////////////////////
1119 // Menu::Impl definition and implementation
1120 /////////////////////////////////////////////////////////////////////
1124 /// populates the menu or one of its submenu
1125 /// This is used as a recursive function
1126 void populate(QMenu & qMenu, MenuDefinition const & menu);
1128 /// Only needed for top level menus.
1129 MenuDefinition * top_level_menu;
1132 /// the name of this menu
1138 /// Get a MenuDefinition item label from the menu backend
1139 static QString label(MenuItem const & mi)
1141 QString label = mi.label();
1142 label.replace("&", "&&");
1144 QString shortcut = mi.shortcut();
1145 if (!shortcut.isEmpty()) {
1146 int pos = label.indexOf(shortcut);
1148 //label.insert(pos, 1, char_type('&'));
1149 label.replace(pos, 0, "&");
1152 QString const binding = mi.binding();
1153 if (!binding.isEmpty())
1154 label += '\t' + binding;
1159 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1161 LYXERR(Debug::GUI, "populating menu " << menu.name());
1162 if (menu.size() == 0) {
1163 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1166 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1167 MenuDefinition::const_iterator m = menu.begin();
1168 MenuDefinition::const_iterator end = menu.end();
1169 for (; m != end; ++m) {
1170 if (m->kind() == MenuItem::Separator)
1171 qMenu.addSeparator();
1172 else if (m->kind() == MenuItem::Submenu) {
1173 QMenu * subMenu = qMenu.addMenu(label(*m));
1174 populate(*subMenu, m->submenu());
1176 // we have a MenuItem::Command
1177 qMenu.addAction(new Action(view, QIcon(), label(*m),
1178 m->func(), QString(), &qMenu));
1183 /////////////////////////////////////////////////////////////////////
1184 // Menu implementation
1185 /////////////////////////////////////////////////////////////////////
1187 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1188 : QMenu(gv), d(new Menu::Impl)
1190 d->top_level_menu = top_level? new MenuDefinition : 0;
1194 if (d->top_level_menu)
1195 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1201 delete d->top_level_menu;
1206 void Menu::updateView()
1208 guiApp->menus().updateMenu(this);
1212 /////////////////////////////////////////////////////////////////////
1213 // Menus::Impl definition and implementation
1214 /////////////////////////////////////////////////////////////////////
1216 struct Menus::Impl {
1218 bool hasMenu(QString const &) const;
1220 MenuDefinition & getMenu(QString const &);
1222 MenuDefinition const & getMenu(QString const &) const;
1224 /// Expands some special entries of the menu
1225 /** The entries with the following kind are expanded to a
1226 sequence of Command MenuItems: Lastfiles, Documents,
1227 ViewFormats, ExportFormats, UpdateFormats, Branches
1229 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1230 BufferView const *) const;
1232 /// Initialize specific MACOS X menubar
1233 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1235 /// Mac special menu.
1236 /** This defines a menu whose entries list the FuncRequests
1237 that will be removed by expand() in other menus. This is
1238 used by the Qt/Mac code
1240 MenuDefinition specialmenu_;
1245 MenuDefinition menubar_;
1247 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1249 /// name to menu for \c menu() method.
1254 Here is what the Qt documentation says about how a menubar is chosen:
1256 1) If the window has a QMenuBar then it is used. 2) If the window
1257 is a modal then its menubar is used. If no menubar is specified
1258 then a default menubar is used (as documented below) 3) If the
1259 window has no parent then the default menubar is used (as
1262 The above 3 steps are applied all the way up the parent window
1263 chain until one of the above are satisifed. If all else fails a
1264 default menubar will be created, the default menubar on Qt/Mac is
1265 an empty menubar, however you can create a different default
1266 menubar by creating a parentless QMenuBar, the first one created
1267 will thus be designated the default menubar, and will be used
1268 whenever a default menubar is needed.
1270 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1271 that this menubar will be used also when one of LyX' dialogs has
1274 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1276 /* Since Qt 4.2, the qt/mac menu code has special code for
1277 specifying the role of a menu entry. However, it does not
1278 work very well with our scheme of creating menus on demand,
1279 and therefore we need to put these entries in a special
1280 invisible menu. (JMarc)
1283 /* The entries of our special mac menu. If we add support for
1284 * special entries in Menus, we could imagine something
1286 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1287 * and therefore avoid hardcoding. I am not sure it is worth
1288 * the hassle, though. (JMarc)
1290 struct MacMenuEntry {
1294 QAction::MenuRole role;
1297 MacMenuEntry entries[] = {
1298 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1299 QAction::AboutRole},
1300 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1301 QAction::PreferencesRole},
1302 {LFUN_RECONFIGURE, "", "Reconfigure",
1303 QAction::ApplicationSpecificRole},
1304 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1306 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1308 // the special menu for Menus. Fill it up only once.
1309 if (specialmenu_.size() == 0) {
1310 for (size_t i = 0 ; i < num_entries ; ++i) {
1311 FuncRequest const func(entries[i].action,
1312 from_utf8(entries[i].arg));
1313 specialmenu_.add(MenuItem(MenuItem::Command,
1314 entries[i].label, func));
1318 // add the entries to a QMenu that will eventually be empty
1319 // and therefore invisible.
1320 QMenu * qMenu = qmb->addMenu("special");
1321 MenuDefinition::const_iterator cit = specialmenu_.begin();
1322 MenuDefinition::const_iterator end = specialmenu_.end();
1323 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1324 Action * action = new Action(view, QIcon(), cit->label(),
1325 cit->func(), QString(), qMenu);
1326 action->setMenuRole(entries[i].role);
1327 qMenu->addAction(action);
1332 void Menus::Impl::expand(MenuDefinition const & frommenu,
1333 MenuDefinition & tomenu, BufferView const * bv) const
1335 if (!tomenu.empty())
1338 for (MenuDefinition::const_iterator cit = frommenu.begin();
1339 cit != frommenu.end() ; ++cit) {
1340 Buffer const * buf = bv ? &bv->buffer() : 0;
1341 switch (cit->kind()) {
1342 case MenuItem::Lastfiles:
1343 tomenu.expandLastfiles();
1346 case MenuItem::Documents:
1347 tomenu.expandDocuments();
1350 case MenuItem::Bookmarks:
1351 tomenu.expandBookmarks();
1354 case MenuItem::ImportFormats:
1355 case MenuItem::ViewFormats:
1356 case MenuItem::UpdateFormats:
1357 case MenuItem::ExportFormats:
1358 tomenu.expandFormats(cit->kind(), buf);
1361 case MenuItem::CharStyles:
1362 tomenu.expandFlexInsert(buf, "charstyle");
1365 case MenuItem::Custom:
1366 tomenu.expandFlexInsert(buf, "custom");
1369 case MenuItem::Elements:
1370 tomenu.expandFlexInsert(buf, "element");
1373 case MenuItem::FloatListInsert:
1374 tomenu.expandFloatListInsert(buf);
1377 case MenuItem::FloatInsert:
1378 tomenu.expandFloatInsert(buf);
1381 case MenuItem::PasteRecent:
1382 tomenu.expandPasteRecent();
1385 case MenuItem::Toolbars:
1386 tomenu.expandToolbars();
1389 case MenuItem::Branches:
1390 tomenu.expandBranches(buf);
1393 case MenuItem::CiteStyles:
1394 tomenu.expandCiteStyles(bv);
1398 tomenu.expandToc(buf);
1401 case MenuItem::Submenu: {
1402 MenuItem item(*cit);
1403 item.setSubmenu(MenuDefinition(cit->submenuname()));
1404 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1405 tomenu.addWithStatusCheck(item);
1409 case MenuItem::Separator:
1410 tomenu.addWithStatusCheck(*cit);
1413 case MenuItem::Command:
1414 if (!specialmenu_.hasFunc(cit->func()))
1415 tomenu.addWithStatusCheck(*cit);
1419 // we do not want the menu to end with a separator
1420 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1421 tomenu.items_.pop_back();
1423 // Check whether the shortcuts are unique
1424 tomenu.checkShortcuts();
1428 bool Menus::Impl::hasMenu(QString const & name) const
1430 return find_if(menulist_.begin(), menulist_.end(),
1431 MenuNamesEqual(name)) != menulist_.end();
1435 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1437 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1438 MenuNamesEqual(name));
1439 if (cit == menulist_.end())
1440 lyxerr << "No submenu named " << name << endl;
1441 LASSERT(cit != menulist_.end(), /**/);
1446 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1448 iterator it = find_if(menulist_.begin(), menulist_.end(),
1449 MenuNamesEqual(name));
1450 if (it == menulist_.end())
1451 lyxerr << "No submenu named " << name << endl;
1452 LASSERT(it != menulist_.end(), /**/);
1457 /////////////////////////////////////////////////////////////////////
1461 /////////////////////////////////////////////////////////////////////
1463 Menus::Menus() : d(new Impl) {}
1470 void Menus::read(Lexer & lex)
1478 LexerKeyword menutags[] = {
1479 { "end", md_endmenuset },
1480 { "menu", md_menu },
1481 { "menubar", md_menubar }
1484 // consistency check
1485 if (compare_ascii_no_case(lex.getString(), "menuset"))
1486 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1488 lex.pushTable(menutags);
1489 lex.setContext("Menus::read");
1493 while (lex.isOK() && !quit) {
1494 switch (lex.lex()) {
1496 d->menubar_.read(lex);
1500 QString const name = toqstr(lex.getDocString());
1501 if (d->hasMenu(name))
1502 d->getMenu(name).read(lex);
1504 MenuDefinition menu(name);
1506 d->menulist_.push_back(menu);
1514 lex.printError("Unknown menu tag");
1522 bool Menus::searchMenu(FuncRequest const & func,
1523 vector<docstring> & names) const
1525 MenuDefinition menu;
1526 d->expand(d->menubar_, menu, 0);
1527 return menu.searchMenu(func, names);
1531 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1535 // setup special mac specific menu item
1536 d->macxMenuBarInit(view, qmb);
1539 // Clear all menubar contents before filling it.
1543 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1545 if (d->menubar_.size() == 0) {
1546 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1547 << d->menubar_.name());
1550 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1552 MenuDefinition menu;
1553 BufferView * bv = 0;
1556 d->expand(d->menubar_, menu, bv);
1558 MenuDefinition::const_iterator m = menu.begin();
1559 MenuDefinition::const_iterator end = menu.end();
1561 for (; m != end; ++m) {
1563 if (m->kind() != MenuItem::Submenu) {
1564 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1568 LYXERR(Debug::GUI, "menu bar item " << m->label()
1569 << " is a submenu named " << m->submenuname());
1571 QString name = m->submenuname();
1572 if (!d->hasMenu(name)) {
1573 LYXERR(Debug::GUI, "\tERROR: " << name
1574 << " submenu has no menu!");
1578 Menu * menu = new Menu(view, m->submenuname(), true);
1579 menu->setTitle(label(*m));
1582 d->name_map_[view][name] = menu;
1587 void Menus::updateMenu(Menu * qmenu)
1589 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1592 if (qmenu->d->name.isEmpty())
1595 // Here, We make sure that theLyXFunc points to the correct LyXView.
1596 theLyXFunc().setLyXView(qmenu->d->view);
1598 if (!d->hasMenu(qmenu->d->name)) {
1599 qmenu->addAction(qt_("No action defined!"));
1600 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1605 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1606 BufferView * bv = 0;
1608 bv = qmenu->d->view->view();
1609 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1610 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1614 Menu * Menus::menu(QString const & name, GuiView & view)
1616 LYXERR(Debug::GUI, "Context menu requested: " << name);
1617 Menu * menu = d->name_map_[&view].value(name, 0);
1618 if (!menu && !name.startsWith("context-")) {
1619 LYXERR0("requested context menu not found: " << name);
1623 menu = new Menu(&view, name, true);
1624 d->name_map_[&view][name] = menu;
1628 } // namespace frontend
1631 #include "Menus_moc.cpp"