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>
72 using namespace lyx::support;
80 // MacOSX specific stuff is at the end.
87 /// The type of elements that can be in a menu
95 /** This is the list of last opened file,
96 typically for the File menu. */
98 /** This is the list of opened Documents,
99 typically for the Documents menu. */
101 /** This is the bookmarks */
105 /** This is a list of viewable formats
106 typically for the File->View menu. */
108 /** This is a list of updatable formats
109 typically for the File->Update menu. */
111 /** This is a list of exportable formats
112 typically for the File->Export menu. */
114 /** This is a list of importable formats
115 typically for the File->Export menu. */
117 /** This is the list of elements available
118 * for insertion into document. */
120 /** This is the list of user-configurable
121 insets to insert into document */
123 /** This is the list of XML elements to
124 insert into the document */
126 /** This is the list of floats that we can
127 insert a list for. */
129 /** This is the list of floats that we can
132 /** This is the list of selections that can
137 /** Available branches in document */
139 /** Available citation styles for a given citation */
143 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
146 QString const & label,
147 QString const & submenu = QString(),
148 bool optional = false)
149 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
151 LASSERT(kind == Submenu, /**/);
155 QString const & label,
156 FuncRequest const & func,
157 bool optional = false)
158 : kind_(kind), label_(label), func_(func), optional_(optional)
160 func_.origin = FuncRequest::MENU;
163 // boost::shared_ptr<MenuDefinition> needs this apprently...
166 /// The label of a given menuitem
167 QString label() const { return label_.split('|')[0]; }
169 /// The keyboard shortcut (usually underlined in the entry)
170 QString shortcut() const
172 return label_.contains('|') ? label_.split('|')[1] : QString();
174 /// The complete label, with label and shortcut separated by a '|'
175 QString fulllabel() const { return label_;}
176 /// The kind of entry
177 Kind kind() const { return kind_; }
178 /// the action (if relevant)
179 FuncRequest const & func() const { return func_; }
180 /// returns true if the entry should be ommited when disabled
181 bool optional() const { return optional_; }
182 /// returns the status of the lfun associated with this entry
183 FuncStatus const & status() const { return status_; }
184 /// returns the status of the lfun associated with this entry
185 FuncStatus & status() { return status_; }
186 /// returns the status of the lfun associated with this entry
187 void status(FuncStatus const & status) { status_ = status; }
189 ///returns the binding associated to this action.
190 QString binding() const
192 if (kind_ != Command)
194 // Get the keys bound to this action, but keep only the
196 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
198 return toqstr(bindings.begin()->print(KeySequence::ForGui));
200 LYXERR(Debug::KBMAP, "No binding for "
201 << lyxaction.getActionName(func_.action)
202 << '(' << func_.argument() << ')');
206 /// the description of the submenu (if relevant)
207 QString const & submenuname() const { return submenuname_; }
208 /// set the description of the submenu
209 void submenuname(QString const & name) { submenuname_ = name; }
211 bool hasSubmenu() const { return !submenu_.isEmpty(); }
213 MenuDefinition const & submenu() const { return submenu_.at(0); }
214 MenuDefinition & submenu() { return submenu_[0]; }
216 void setSubmenu(MenuDefinition const & menu)
219 submenu_.append(menu);
230 QString submenuname_;
235 /// contains 0 or 1 item.
236 QList<MenuDefinition> submenu_;
240 class MenuDefinition {
243 typedef std::vector<MenuItem> ItemList;
245 typedef ItemList::const_iterator const_iterator;
247 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
252 QString const & name() const { return name_; }
254 bool empty() const { return items_.empty(); }
255 /// Clear the menu content.
256 void clear() { items_.clear(); }
258 size_t size() const { return items_.size(); }
260 MenuItem const & operator[](size_t) const;
262 const_iterator begin() const { return items_.begin(); }
264 const_iterator end() const { return items_.end(); }
266 // search for func in this menu iteratively, and put menu
268 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
271 bool hasFunc(FuncRequest const &) const;
272 /// Add the menu item unconditionally
273 void add(MenuItem const & item) { items_.push_back(item); }
274 /// Checks the associated FuncRequest status before adding the
276 void addWithStatusCheck(MenuItem const &);
277 // Check whether the menu shortcuts are unique
278 void checkShortcuts() const;
280 void expandLastfiles();
281 void expandDocuments();
282 void expandBookmarks();
283 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
284 void expandFloatListInsert(Buffer const * buf);
285 void expandFloatInsert(Buffer const * buf);
286 void expandFlexInsert(Buffer const * buf, std::string s);
287 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
288 void expandToc(Buffer const * buf);
289 void expandPasteRecent();
290 void expandToolbars();
291 void expandBranches(Buffer const * buf);
292 void expandCiteStyles(BufferView const *);
300 /// Helper for std::find_if
304 MenuNamesEqual(QString const & name) : name_(name) {}
305 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
312 typedef std::vector<MenuDefinition> MenuList;
314 typedef MenuList::const_iterator const_iterator;
316 typedef MenuList::iterator iterator;
318 /////////////////////////////////////////////////////////////////////
319 // MenuDefinition implementation
320 /////////////////////////////////////////////////////////////////////
322 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
326 case MenuItem::Command: {
327 FuncStatus status = lyx::getStatus(i.func());
328 if (status.unknown() || (!status.enabled() && i.optional()))
331 items_.back().status(status);
335 case MenuItem::Submenu: {
336 if (i.hasSubmenu()) {
337 bool enabled = false;
338 for (const_iterator cit = i.submenu().begin();
339 cit != i.submenu().end(); ++cit) {
340 if ((cit->kind() == MenuItem::Command
341 || cit->kind() == MenuItem::Submenu)
342 && cit->status().enabled()) {
347 if (enabled || !i.optional()) {
349 items_.back().status().enabled(enabled);
357 case MenuItem::Separator:
358 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
368 void MenuDefinition::read(Lexer & lex)
396 LexerKeyword menutags[] = {
397 { "bookmarks", md_bookmarks },
398 { "branches", md_branches },
399 { "charstyles", md_charstyles },
400 { "citestyles", md_citestyles },
401 { "custom", md_custom },
402 { "documents", md_documents },
403 { "elements", md_elements },
404 { "end", md_endmenu },
405 { "exportformats", md_exportformats },
406 { "floatinsert", md_floatinsert },
407 { "floatlistinsert", md_floatlistinsert },
408 { "importformats", md_importformats },
410 { "lastfiles", md_lastfiles },
411 { "optitem", md_optitem },
412 { "optsubmenu", md_optsubmenu },
413 { "pasterecent", md_pasterecent },
414 { "separator", md_separator },
415 { "submenu", md_submenu },
417 { "toolbars", md_toolbars },
418 { "updateformats", md_updateformats },
419 { "viewformats", md_viewformats }
422 lex.pushTable(menutags);
423 lex.setContext("MenuDefinition::read: ");
426 bool optional = false;
428 while (lex.isOK() && !quit) {
432 // fallback to md_item
435 docstring const name = translateIfPossible(lex.getDocString());
437 string const command = lex.getString();
438 FuncRequest func = lyxaction.lookupFunc(command);
439 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
445 add(MenuItem(MenuItem::Separator));
449 add(MenuItem(MenuItem::Lastfiles));
453 add(MenuItem(MenuItem::CharStyles));
457 add(MenuItem(MenuItem::Custom));
461 add(MenuItem(MenuItem::Elements));
465 add(MenuItem(MenuItem::Documents));
469 add(MenuItem(MenuItem::Bookmarks));
473 add(MenuItem(MenuItem::Toc));
477 add(MenuItem(MenuItem::ViewFormats));
480 case md_updateformats:
481 add(MenuItem(MenuItem::UpdateFormats));
484 case md_exportformats:
485 add(MenuItem(MenuItem::ExportFormats));
488 case md_importformats:
489 add(MenuItem(MenuItem::ImportFormats));
492 case md_floatlistinsert:
493 add(MenuItem(MenuItem::FloatListInsert));
497 add(MenuItem(MenuItem::FloatInsert));
501 add(MenuItem(MenuItem::PasteRecent));
505 add(MenuItem(MenuItem::Toolbars));
509 add(MenuItem(MenuItem::Branches));
513 add(MenuItem(MenuItem::CiteStyles));
518 // fallback to md_submenu
521 docstring const mlabel = translateIfPossible(lex.getDocString());
523 docstring const mname = lex.getDocString();
524 add(MenuItem(MenuItem::Submenu,
525 toqstr(mlabel), toqstr(mname), optional));
535 lex.printError("Unknown menu tag");
543 MenuItem const & MenuDefinition::operator[](size_type i) const
549 bool MenuDefinition::hasFunc(FuncRequest const & func) const
551 for (const_iterator it = begin(), et = end(); it != et; ++it)
552 if (it->func() == func)
558 void MenuDefinition::checkShortcuts() const
560 // This is a quadratic algorithm, but we do not care because
561 // menus are short enough
562 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
563 QString shortcut = it1->shortcut();
564 if (shortcut.isEmpty())
566 if (!it1->label().contains(shortcut))
567 LYXERR0("Menu warning: menu entry \""
569 << "\" does not contain shortcut `"
570 << shortcut << "'." << endl);
571 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
572 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
573 LYXERR0("Menu warning: menu entries "
574 << '"' << it1->fulllabel()
575 << "\" and \"" << it2->fulllabel()
576 << "\" share the same shortcut."
584 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
586 const_iterator m = begin();
587 const_iterator m_end = end();
588 for (; m != m_end; ++m) {
589 if (m->kind() == MenuItem::Command && m->func() == func) {
590 names.push_back(qstring_to_ucs4(m->label()));
593 if (m->kind() == MenuItem::Submenu) {
594 names.push_back(qstring_to_ucs4(m->label()));
595 if (!m->hasSubmenu()) {
596 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
597 << m->label() << " name=" << m->submenuname());
601 if (m->submenu().searchMenu(func, names))
610 bool compareFormat(Format const * p1, Format const * p2)
616 QString limitStringLength(docstring const & str)
618 size_t const max_item_length = 45;
620 if (str.size() > max_item_length)
621 return toqstr(str.substr(0, max_item_length - 3) + "...");
627 void MenuDefinition::expandLastfiles()
629 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
630 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
634 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
635 string const file = lfit->absFilename();
636 QString const label = QString("%1. %2|%3").arg(ii)
637 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
638 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
643 void MenuDefinition::expandDocuments()
645 Buffer * first = theBufferList().first();
650 // We cannot use a for loop as the buffer list cycles.
652 QString label = toqstr(b->fileName().displayName(20));
656 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
657 add(MenuItem(MenuItem::Command, label,
658 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
660 b = theBufferList().next(b);
662 } while (b != first);
664 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
665 FuncRequest(LFUN_NOACTION)));
670 void MenuDefinition::expandBookmarks()
672 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
674 for (size_t i = 1; i <= bm.size(); ++i) {
676 string const file = bm.bookmark(i).filename.absFilename();
677 QString const label = QString("%1. %2|%3").arg(i)
678 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
679 add(MenuItem(MenuItem::Command, label,
680 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
686 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
688 if (!buf && kind != MenuItem::ImportFormats) {
689 add(MenuItem(MenuItem::Command,
690 qt_("No Document Open!"),
691 FuncRequest(LFUN_NOACTION)));
695 typedef vector<Format const *> Formats;
700 case MenuItem::ImportFormats:
701 formats = theConverters().importableFormats();
702 action = LFUN_BUFFER_IMPORT;
704 case MenuItem::ViewFormats:
705 formats = buf->exportableFormats(true);
706 action = LFUN_BUFFER_VIEW;
708 case MenuItem::UpdateFormats:
709 formats = buf->exportableFormats(true);
710 action = LFUN_BUFFER_UPDATE;
713 formats = buf->exportableFormats(false);
714 action = LFUN_BUFFER_EXPORT;
716 sort(formats.begin(), formats.end(), &compareFormat);
718 Formats::const_iterator fit = formats.begin();
719 Formats::const_iterator end = formats.end();
720 for (; fit != end ; ++fit) {
723 QString label = toqstr((*fit)->prettyname());
724 QString const shortcut = toqstr((*fit)->shortcut());
727 case MenuItem::ImportFormats:
728 // FIXME: This is a hack, we should rather solve
729 // FIXME: bug 2488 instead.
730 if ((*fit)->name() == "text")
731 label = qt_("Plain Text");
732 else if ((*fit)->name() == "textparagraph")
733 label = qt_("Plain Text, Join Lines");
736 case MenuItem::ViewFormats:
737 case MenuItem::ExportFormats:
738 case MenuItem::UpdateFormats:
739 if (!(*fit)->documentFormat())
743 LASSERT(false, /**/);
746 // FIXME: if we had proper support for translating the
747 // format names defined in configure.py, there would
748 // not be a need to check whether the shortcut is
749 // correct. If we add it uncondiitonally, it would
750 // create useless warnings on bad shortcuts
751 if (!shortcut.isEmpty() && label.contains(shortcut))
752 label += '|' + shortcut;
755 addWithStatusCheck(MenuItem(MenuItem::Command, label,
756 FuncRequest(action, (*fit)->name())));
758 add(MenuItem(MenuItem::Command, label,
759 FuncRequest(action, (*fit)->name())));
764 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
767 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
768 FuncRequest(LFUN_NOACTION)));
772 FloatList const & floats = buf->params().documentClass().floats();
773 FloatList::const_iterator cit = floats.begin();
774 FloatList::const_iterator end = floats.end();
775 for (; cit != end; ++cit) {
776 addWithStatusCheck(MenuItem(MenuItem::Command,
777 qt_(cit->second.listName()),
778 FuncRequest(LFUN_FLOAT_LIST,
779 cit->second.type())));
784 void MenuDefinition::expandFloatInsert(Buffer const * buf)
787 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
788 FuncRequest(LFUN_NOACTION)));
792 FloatList const & floats = buf->params().documentClass().floats();
793 FloatList::const_iterator cit = floats.begin();
794 FloatList::const_iterator end = floats.end();
795 for (; cit != end; ++cit) {
797 QString const label = qt_(cit->second.name());
798 addWithStatusCheck(MenuItem(MenuItem::Command, label,
799 FuncRequest(LFUN_FLOAT_INSERT,
800 cit->second.type())));
805 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
808 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
809 FuncRequest(LFUN_NOACTION)));
812 TextClass::InsetLayouts const & insetLayouts =
813 buf->params().documentClass().insetLayouts();
814 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
815 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
816 for (; cit != end; ++cit) {
817 docstring const label = cit->first;
818 if (cit->second.lyxtype() == s)
819 addWithStatusCheck(MenuItem(MenuItem::Command,
820 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
826 size_t const max_number_of_items = 25;
828 void MenuDefinition::expandToc2(Toc const & toc_list,
829 size_t from, size_t to, int depth)
831 int shortcut_count = 0;
833 // check whether depth is smaller than the smallest depth in toc.
834 int min_depth = 1000;
835 for (size_t i = from; i < to; ++i)
836 min_depth = min(min_depth, toc_list[i].depth());
837 if (min_depth > depth)
840 if (to - from <= max_number_of_items) {
841 for (size_t i = from; i < to; ++i) {
842 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
843 label += limitStringLength(toc_list[i].str());
844 if (toc_list[i].depth() == depth
845 && shortcut_count < 9) {
846 if (label.contains(QString::number(shortcut_count + 1)))
847 label += '|' + QString::number(++shortcut_count);
849 add(MenuItem(MenuItem::Command, label,
850 FuncRequest(toc_list[i].action())));
855 size_t new_pos = pos + 1;
856 while (new_pos < to && toc_list[new_pos].depth() > depth)
859 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
860 label += limitStringLength(toc_list[pos].str());
861 if (toc_list[pos].depth() == depth &&
862 shortcut_count < 9) {
863 if (label.contains(QString::number(shortcut_count + 1)))
864 label += '|' + QString::number(++shortcut_count);
866 if (new_pos == pos + 1) {
867 add(MenuItem(MenuItem::Command,
868 label, FuncRequest(toc_list[pos].action())));
871 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
872 MenuItem item(MenuItem::Submenu, label);
873 item.setSubmenu(sub);
882 void MenuDefinition::expandToc(Buffer const * buf)
884 // To make things very cleanly, we would have to pass buf to
885 // all MenuItem constructors and to expandToc2. However, we
886 // know that all the entries in a TOC will be have status_ ==
887 // OK, so we avoid this unnecessary overhead (JMarc)
890 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
891 FuncRequest(LFUN_NOACTION)));
895 Buffer* cbuf = const_cast<Buffer*>(buf);
896 cbuf->tocBackend().update();
897 cbuf->structureChanged();
899 // Add an entry for the master doc if this is a child doc
900 Buffer const * const master = buf->masterBuffer();
902 ParIterator const pit = par_iterator_begin(master->inset());
903 string const arg = convert<string>(pit->id());
904 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
905 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
908 MenuDefinition other_lists;
910 FloatList const & floatlist = buf->params().documentClass().floats();
911 TocList const & toc_list = buf->tocBackend().tocs();
912 TocList::const_iterator cit = toc_list.begin();
913 TocList::const_iterator end = toc_list.end();
914 for (; cit != end; ++cit) {
916 if (cit->first == "tableofcontents")
919 string const & floatName = floatlist.getType(cit->first).listName();
921 bool in_other_list = true;
922 if (!floatName.empty()) {
923 label = qt_(floatName);
924 in_other_list = false;
926 else if (cit->first == "child") {
927 label = qt_("Child Documents");
928 in_other_list = false;
929 } else if (cit->first == "graphics")
930 label = qt_("List of Graphics");
931 else if (cit->first == "equation")
932 label = qt_("List of Equations");
933 else if (cit->first == "index")
934 label = qt_("List of Indexes");
935 else if (cit->first == "listing") {
936 // FIXME: the listing navigate menu causes a crash for unknown
937 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
938 // This is a temporary fix:
939 //label = qt_("List of Listings");
942 else if (cit->first == "marginalnote")
943 label = qt_("List of Marginal notes");
944 else if (cit->first == "note")
945 label = qt_("List of Notes");
946 else if (cit->first == "footnote")
947 label = qt_("List of Footnotes");
948 else if (cit->first == "label")
949 label = qt_("Labels and References");
950 else if (cit->first == "citation")
951 label = qt_("List of Citations");
953 // This should not happen unless the entry is missing above.
954 label = qt_("Other floats: ") + toqstr(cit->first);
956 MenuDefinition submenu;
958 if (cit->second.size() >= 30) {
959 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
960 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
962 TocIterator ccit = cit->second.begin();
963 TocIterator eend = cit->second.end();
964 for (; ccit != eend; ++ccit) {
965 QString const label = limitStringLength(ccit->str());
966 submenu.add(MenuItem(MenuItem::Command, label,
967 FuncRequest(ccit->action())));
971 MenuItem item(MenuItem::Submenu, label);
972 item.setSubmenu(submenu);
974 other_lists.add(item);
976 item.setSubmenu(submenu);
980 if (!other_lists.empty()) {
981 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
982 item.setSubmenu(other_lists);
988 cit = toc_list.find("tableofcontents");
990 addWithStatusCheck(MenuItem(MenuItem::Command,
991 qt_("No Table of contents"),
994 expandToc2(cit->second, 0, cit->second.size(), 0);
999 void MenuDefinition::expandPasteRecent()
1001 vector<docstring> const sel = cap::availableSelections();
1003 vector<docstring>::const_iterator cit = sel.begin();
1004 vector<docstring>::const_iterator end = sel.end();
1006 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1007 add(MenuItem(MenuItem::Command, toqstr(*cit),
1008 FuncRequest(LFUN_PASTE, convert<string>(index))));
1013 void MenuDefinition::expandToolbars()
1016 // extracts the toolbars from the backend
1017 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1018 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1020 for (; cit != end; ++cit) {
1021 QString label = qt_(cit->gui_name);
1022 // frontends are not supposed to turn on/off toolbars,
1023 // if they cannot update ToolbarBackend::flags. That
1024 // is to say, ToolbarsBackend::flags should reflect
1025 // the true state of toolbars.
1027 // menu is displayed as
1031 // in the case of auto.
1032 if (cit->flags & ToolbarInfo::AUTO)
1033 label += qt_(" (auto)");
1034 add(MenuItem(MenuItem::Command, label,
1035 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1040 void MenuDefinition::expandBranches(Buffer const * buf)
1043 add(MenuItem(MenuItem::Command,
1044 qt_("No Document Open!"),
1045 FuncRequest(LFUN_NOACTION)));
1049 BufferParams const & params = buf->masterBuffer()->params();
1050 if (params.branchlist().empty()) {
1051 add(MenuItem(MenuItem::Command,
1052 qt_("No Branch in Document!"),
1053 FuncRequest(LFUN_NOACTION)));
1057 BranchList::const_iterator cit = params.branchlist().begin();
1058 BranchList::const_iterator end = params.branchlist().end();
1060 for (int ii = 1; cit != end; ++cit, ++ii) {
1061 docstring label = cit->getBranch();
1063 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1064 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1065 FuncRequest(LFUN_BRANCH_INSERT,
1066 cit->getBranch())));
1071 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1074 add(MenuItem(MenuItem::Command,
1075 qt_("No Document Open!"),
1076 FuncRequest(LFUN_NOACTION)));
1080 Inset const * inset = bv->cursor().nextInset();
1081 if (!inset || inset->lyxCode() != CITE_CODE) {
1082 add(MenuItem(MenuItem::Command,
1083 qt_("No Citation in Scope!"),
1084 FuncRequest(LFUN_NOACTION)));
1087 InsetCommand const * citinset =
1088 static_cast<InsetCommand const *>(inset);
1090 Buffer const * buf = &bv->buffer();
1091 docstring key = citinset->getParam("key");
1092 // we can only handle one key currently
1093 if (contains(key, ','))
1094 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1096 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1097 vector<docstring> citeStrings =
1098 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1100 vector<docstring>::const_iterator cit = citeStrings.begin();
1101 vector<docstring>::const_iterator end = citeStrings.end();
1103 for (int ii = 1; cit != end; ++cit, ++ii) {
1104 docstring label = *cit;
1106 CiteStyle cst = citeStyleList[ii - 1];
1108 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1109 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1110 "changetype " + from_utf8(citationStyleToString(cs)))));
1117 /////////////////////////////////////////////////////////////////////
1118 // Menu::Impl definition and implementation
1119 /////////////////////////////////////////////////////////////////////
1123 /// populates the menu or one of its submenu
1124 /// This is used as a recursive function
1125 void populate(QMenu & qMenu, MenuDefinition const & menu);
1127 /// Only needed for top level menus.
1128 MenuDefinition * top_level_menu;
1131 /// the name of this menu
1137 /// Get a MenuDefinition item label from the menu backend
1138 static QString label(MenuItem const & mi)
1140 QString label = mi.label();
1141 label.replace("&", "&&");
1143 QString shortcut = mi.shortcut();
1144 if (!shortcut.isEmpty()) {
1145 int pos = label.indexOf(shortcut);
1147 //label.insert(pos, 1, char_type('&'));
1148 label.replace(pos, 0, "&");
1151 QString const binding = mi.binding();
1152 if (!binding.isEmpty())
1153 label += '\t' + binding;
1158 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1160 LYXERR(Debug::GUI, "populating menu " << menu.name());
1161 if (menu.size() == 0) {
1162 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1165 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1166 MenuDefinition::const_iterator m = menu.begin();
1167 MenuDefinition::const_iterator end = menu.end();
1168 for (; m != end; ++m) {
1169 if (m->kind() == MenuItem::Separator)
1170 qMenu.addSeparator();
1171 else if (m->kind() == MenuItem::Submenu) {
1172 QMenu * subMenu = qMenu.addMenu(label(*m));
1173 populate(*subMenu, m->submenu());
1175 // we have a MenuItem::Command
1176 qMenu.addAction(new Action(view, QIcon(), label(*m),
1177 m->func(), QString(), &qMenu));
1182 /////////////////////////////////////////////////////////////////////
1183 // Menu implementation
1184 /////////////////////////////////////////////////////////////////////
1186 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1187 : QMenu(gv), d(new Menu::Impl)
1189 d->top_level_menu = top_level? new MenuDefinition : 0;
1193 if (d->top_level_menu)
1194 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1200 delete d->top_level_menu;
1205 void Menu::updateView()
1207 guiApp->menus().updateMenu(this);
1211 /////////////////////////////////////////////////////////////////////
1212 // Menus::Impl definition and implementation
1213 /////////////////////////////////////////////////////////////////////
1215 struct Menus::Impl {
1217 bool hasMenu(QString const &) const;
1219 MenuDefinition & getMenu(QString const &);
1221 MenuDefinition const & getMenu(QString const &) const;
1223 /// Expands some special entries of the menu
1224 /** The entries with the following kind are expanded to a
1225 sequence of Command MenuItems: Lastfiles, Documents,
1226 ViewFormats, ExportFormats, UpdateFormats, Branches
1228 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1229 BufferView const *) const;
1231 /// Initialize specific MACOS X menubar
1232 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1234 /// Mac special menu.
1235 /** This defines a menu whose entries list the FuncRequests
1236 that will be removed by expand() in other menus. This is
1237 used by the Qt/Mac code
1239 MenuDefinition specialmenu_;
1244 MenuDefinition menubar_;
1246 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1248 /// name to menu for \c menu() method.
1253 Here is what the Qt documentation says about how a menubar is chosen:
1255 1) If the window has a QMenuBar then it is used. 2) If the window
1256 is a modal then its menubar is used. If no menubar is specified
1257 then a default menubar is used (as documented below) 3) If the
1258 window has no parent then the default menubar is used (as
1261 The above 3 steps are applied all the way up the parent window
1262 chain until one of the above are satisifed. If all else fails a
1263 default menubar will be created, the default menubar on Qt/Mac is
1264 an empty menubar, however you can create a different default
1265 menubar by creating a parentless QMenuBar, the first one created
1266 will thus be designated the default menubar, and will be used
1267 whenever a default menubar is needed.
1269 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1270 that this menubar will be used also when one of LyX' dialogs has
1273 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1275 /* Since Qt 4.2, the qt/mac menu code has special code for
1276 specifying the role of a menu entry. However, it does not
1277 work very well with our scheme of creating menus on demand,
1278 and therefore we need to put these entries in a special
1279 invisible menu. (JMarc)
1282 /* The entries of our special mac menu. If we add support for
1283 * special entries in Menus, we could imagine something
1285 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1286 * and therefore avoid hardcoding. I am not sure it is worth
1287 * the hassle, though. (JMarc)
1289 struct MacMenuEntry {
1293 QAction::MenuRole role;
1296 MacMenuEntry entries[] = {
1297 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1298 QAction::AboutRole},
1299 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1300 QAction::PreferencesRole},
1301 {LFUN_RECONFIGURE, "", "Reconfigure",
1302 QAction::ApplicationSpecificRole},
1303 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1305 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1307 // the special menu for Menus. Fill it up only once.
1308 if (specialmenu_.size() == 0) {
1309 for (size_t i = 0 ; i < num_entries ; ++i) {
1310 FuncRequest const func(entries[i].action,
1311 from_utf8(entries[i].arg));
1312 specialmenu_.add(MenuItem(MenuItem::Command,
1313 entries[i].label, func));
1317 // add the entries to a QMenu that will eventually be empty
1318 // and therefore invisible.
1319 QMenu * qMenu = qmb->addMenu("special");
1320 MenuDefinition::const_iterator cit = specialmenu_.begin();
1321 MenuDefinition::const_iterator end = specialmenu_.end();
1322 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1323 Action * action = new Action(view, QIcon(), cit->label(),
1324 cit->func(), QString(), qMenu);
1325 action->setMenuRole(entries[i].role);
1326 qMenu->addAction(action);
1331 void Menus::Impl::expand(MenuDefinition const & frommenu,
1332 MenuDefinition & tomenu, BufferView const * bv) const
1334 if (!tomenu.empty())
1337 for (MenuDefinition::const_iterator cit = frommenu.begin();
1338 cit != frommenu.end() ; ++cit) {
1339 Buffer const * buf = bv ? &bv->buffer() : 0;
1340 switch (cit->kind()) {
1341 case MenuItem::Lastfiles:
1342 tomenu.expandLastfiles();
1345 case MenuItem::Documents:
1346 tomenu.expandDocuments();
1349 case MenuItem::Bookmarks:
1350 tomenu.expandBookmarks();
1353 case MenuItem::ImportFormats:
1354 case MenuItem::ViewFormats:
1355 case MenuItem::UpdateFormats:
1356 case MenuItem::ExportFormats:
1357 tomenu.expandFormats(cit->kind(), buf);
1360 case MenuItem::CharStyles:
1361 tomenu.expandFlexInsert(buf, "charstyle");
1364 case MenuItem::Custom:
1365 tomenu.expandFlexInsert(buf, "custom");
1368 case MenuItem::Elements:
1369 tomenu.expandFlexInsert(buf, "element");
1372 case MenuItem::FloatListInsert:
1373 tomenu.expandFloatListInsert(buf);
1376 case MenuItem::FloatInsert:
1377 tomenu.expandFloatInsert(buf);
1380 case MenuItem::PasteRecent:
1381 tomenu.expandPasteRecent();
1384 case MenuItem::Toolbars:
1385 tomenu.expandToolbars();
1388 case MenuItem::Branches:
1389 tomenu.expandBranches(buf);
1392 case MenuItem::CiteStyles:
1393 tomenu.expandCiteStyles(bv);
1397 tomenu.expandToc(buf);
1400 case MenuItem::Submenu: {
1401 MenuItem item(*cit);
1402 item.setSubmenu(MenuDefinition(cit->submenuname()));
1403 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1404 tomenu.addWithStatusCheck(item);
1408 case MenuItem::Separator:
1409 tomenu.addWithStatusCheck(*cit);
1412 case MenuItem::Command:
1413 if (!specialmenu_.hasFunc(cit->func()))
1414 tomenu.addWithStatusCheck(*cit);
1418 // we do not want the menu to end with a separator
1419 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1420 tomenu.items_.pop_back();
1422 // Check whether the shortcuts are unique
1423 tomenu.checkShortcuts();
1427 bool Menus::Impl::hasMenu(QString const & name) const
1429 return find_if(menulist_.begin(), menulist_.end(),
1430 MenuNamesEqual(name)) != menulist_.end();
1434 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1436 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1437 MenuNamesEqual(name));
1438 if (cit == menulist_.end())
1439 lyxerr << "No submenu named " << name << endl;
1440 LASSERT(cit != menulist_.end(), /**/);
1445 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1447 iterator it = find_if(menulist_.begin(), menulist_.end(),
1448 MenuNamesEqual(name));
1449 if (it == menulist_.end())
1450 lyxerr << "No submenu named " << name << endl;
1451 LASSERT(it != menulist_.end(), /**/);
1456 /////////////////////////////////////////////////////////////////////
1460 /////////////////////////////////////////////////////////////////////
1462 Menus::Menus() : d(new Impl) {}
1469 void Menus::read(Lexer & lex)
1477 LexerKeyword menutags[] = {
1478 { "end", md_endmenuset },
1479 { "menu", md_menu },
1480 { "menubar", md_menubar }
1483 // consistency check
1484 if (compare_ascii_no_case(lex.getString(), "menuset"))
1485 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1487 lex.pushTable(menutags);
1488 lex.setContext("Menus::read");
1492 while (lex.isOK() && !quit) {
1493 switch (lex.lex()) {
1495 d->menubar_.read(lex);
1499 QString const name = toqstr(lex.getDocString());
1500 if (d->hasMenu(name))
1501 d->getMenu(name).read(lex);
1503 MenuDefinition menu(name);
1505 d->menulist_.push_back(menu);
1513 lex.printError("Unknown menu tag");
1521 bool Menus::searchMenu(FuncRequest const & func,
1522 vector<docstring> & names) const
1524 MenuDefinition menu;
1525 d->expand(d->menubar_, menu, 0);
1526 return menu.searchMenu(func, names);
1530 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1534 // setup special mac specific menu item
1535 d->macxMenuBarInit(view, qmb);
1538 // Clear all menubar contents before filling it.
1542 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1544 if (d->menubar_.size() == 0) {
1545 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1546 << d->menubar_.name());
1549 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1551 MenuDefinition menu;
1552 BufferView * bv = 0;
1555 d->expand(d->menubar_, menu, bv);
1557 MenuDefinition::const_iterator m = menu.begin();
1558 MenuDefinition::const_iterator end = menu.end();
1560 for (; m != end; ++m) {
1562 if (m->kind() != MenuItem::Submenu) {
1563 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1567 LYXERR(Debug::GUI, "menu bar item " << m->label()
1568 << " is a submenu named " << m->submenuname());
1570 QString name = m->submenuname();
1571 if (!d->hasMenu(name)) {
1572 LYXERR(Debug::GUI, "\tERROR: " << name
1573 << " submenu has no menu!");
1577 Menu * menu = new Menu(view, m->submenuname(), true);
1578 menu->setTitle(label(*m));
1581 d->name_map_[view][name] = menu;
1586 void Menus::updateMenu(Menu * qmenu)
1588 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1591 if (qmenu->d->name.isEmpty())
1594 // Here, We make sure that theLyXFunc points to the correct LyXView.
1595 theLyXFunc().setLyXView(qmenu->d->view);
1597 if (!d->hasMenu(qmenu->d->name)) {
1598 qmenu->addAction(qt_("No action defined!"));
1599 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1604 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1605 BufferView * bv = 0;
1607 bv = qmenu->d->view->view();
1608 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1609 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1613 Menu * Menus::menu(QString const & name, GuiView & view)
1615 LYXERR(Debug::GUI, "Context menu requested: " << name);
1616 Menu * menu = d->name_map_[&view].value(name, 0);
1617 if (!menu && !name.startsWith("context-")) {
1618 LYXERR0("requested context menu not found: " << name);
1622 menu = new Menu(&view, name, true);
1623 d->name_map_[&view][name] = menu;
1627 } // namespace frontend
1630 #include "Menus_moc.cpp"