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"
45 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TocBackend.h"
51 #include "insets/Inset.h"
52 #include "insets/InsetCitation.h"
53 #include "insets/InsetGraphics.h"
55 #include "support/lassert.h"
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/docstring_list.h"
59 #include "support/filetools.h"
60 #include "support/gettext.h"
61 #include "support/lstrings.h"
69 #include <boost/shared_ptr.hpp>
75 using namespace lyx::support;
83 // MacOSX specific stuff is at the end.
90 /// The type of elements that can be in a menu
98 /** This is the list of last opened file,
99 typically for the File menu. */
101 /** This is the list of opened Documents,
102 typically for the Documents menu. */
104 /** This is the bookmarks */
108 /** This is a list of viewable formats
109 typically for the File->View menu. */
111 /** This is a list of updatable formats
112 typically for the File->Update menu. */
114 /** This is a list of exportable formats
115 typically for the File->Export menu. */
117 /** This is a list of importable formats
118 typically for the File->Export menu. */
120 /** This is the list of elements available
121 * for insertion into document. */
123 /** This is the list of user-configurable
124 insets to insert into document */
126 /** This is the list of XML elements to
127 insert into the document */
129 /** This is the list of floats that we can
130 insert a list for. */
132 /** This is the list of floats that we can
135 /** This is the list of selections that can
140 /** Available branches in document */
142 /** Available citation styles for a given citation */
144 /** Available graphics groups */
148 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
151 QString const & label,
152 QString const & submenu = QString(),
153 bool optional = false)
154 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
156 LASSERT(kind == Submenu, /**/);
160 QString const & label,
161 FuncRequest const & func,
162 bool optional = false)
163 : kind_(kind), label_(label), func_(func), optional_(optional)
165 func_.origin = FuncRequest::MENU;
168 // boost::shared_ptr<MenuDefinition> needs this apprently...
171 /// The label of a given menuitem
172 QString label() const { return label_.split('|')[0]; }
174 /// The keyboard shortcut (usually underlined in the entry)
175 QString shortcut() const
177 return label_.contains('|') ? label_.split('|')[1] : QString();
179 /// The complete label, with label and shortcut separated by a '|'
180 QString fulllabel() const { return label_;}
181 /// The kind of entry
182 Kind kind() const { return kind_; }
183 /// the action (if relevant)
184 FuncRequest const & func() const { return func_; }
185 /// returns true if the entry should be ommited when disabled
186 bool optional() const { return optional_; }
187 /// returns the status of the lfun associated with this entry
188 FuncStatus const & status() const { return status_; }
189 /// returns the status of the lfun associated with this entry
190 FuncStatus & status() { return status_; }
191 /// returns the status of the lfun associated with this entry
192 void status(FuncStatus const & status) { status_ = status; }
194 ///returns the binding associated to this action.
195 QString binding() const
197 if (kind_ != Command)
199 // Get the keys bound to this action, but keep only the
201 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
203 return toqstr(bindings.begin()->print(KeySequence::ForGui));
205 LYXERR(Debug::KBMAP, "No binding for "
206 << lyxaction.getActionName(func_.action)
207 << '(' << func_.argument() << ')');
211 /// the description of the submenu (if relevant)
212 QString const & submenuname() const { return submenuname_; }
213 /// set the description of the submenu
214 void submenuname(QString const & name) { submenuname_ = name; }
216 bool hasSubmenu() const { return !submenu_.isEmpty(); }
218 MenuDefinition const & submenu() const { return submenu_.at(0); }
219 MenuDefinition & submenu() { return submenu_[0]; }
221 void setSubmenu(MenuDefinition const & menu)
224 submenu_.append(menu);
235 QString submenuname_;
240 /// contains 0 or 1 item.
241 QList<MenuDefinition> submenu_;
245 class MenuDefinition {
248 typedef std::vector<MenuItem> ItemList;
250 typedef ItemList::const_iterator const_iterator;
252 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
257 QString const & name() const { return name_; }
259 bool empty() const { return items_.empty(); }
260 /// Clear the menu content.
261 void clear() { items_.clear(); }
263 size_t size() const { return items_.size(); }
265 MenuItem const & operator[](size_t) const;
267 const_iterator begin() const { return items_.begin(); }
269 const_iterator end() const { return items_.end(); }
271 // search for func in this menu iteratively, and put menu
273 bool searchMenu(FuncRequest const & func, docstring_list & names)
276 bool hasFunc(FuncRequest const &) const;
277 /// Add the menu item unconditionally
278 void add(MenuItem const & item) { items_.push_back(item); }
279 /// Checks the associated FuncRequest status before adding the
281 void addWithStatusCheck(MenuItem const &);
282 // Check whether the menu shortcuts are unique
283 void checkShortcuts() const;
285 void expandLastfiles();
286 void expandDocuments();
287 void expandBookmarks();
288 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
289 void expandFloatListInsert(Buffer const * buf);
290 void expandFloatInsert(Buffer const * buf);
291 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
292 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
293 void expandToc(Buffer const * buf);
294 void expandPasteRecent(Buffer const * buf);
295 void expandToolbars();
296 void expandBranches(Buffer const * buf);
297 void expandCiteStyles(BufferView const *);
298 void expandGraphicsGroups(BufferView const *);
306 /// Helper for std::find_if
310 MenuNamesEqual(QString const & name) : name_(name) {}
311 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
318 typedef std::vector<MenuDefinition> MenuList;
320 typedef MenuList::const_iterator const_iterator;
322 typedef MenuList::iterator iterator;
324 /////////////////////////////////////////////////////////////////////
325 // MenuDefinition implementation
326 /////////////////////////////////////////////////////////////////////
328 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
332 case MenuItem::Command: {
333 FuncStatus status = lyx::getStatus(i.func());
334 if (status.unknown() || (!status.enabled() && i.optional()))
337 items_.back().status(status);
341 case MenuItem::Submenu: {
342 bool enabled = false;
343 if (i.hasSubmenu()) {
344 for (const_iterator cit = i.submenu().begin();
345 cit != i.submenu().end(); ++cit) {
346 if ((cit->kind() == MenuItem::Command
347 || cit->kind() == MenuItem::Submenu)
348 && cit->status().enabled()) {
354 if (enabled || !i.optional()) {
356 items_.back().status().setEnabled(enabled);
361 case MenuItem::Separator:
362 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
372 void MenuDefinition::read(Lexer & lex)
401 LexerKeyword menutags[] = {
402 { "bookmarks", md_bookmarks },
403 { "branches", md_branches },
404 { "charstyles", md_charstyles },
405 { "citestyles", md_citestyles },
406 { "custom", md_custom },
407 { "documents", md_documents },
408 { "elements", md_elements },
409 { "end", md_endmenu },
410 { "exportformats", md_exportformats },
411 { "floatinsert", md_floatinsert },
412 { "floatlistinsert", md_floatlistinsert },
413 { "graphicsgroups", md_graphicsgroups },
414 { "importformats", md_importformats },
416 { "lastfiles", md_lastfiles },
417 { "optitem", md_optitem },
418 { "optsubmenu", md_optsubmenu },
419 { "pasterecent", md_pasterecent },
420 { "separator", md_separator },
421 { "submenu", md_submenu },
423 { "toolbars", md_toolbars },
424 { "updateformats", md_updateformats },
425 { "viewformats", md_viewformats }
428 lex.pushTable(menutags);
429 lex.setContext("MenuDefinition::read: ");
432 bool optional = false;
434 while (lex.isOK() && !quit) {
438 // fallback to md_item
441 docstring const name = translateIfPossible(lex.getDocString());
443 string const command = lex.getString();
444 FuncRequest func = lyxaction.lookupFunc(command);
445 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
451 add(MenuItem(MenuItem::Separator));
455 add(MenuItem(MenuItem::Lastfiles));
459 add(MenuItem(MenuItem::CharStyles));
463 add(MenuItem(MenuItem::Custom));
467 add(MenuItem(MenuItem::Elements));
471 add(MenuItem(MenuItem::Documents));
475 add(MenuItem(MenuItem::Bookmarks));
479 add(MenuItem(MenuItem::Toc));
483 add(MenuItem(MenuItem::ViewFormats));
486 case md_updateformats:
487 add(MenuItem(MenuItem::UpdateFormats));
490 case md_exportformats:
491 add(MenuItem(MenuItem::ExportFormats));
494 case md_importformats:
495 add(MenuItem(MenuItem::ImportFormats));
498 case md_floatlistinsert:
499 add(MenuItem(MenuItem::FloatListInsert));
503 add(MenuItem(MenuItem::FloatInsert));
507 add(MenuItem(MenuItem::PasteRecent));
511 add(MenuItem(MenuItem::Toolbars));
515 add(MenuItem(MenuItem::Branches));
519 add(MenuItem(MenuItem::CiteStyles));
522 case md_graphicsgroups:
523 add(MenuItem(MenuItem::GraphicsGroups));
528 // fallback to md_submenu
531 docstring const mlabel = translateIfPossible(lex.getDocString());
533 docstring const mname = lex.getDocString();
534 add(MenuItem(MenuItem::Submenu,
535 toqstr(mlabel), toqstr(mname), optional));
545 lex.printError("Unknown menu tag");
553 MenuItem const & MenuDefinition::operator[](size_type i) const
559 bool MenuDefinition::hasFunc(FuncRequest const & func) const
561 for (const_iterator it = begin(), et = end(); it != et; ++it)
562 if (it->func() == func)
568 void MenuDefinition::checkShortcuts() const
570 // This is a quadratic algorithm, but we do not care because
571 // menus are short enough
572 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
573 QString shortcut = it1->shortcut();
574 if (shortcut.isEmpty())
576 if (!it1->label().contains(shortcut))
577 LYXERR0("Menu warning: menu entry \""
579 << "\" does not contain shortcut `"
580 << shortcut << "'.");
581 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
582 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
583 LYXERR0("Menu warning: menu entries "
584 << '"' << it1->fulllabel()
585 << "\" and \"" << it2->fulllabel()
586 << "\" share the same shortcut.");
593 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
595 const_iterator m = begin();
596 const_iterator m_end = end();
597 for (; m != m_end; ++m) {
598 if (m->kind() == MenuItem::Command && m->func() == func) {
599 names.push_back(qstring_to_ucs4(m->label()));
602 if (m->kind() == MenuItem::Submenu) {
603 names.push_back(qstring_to_ucs4(m->label()));
604 if (!m->hasSubmenu()) {
605 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
606 << m->label() << " name=" << m->submenuname());
610 if (m->submenu().searchMenu(func, names))
619 bool compareFormat(Format const * p1, Format const * p2)
625 QString limitStringLength(docstring const & str)
627 size_t const max_item_length = 45;
629 if (str.size() > max_item_length)
630 return toqstr(str.substr(0, max_item_length - 3) + "...");
636 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
641 graphics::getGraphicsGroups(bv->buffer(), grp);
645 set<string>::const_iterator it = grp.begin();
646 set<string>::const_iterator end = grp.end();
647 add(MenuItem(MenuItem::Command, qt_("No Group"),
648 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
649 for (; it != end; it++) {
650 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
651 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
655 void MenuDefinition::expandLastfiles()
657 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
658 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
662 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
663 string const file = lfit->absFilename();
664 QString const label = QString("%1. %2|%3").arg(ii)
665 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
666 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
671 void MenuDefinition::expandDocuments()
673 Buffer * first = theBufferList().first();
678 // We cannot use a for loop as the buffer list cycles.
680 QString label = toqstr(b->fileName().displayName(20));
684 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
685 add(MenuItem(MenuItem::Command, label,
686 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
688 b = theBufferList().next(b);
690 } while (b != first);
692 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
693 FuncRequest(LFUN_NOACTION)));
698 void MenuDefinition::expandBookmarks()
700 lyx::BookmarksSection const & bm = theSession().bookmarks();
702 for (size_t i = 1; i <= bm.size(); ++i) {
704 string const file = bm.bookmark(i).filename.absFilename();
705 QString const label = QString("%1. %2|%3").arg(i)
706 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
707 add(MenuItem(MenuItem::Command, label,
708 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
714 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
716 if (!buf && kind != MenuItem::ImportFormats) {
717 add(MenuItem(MenuItem::Command,
718 qt_("No Document Open!"),
719 FuncRequest(LFUN_NOACTION)));
723 typedef vector<Format const *> Formats;
728 case MenuItem::ImportFormats:
729 formats = theConverters().importableFormats();
730 action = LFUN_BUFFER_IMPORT;
732 case MenuItem::ViewFormats:
733 formats = buf->exportableFormats(true);
734 action = LFUN_BUFFER_VIEW;
736 case MenuItem::UpdateFormats:
737 formats = buf->exportableFormats(true);
738 action = LFUN_BUFFER_UPDATE;
741 formats = buf->exportableFormats(false);
742 action = LFUN_BUFFER_EXPORT;
744 sort(formats.begin(), formats.end(), &compareFormat);
746 Formats::const_iterator fit = formats.begin();
747 Formats::const_iterator end = formats.end();
748 for (; fit != end ; ++fit) {
752 docstring lab = from_utf8((*fit)->prettyname());
753 docstring scut = from_utf8((*fit)->shortcut());
754 docstring const tmplab = lab;
757 lab += char_type('|') + scut;
758 docstring lab_i18n = translateIfPossible(lab);
759 bool const untranslated = (lab == lab_i18n);
760 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
761 QString label = toqstr(lab);
763 // this might happen if the shortcut
764 // has been redefined
765 label = toqstr(translateIfPossible(tmplab));
768 case MenuItem::ImportFormats:
771 case MenuItem::ViewFormats:
772 case MenuItem::ExportFormats:
773 case MenuItem::UpdateFormats:
774 if (!(*fit)->documentFormat())
778 LASSERT(false, /**/);
781 if (!shortcut.isEmpty())
782 label += '|' + shortcut;
785 addWithStatusCheck(MenuItem(MenuItem::Command, label,
786 FuncRequest(action, (*fit)->name())));
788 add(MenuItem(MenuItem::Command, label,
789 FuncRequest(action, (*fit)->name())));
794 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
797 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
798 FuncRequest(LFUN_NOACTION)));
802 FloatList const & floats = buf->params().documentClass().floats();
803 FloatList::const_iterator cit = floats.begin();
804 FloatList::const_iterator end = floats.end();
805 for (; cit != end; ++cit) {
806 addWithStatusCheck(MenuItem(MenuItem::Command,
807 qt_(cit->second.listName()),
808 FuncRequest(LFUN_FLOAT_LIST_INSERT,
809 cit->second.type())));
814 void MenuDefinition::expandFloatInsert(Buffer const * buf)
817 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
818 FuncRequest(LFUN_NOACTION)));
822 FloatList const & floats = buf->params().documentClass().floats();
823 FloatList::const_iterator cit = floats.begin();
824 FloatList::const_iterator end = floats.end();
825 for (; cit != end; ++cit) {
827 QString const label = qt_(cit->second.name());
828 addWithStatusCheck(MenuItem(MenuItem::Command, label,
829 FuncRequest(LFUN_FLOAT_INSERT,
830 cit->second.type())));
835 void MenuDefinition::expandFlexInsert(
836 Buffer const * buf, InsetLayout::InsetLyXType type)
839 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
840 FuncRequest(LFUN_NOACTION)));
843 TextClass::InsetLayouts const & insetLayouts =
844 buf->params().documentClass().insetLayouts();
845 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
846 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
847 for (; cit != end; ++cit) {
848 if (cit->second.lyxtype() == type) {
849 docstring const label = cit->first;
850 addWithStatusCheck(MenuItem(MenuItem::Command,
851 toqstr(translateIfPossible(label)),
852 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
855 // FIXME This is a little clunky.
856 if (items_.empty() && type == InsetLayout::CUSTOM)
857 add(MenuItem(MenuItem::Command,
858 qt_("No custom insets defined!"),
859 FuncRequest(LFUN_NOACTION)));
863 size_t const max_number_of_items = 25;
865 void MenuDefinition::expandToc2(Toc const & toc_list,
866 size_t from, size_t to, int depth)
868 int shortcut_count = 0;
870 // check whether depth is smaller than the smallest depth in toc.
871 int min_depth = 1000;
872 for (size_t i = from; i < to; ++i)
873 min_depth = min(min_depth, toc_list[i].depth());
874 if (min_depth > depth)
877 if (to - from <= max_number_of_items) {
878 for (size_t i = from; i < to; ++i) {
879 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
880 label += limitStringLength(toc_list[i].str());
881 if (toc_list[i].depth() == depth
882 && shortcut_count < 9) {
883 if (label.contains(QString::number(shortcut_count + 1)))
884 label += '|' + QString::number(++shortcut_count);
886 add(MenuItem(MenuItem::Command, label,
887 FuncRequest(toc_list[i].action())));
892 size_t new_pos = pos + 1;
893 while (new_pos < to && toc_list[new_pos].depth() > depth)
896 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
897 label += limitStringLength(toc_list[pos].str());
898 if (toc_list[pos].depth() == depth &&
899 shortcut_count < 9) {
900 if (label.contains(QString::number(shortcut_count + 1)))
901 label += '|' + QString::number(++shortcut_count);
903 if (new_pos == pos + 1) {
904 add(MenuItem(MenuItem::Command,
905 label, FuncRequest(toc_list[pos].action())));
908 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
909 MenuItem item(MenuItem::Submenu, label);
910 item.setSubmenu(sub);
919 void MenuDefinition::expandToc(Buffer const * buf)
921 // To make things very cleanly, we would have to pass buf to
922 // all MenuItem constructors and to expandToc2. However, we
923 // know that all the entries in a TOC will be have status_ ==
924 // OK, so we avoid this unnecessary overhead (JMarc)
927 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
928 FuncRequest(LFUN_NOACTION)));
932 // Add an entry for the master doc if this is a child doc
933 Buffer const * const master = buf->masterBuffer();
935 ParIterator const pit = par_iterator_begin(master->inset());
936 string const arg = convert<string>(pit->id());
937 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
938 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
941 MenuDefinition other_lists;
943 FloatList const & floatlist = buf->params().documentClass().floats();
944 TocList const & toc_list = buf->tocBackend().tocs();
945 TocList::const_iterator cit = toc_list.begin();
946 TocList::const_iterator end = toc_list.end();
947 for (; cit != end; ++cit) {
949 if (cit->first == "tableofcontents")
952 MenuDefinition submenu;
953 if (cit->second.size() >= 30) {
954 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
955 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
957 TocIterator ccit = cit->second.begin();
958 TocIterator eend = cit->second.end();
959 for (; ccit != eend; ++ccit) {
960 submenu.add(MenuItem(MenuItem::Command,
961 limitStringLength(ccit->str()),
962 FuncRequest(ccit->action())));
966 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
967 item.setSubmenu(submenu);
968 if (floatlist.typeExist(cit->first) || cit->first == "child") {
969 // Those two types deserve to be in the main menu.
970 item.setSubmenu(submenu);
973 other_lists.add(item);
975 if (!other_lists.empty()) {
976 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
977 item.setSubmenu(other_lists);
982 cit = toc_list.find("tableofcontents");
984 addWithStatusCheck(MenuItem(MenuItem::Command,
985 qt_("No Table of contents"),
988 expandToc2(cit->second, 0, cit->second.size(), 0);
992 void MenuDefinition::expandPasteRecent(Buffer const * buf)
994 docstring_list const sel = cap::availableSelections(buf);
996 docstring_list::const_iterator cit = sel.begin();
997 docstring_list::const_iterator end = sel.end();
999 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1000 add(MenuItem(MenuItem::Command, toqstr(*cit),
1001 FuncRequest(LFUN_PASTE, convert<string>(index))));
1006 void MenuDefinition::expandToolbars()
1008 MenuDefinition other_lists;
1009 // extracts the toolbars from the backend
1010 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1011 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1012 for (; cit != end; ++cit) {
1013 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1014 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1015 if (guiApp->toolbars().isMainToolbar(cit->name))
1018 other_lists.add(item);
1021 if (!other_lists.empty()) {
1022 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1023 item.setSubmenu(other_lists);
1029 void MenuDefinition::expandBranches(Buffer const * buf)
1032 add(MenuItem(MenuItem::Command,
1033 qt_("No Document Open!"),
1034 FuncRequest(LFUN_NOACTION)));
1038 BufferParams const & params = buf->masterBuffer()->params();
1039 if (params.branchlist().empty()) {
1040 add(MenuItem(MenuItem::Command,
1041 qt_("No Branch in Document!"),
1042 FuncRequest(LFUN_NOACTION)));
1046 BranchList::const_iterator cit = params.branchlist().begin();
1047 BranchList::const_iterator end = params.branchlist().end();
1049 for (int ii = 1; cit != end; ++cit, ++ii) {
1050 docstring label = cit->branch();
1052 label = convert<docstring>(ii) + ". " + label
1053 + char_type('|') + convert<docstring>(ii);
1055 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1056 FuncRequest(LFUN_BRANCH_INSERT,
1062 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1065 add(MenuItem(MenuItem::Command,
1066 qt_("No Document Open!"),
1067 FuncRequest(LFUN_NOACTION)));
1071 Inset const * inset = bv->cursor().nextInset();
1072 if (!inset || inset->lyxCode() != CITE_CODE) {
1073 add(MenuItem(MenuItem::Command,
1074 qt_("No Citation in Scope!"),
1075 FuncRequest(LFUN_NOACTION)));
1078 InsetCommand const * citinset =
1079 static_cast<InsetCommand const *>(inset);
1081 Buffer const * buf = &bv->buffer();
1082 docstring key = citinset->getParam("key");
1083 // we can only handle one key currently
1084 if (contains(key, ','))
1085 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1087 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1088 docstring_list citeStrings =
1089 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1091 docstring_list::const_iterator cit = citeStrings.begin();
1092 docstring_list::const_iterator end = citeStrings.end();
1094 for (int ii = 1; cit != end; ++cit, ++ii) {
1095 docstring label = *cit;
1097 CiteStyle cst = citeStyleList[ii - 1];
1099 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1100 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1101 "changetype " + from_utf8(citationStyleToString(cs)))));
1108 /////////////////////////////////////////////////////////////////////
1109 // Menu::Impl definition and implementation
1110 /////////////////////////////////////////////////////////////////////
1114 /// populates the menu or one of its submenu
1115 /// This is used as a recursive function
1116 void populate(QMenu & qMenu, MenuDefinition const & menu);
1118 /// Only needed for top level menus.
1119 MenuDefinition * top_level_menu;
1122 /// the name of this menu
1128 /// Get a MenuDefinition item label from the menu backend
1129 static QString label(MenuItem const & mi)
1131 QString label = mi.label();
1132 label.replace("&", "&&");
1134 QString shortcut = mi.shortcut();
1135 if (!shortcut.isEmpty()) {
1136 int pos = label.indexOf(shortcut);
1138 //label.insert(pos, 1, char_type('&'));
1139 label.replace(pos, 0, "&");
1142 QString const binding = mi.binding();
1143 if (!binding.isEmpty())
1144 label += '\t' + binding;
1149 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1151 LYXERR(Debug::GUI, "populating menu " << menu.name());
1152 if (menu.size() == 0) {
1153 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1156 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1157 MenuDefinition::const_iterator m = menu.begin();
1158 MenuDefinition::const_iterator end = menu.end();
1159 for (; m != end; ++m) {
1160 if (m->kind() == MenuItem::Separator)
1161 qMenu.addSeparator();
1162 else if (m->kind() == MenuItem::Submenu) {
1163 QMenu * subMenu = qMenu.addMenu(label(*m));
1164 populate(*subMenu, m->submenu());
1165 subMenu->setEnabled(m->status().enabled());
1167 // we have a MenuItem::Command
1168 qMenu.addAction(new Action(view, QIcon(), label(*m),
1169 m->func(), QString(), &qMenu));
1174 /////////////////////////////////////////////////////////////////////
1175 // Menu implementation
1176 /////////////////////////////////////////////////////////////////////
1178 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1179 : QMenu(gv), d(new Menu::Impl)
1181 d->top_level_menu = top_level? new MenuDefinition : 0;
1185 if (d->top_level_menu)
1186 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1192 delete d->top_level_menu;
1197 void Menu::updateView()
1199 guiApp->menus().updateMenu(this);
1203 /////////////////////////////////////////////////////////////////////
1204 // Menus::Impl definition and implementation
1205 /////////////////////////////////////////////////////////////////////
1207 struct Menus::Impl {
1209 bool hasMenu(QString const &) const;
1211 MenuDefinition & getMenu(QString const &);
1213 MenuDefinition const & getMenu(QString const &) const;
1215 /// Expands some special entries of the menu
1216 /** The entries with the following kind are expanded to a
1217 sequence of Command MenuItems: Lastfiles, Documents,
1218 ViewFormats, ExportFormats, UpdateFormats, Branches
1220 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1221 BufferView const *) const;
1223 /// Initialize specific MACOS X menubar
1224 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1226 /// Mac special menu.
1227 /** This defines a menu whose entries list the FuncRequests
1228 that will be removed by expand() in other menus. This is
1229 used by the Qt/Mac code.
1231 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1232 such that the items will keep accessing the FuncRequests in
1233 the MenuDefinition. While Menus::Impl might be recreated,
1234 we keep mac_special_menu_ in memory by making it static.
1236 static MenuDefinition mac_special_menu_;
1241 MenuDefinition menubar_;
1243 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1245 /// name to menu for \c menu() method.
1250 MenuDefinition Menus::Impl::mac_special_menu_;
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 (mac_special_menu_.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 mac_special_menu_.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 = mac_special_menu_.begin();
1322 MenuDefinition::const_iterator end = mac_special_menu_.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, InsetLayout::CHARSTYLE);
1365 case MenuItem::Custom:
1366 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1369 case MenuItem::Elements:
1370 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1373 case MenuItem::FloatListInsert:
1374 tomenu.expandFloatListInsert(buf);
1377 case MenuItem::FloatInsert:
1378 tomenu.expandFloatInsert(buf);
1381 case MenuItem::PasteRecent:
1382 tomenu.expandPasteRecent(buf);
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::GraphicsGroups:
1402 tomenu.expandGraphicsGroups(bv);
1405 case MenuItem::Submenu: {
1406 MenuItem item(*cit);
1407 item.setSubmenu(MenuDefinition(cit->submenuname()));
1408 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1409 tomenu.addWithStatusCheck(item);
1413 case MenuItem::Separator:
1414 tomenu.addWithStatusCheck(*cit);
1417 case MenuItem::Command:
1418 if (!mac_special_menu_.hasFunc(cit->func()))
1419 tomenu.addWithStatusCheck(*cit);
1423 // we do not want the menu to end with a separator
1424 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1425 tomenu.items_.pop_back();
1427 // Check whether the shortcuts are unique
1428 tomenu.checkShortcuts();
1432 bool Menus::Impl::hasMenu(QString const & name) const
1434 return find_if(menulist_.begin(), menulist_.end(),
1435 MenuNamesEqual(name)) != menulist_.end();
1439 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1441 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1442 MenuNamesEqual(name));
1443 if (cit == menulist_.end())
1444 LYXERR0("No submenu named " << name);
1445 LASSERT(cit != menulist_.end(), /**/);
1450 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1452 iterator it = find_if(menulist_.begin(), menulist_.end(),
1453 MenuNamesEqual(name));
1454 if (it == menulist_.end())
1455 LYXERR0("No submenu named " << name);
1456 LASSERT(it != menulist_.end(), /**/);
1461 /////////////////////////////////////////////////////////////////////
1465 /////////////////////////////////////////////////////////////////////
1467 Menus::Menus() : d(new Impl) {}
1483 void Menus::read(Lexer & lex)
1491 LexerKeyword menutags[] = {
1492 { "end", md_endmenuset },
1493 { "menu", md_menu },
1494 { "menubar", md_menubar }
1497 // consistency check
1498 if (compare_ascii_no_case(lex.getString(), "menuset"))
1499 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1501 lex.pushTable(menutags);
1502 lex.setContext("Menus::read");
1506 while (lex.isOK() && !quit) {
1507 switch (lex.lex()) {
1509 d->menubar_.read(lex);
1513 QString const name = toqstr(lex.getDocString());
1514 if (d->hasMenu(name))
1515 d->getMenu(name).read(lex);
1517 MenuDefinition menu(name);
1519 d->menulist_.push_back(menu);
1527 lex.printError("Unknown menu tag");
1535 bool Menus::searchMenu(FuncRequest const & func,
1536 docstring_list & names) const
1538 MenuDefinition menu;
1539 d->expand(d->menubar_, menu, 0);
1540 return menu.searchMenu(func, names);
1544 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1548 // setup special mac specific menu items, but only do this
1549 // the first time a QMenuBar is created. Otherwise Qt will
1550 // create duplicate items in the application menu. It seems
1551 // that Qt does not remove them when the QMenubar is cleared.
1552 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1553 d->macxMenuBarInit(view, qmb);
1556 // Clear all menubar contents before filling it.
1560 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1562 if (d->menubar_.size() == 0) {
1563 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1564 << d->menubar_.name());
1567 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1569 MenuDefinition menu;
1570 BufferView * bv = 0;
1573 d->expand(d->menubar_, menu, bv);
1575 MenuDefinition::const_iterator m = menu.begin();
1576 MenuDefinition::const_iterator end = menu.end();
1578 for (; m != end; ++m) {
1580 if (m->kind() != MenuItem::Submenu) {
1581 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1585 LYXERR(Debug::GUI, "menu bar item " << m->label()
1586 << " is a submenu named " << m->submenuname());
1588 QString name = m->submenuname();
1589 if (!d->hasMenu(name)) {
1590 LYXERR(Debug::GUI, "\tERROR: " << name
1591 << " submenu has no menu!");
1595 Menu * menu = new Menu(view, m->submenuname(), true);
1596 menu->setTitle(label(*m));
1599 d->name_map_[view][name] = menu;
1604 void Menus::updateMenu(Menu * qmenu)
1606 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1609 if (qmenu->d->name.isEmpty())
1612 // Here, We make sure that theLyXFunc points to the correct LyXView.
1613 theLyXFunc().setLyXView(qmenu->d->view);
1615 if (!d->hasMenu(qmenu->d->name)) {
1616 qmenu->addAction(qt_("No action defined!"));
1617 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1622 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1623 BufferView * bv = 0;
1625 bv = qmenu->d->view->view();
1626 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1627 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1631 Menu * Menus::menu(QString const & name, GuiView & view)
1633 LYXERR(Debug::GUI, "Context menu requested: " << name);
1634 Menu * menu = d->name_map_[&view].value(name, 0);
1635 if (!menu && !name.startsWith("context-")) {
1636 LYXERR0("requested context menu not found: " << name);
1640 menu = new Menu(&view, name, true);
1641 d->name_map_[&view][name] = menu;
1645 } // namespace frontend
1648 #include "moc_Menus.cpp"