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"
39 #include "IndicesList.h"
42 #include "LyXAction.h"
43 #include "LyX.h" // for lastfiles
45 #include "Paragraph.h"
46 #include "ParIterator.h"
48 #include "TextClass.h"
49 #include "TocBackend.h"
52 #include "insets/Inset.h"
53 #include "insets/InsetCitation.h"
54 #include "insets/InsetGraphics.h"
56 #include "support/lassert.h"
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/docstring_list.h"
60 #include "support/filetools.h"
61 #include "support/gettext.h"
62 #include "support/lstrings.h"
70 #include <boost/shared_ptr.hpp>
76 using namespace lyx::support;
84 // MacOSX specific stuff is at the end.
91 /// The type of elements that can be in a menu
99 /** This type of item explains why something is unavailable. If this
100 menuitem is in a submenu, the submenu is enabled to make sure the
101 user sees the information. */
103 /** This type of item merely shows that there might be a list or
104 something alike at this position, but the list is still empty.
105 If this item is in a submenu, the submenu will not always be
108 /** This is the list of last opened file,
109 typically for the File menu. */
111 /** This is the list of opened Documents,
112 typically for the Documents menu. */
114 /** This is the bookmarks */
118 /** This is a list of viewable formats
119 typically for the File->View menu. */
121 /** This is a list of updatable formats
122 typically for the File->Update menu. */
124 /** This is a list of exportable formats
125 typically for the File->Export menu. */
127 /** This is a list of importable formats
128 typically for the File->Export menu. */
130 /** This is the list of elements available
131 * for insertion into document. */
133 /** This is the list of user-configurable
134 insets to insert into document */
136 /** This is the list of XML elements to
137 insert into the document */
139 /** This is the list of floats that we can
140 insert a list for. */
142 /** This is the list of floats that we can
145 /** This is the list of selections that can
150 /** Available branches in document */
152 /** Available indices in document */
154 /** Context menu for indices in document */
156 /** Available index lists in document */
158 /** Context menu for available indices lists in document */
160 /** Available citation styles for a given citation */
162 /** Available graphics groups */
166 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
169 QString const & label,
170 QString const & submenu = QString(),
171 bool optional = false)
172 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
174 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
178 QString const & label,
179 FuncRequest const & func,
180 bool optional = false,
181 FuncRequest::Origin origin = FuncRequest::MENU)
182 : kind_(kind), label_(label), func_(func), optional_(optional)
184 func_.origin = origin;
187 // boost::shared_ptr<MenuDefinition> needs this apprently...
190 /// The label of a given menuitem
191 QString label() const { return label_.split('|')[0]; }
193 /// The keyboard shortcut (usually underlined in the entry)
194 QString shortcut() const
196 return label_.contains('|') ? label_.split('|')[1] : QString();
198 /// The complete label, with label and shortcut separated by a '|'
199 QString fulllabel() const { return label_;}
200 /// The kind of entry
201 Kind kind() const { return kind_; }
202 /// the action (if relevant)
203 FuncRequest const & func() const { return func_; }
204 /// returns true if the entry should be ommited when disabled
205 bool optional() const { return optional_; }
206 /// returns the status of the lfun associated with this entry
207 FuncStatus const & status() const { return status_; }
208 /// returns the status of the lfun associated with this entry
209 FuncStatus & status() { return status_; }
210 /// returns the status of the lfun associated with this entry
211 void status(FuncStatus const & status) { status_ = status; }
213 ///returns the binding associated to this action.
214 QString binding() const
216 if (kind_ != Command)
218 // Get the keys bound to this action, but keep only the
220 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
222 return toqstr(bindings.begin()->print(KeySequence::ForGui));
224 LYXERR(Debug::KBMAP, "No binding for "
225 << lyxaction.getActionName(func_.action)
226 << '(' << func_.argument() << ')');
230 /// the description of the submenu (if relevant)
231 QString const & submenuname() const { return submenuname_; }
232 /// set the description of the submenu
233 void submenuname(QString const & name) { submenuname_ = name; }
235 bool hasSubmenu() const { return !submenu_.isEmpty(); }
237 MenuDefinition const & submenu() const { return submenu_.at(0); }
238 MenuDefinition & submenu() { return submenu_[0]; }
240 void setSubmenu(MenuDefinition const & menu)
243 submenu_.append(menu);
254 QString submenuname_;
259 /// contains 0 or 1 item.
260 QList<MenuDefinition> submenu_;
264 class MenuDefinition {
267 typedef std::vector<MenuItem> ItemList;
269 typedef ItemList::const_iterator const_iterator;
271 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
276 QString const & name() const { return name_; }
278 bool empty() const { return items_.empty(); }
279 /// Clear the menu content.
280 void clear() { items_.clear(); }
282 size_t size() const { return items_.size(); }
284 MenuItem const & operator[](size_t) const;
286 const_iterator begin() const { return items_.begin(); }
288 const_iterator end() const { return items_.end(); }
290 // search for func in this menu iteratively, and put menu
292 bool searchMenu(FuncRequest const & func, docstring_list & names)
295 bool hasFunc(FuncRequest const &) const;
296 /// Add the menu item unconditionally
297 void add(MenuItem const & item) { items_.push_back(item); }
298 /// Checks the associated FuncRequest status before adding the
300 void addWithStatusCheck(MenuItem const &);
301 // Check whether the menu shortcuts are unique
302 void checkShortcuts() const;
304 void expandLastfiles();
305 void expandDocuments();
306 void expandBookmarks();
307 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
308 void expandFloatListInsert(Buffer const * buf);
309 void expandFloatInsert(Buffer const * buf);
310 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
311 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
312 void expandToc(Buffer const * buf);
313 void expandPasteRecent(Buffer const * buf);
314 void expandToolbars();
315 void expandBranches(Buffer const * buf);
316 void expandIndices(Buffer const * buf, bool listof = false);
317 void expandIndicesContext(Buffer const * buf, bool listof = false);
318 void expandCiteStyles(BufferView const *);
319 void expandGraphicsGroups(BufferView const *);
327 /// Helper for std::find_if
331 MenuNamesEqual(QString const & name) : name_(name) {}
332 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
339 typedef std::vector<MenuDefinition> MenuList;
341 typedef MenuList::const_iterator const_iterator;
343 typedef MenuList::iterator iterator;
345 /////////////////////////////////////////////////////////////////////
346 // MenuDefinition implementation
347 /////////////////////////////////////////////////////////////////////
349 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
353 case MenuItem::Command: {
354 FuncStatus status = lyx::getStatus(i.func());
355 if (status.unknown() || (!status.enabled() && i.optional()))
358 items_.back().status(status);
362 case MenuItem::Submenu: {
363 bool enabled = false;
364 if (i.hasSubmenu()) {
365 for (const_iterator cit = i.submenu().begin();
366 cit != i.submenu().end(); ++cit) {
367 // Only these kind of items affect the status of the submenu
368 if ((cit->kind() == MenuItem::Command
369 || cit->kind() == MenuItem::Submenu
370 || cit->kind() == MenuItem::Help)
371 && cit->status().enabled()) {
377 if (enabled || !i.optional()) {
379 items_.back().status().setEnabled(enabled);
384 case MenuItem::Separator:
385 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
395 void MenuDefinition::read(Lexer & lex)
412 md_indiceslistscontext,
428 LexerKeyword menutags[] = {
429 { "bookmarks", md_bookmarks },
430 { "branches", md_branches },
431 { "charstyles", md_charstyles },
432 { "citestyles", md_citestyles },
433 { "custom", md_custom },
434 { "documents", md_documents },
435 { "elements", md_elements },
436 { "end", md_endmenu },
437 { "exportformats", md_exportformats },
438 { "floatinsert", md_floatinsert },
439 { "floatlistinsert", md_floatlistinsert },
440 { "graphicsgroups", md_graphicsgroups },
441 { "importformats", md_importformats },
442 { "indices", md_indices },
443 { "indicescontext", md_indicescontext },
444 { "indiceslists", md_indiceslists },
445 { "indiceslistscontext", md_indiceslistscontext },
447 { "lastfiles", md_lastfiles },
448 { "optitem", md_optitem },
449 { "optsubmenu", md_optsubmenu },
450 { "pasterecent", md_pasterecent },
451 { "separator", md_separator },
452 { "submenu", md_submenu },
454 { "toolbars", md_toolbars },
455 { "updateformats", md_updateformats },
456 { "viewformats", md_viewformats }
459 lex.pushTable(menutags);
460 lex.setContext("MenuDefinition::read: ");
463 bool optional = false;
465 while (lex.isOK() && !quit) {
469 // fallback to md_item
472 docstring const name = translateIfPossible(lex.getDocString());
474 string const command = lex.getString();
475 FuncRequest func = lyxaction.lookupFunc(command);
476 FuncRequest::Origin origin = FuncRequest::MENU;
477 if (name_.startsWith("context-toc-"))
478 origin = FuncRequest::TOC;
479 add(MenuItem(MenuItem::Command, toqstr(name), func, optional, origin));
485 add(MenuItem(MenuItem::Separator));
489 add(MenuItem(MenuItem::Lastfiles));
493 add(MenuItem(MenuItem::CharStyles));
497 add(MenuItem(MenuItem::Custom));
501 add(MenuItem(MenuItem::Elements));
505 add(MenuItem(MenuItem::Documents));
509 add(MenuItem(MenuItem::Bookmarks));
513 add(MenuItem(MenuItem::Toc));
517 add(MenuItem(MenuItem::ViewFormats));
520 case md_updateformats:
521 add(MenuItem(MenuItem::UpdateFormats));
524 case md_exportformats:
525 add(MenuItem(MenuItem::ExportFormats));
528 case md_importformats:
529 add(MenuItem(MenuItem::ImportFormats));
532 case md_floatlistinsert:
533 add(MenuItem(MenuItem::FloatListInsert));
537 add(MenuItem(MenuItem::FloatInsert));
541 add(MenuItem(MenuItem::PasteRecent));
545 add(MenuItem(MenuItem::Toolbars));
549 add(MenuItem(MenuItem::Branches));
553 add(MenuItem(MenuItem::CiteStyles));
556 case md_graphicsgroups:
557 add(MenuItem(MenuItem::GraphicsGroups));
561 add(MenuItem(MenuItem::Indices));
564 case md_indicescontext:
565 add(MenuItem(MenuItem::IndicesContext));
568 case md_indiceslists:
569 add(MenuItem(MenuItem::IndicesLists));
572 case md_indiceslistscontext:
573 add(MenuItem(MenuItem::IndicesListsContext));
578 // fallback to md_submenu
581 docstring const mlabel = translateIfPossible(lex.getDocString());
583 docstring const mname = lex.getDocString();
584 add(MenuItem(MenuItem::Submenu,
585 toqstr(mlabel), toqstr(mname), optional));
595 lex.printError("Unknown menu tag");
603 MenuItem const & MenuDefinition::operator[](size_type i) const
609 bool MenuDefinition::hasFunc(FuncRequest const & func) const
611 for (const_iterator it = begin(), et = end(); it != et; ++it)
612 if (it->func() == func)
618 void MenuDefinition::checkShortcuts() const
620 // This is a quadratic algorithm, but we do not care because
621 // menus are short enough
622 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
623 QString shortcut = it1->shortcut();
624 if (shortcut.isEmpty())
626 if (!it1->label().contains(shortcut))
627 LYXERR0("Menu warning: menu entry \""
629 << "\" does not contain shortcut `"
630 << shortcut << "'.");
631 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
632 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
633 LYXERR0("Menu warning: menu entries "
634 << '"' << it1->fulllabel()
635 << "\" and \"" << it2->fulllabel()
636 << "\" share the same shortcut.");
643 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
645 const_iterator m = begin();
646 const_iterator m_end = end();
647 for (; m != m_end; ++m) {
648 if (m->kind() == MenuItem::Command && m->func() == func) {
649 names.push_back(qstring_to_ucs4(m->label()));
652 if (m->kind() == MenuItem::Submenu) {
653 names.push_back(qstring_to_ucs4(m->label()));
654 if (!m->hasSubmenu()) {
655 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
656 << m->label() << " name=" << m->submenuname());
660 if (m->submenu().searchMenu(func, names))
669 bool compareFormat(Format const * p1, Format const * p2)
675 QString limitStringLength(docstring const & str)
677 size_t const max_item_length = 45;
679 if (str.size() > max_item_length)
680 return toqstr(str.substr(0, max_item_length - 3) + "...");
686 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
691 graphics::getGraphicsGroups(bv->buffer(), grp);
695 set<string>::const_iterator it = grp.begin();
696 set<string>::const_iterator end = grp.end();
697 add(MenuItem(MenuItem::Command, qt_("No Group"),
698 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
699 for (; it != end; it++) {
700 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
701 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
705 void MenuDefinition::expandLastfiles()
707 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
708 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
712 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
713 string const file = lfit->absFilename();
714 QString const label = QString("%1. %2|%3").arg(ii)
715 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
716 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
721 void MenuDefinition::expandDocuments()
723 MenuItem item(MenuItem::Submenu, qt_("Invisible"));
724 item.setSubmenu(MenuDefinition(qt_("Invisible")));
726 Buffer * first = theBufferList().first();
732 // We cannot use a for loop as the buffer list cycles.
734 QString label = toqstr(b->fileName().displayName(20));
737 bool const shown = guiApp->currentView()->workArea(*b);
738 int ii = shown ? vis : invis;
740 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
742 add(MenuItem(MenuItem::Command, label,
743 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
746 item.submenu().add(MenuItem(MenuItem::Command, label,
747 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
750 b = theBufferList().next(b);
751 } while (b != first);
752 if (!item.submenu().empty())
755 add(MenuItem(MenuItem::Info, qt_("<No documents open>")));
759 void MenuDefinition::expandBookmarks()
761 lyx::BookmarksSection const & bm = theSession().bookmarks();
764 for (size_t i = 1; i <= bm.size(); ++i) {
766 string const file = bm.bookmark(i).filename.absFilename();
767 QString const label = QString("%1. %2|%3").arg(i)
768 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
769 add(MenuItem(MenuItem::Command, label,
770 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
775 add(MenuItem(MenuItem::Info, qt_("<No bookmarks saved yet>")));
779 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
781 if (!buf && kind != MenuItem::ImportFormats)
784 typedef vector<Format const *> Formats;
789 case MenuItem::ImportFormats:
790 formats = theConverters().importableFormats();
791 action = LFUN_BUFFER_IMPORT;
793 case MenuItem::ViewFormats:
794 formats = buf->exportableFormats(true);
795 action = LFUN_BUFFER_VIEW;
797 case MenuItem::UpdateFormats:
798 formats = buf->exportableFormats(true);
799 action = LFUN_BUFFER_UPDATE;
802 formats = buf->exportableFormats(false);
803 action = LFUN_BUFFER_EXPORT;
805 sort(formats.begin(), formats.end(), &compareFormat);
807 Formats::const_iterator fit = formats.begin();
808 Formats::const_iterator end = formats.end();
809 for (; fit != end ; ++fit) {
813 docstring lab = from_utf8((*fit)->prettyname());
814 docstring scut = from_utf8((*fit)->shortcut());
815 docstring const tmplab = lab;
818 lab += char_type('|') + scut;
819 docstring lab_i18n = translateIfPossible(lab);
820 bool const untranslated = (lab == lab_i18n);
821 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
822 QString label = toqstr(lab);
824 // this might happen if the shortcut
825 // has been redefined
826 label = toqstr(translateIfPossible(tmplab));
829 case MenuItem::ImportFormats:
832 case MenuItem::ViewFormats:
833 case MenuItem::UpdateFormats:
834 if ((*fit)->name() == buf->getDefaultOutputFormat())
836 case MenuItem::ExportFormats:
837 if (!(*fit)->documentFormat())
841 LASSERT(false, /**/);
844 if (!shortcut.isEmpty())
845 label += '|' + shortcut;
848 addWithStatusCheck(MenuItem(MenuItem::Command, label,
849 FuncRequest(action, (*fit)->name())));
851 add(MenuItem(MenuItem::Command, label,
852 FuncRequest(action, (*fit)->name())));
857 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
862 FloatList const & floats = buf->params().documentClass().floats();
863 FloatList::const_iterator cit = floats.begin();
864 FloatList::const_iterator end = floats.end();
865 for (; cit != end; ++cit) {
866 addWithStatusCheck(MenuItem(MenuItem::Command,
867 qt_(cit->second.listName()),
868 FuncRequest(LFUN_FLOAT_LIST_INSERT,
869 cit->second.type())));
874 void MenuDefinition::expandFloatInsert(Buffer const * buf)
879 FloatList const & floats = buf->params().documentClass().floats();
880 FloatList::const_iterator cit = floats.begin();
881 FloatList::const_iterator end = floats.end();
882 for (; cit != end; ++cit) {
884 QString const label = qt_(cit->second.name());
885 addWithStatusCheck(MenuItem(MenuItem::Command, label,
886 FuncRequest(LFUN_FLOAT_INSERT,
887 cit->second.type())));
892 void MenuDefinition::expandFlexInsert(
893 Buffer const * buf, InsetLayout::InsetLyXType type)
898 TextClass::InsetLayouts const & insetLayouts =
899 buf->params().documentClass().insetLayouts();
900 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
901 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
902 for (; cit != end; ++cit) {
903 if (cit->second.lyxtype() == type) {
904 docstring const label = cit->first;
905 addWithStatusCheck(MenuItem(MenuItem::Command,
906 toqstr(translateIfPossible(label)),
907 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
910 // FIXME This is a little clunky.
911 if (items_.empty() && type == InsetLayout::CUSTOM)
912 add(MenuItem(MenuItem::Help, qt_("No custom insets defined!")));
916 size_t const max_number_of_items = 25;
918 void MenuDefinition::expandToc2(Toc const & toc_list,
919 size_t from, size_t to, int depth)
921 int shortcut_count = 0;
923 // check whether depth is smaller than the smallest depth in toc.
924 int min_depth = 1000;
925 for (size_t i = from; i < to; ++i)
926 min_depth = min(min_depth, toc_list[i].depth());
927 if (min_depth > depth)
930 if (to - from <= max_number_of_items) {
931 for (size_t i = from; i < to; ++i) {
932 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
933 label += limitStringLength(toc_list[i].str());
934 if (toc_list[i].depth() == depth
935 && shortcut_count < 9) {
936 if (label.contains(QString::number(shortcut_count + 1)))
937 label += '|' + QString::number(++shortcut_count);
939 add(MenuItem(MenuItem::Command, label,
940 FuncRequest(toc_list[i].action())));
945 size_t new_pos = pos + 1;
946 while (new_pos < to && toc_list[new_pos].depth() > depth)
949 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
950 label += limitStringLength(toc_list[pos].str());
951 if (toc_list[pos].depth() == depth &&
952 shortcut_count < 9) {
953 if (label.contains(QString::number(shortcut_count + 1)))
954 label += '|' + QString::number(++shortcut_count);
956 if (new_pos == pos + 1) {
957 add(MenuItem(MenuItem::Command,
958 label, FuncRequest(toc_list[pos].action())));
961 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
962 MenuItem item(MenuItem::Submenu, label);
963 item.setSubmenu(sub);
972 void MenuDefinition::expandToc(Buffer const * buf)
974 // To make things very cleanly, we would have to pass buf to
975 // all MenuItem constructors and to expandToc2. However, we
976 // know that all the entries in a TOC will be have status_ ==
977 // OK, so we avoid this unnecessary overhead (JMarc)
980 add(MenuItem(MenuItem::Info, qt_("<No document open>")));
984 // Add an entry for the master doc if this is a child doc
985 Buffer const * const master = buf->masterBuffer();
987 ParIterator const pit = par_iterator_begin(master->inset());
988 string const arg = convert<string>(pit->id());
989 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
990 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
993 MenuDefinition other_lists;
995 FloatList const & floatlist = buf->params().documentClass().floats();
996 TocList const & toc_list = buf->tocBackend().tocs();
997 TocList::const_iterator cit = toc_list.begin();
998 TocList::const_iterator end = toc_list.end();
999 for (; cit != end; ++cit) {
1000 // Handle this later
1001 if (cit->first == "tableofcontents")
1004 MenuDefinition submenu;
1005 if (cit->second.size() >= 30) {
1006 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1007 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1009 TocIterator ccit = cit->second.begin();
1010 TocIterator eend = cit->second.end();
1011 for (; ccit != eend; ++ccit) {
1012 submenu.add(MenuItem(MenuItem::Command,
1013 limitStringLength(ccit->str()),
1014 FuncRequest(ccit->action())));
1018 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1019 item.setSubmenu(submenu);
1020 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1021 // Those two types deserve to be in the main menu.
1022 item.setSubmenu(submenu);
1025 other_lists.add(item);
1027 if (!other_lists.empty()) {
1028 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1029 item.setSubmenu(other_lists);
1033 // Handle normal TOC
1034 cit = toc_list.find("tableofcontents");
1036 LYXERR(Debug::GUI, "No table of contents.");
1038 if (cit->second.size() > 0 )
1039 expandToc2(cit->second, 0, cit->second.size(), 0);
1041 add(MenuItem(MenuItem::Info, qt_("<Empty table of contents>")));
1046 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1048 docstring_list const sel = cap::availableSelections(buf);
1050 docstring_list::const_iterator cit = sel.begin();
1051 docstring_list::const_iterator end = sel.end();
1053 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1054 add(MenuItem(MenuItem::Command, toqstr(*cit),
1055 FuncRequest(LFUN_PASTE, convert<string>(index))));
1060 void MenuDefinition::expandToolbars()
1062 MenuDefinition other_lists;
1063 // extracts the toolbars from the backend
1064 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1065 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1066 for (; cit != end; ++cit) {
1067 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1068 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1069 if (guiApp->toolbars().isMainToolbar(cit->name))
1072 other_lists.add(item);
1075 if (!other_lists.empty()) {
1076 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1077 item.setSubmenu(other_lists);
1083 void MenuDefinition::expandBranches(Buffer const * buf)
1088 BufferParams const & master_params = buf->masterBuffer()->params();
1089 BufferParams const & params = buf->params();
1090 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1091 add(MenuItem(MenuItem::Help, qt_("No branches set for document!")));
1095 BranchList::const_iterator cit = master_params.branchlist().begin();
1096 BranchList::const_iterator end = master_params.branchlist().end();
1098 for (int ii = 1; cit != end; ++cit, ++ii) {
1099 docstring label = cit->branch();
1101 label = convert<docstring>(ii) + ". " + label
1102 + char_type('|') + convert<docstring>(ii);
1104 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1105 FuncRequest(LFUN_BRANCH_INSERT,
1109 if (buf == buf->masterBuffer())
1112 MenuDefinition child_branches;
1114 BranchList::const_iterator ccit = params.branchlist().begin();
1115 BranchList::const_iterator cend = params.branchlist().end();
1117 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1118 docstring label = ccit->branch();
1120 label = convert<docstring>(ii) + ". " + label
1121 + char_type('|') + convert<docstring>(ii);
1123 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1125 FuncRequest(LFUN_BRANCH_INSERT,
1129 if (!child_branches.empty()) {
1130 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1131 item.setSubmenu(child_branches);
1137 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1142 BufferParams const & params = buf->masterBuffer()->params();
1143 if (!params.use_indices) {
1145 addWithStatusCheck(MenuItem(MenuItem::Command,
1146 qt_("Index List|I"),
1147 FuncRequest(LFUN_INDEX_PRINT,
1148 from_ascii("idx"))));
1150 addWithStatusCheck(MenuItem(MenuItem::Command,
1151 qt_("Index Entry|d"),
1152 FuncRequest(LFUN_INDEX_INSERT,
1153 from_ascii("idx"))));
1157 if (params.indiceslist().empty())
1160 IndicesList::const_iterator cit = params.indiceslist().begin();
1161 IndicesList::const_iterator end = params.indiceslist().end();
1163 for (int ii = 1; cit != end; ++cit, ++ii) {
1165 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1166 FuncRequest(LFUN_INDEX_PRINT,
1169 docstring label = _("Index Entry");
1170 label += " (" + cit->index() + ")";
1171 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1172 FuncRequest(LFUN_INDEX_INSERT,
1179 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1184 BufferParams const & params = buf->masterBuffer()->params();
1185 if (!params.use_indices || params.indiceslist().empty())
1188 IndicesList::const_iterator cit = params.indiceslist().begin();
1189 IndicesList::const_iterator end = params.indiceslist().end();
1191 for (int ii = 1; cit != end; ++cit, ++ii) {
1193 InsetCommandParams p(INDEX_PRINT_CODE);
1194 p["type"] = cit->shortcut();
1195 string const data = InsetCommand::params2string("index_print", p);
1196 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1197 FuncRequest(LFUN_NEXT_INSET_MODIFY, data)));
1199 docstring label = _("Index Entry");
1200 label += " (" + cit->index() + ")";
1201 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1202 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1203 from_ascii("changetype ") + cit->shortcut())));
1209 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1214 Inset const * inset = bv->cursor().nextInset();
1215 if (!inset || inset->lyxCode() != CITE_CODE) {
1216 add(MenuItem(MenuItem::Command,
1217 qt_("No Citation in Scope!"),
1218 FuncRequest(LFUN_NOACTION)));
1221 InsetCommand const * citinset =
1222 static_cast<InsetCommand const *>(inset);
1224 Buffer const * buf = &bv->buffer();
1225 docstring key = citinset->getParam("key");
1226 // we can only handle one key currently
1227 if (contains(key, ','))
1228 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1230 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1231 docstring_list citeStrings =
1232 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1234 docstring_list::const_iterator cit = citeStrings.begin();
1235 docstring_list::const_iterator end = citeStrings.end();
1237 for (int ii = 1; cit != end; ++cit, ++ii) {
1238 docstring label = *cit;
1240 CiteStyle cst = citeStyleList[ii - 1];
1242 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1243 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1244 "changetype " + from_utf8(citationStyleToString(cs)))));
1251 /////////////////////////////////////////////////////////////////////
1252 // Menu::Impl definition and implementation
1253 /////////////////////////////////////////////////////////////////////
1257 /// populates the menu or one of its submenu
1258 /// This is used as a recursive function
1259 void populate(QMenu & qMenu, MenuDefinition const & menu);
1261 /// Only needed for top level menus.
1262 MenuDefinition * top_level_menu;
1265 /// the name of this menu
1271 /// Get a MenuDefinition item label from the menu backend
1272 static QString label(MenuItem const & mi)
1274 QString label = mi.label();
1275 label.replace("&", "&&");
1277 QString shortcut = mi.shortcut();
1278 if (!shortcut.isEmpty()) {
1279 int pos = label.indexOf(shortcut);
1281 //label.insert(pos, 1, char_type('&'));
1282 label.replace(pos, 0, "&");
1285 QString const binding = mi.binding();
1286 if (!binding.isEmpty())
1287 label += '\t' + binding;
1292 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1294 LYXERR(Debug::GUI, "populating menu " << menu.name());
1295 if (menu.size() == 0) {
1296 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1299 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1300 MenuDefinition::const_iterator m = menu.begin();
1301 MenuDefinition::const_iterator end = menu.end();
1302 for (; m != end; ++m) {
1303 if (m->kind() == MenuItem::Separator)
1304 qMenu.addSeparator();
1305 else if (m->kind() == MenuItem::Submenu) {
1306 QMenu * subMenu = qMenu.addMenu(label(*m));
1307 populate(*subMenu, m->submenu());
1308 subMenu->setEnabled(m->status().enabled());
1310 // we have a MenuItem::Command
1311 qMenu.addAction(new Action(view, QIcon(), label(*m),
1312 m->func(), QString(), &qMenu));
1317 /////////////////////////////////////////////////////////////////////
1318 // Menu implementation
1319 /////////////////////////////////////////////////////////////////////
1321 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1322 : QMenu(gv), d(new Menu::Impl)
1324 d->top_level_menu = top_level? new MenuDefinition : 0;
1328 if (d->top_level_menu)
1329 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1335 delete d->top_level_menu;
1340 void Menu::updateView()
1342 guiApp->menus().updateMenu(this);
1346 /////////////////////////////////////////////////////////////////////
1347 // Menus::Impl definition and implementation
1348 /////////////////////////////////////////////////////////////////////
1350 struct Menus::Impl {
1352 bool hasMenu(QString const &) const;
1354 MenuDefinition & getMenu(QString const &);
1356 MenuDefinition const & getMenu(QString const &) const;
1358 /// Expands some special entries of the menu
1359 /** The entries with the following kind are expanded to a
1360 sequence of Command MenuItems: Lastfiles, Documents,
1361 ViewFormats, ExportFormats, UpdateFormats, Branches, Indices
1363 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1364 BufferView const *) const;
1366 /// Initialize specific MACOS X menubar
1367 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1369 /// Mac special menu.
1370 /** This defines a menu whose entries list the FuncRequests
1371 that will be removed by expand() in other menus. This is
1372 used by the Qt/Mac code.
1374 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1375 such that the items will keep accessing the FuncRequests in
1376 the MenuDefinition. While Menus::Impl might be recreated,
1377 we keep mac_special_menu_ in memory by making it static.
1379 static MenuDefinition mac_special_menu_;
1384 MenuDefinition menubar_;
1386 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1388 /// name to menu for \c menu() method.
1393 MenuDefinition Menus::Impl::mac_special_menu_;
1397 Here is what the Qt documentation says about how a menubar is chosen:
1399 1) If the window has a QMenuBar then it is used. 2) If the window
1400 is a modal then its menubar is used. If no menubar is specified
1401 then a default menubar is used (as documented below) 3) If the
1402 window has no parent then the default menubar is used (as
1405 The above 3 steps are applied all the way up the parent window
1406 chain until one of the above are satisifed. If all else fails a
1407 default menubar will be created, the default menubar on Qt/Mac is
1408 an empty menubar, however you can create a different default
1409 menubar by creating a parentless QMenuBar, the first one created
1410 will thus be designated the default menubar, and will be used
1411 whenever a default menubar is needed.
1413 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1414 that this menubar will be used also when one of LyX' dialogs has
1417 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1419 /* Since Qt 4.2, the qt/mac menu code has special code for
1420 specifying the role of a menu entry. However, it does not
1421 work very well with our scheme of creating menus on demand,
1422 and therefore we need to put these entries in a special
1423 invisible menu. (JMarc)
1426 /* The entries of our special mac menu. If we add support for
1427 * special entries in Menus, we could imagine something
1429 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1430 * and therefore avoid hardcoding. I am not sure it is worth
1431 * the hassle, though. (JMarc)
1433 struct MacMenuEntry {
1437 QAction::MenuRole role;
1440 MacMenuEntry entries[] = {
1441 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1442 QAction::AboutRole},
1443 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1444 QAction::PreferencesRole},
1445 {LFUN_RECONFIGURE, "", "Reconfigure",
1446 QAction::ApplicationSpecificRole},
1447 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1449 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1451 // the special menu for Menus. Fill it up only once.
1452 if (mac_special_menu_.size() == 0) {
1453 for (size_t i = 0 ; i < num_entries ; ++i) {
1454 FuncRequest const func(entries[i].action,
1455 from_utf8(entries[i].arg));
1456 mac_special_menu_.add(MenuItem(MenuItem::Command,
1457 entries[i].label, func));
1461 // add the entries to a QMenu that will eventually be empty
1462 // and therefore invisible.
1463 QMenu * qMenu = qmb->addMenu("special");
1464 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1465 MenuDefinition::const_iterator end = mac_special_menu_.end();
1466 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1467 Action * action = new Action(view, QIcon(), cit->label(),
1468 cit->func(), QString(), qMenu);
1469 action->setMenuRole(entries[i].role);
1470 qMenu->addAction(action);
1475 void Menus::Impl::expand(MenuDefinition const & frommenu,
1476 MenuDefinition & tomenu, BufferView const * bv) const
1478 if (!tomenu.empty())
1481 for (MenuDefinition::const_iterator cit = frommenu.begin();
1482 cit != frommenu.end() ; ++cit) {
1483 Buffer const * buf = bv ? &bv->buffer() : 0;
1484 switch (cit->kind()) {
1485 case MenuItem::Lastfiles:
1486 tomenu.expandLastfiles();
1489 case MenuItem::Documents:
1490 tomenu.expandDocuments();
1493 case MenuItem::Bookmarks:
1494 tomenu.expandBookmarks();
1497 case MenuItem::ImportFormats:
1498 case MenuItem::ViewFormats:
1499 case MenuItem::UpdateFormats:
1500 case MenuItem::ExportFormats:
1501 tomenu.expandFormats(cit->kind(), buf);
1504 case MenuItem::CharStyles:
1505 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1508 case MenuItem::Custom:
1509 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1512 case MenuItem::Elements:
1513 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1516 case MenuItem::FloatListInsert:
1517 tomenu.expandFloatListInsert(buf);
1520 case MenuItem::FloatInsert:
1521 tomenu.expandFloatInsert(buf);
1524 case MenuItem::PasteRecent:
1525 tomenu.expandPasteRecent(buf);
1528 case MenuItem::Toolbars:
1529 tomenu.expandToolbars();
1532 case MenuItem::Branches:
1533 tomenu.expandBranches(buf);
1536 case MenuItem::Indices:
1537 tomenu.expandIndices(buf);
1540 case MenuItem::IndicesContext:
1541 tomenu.expandIndicesContext(buf);
1544 case MenuItem::IndicesLists:
1545 tomenu.expandIndices(buf, true);
1548 case MenuItem::IndicesListsContext:
1549 tomenu.expandIndicesContext(buf, true);
1552 case MenuItem::CiteStyles:
1553 tomenu.expandCiteStyles(bv);
1557 tomenu.expandToc(buf);
1560 case MenuItem::GraphicsGroups:
1561 tomenu.expandGraphicsGroups(bv);
1564 case MenuItem::Submenu: {
1565 MenuItem item(*cit);
1566 item.setSubmenu(MenuDefinition(cit->submenuname()));
1567 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1568 tomenu.addWithStatusCheck(item);
1572 case MenuItem::Info:
1573 case MenuItem::Help:
1574 case MenuItem::Separator:
1575 tomenu.addWithStatusCheck(*cit);
1578 case MenuItem::Command:
1579 if (!mac_special_menu_.hasFunc(cit->func()))
1580 tomenu.addWithStatusCheck(*cit);
1584 // we do not want the menu to end with a separator
1585 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1586 tomenu.items_.pop_back();
1588 // Check whether the shortcuts are unique
1589 tomenu.checkShortcuts();
1593 bool Menus::Impl::hasMenu(QString const & name) const
1595 return find_if(menulist_.begin(), menulist_.end(),
1596 MenuNamesEqual(name)) != menulist_.end();
1600 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1602 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1603 MenuNamesEqual(name));
1604 if (cit == menulist_.end())
1605 LYXERR0("No submenu named " << name);
1606 LASSERT(cit != menulist_.end(), /**/);
1611 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1613 iterator it = find_if(menulist_.begin(), menulist_.end(),
1614 MenuNamesEqual(name));
1615 if (it == menulist_.end())
1616 LYXERR0("No submenu named " << name);
1617 LASSERT(it != menulist_.end(), /**/);
1622 /////////////////////////////////////////////////////////////////////
1626 /////////////////////////////////////////////////////////////////////
1628 Menus::Menus() : d(new Impl) {}
1644 void Menus::read(Lexer & lex)
1652 LexerKeyword menutags[] = {
1653 { "end", md_endmenuset },
1654 { "menu", md_menu },
1655 { "menubar", md_menubar }
1658 // consistency check
1659 if (compare_ascii_no_case(lex.getString(), "menuset"))
1660 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1662 lex.pushTable(menutags);
1663 lex.setContext("Menus::read");
1667 while (lex.isOK() && !quit) {
1668 switch (lex.lex()) {
1670 d->menubar_.read(lex);
1674 QString const name = toqstr(lex.getDocString());
1675 if (d->hasMenu(name))
1676 d->getMenu(name).read(lex);
1678 MenuDefinition menu(name);
1680 d->menulist_.push_back(menu);
1688 lex.printError("Unknown menu tag");
1696 bool Menus::searchMenu(FuncRequest const & func,
1697 docstring_list & names) const
1699 MenuDefinition menu;
1700 d->expand(d->menubar_, menu, 0);
1701 return menu.searchMenu(func, names);
1705 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1709 // setup special mac specific menu items, but only do this
1710 // the first time a QMenuBar is created. Otherwise Qt will
1711 // create duplicate items in the application menu. It seems
1712 // that Qt does not remove them when the QMenubar is cleared.
1713 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1714 d->macxMenuBarInit(view, qmb);
1717 // Clear all menubar contents before filling it.
1721 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1723 if (d->menubar_.size() == 0) {
1724 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1725 << d->menubar_.name());
1728 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1730 MenuDefinition menu;
1731 BufferView * bv = 0;
1734 d->expand(d->menubar_, menu, bv);
1736 MenuDefinition::const_iterator m = menu.begin();
1737 MenuDefinition::const_iterator end = menu.end();
1739 for (; m != end; ++m) {
1741 if (m->kind() != MenuItem::Submenu) {
1742 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1746 LYXERR(Debug::GUI, "menu bar item " << m->label()
1747 << " is a submenu named " << m->submenuname());
1749 QString name = m->submenuname();
1750 if (!d->hasMenu(name)) {
1751 LYXERR(Debug::GUI, "\tERROR: " << name
1752 << " submenu has no menu!");
1756 Menu * menu = new Menu(view, m->submenuname(), true);
1757 menu->setTitle(label(*m));
1760 d->name_map_[view][name] = menu;
1765 void Menus::updateMenu(Menu * qmenu)
1767 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1770 if (qmenu->d->name.isEmpty())
1773 // Here, We make sure that theLyXFunc points to the correct LyXView.
1774 theLyXFunc().setLyXView(qmenu->d->view);
1776 if (!d->hasMenu(qmenu->d->name)) {
1777 qmenu->addAction(qt_("No action defined!"));
1778 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1783 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1784 BufferView * bv = 0;
1786 bv = qmenu->d->view->view();
1787 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1788 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1792 Menu * Menus::menu(QString const & name, GuiView & view)
1794 LYXERR(Debug::GUI, "Context menu requested: " << name);
1795 Menu * menu = d->name_map_[&view].value(name, 0);
1796 if (!menu && !name.startsWith("context-")) {
1797 LYXERR0("requested context menu not found: " << name);
1801 menu = new Menu(&view, name, true);
1802 d->name_map_[&view][name] = menu;
1806 } // namespace frontend
1809 #include "moc_Menus.cpp"