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 << "'.");
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.");
583 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
585 const_iterator m = begin();
586 const_iterator m_end = end();
587 for (; m != m_end; ++m) {
588 if (m->kind() == MenuItem::Command && m->func() == func) {
589 names.push_back(qstring_to_ucs4(m->label()));
592 if (m->kind() == MenuItem::Submenu) {
593 names.push_back(qstring_to_ucs4(m->label()));
594 if (!m->hasSubmenu()) {
595 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
596 << m->label() << " name=" << m->submenuname());
600 if (m->submenu().searchMenu(func, names))
609 bool compareFormat(Format const * p1, Format const * p2)
615 QString limitStringLength(docstring const & str)
617 size_t const max_item_length = 45;
619 if (str.size() > max_item_length)
620 return toqstr(str.substr(0, max_item_length - 3) + "...");
626 void MenuDefinition::expandLastfiles()
628 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
629 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
633 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
634 string const file = lfit->absFilename();
635 QString const label = QString("%1. %2|%3").arg(ii)
636 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
637 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
642 void MenuDefinition::expandDocuments()
644 Buffer * first = theBufferList().first();
649 // We cannot use a for loop as the buffer list cycles.
651 QString label = toqstr(b->fileName().displayName(20));
655 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
656 add(MenuItem(MenuItem::Command, label,
657 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
659 b = theBufferList().next(b);
661 } while (b != first);
663 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
664 FuncRequest(LFUN_NOACTION)));
669 void MenuDefinition::expandBookmarks()
671 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
673 for (size_t i = 1; i <= bm.size(); ++i) {
675 string const file = bm.bookmark(i).filename.absFilename();
676 QString const label = QString("%1. %2|%3").arg(i)
677 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
678 add(MenuItem(MenuItem::Command, label,
679 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
685 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
687 if (!buf && kind != MenuItem::ImportFormats) {
688 add(MenuItem(MenuItem::Command,
689 qt_("No Document Open!"),
690 FuncRequest(LFUN_NOACTION)));
694 typedef vector<Format const *> Formats;
699 case MenuItem::ImportFormats:
700 formats = theConverters().importableFormats();
701 action = LFUN_BUFFER_IMPORT;
703 case MenuItem::ViewFormats:
704 formats = buf->exportableFormats(true);
705 action = LFUN_BUFFER_VIEW;
707 case MenuItem::UpdateFormats:
708 formats = buf->exportableFormats(true);
709 action = LFUN_BUFFER_UPDATE;
712 formats = buf->exportableFormats(false);
713 action = LFUN_BUFFER_EXPORT;
715 sort(formats.begin(), formats.end(), &compareFormat);
717 Formats::const_iterator fit = formats.begin();
718 Formats::const_iterator end = formats.end();
719 for (; fit != end ; ++fit) {
722 QString label = toqstr((*fit)->prettyname());
723 QString const shortcut = toqstr((*fit)->shortcut());
726 case MenuItem::ImportFormats:
727 // FIXME: This is a hack, we should rather solve
728 // FIXME: bug 2488 instead.
729 if ((*fit)->name() == "text")
730 label = qt_("Plain Text");
731 else if ((*fit)->name() == "textparagraph")
732 label = qt_("Plain Text, Join Lines");
735 case MenuItem::ViewFormats:
736 case MenuItem::ExportFormats:
737 case MenuItem::UpdateFormats:
738 if (!(*fit)->documentFormat())
742 LASSERT(false, /**/);
745 // FIXME: if we had proper support for translating the
746 // format names defined in configure.py, there would
747 // not be a need to check whether the shortcut is
748 // correct. If we add it uncondiitonally, it would
749 // create useless warnings on bad shortcuts
750 if (!shortcut.isEmpty() && label.contains(shortcut))
751 label += '|' + shortcut;
754 addWithStatusCheck(MenuItem(MenuItem::Command, label,
755 FuncRequest(action, (*fit)->name())));
757 add(MenuItem(MenuItem::Command, label,
758 FuncRequest(action, (*fit)->name())));
763 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
766 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
767 FuncRequest(LFUN_NOACTION)));
771 FloatList const & floats = buf->params().documentClass().floats();
772 FloatList::const_iterator cit = floats.begin();
773 FloatList::const_iterator end = floats.end();
774 for (; cit != end; ++cit) {
775 addWithStatusCheck(MenuItem(MenuItem::Command,
776 qt_(cit->second.listName()),
777 FuncRequest(LFUN_FLOAT_LIST,
778 cit->second.type())));
783 void MenuDefinition::expandFloatInsert(Buffer const * buf)
786 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
787 FuncRequest(LFUN_NOACTION)));
791 FloatList const & floats = buf->params().documentClass().floats();
792 FloatList::const_iterator cit = floats.begin();
793 FloatList::const_iterator end = floats.end();
794 for (; cit != end; ++cit) {
796 QString const label = qt_(cit->second.name());
797 addWithStatusCheck(MenuItem(MenuItem::Command, label,
798 FuncRequest(LFUN_FLOAT_INSERT,
799 cit->second.type())));
804 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
807 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
808 FuncRequest(LFUN_NOACTION)));
811 TextClass::InsetLayouts const & insetLayouts =
812 buf->params().documentClass().insetLayouts();
813 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
814 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
815 for (; cit != end; ++cit) {
816 docstring const label = cit->first;
817 if (cit->second.lyxtype() == s)
818 addWithStatusCheck(MenuItem(MenuItem::Command,
819 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
825 size_t const max_number_of_items = 25;
827 void MenuDefinition::expandToc2(Toc const & toc_list,
828 size_t from, size_t to, int depth)
830 int shortcut_count = 0;
832 // check whether depth is smaller than the smallest depth in toc.
833 int min_depth = 1000;
834 for (size_t i = from; i < to; ++i)
835 min_depth = min(min_depth, toc_list[i].depth());
836 if (min_depth > depth)
839 if (to - from <= max_number_of_items) {
840 for (size_t i = from; i < to; ++i) {
841 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
842 label += limitStringLength(toc_list[i].str());
843 if (toc_list[i].depth() == depth
844 && shortcut_count < 9) {
845 if (label.contains(QString::number(shortcut_count + 1)))
846 label += '|' + QString::number(++shortcut_count);
848 add(MenuItem(MenuItem::Command, label,
849 FuncRequest(toc_list[i].action())));
854 size_t new_pos = pos + 1;
855 while (new_pos < to && toc_list[new_pos].depth() > depth)
858 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
859 label += limitStringLength(toc_list[pos].str());
860 if (toc_list[pos].depth() == depth &&
861 shortcut_count < 9) {
862 if (label.contains(QString::number(shortcut_count + 1)))
863 label += '|' + QString::number(++shortcut_count);
865 if (new_pos == pos + 1) {
866 add(MenuItem(MenuItem::Command,
867 label, FuncRequest(toc_list[pos].action())));
870 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
871 MenuItem item(MenuItem::Submenu, label);
872 item.setSubmenu(sub);
881 void MenuDefinition::expandToc(Buffer const * buf)
883 // To make things very cleanly, we would have to pass buf to
884 // all MenuItem constructors and to expandToc2. However, we
885 // know that all the entries in a TOC will be have status_ ==
886 // OK, so we avoid this unnecessary overhead (JMarc)
889 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
890 FuncRequest(LFUN_NOACTION)));
894 Buffer* cbuf = const_cast<Buffer*>(buf);
895 cbuf->tocBackend().update();
896 cbuf->structureChanged();
898 // Add an entry for the master doc if this is a child doc
899 Buffer const * const master = buf->masterBuffer();
901 ParIterator const pit = par_iterator_begin(master->inset());
902 string const arg = convert<string>(pit->id());
903 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
904 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
907 MenuDefinition other_lists;
909 FloatList const & floatlist = buf->params().documentClass().floats();
910 TocList const & toc_list = buf->tocBackend().tocs();
911 TocList::const_iterator cit = toc_list.begin();
912 TocList::const_iterator end = toc_list.end();
913 for (; cit != end; ++cit) {
915 if (cit->first == "tableofcontents")
918 string const & floatName = floatlist.getType(cit->first).listName();
920 bool in_other_list = true;
921 if (!floatName.empty()) {
922 label = qt_(floatName);
923 in_other_list = false;
925 else if (cit->first == "child") {
926 label = qt_("Child Documents");
927 in_other_list = false;
928 } else if (cit->first == "graphics")
929 label = qt_("List of Graphics");
930 else if (cit->first == "equation")
931 label = qt_("List of Equations");
932 else if (cit->first == "index")
933 label = qt_("List of Indexes");
934 else if (cit->first == "listing") {
935 // FIXME: the listing navigate menu causes a crash for unknown
936 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
937 // This is a temporary fix:
938 //label = qt_("List of Listings");
941 else if (cit->first == "marginalnote")
942 label = qt_("List of Marginal notes");
943 else if (cit->first == "note")
944 label = qt_("List of Notes");
945 else if (cit->first == "footnote")
946 label = qt_("List of Footnotes");
947 else if (cit->first == "label")
948 label = qt_("Labels and References");
949 else if (cit->first == "citation")
950 label = qt_("List of Citations");
952 // This should not happen unless the entry is missing above.
953 label = qt_("Other floats: ") + toqstr(cit->first);
955 MenuDefinition submenu;
957 if (cit->second.size() >= 30) {
958 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
959 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
961 TocIterator ccit = cit->second.begin();
962 TocIterator eend = cit->second.end();
963 for (; ccit != eend; ++ccit) {
964 QString const label = limitStringLength(ccit->str());
965 submenu.add(MenuItem(MenuItem::Command, label,
966 FuncRequest(ccit->action())));
970 MenuItem item(MenuItem::Submenu, label);
971 item.setSubmenu(submenu);
973 other_lists.add(item);
975 item.setSubmenu(submenu);
979 if (!other_lists.empty()) {
980 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
981 item.setSubmenu(other_lists);
987 cit = toc_list.find("tableofcontents");
989 addWithStatusCheck(MenuItem(MenuItem::Command,
990 qt_("No Table of contents"),
993 expandToc2(cit->second, 0, cit->second.size(), 0);
998 void MenuDefinition::expandPasteRecent()
1000 vector<docstring> const sel = cap::availableSelections();
1002 vector<docstring>::const_iterator cit = sel.begin();
1003 vector<docstring>::const_iterator end = sel.end();
1005 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1006 add(MenuItem(MenuItem::Command, toqstr(*cit),
1007 FuncRequest(LFUN_PASTE, convert<string>(index))));
1012 void MenuDefinition::expandToolbars()
1015 // extracts the toolbars from the backend
1016 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1017 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1019 for (; cit != end; ++cit) {
1020 QString label = qt_(cit->gui_name);
1021 // frontends are not supposed to turn on/off toolbars,
1022 // if they cannot update ToolbarBackend::flags. That
1023 // is to say, ToolbarsBackend::flags should reflect
1024 // the true state of toolbars.
1026 // menu is displayed as
1030 // in the case of auto.
1031 if (cit->flags & ToolbarInfo::AUTO)
1032 label += qt_(" (auto)");
1033 add(MenuItem(MenuItem::Command, label,
1034 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1039 void MenuDefinition::expandBranches(Buffer const * buf)
1042 add(MenuItem(MenuItem::Command,
1043 qt_("No Document Open!"),
1044 FuncRequest(LFUN_NOACTION)));
1048 BufferParams const & params = buf->masterBuffer()->params();
1049 if (params.branchlist().empty()) {
1050 add(MenuItem(MenuItem::Command,
1051 qt_("No Branch in Document!"),
1052 FuncRequest(LFUN_NOACTION)));
1056 BranchList::const_iterator cit = params.branchlist().begin();
1057 BranchList::const_iterator end = params.branchlist().end();
1059 for (int ii = 1; cit != end; ++cit, ++ii) {
1060 docstring label = cit->getBranch();
1062 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1063 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1064 FuncRequest(LFUN_BRANCH_INSERT,
1065 cit->getBranch())));
1070 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1073 add(MenuItem(MenuItem::Command,
1074 qt_("No Document Open!"),
1075 FuncRequest(LFUN_NOACTION)));
1079 Inset const * inset = bv->cursor().nextInset();
1080 if (!inset || inset->lyxCode() != CITE_CODE) {
1081 add(MenuItem(MenuItem::Command,
1082 qt_("No Citation in Scope!"),
1083 FuncRequest(LFUN_NOACTION)));
1086 InsetCommand const * citinset =
1087 static_cast<InsetCommand const *>(inset);
1089 Buffer const * buf = &bv->buffer();
1090 docstring key = citinset->getParam("key");
1091 // we can only handle one key currently
1092 if (contains(key, ','))
1093 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1095 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1096 vector<docstring> citeStrings =
1097 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1099 vector<docstring>::const_iterator cit = citeStrings.begin();
1100 vector<docstring>::const_iterator end = citeStrings.end();
1102 for (int ii = 1; cit != end; ++cit, ++ii) {
1103 docstring label = *cit;
1105 CiteStyle cst = citeStyleList[ii - 1];
1107 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1108 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1109 "changetype " + from_utf8(citationStyleToString(cs)))));
1116 /////////////////////////////////////////////////////////////////////
1117 // Menu::Impl definition and implementation
1118 /////////////////////////////////////////////////////////////////////
1122 /// populates the menu or one of its submenu
1123 /// This is used as a recursive function
1124 void populate(QMenu & qMenu, MenuDefinition const & menu);
1126 /// Only needed for top level menus.
1127 MenuDefinition * top_level_menu;
1130 /// the name of this menu
1136 /// Get a MenuDefinition item label from the menu backend
1137 static QString label(MenuItem const & mi)
1139 QString label = mi.label();
1140 label.replace("&", "&&");
1142 QString shortcut = mi.shortcut();
1143 if (!shortcut.isEmpty()) {
1144 int pos = label.indexOf(shortcut);
1146 //label.insert(pos, 1, char_type('&'));
1147 label.replace(pos, 0, "&");
1150 QString const binding = mi.binding();
1151 if (!binding.isEmpty())
1152 label += '\t' + binding;
1157 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1159 LYXERR(Debug::GUI, "populating menu " << menu.name());
1160 if (menu.size() == 0) {
1161 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1164 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1165 MenuDefinition::const_iterator m = menu.begin();
1166 MenuDefinition::const_iterator end = menu.end();
1167 for (; m != end; ++m) {
1168 if (m->kind() == MenuItem::Separator)
1169 qMenu.addSeparator();
1170 else if (m->kind() == MenuItem::Submenu) {
1171 QMenu * subMenu = qMenu.addMenu(label(*m));
1172 populate(*subMenu, m->submenu());
1174 // we have a MenuItem::Command
1175 qMenu.addAction(new Action(view, QIcon(), label(*m),
1176 m->func(), QString(), &qMenu));
1181 /////////////////////////////////////////////////////////////////////
1182 // Menu implementation
1183 /////////////////////////////////////////////////////////////////////
1185 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1186 : QMenu(gv), d(new Menu::Impl)
1188 d->top_level_menu = top_level? new MenuDefinition : 0;
1192 if (d->top_level_menu)
1193 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1199 delete d->top_level_menu;
1204 void Menu::updateView()
1206 guiApp->menus().updateMenu(this);
1210 /////////////////////////////////////////////////////////////////////
1211 // Menus::Impl definition and implementation
1212 /////////////////////////////////////////////////////////////////////
1214 struct Menus::Impl {
1216 bool hasMenu(QString const &) const;
1218 MenuDefinition & getMenu(QString const &);
1220 MenuDefinition const & getMenu(QString const &) const;
1222 /// Expands some special entries of the menu
1223 /** The entries with the following kind are expanded to a
1224 sequence of Command MenuItems: Lastfiles, Documents,
1225 ViewFormats, ExportFormats, UpdateFormats, Branches
1227 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1228 BufferView const *) const;
1230 /// Initialize specific MACOS X menubar
1231 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1233 /// Mac special menu.
1234 /** This defines a menu whose entries list the FuncRequests
1235 that will be removed by expand() in other menus. This is
1236 used by the Qt/Mac code
1238 MenuDefinition specialmenu_;
1243 MenuDefinition menubar_;
1245 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1247 /// name to menu for \c menu() method.
1252 Here is what the Qt documentation says about how a menubar is chosen:
1254 1) If the window has a QMenuBar then it is used. 2) If the window
1255 is a modal then its menubar is used. If no menubar is specified
1256 then a default menubar is used (as documented below) 3) If the
1257 window has no parent then the default menubar is used (as
1260 The above 3 steps are applied all the way up the parent window
1261 chain until one of the above are satisifed. If all else fails a
1262 default menubar will be created, the default menubar on Qt/Mac is
1263 an empty menubar, however you can create a different default
1264 menubar by creating a parentless QMenuBar, the first one created
1265 will thus be designated the default menubar, and will be used
1266 whenever a default menubar is needed.
1268 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1269 that this menubar will be used also when one of LyX' dialogs has
1272 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1274 /* Since Qt 4.2, the qt/mac menu code has special code for
1275 specifying the role of a menu entry. However, it does not
1276 work very well with our scheme of creating menus on demand,
1277 and therefore we need to put these entries in a special
1278 invisible menu. (JMarc)
1281 /* The entries of our special mac menu. If we add support for
1282 * special entries in Menus, we could imagine something
1284 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1285 * and therefore avoid hardcoding. I am not sure it is worth
1286 * the hassle, though. (JMarc)
1288 struct MacMenuEntry {
1292 QAction::MenuRole role;
1295 MacMenuEntry entries[] = {
1296 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1297 QAction::AboutRole},
1298 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1299 QAction::PreferencesRole},
1300 {LFUN_RECONFIGURE, "", "Reconfigure",
1301 QAction::ApplicationSpecificRole},
1302 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1304 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1306 // the special menu for Menus. Fill it up only once.
1307 if (specialmenu_.size() == 0) {
1308 for (size_t i = 0 ; i < num_entries ; ++i) {
1309 FuncRequest const func(entries[i].action,
1310 from_utf8(entries[i].arg));
1311 specialmenu_.add(MenuItem(MenuItem::Command,
1312 entries[i].label, func));
1316 // add the entries to a QMenu that will eventually be empty
1317 // and therefore invisible.
1318 QMenu * qMenu = qmb->addMenu("special");
1319 MenuDefinition::const_iterator cit = specialmenu_.begin();
1320 MenuDefinition::const_iterator end = specialmenu_.end();
1321 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1322 Action * action = new Action(view, QIcon(), cit->label(),
1323 cit->func(), QString(), qMenu);
1324 action->setMenuRole(entries[i].role);
1325 qMenu->addAction(action);
1330 void Menus::Impl::expand(MenuDefinition const & frommenu,
1331 MenuDefinition & tomenu, BufferView const * bv) const
1333 if (!tomenu.empty())
1336 for (MenuDefinition::const_iterator cit = frommenu.begin();
1337 cit != frommenu.end() ; ++cit) {
1338 Buffer const * buf = bv ? &bv->buffer() : 0;
1339 switch (cit->kind()) {
1340 case MenuItem::Lastfiles:
1341 tomenu.expandLastfiles();
1344 case MenuItem::Documents:
1345 tomenu.expandDocuments();
1348 case MenuItem::Bookmarks:
1349 tomenu.expandBookmarks();
1352 case MenuItem::ImportFormats:
1353 case MenuItem::ViewFormats:
1354 case MenuItem::UpdateFormats:
1355 case MenuItem::ExportFormats:
1356 tomenu.expandFormats(cit->kind(), buf);
1359 case MenuItem::CharStyles:
1360 tomenu.expandFlexInsert(buf, "charstyle");
1363 case MenuItem::Custom:
1364 tomenu.expandFlexInsert(buf, "custom");
1367 case MenuItem::Elements:
1368 tomenu.expandFlexInsert(buf, "element");
1371 case MenuItem::FloatListInsert:
1372 tomenu.expandFloatListInsert(buf);
1375 case MenuItem::FloatInsert:
1376 tomenu.expandFloatInsert(buf);
1379 case MenuItem::PasteRecent:
1380 tomenu.expandPasteRecent();
1383 case MenuItem::Toolbars:
1384 tomenu.expandToolbars();
1387 case MenuItem::Branches:
1388 tomenu.expandBranches(buf);
1391 case MenuItem::CiteStyles:
1392 tomenu.expandCiteStyles(bv);
1396 tomenu.expandToc(buf);
1399 case MenuItem::Submenu: {
1400 MenuItem item(*cit);
1401 item.setSubmenu(MenuDefinition(cit->submenuname()));
1402 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1403 tomenu.addWithStatusCheck(item);
1407 case MenuItem::Separator:
1408 tomenu.addWithStatusCheck(*cit);
1411 case MenuItem::Command:
1412 if (!specialmenu_.hasFunc(cit->func()))
1413 tomenu.addWithStatusCheck(*cit);
1417 // we do not want the menu to end with a separator
1418 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1419 tomenu.items_.pop_back();
1421 // Check whether the shortcuts are unique
1422 tomenu.checkShortcuts();
1426 bool Menus::Impl::hasMenu(QString const & name) const
1428 return find_if(menulist_.begin(), menulist_.end(),
1429 MenuNamesEqual(name)) != menulist_.end();
1433 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1435 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1436 MenuNamesEqual(name));
1437 if (cit == menulist_.end())
1438 LYXERR0("No submenu named " << name);
1439 LASSERT(cit != menulist_.end(), /**/);
1444 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1446 iterator it = find_if(menulist_.begin(), menulist_.end(),
1447 MenuNamesEqual(name));
1448 if (it == menulist_.end())
1449 LYXERR0("No submenu named " << name);
1450 LASSERT(it != menulist_.end(), /**/);
1455 /////////////////////////////////////////////////////////////////////
1459 /////////////////////////////////////////////////////////////////////
1461 Menus::Menus() : d(new Impl) {}
1468 void Menus::read(Lexer & lex)
1476 LexerKeyword menutags[] = {
1477 { "end", md_endmenuset },
1478 { "menu", md_menu },
1479 { "menubar", md_menubar }
1482 // consistency check
1483 if (compare_ascii_no_case(lex.getString(), "menuset"))
1484 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1486 lex.pushTable(menutags);
1487 lex.setContext("Menus::read");
1491 while (lex.isOK() && !quit) {
1492 switch (lex.lex()) {
1494 d->menubar_.read(lex);
1498 QString const name = toqstr(lex.getDocString());
1499 if (d->hasMenu(name))
1500 d->getMenu(name).read(lex);
1502 MenuDefinition menu(name);
1504 d->menulist_.push_back(menu);
1512 lex.printError("Unknown menu tag");
1520 bool Menus::searchMenu(FuncRequest const & func,
1521 vector<docstring> & names) const
1523 MenuDefinition menu;
1524 d->expand(d->menubar_, menu, 0);
1525 return menu.searchMenu(func, names);
1529 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1533 // setup special mac specific menu item
1534 d->macxMenuBarInit(view, qmb);
1537 // Clear all menubar contents before filling it.
1541 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1543 if (d->menubar_.size() == 0) {
1544 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1545 << d->menubar_.name());
1548 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1550 MenuDefinition menu;
1551 BufferView * bv = 0;
1554 d->expand(d->menubar_, menu, bv);
1556 MenuDefinition::const_iterator m = menu.begin();
1557 MenuDefinition::const_iterator end = menu.end();
1559 for (; m != end; ++m) {
1561 if (m->kind() != MenuItem::Submenu) {
1562 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1566 LYXERR(Debug::GUI, "menu bar item " << m->label()
1567 << " is a submenu named " << m->submenuname());
1569 QString name = m->submenuname();
1570 if (!d->hasMenu(name)) {
1571 LYXERR(Debug::GUI, "\tERROR: " << name
1572 << " submenu has no menu!");
1576 Menu * menu = new Menu(view, m->submenuname(), true);
1577 menu->setTitle(label(*m));
1580 d->name_map_[view][name] = menu;
1585 void Menus::updateMenu(Menu * qmenu)
1587 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1590 if (qmenu->d->name.isEmpty())
1593 // Here, We make sure that theLyXFunc points to the correct LyXView.
1594 theLyXFunc().setLyXView(qmenu->d->view);
1596 if (!d->hasMenu(qmenu->d->name)) {
1597 qmenu->addAction(qt_("No action defined!"));
1598 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1603 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1604 BufferView * bv = 0;
1606 bv = qmenu->d->view->view();
1607 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1608 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1612 Menu * Menus::menu(QString const & name, GuiView & view)
1614 LYXERR(Debug::GUI, "Context menu requested: " << name);
1615 Menu * menu = d->name_map_[&view].value(name, 0);
1616 if (!menu && !name.startsWith("context-")) {
1617 LYXERR0("requested context menu not found: " << name);
1621 menu = new Menu(&view, name, true);
1622 d->name_map_[&view][name] = menu;
1626 } // namespace frontend
1629 #include "Menus_moc.cpp"