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 "SpellChecker.h"
49 #include "TextClass.h"
50 #include "TocBackend.h"
53 #include "insets/Inset.h"
54 #include "insets/InsetCitation.h"
55 #include "insets/InsetGraphics.h"
57 #include "support/lassert.h"
58 #include "support/convert.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/filetools.h"
62 #include "support/gettext.h"
63 #include "support/lstrings.h"
71 #include <boost/shared_ptr.hpp>
77 using namespace lyx::support;
85 // MacOSX specific stuff is at the end.
92 /// The type of elements that can be in a menu
100 /** This type of item explains why something is unavailable. If this
101 menuitem is in a submenu, the submenu is enabled to make sure the
102 user sees the information. */
104 /** This type of item merely shows that there might be a list or
105 something alike at this position, but the list is still empty.
106 If this item is in a submenu, the submenu will not always be
109 /** This is the list of last opened file,
110 typically for the File menu. */
112 /** This is the list of opened Documents,
113 typically for the Documents menu. */
115 /** This is the bookmarks */
119 /** This is a list of viewable formats
120 typically for the File->View menu. */
122 /** This is a list of updatable formats
123 typically for the File->Update menu. */
125 /** This is a list of exportable formats
126 typically for the File->Export menu. */
128 /** This is a list of importable formats
129 typically for the File->Export menu. */
131 /** This is the list of elements available
132 * for insertion into document. */
134 /** This is the list of user-configurable
135 insets to insert into document */
137 /** This is the list of XML elements to
138 insert into the document */
140 /** This is the list of floats that we can
141 insert a list for. */
143 /** This is the list of floats that we can
146 /** This is the list of selections that can
151 /** Available branches in document */
153 /** Available indices in document */
155 /** Context menu for indices in document */
157 /** Available index lists in document */
159 /** Context menu for available indices lists in document */
161 /** Available citation styles for a given citation */
163 /** Available graphics groups */
165 /// Words suggested by the spellchecker.
169 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
172 QString const & label,
173 QString const & submenu = QString(),
174 bool optional = false)
175 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
177 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
181 QString const & label,
182 FuncRequest const & func,
183 bool optional = false,
184 FuncRequest::Origin origin = FuncRequest::MENU)
185 : kind_(kind), label_(label), func_(func), optional_(optional)
187 func_.origin = origin;
190 // boost::shared_ptr<MenuDefinition> needs this apprently...
193 /// The label of a given menuitem
194 QString label() const { return label_.split('|')[0]; }
196 /// The keyboard shortcut (usually underlined in the entry)
197 QString shortcut() const
199 return label_.contains('|') ? label_.split('|')[1] : QString();
201 /// The complete label, with label and shortcut separated by a '|'
202 QString fulllabel() const { return label_;}
203 /// The kind of entry
204 Kind kind() const { return kind_; }
205 /// the action (if relevant)
206 FuncRequest const & func() const { return func_; }
207 /// returns true if the entry should be ommited when disabled
208 bool optional() const { return optional_; }
209 /// returns the status of the lfun associated with this entry
210 FuncStatus const & status() const { return status_; }
211 /// returns the status of the lfun associated with this entry
212 FuncStatus & status() { return status_; }
213 /// returns the status of the lfun associated with this entry
214 void status(FuncStatus const & status) { status_ = status; }
216 ///returns the binding associated to this action.
217 QString binding() const
219 if (kind_ != Command)
221 // Get the keys bound to this action, but keep only the
223 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
225 return toqstr(bindings.begin()->print(KeySequence::ForGui));
227 LYXERR(Debug::KBMAP, "No binding for "
228 << lyxaction.getActionName(func_.action)
229 << '(' << func_.argument() << ')');
233 /// the description of the submenu (if relevant)
234 QString const & submenuname() const { return submenuname_; }
235 /// set the description of the submenu
236 void submenuname(QString const & name) { submenuname_ = name; }
238 bool hasSubmenu() const { return !submenu_.isEmpty(); }
240 MenuDefinition const & submenu() const { return submenu_.at(0); }
241 MenuDefinition & submenu() { return submenu_[0]; }
243 void setSubmenu(MenuDefinition const & menu)
246 submenu_.append(menu);
257 QString submenuname_;
262 /// contains 0 or 1 item.
263 QList<MenuDefinition> submenu_;
267 class MenuDefinition {
270 typedef std::vector<MenuItem> ItemList;
272 typedef ItemList::const_iterator const_iterator;
274 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
279 QString const & name() const { return name_; }
281 bool empty() const { return items_.empty(); }
282 /// Clear the menu content.
283 void clear() { items_.clear(); }
285 size_t size() const { return items_.size(); }
287 MenuItem const & operator[](size_t) const;
289 const_iterator begin() const { return items_.begin(); }
291 const_iterator end() const { return items_.end(); }
293 // search for func in this menu iteratively, and put menu
295 bool searchMenu(FuncRequest const & func, docstring_list & names)
298 bool hasFunc(FuncRequest const &) const;
299 /// Add the menu item unconditionally
300 void add(MenuItem const & item) { items_.push_back(item); }
301 /// Checks the associated FuncRequest status before adding the
303 void addWithStatusCheck(MenuItem const &);
304 // Check whether the menu shortcuts are unique
305 void checkShortcuts() const;
307 void expandLastfiles();
308 void expandDocuments();
309 void expandBookmarks();
310 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
311 void expandFloatListInsert(Buffer const * buf);
312 void expandFloatInsert(Buffer const * buf);
313 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
314 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
315 void expandToc(Buffer const * buf);
316 void expandPasteRecent(Buffer const * buf);
317 void expandToolbars();
318 void expandBranches(Buffer const * buf);
319 void expandIndices(Buffer const * buf, bool listof = false);
320 void expandIndicesContext(Buffer const * buf, bool listof = false);
321 void expandCiteStyles(BufferView const *);
322 void expandGraphicsGroups(BufferView const *);
323 void expandSpellingSuggestions(BufferView const *);
331 /// Helper for std::find_if
335 MenuNamesEqual(QString const & name) : name_(name) {}
336 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
343 typedef std::vector<MenuDefinition> MenuList;
345 typedef MenuList::const_iterator const_iterator;
347 typedef MenuList::iterator iterator;
349 /////////////////////////////////////////////////////////////////////
350 // MenuDefinition implementation
351 /////////////////////////////////////////////////////////////////////
353 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
357 case MenuItem::Command: {
358 FuncStatus status = lyx::getStatus(i.func());
359 if (status.unknown() || (!status.enabled() && i.optional()))
362 items_.back().status(status);
366 case MenuItem::Submenu: {
367 bool enabled = false;
368 if (i.hasSubmenu()) {
369 for (const_iterator cit = i.submenu().begin();
370 cit != i.submenu().end(); ++cit) {
371 // Only these kind of items affect the status of the submenu
372 if ((cit->kind() == MenuItem::Command
373 || cit->kind() == MenuItem::Submenu
374 || cit->kind() == MenuItem::Help)
375 && cit->status().enabled()) {
381 if (enabled || !i.optional()) {
383 items_.back().status().setEnabled(enabled);
388 case MenuItem::Separator:
389 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
399 void MenuDefinition::read(Lexer & lex)
416 md_indiceslistscontext,
430 md_spellingsuggestions
433 LexerKeyword menutags[] = {
434 { "bookmarks", md_bookmarks },
435 { "branches", md_branches },
436 { "charstyles", md_charstyles },
437 { "citestyles", md_citestyles },
438 { "custom", md_custom },
439 { "documents", md_documents },
440 { "elements", md_elements },
441 { "end", md_endmenu },
442 { "exportformats", md_exportformats },
443 { "floatinsert", md_floatinsert },
444 { "floatlistinsert", md_floatlistinsert },
445 { "graphicsgroups", md_graphicsgroups },
446 { "importformats", md_importformats },
447 { "indices", md_indices },
448 { "indicescontext", md_indicescontext },
449 { "indiceslists", md_indiceslists },
450 { "indiceslistscontext", md_indiceslistscontext },
452 { "lastfiles", md_lastfiles },
453 { "optitem", md_optitem },
454 { "optsubmenu", md_optsubmenu },
455 { "pasterecent", md_pasterecent },
456 { "separator", md_separator },
457 { "spellingsuggestions", md_spellingsuggestions },
458 { "submenu", md_submenu },
460 { "toolbars", md_toolbars },
461 { "updateformats", md_updateformats },
462 { "viewformats", md_viewformats }
465 lex.pushTable(menutags);
466 lex.setContext("MenuDefinition::read: ");
469 bool optional = false;
471 while (lex.isOK() && !quit) {
475 // fallback to md_item
478 docstring const name = translateIfPossible(lex.getDocString());
480 string const command = lex.getString();
481 FuncRequest func = lyxaction.lookupFunc(command);
482 FuncRequest::Origin origin = FuncRequest::MENU;
483 if (name_.startsWith("context-toc-"))
484 origin = FuncRequest::TOC;
485 add(MenuItem(MenuItem::Command, toqstr(name), func, optional, origin));
491 add(MenuItem(MenuItem::Separator));
495 add(MenuItem(MenuItem::Lastfiles));
499 add(MenuItem(MenuItem::CharStyles));
503 add(MenuItem(MenuItem::Custom));
507 add(MenuItem(MenuItem::Elements));
511 add(MenuItem(MenuItem::Documents));
515 add(MenuItem(MenuItem::Bookmarks));
519 add(MenuItem(MenuItem::Toc));
523 add(MenuItem(MenuItem::ViewFormats));
526 case md_updateformats:
527 add(MenuItem(MenuItem::UpdateFormats));
530 case md_exportformats:
531 add(MenuItem(MenuItem::ExportFormats));
534 case md_importformats:
535 add(MenuItem(MenuItem::ImportFormats));
538 case md_floatlistinsert:
539 add(MenuItem(MenuItem::FloatListInsert));
543 add(MenuItem(MenuItem::FloatInsert));
547 add(MenuItem(MenuItem::PasteRecent));
551 add(MenuItem(MenuItem::Toolbars));
555 add(MenuItem(MenuItem::Branches));
559 add(MenuItem(MenuItem::CiteStyles));
562 case md_graphicsgroups:
563 add(MenuItem(MenuItem::GraphicsGroups));
566 case md_spellingsuggestions:
567 add(MenuItem(MenuItem::SpellingSuggestions));
571 add(MenuItem(MenuItem::Indices));
574 case md_indicescontext:
575 add(MenuItem(MenuItem::IndicesContext));
578 case md_indiceslists:
579 add(MenuItem(MenuItem::IndicesLists));
582 case md_indiceslistscontext:
583 add(MenuItem(MenuItem::IndicesListsContext));
588 // fallback to md_submenu
591 docstring const mlabel = translateIfPossible(lex.getDocString());
593 docstring const mname = lex.getDocString();
594 add(MenuItem(MenuItem::Submenu,
595 toqstr(mlabel), toqstr(mname), optional));
605 lex.printError("Unknown menu tag");
613 MenuItem const & MenuDefinition::operator[](size_type i) const
619 bool MenuDefinition::hasFunc(FuncRequest const & func) const
621 for (const_iterator it = begin(), et = end(); it != et; ++it)
622 if (it->func() == func)
628 void MenuDefinition::checkShortcuts() const
630 // This is a quadratic algorithm, but we do not care because
631 // menus are short enough
632 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
633 QString shortcut = it1->shortcut();
634 if (shortcut.isEmpty())
636 if (!it1->label().contains(shortcut))
637 LYXERR0("Menu warning: menu entry \""
639 << "\" does not contain shortcut `"
640 << shortcut << "'.");
641 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
642 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
643 LYXERR0("Menu warning: menu entries "
644 << '"' << it1->fulllabel()
645 << "\" and \"" << it2->fulllabel()
646 << "\" share the same shortcut.");
653 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
655 const_iterator m = begin();
656 const_iterator m_end = end();
657 for (; m != m_end; ++m) {
658 if (m->kind() == MenuItem::Command && m->func() == func) {
659 names.push_back(qstring_to_ucs4(m->label()));
662 if (m->kind() == MenuItem::Submenu) {
663 names.push_back(qstring_to_ucs4(m->label()));
664 if (!m->hasSubmenu()) {
665 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
666 << m->label() << " name=" << m->submenuname());
670 if (m->submenu().searchMenu(func, names))
679 bool compareFormat(Format const * p1, Format const * p2)
685 QString limitStringLength(docstring const & str)
687 size_t const max_item_length = 45;
689 if (str.size() > max_item_length)
690 return toqstr(str.substr(0, max_item_length - 3) + "...");
696 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
701 graphics::getGraphicsGroups(bv->buffer(), grp);
705 set<string>::const_iterator it = grp.begin();
706 set<string>::const_iterator end = grp.end();
707 add(MenuItem(MenuItem::Command, qt_("No Group"),
708 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
709 for (; it != end; it++) {
710 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
711 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
716 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
720 Paragraph const & par = bv->cursor().paragraph();
721 if (!par.isMisspelled(bv->cursor().pos()))
723 LYXERR0("Misspelled Word!");
725 SpellChecker * speller = theSpellChecker();
728 MenuItem item(MenuItem::Submenu, qt_("more spelling suggestions"));
729 item.setSubmenu(MenuDefinition(qt_("more spelling suggestions")));
730 while (!(word = speller->nextMiss()).empty()) {
731 LYXERR0("Misspelled Word = " << word);
732 MenuItem w(MenuItem::Command, toqstr(word),
733 FuncRequest(LFUN_WORD_REPLACE, word));
737 item.submenu().add(w);
746 void MenuDefinition::expandLastfiles()
748 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
749 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
753 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
754 string const file = lfit->absFilename();
755 QString const label = QString("%1. %2|%3").arg(ii)
756 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
757 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
762 void MenuDefinition::expandDocuments()
764 MenuItem item(MenuItem::Submenu, qt_("Invisible"));
765 item.setSubmenu(MenuDefinition(qt_("Invisible")));
767 Buffer * first = theBufferList().first();
773 // We cannot use a for loop as the buffer list cycles.
775 QString label = toqstr(b->fileName().displayName(20));
778 bool const shown = guiApp->currentView()->workArea(*b);
779 int ii = shown ? vis : invis;
781 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
783 add(MenuItem(MenuItem::Command, label,
784 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
787 item.submenu().add(MenuItem(MenuItem::Command, label,
788 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
791 b = theBufferList().next(b);
792 } while (b != first);
793 if (!item.submenu().empty())
796 add(MenuItem(MenuItem::Info, qt_("<No documents open>")));
800 void MenuDefinition::expandBookmarks()
802 lyx::BookmarksSection const & bm = theSession().bookmarks();
805 for (size_t i = 1; i <= bm.size(); ++i) {
807 string const file = bm.bookmark(i).filename.absFilename();
808 QString const label = QString("%1. %2|%3").arg(i)
809 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
810 add(MenuItem(MenuItem::Command, label,
811 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
816 add(MenuItem(MenuItem::Info, qt_("<No bookmarks saved yet>")));
820 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
822 if (!buf && kind != MenuItem::ImportFormats)
825 typedef vector<Format const *> Formats;
830 case MenuItem::ImportFormats:
831 formats = theConverters().importableFormats();
832 action = LFUN_BUFFER_IMPORT;
834 case MenuItem::ViewFormats:
835 formats = buf->exportableFormats(true);
836 action = LFUN_BUFFER_VIEW;
838 case MenuItem::UpdateFormats:
839 formats = buf->exportableFormats(true);
840 action = LFUN_BUFFER_UPDATE;
843 formats = buf->exportableFormats(false);
844 action = LFUN_BUFFER_EXPORT;
846 sort(formats.begin(), formats.end(), &compareFormat);
848 Formats::const_iterator fit = formats.begin();
849 Formats::const_iterator end = formats.end();
850 for (; fit != end ; ++fit) {
854 docstring lab = from_utf8((*fit)->prettyname());
855 docstring scut = from_utf8((*fit)->shortcut());
856 docstring const tmplab = lab;
859 lab += char_type('|') + scut;
860 docstring lab_i18n = translateIfPossible(lab);
861 bool const untranslated = (lab == lab_i18n);
862 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
863 QString label = toqstr(lab);
865 // this might happen if the shortcut
866 // has been redefined
867 label = toqstr(translateIfPossible(tmplab));
870 case MenuItem::ImportFormats:
873 case MenuItem::ViewFormats:
874 case MenuItem::UpdateFormats:
875 if ((*fit)->name() == buf->getDefaultOutputFormat())
877 case MenuItem::ExportFormats:
878 if (!(*fit)->documentFormat())
882 LASSERT(false, /**/);
885 if (!shortcut.isEmpty())
886 label += '|' + shortcut;
889 addWithStatusCheck(MenuItem(MenuItem::Command, label,
890 FuncRequest(action, (*fit)->name())));
892 add(MenuItem(MenuItem::Command, label,
893 FuncRequest(action, (*fit)->name())));
898 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
903 FloatList const & floats = buf->params().documentClass().floats();
904 FloatList::const_iterator cit = floats.begin();
905 FloatList::const_iterator end = floats.end();
906 for (; cit != end; ++cit) {
907 addWithStatusCheck(MenuItem(MenuItem::Command,
908 qt_(cit->second.listName()),
909 FuncRequest(LFUN_FLOAT_LIST_INSERT,
910 cit->second.type())));
915 void MenuDefinition::expandFloatInsert(Buffer const * buf)
920 FloatList const & floats = buf->params().documentClass().floats();
921 FloatList::const_iterator cit = floats.begin();
922 FloatList::const_iterator end = floats.end();
923 for (; cit != end; ++cit) {
925 QString const label = qt_(cit->second.name());
926 addWithStatusCheck(MenuItem(MenuItem::Command, label,
927 FuncRequest(LFUN_FLOAT_INSERT,
928 cit->second.type())));
933 void MenuDefinition::expandFlexInsert(
934 Buffer const * buf, InsetLayout::InsetLyXType type)
939 TextClass::InsetLayouts const & insetLayouts =
940 buf->params().documentClass().insetLayouts();
941 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
942 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
943 for (; cit != end; ++cit) {
944 if (cit->second.lyxtype() == type) {
945 docstring const label = cit->first;
946 addWithStatusCheck(MenuItem(MenuItem::Command,
947 toqstr(translateIfPossible(label)),
948 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
951 // FIXME This is a little clunky.
952 if (items_.empty() && type == InsetLayout::CUSTOM)
953 add(MenuItem(MenuItem::Help, qt_("No custom insets defined!")));
957 size_t const max_number_of_items = 25;
959 void MenuDefinition::expandToc2(Toc const & toc_list,
960 size_t from, size_t to, int depth)
962 int shortcut_count = 0;
964 // check whether depth is smaller than the smallest depth in toc.
965 int min_depth = 1000;
966 for (size_t i = from; i < to; ++i)
967 min_depth = min(min_depth, toc_list[i].depth());
968 if (min_depth > depth)
971 if (to - from <= max_number_of_items) {
972 for (size_t i = from; i < to; ++i) {
973 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
974 label += limitStringLength(toc_list[i].str());
975 if (toc_list[i].depth() == depth
976 && shortcut_count < 9) {
977 if (label.contains(QString::number(shortcut_count + 1)))
978 label += '|' + QString::number(++shortcut_count);
980 add(MenuItem(MenuItem::Command, label,
981 FuncRequest(toc_list[i].action())));
986 size_t new_pos = pos + 1;
987 while (new_pos < to && toc_list[new_pos].depth() > depth)
990 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
991 label += limitStringLength(toc_list[pos].str());
992 if (toc_list[pos].depth() == depth &&
993 shortcut_count < 9) {
994 if (label.contains(QString::number(shortcut_count + 1)))
995 label += '|' + QString::number(++shortcut_count);
997 if (new_pos == pos + 1) {
998 add(MenuItem(MenuItem::Command,
999 label, FuncRequest(toc_list[pos].action())));
1002 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
1003 MenuItem item(MenuItem::Submenu, label);
1004 item.setSubmenu(sub);
1013 void MenuDefinition::expandToc(Buffer const * buf)
1015 // To make things very cleanly, we would have to pass buf to
1016 // all MenuItem constructors and to expandToc2. However, we
1017 // know that all the entries in a TOC will be have status_ ==
1018 // OK, so we avoid this unnecessary overhead (JMarc)
1021 add(MenuItem(MenuItem::Info, qt_("<No document open>")));
1025 // Add an entry for the master doc if this is a child doc
1026 Buffer const * const master = buf->masterBuffer();
1027 if (buf != master) {
1028 ParIterator const pit = par_iterator_begin(master->inset());
1029 string const arg = convert<string>(pit->id());
1030 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1031 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1034 MenuDefinition other_lists;
1036 FloatList const & floatlist = buf->params().documentClass().floats();
1037 TocList const & toc_list = buf->tocBackend().tocs();
1038 TocList::const_iterator cit = toc_list.begin();
1039 TocList::const_iterator end = toc_list.end();
1040 for (; cit != end; ++cit) {
1041 // Handle this later
1042 if (cit->first == "tableofcontents")
1045 MenuDefinition submenu;
1046 if (cit->second.size() >= 30) {
1047 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1048 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1050 TocIterator ccit = cit->second.begin();
1051 TocIterator eend = cit->second.end();
1052 for (; ccit != eend; ++ccit) {
1053 submenu.add(MenuItem(MenuItem::Command,
1054 limitStringLength(ccit->str()),
1055 FuncRequest(ccit->action())));
1059 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1060 item.setSubmenu(submenu);
1061 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1062 // Those two types deserve to be in the main menu.
1063 item.setSubmenu(submenu);
1066 other_lists.add(item);
1068 if (!other_lists.empty()) {
1069 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1070 item.setSubmenu(other_lists);
1074 // Handle normal TOC
1075 cit = toc_list.find("tableofcontents");
1077 LYXERR(Debug::GUI, "No table of contents.");
1079 if (cit->second.size() > 0 )
1080 expandToc2(cit->second, 0, cit->second.size(), 0);
1082 add(MenuItem(MenuItem::Info, qt_("<Empty table of contents>")));
1087 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1089 docstring_list const sel = cap::availableSelections(buf);
1091 docstring_list::const_iterator cit = sel.begin();
1092 docstring_list::const_iterator end = sel.end();
1094 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1095 add(MenuItem(MenuItem::Command, toqstr(*cit),
1096 FuncRequest(LFUN_PASTE, convert<string>(index))));
1101 void MenuDefinition::expandToolbars()
1103 MenuDefinition other_lists;
1104 // extracts the toolbars from the backend
1105 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1106 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1107 for (; cit != end; ++cit) {
1108 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1109 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1110 if (guiApp->toolbars().isMainToolbar(cit->name))
1113 other_lists.add(item);
1116 if (!other_lists.empty()) {
1117 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1118 item.setSubmenu(other_lists);
1124 void MenuDefinition::expandBranches(Buffer const * buf)
1129 BufferParams const & master_params = buf->masterBuffer()->params();
1130 BufferParams const & params = buf->params();
1131 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1132 add(MenuItem(MenuItem::Help, qt_("No branches set for document!")));
1136 BranchList::const_iterator cit = master_params.branchlist().begin();
1137 BranchList::const_iterator end = master_params.branchlist().end();
1139 for (int ii = 1; cit != end; ++cit, ++ii) {
1140 docstring label = cit->branch();
1142 label = convert<docstring>(ii) + ". " + label
1143 + char_type('|') + convert<docstring>(ii);
1145 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1146 FuncRequest(LFUN_BRANCH_INSERT,
1150 if (buf == buf->masterBuffer())
1153 MenuDefinition child_branches;
1155 BranchList::const_iterator ccit = params.branchlist().begin();
1156 BranchList::const_iterator cend = params.branchlist().end();
1158 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1159 docstring label = ccit->branch();
1161 label = convert<docstring>(ii) + ". " + label
1162 + char_type('|') + convert<docstring>(ii);
1164 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1166 FuncRequest(LFUN_BRANCH_INSERT,
1170 if (!child_branches.empty()) {
1171 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1172 item.setSubmenu(child_branches);
1178 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1183 BufferParams const & params = buf->masterBuffer()->params();
1184 if (!params.use_indices) {
1186 addWithStatusCheck(MenuItem(MenuItem::Command,
1187 qt_("Index List|I"),
1188 FuncRequest(LFUN_INDEX_PRINT,
1189 from_ascii("idx"))));
1191 addWithStatusCheck(MenuItem(MenuItem::Command,
1192 qt_("Index Entry|d"),
1193 FuncRequest(LFUN_INDEX_INSERT,
1194 from_ascii("idx"))));
1198 if (params.indiceslist().empty())
1201 IndicesList::const_iterator cit = params.indiceslist().begin();
1202 IndicesList::const_iterator end = params.indiceslist().end();
1204 for (int ii = 1; cit != end; ++cit, ++ii) {
1206 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1207 FuncRequest(LFUN_INDEX_PRINT,
1210 docstring label = _("Index Entry");
1211 label += " (" + cit->index() + ")";
1212 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1213 FuncRequest(LFUN_INDEX_INSERT,
1220 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1225 BufferParams const & params = buf->masterBuffer()->params();
1226 if (!params.use_indices || params.indiceslist().empty())
1229 IndicesList::const_iterator cit = params.indiceslist().begin();
1230 IndicesList::const_iterator end = params.indiceslist().end();
1232 for (int ii = 1; cit != end; ++cit, ++ii) {
1234 InsetCommandParams p(INDEX_PRINT_CODE);
1235 p["type"] = cit->shortcut();
1236 string const data = InsetCommand::params2string("index_print", p);
1237 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1238 FuncRequest(LFUN_NEXT_INSET_MODIFY, data)));
1240 docstring label = _("Index Entry");
1241 label += " (" + cit->index() + ")";
1242 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1243 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1244 from_ascii("changetype ") + cit->shortcut())));
1250 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1255 Inset const * inset = bv->cursor().nextInset();
1256 if (!inset || inset->lyxCode() != CITE_CODE) {
1257 add(MenuItem(MenuItem::Command,
1258 qt_("No Citation in Scope!"),
1259 FuncRequest(LFUN_NOACTION)));
1262 InsetCommand const * citinset =
1263 static_cast<InsetCommand const *>(inset);
1265 Buffer const * buf = &bv->buffer();
1266 docstring key = citinset->getParam("key");
1267 // we can only handle one key currently
1268 if (contains(key, ','))
1269 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1271 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1272 docstring_list citeStrings =
1273 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1275 docstring_list::const_iterator cit = citeStrings.begin();
1276 docstring_list::const_iterator end = citeStrings.end();
1278 for (int ii = 1; cit != end; ++cit, ++ii) {
1279 docstring label = *cit;
1281 CiteStyle cst = citeStyleList[ii - 1];
1283 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1284 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1285 "changetype " + from_utf8(citationStyleToString(cs)))));
1292 /////////////////////////////////////////////////////////////////////
1293 // Menu::Impl definition and implementation
1294 /////////////////////////////////////////////////////////////////////
1298 /// populates the menu or one of its submenu
1299 /// This is used as a recursive function
1300 void populate(QMenu & qMenu, MenuDefinition const & menu);
1302 /// Only needed for top level menus.
1303 MenuDefinition * top_level_menu;
1306 /// the name of this menu
1312 /// Get a MenuDefinition item label from the menu backend
1313 static QString label(MenuItem const & mi)
1315 QString label = mi.label();
1316 label.replace("&", "&&");
1318 QString shortcut = mi.shortcut();
1319 if (!shortcut.isEmpty()) {
1320 int pos = label.indexOf(shortcut);
1322 //label.insert(pos, 1, char_type('&'));
1323 label.replace(pos, 0, "&");
1326 QString const binding = mi.binding();
1327 if (!binding.isEmpty())
1328 label += '\t' + binding;
1333 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1335 LYXERR(Debug::GUI, "populating menu " << menu.name());
1336 if (menu.size() == 0) {
1337 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1340 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1341 MenuDefinition::const_iterator m = menu.begin();
1342 MenuDefinition::const_iterator end = menu.end();
1343 for (; m != end; ++m) {
1344 if (m->kind() == MenuItem::Separator)
1345 qMenu.addSeparator();
1346 else if (m->kind() == MenuItem::Submenu) {
1347 QMenu * subMenu = qMenu.addMenu(label(*m));
1348 populate(*subMenu, m->submenu());
1349 subMenu->setEnabled(m->status().enabled());
1351 // we have a MenuItem::Command
1352 qMenu.addAction(new Action(view, QIcon(), label(*m),
1353 m->func(), QString(), &qMenu));
1358 /////////////////////////////////////////////////////////////////////
1359 // Menu implementation
1360 /////////////////////////////////////////////////////////////////////
1362 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1363 : QMenu(gv), d(new Menu::Impl)
1365 d->top_level_menu = top_level? new MenuDefinition : 0;
1369 if (d->top_level_menu)
1370 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1376 delete d->top_level_menu;
1381 void Menu::updateView()
1383 guiApp->menus().updateMenu(this);
1387 /////////////////////////////////////////////////////////////////////
1388 // Menus::Impl definition and implementation
1389 /////////////////////////////////////////////////////////////////////
1391 struct Menus::Impl {
1393 bool hasMenu(QString const &) const;
1395 MenuDefinition & getMenu(QString const &);
1397 MenuDefinition const & getMenu(QString const &) const;
1399 /// Expands some special entries of the menu
1400 /** The entries with the following kind are expanded to a
1401 sequence of Command MenuItems: Lastfiles, Documents,
1402 ViewFormats, ExportFormats, UpdateFormats, Branches, Indices
1404 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1405 BufferView const *) const;
1407 /// Initialize specific MACOS X menubar
1408 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1410 /// Mac special menu.
1411 /** This defines a menu whose entries list the FuncRequests
1412 that will be removed by expand() in other menus. This is
1413 used by the Qt/Mac code.
1415 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1416 such that the items will keep accessing the FuncRequests in
1417 the MenuDefinition. While Menus::Impl might be recreated,
1418 we keep mac_special_menu_ in memory by making it static.
1420 static MenuDefinition mac_special_menu_;
1425 MenuDefinition menubar_;
1427 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1429 /// name to menu for \c menu() method.
1434 MenuDefinition Menus::Impl::mac_special_menu_;
1438 Here is what the Qt documentation says about how a menubar is chosen:
1440 1) If the window has a QMenuBar then it is used. 2) If the window
1441 is a modal then its menubar is used. If no menubar is specified
1442 then a default menubar is used (as documented below) 3) If the
1443 window has no parent then the default menubar is used (as
1446 The above 3 steps are applied all the way up the parent window
1447 chain until one of the above are satisifed. If all else fails a
1448 default menubar will be created, the default menubar on Qt/Mac is
1449 an empty menubar, however you can create a different default
1450 menubar by creating a parentless QMenuBar, the first one created
1451 will thus be designated the default menubar, and will be used
1452 whenever a default menubar is needed.
1454 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1455 that this menubar will be used also when one of LyX' dialogs has
1458 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1460 /* Since Qt 4.2, the qt/mac menu code has special code for
1461 specifying the role of a menu entry. However, it does not
1462 work very well with our scheme of creating menus on demand,
1463 and therefore we need to put these entries in a special
1464 invisible menu. (JMarc)
1467 /* The entries of our special mac menu. If we add support for
1468 * special entries in Menus, we could imagine something
1470 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1471 * and therefore avoid hardcoding. I am not sure it is worth
1472 * the hassle, though. (JMarc)
1474 struct MacMenuEntry {
1478 QAction::MenuRole role;
1481 MacMenuEntry entries[] = {
1482 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1483 QAction::AboutRole},
1484 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1485 QAction::PreferencesRole},
1486 {LFUN_RECONFIGURE, "", "Reconfigure",
1487 QAction::ApplicationSpecificRole},
1488 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1490 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1492 // the special menu for Menus. Fill it up only once.
1493 if (mac_special_menu_.size() == 0) {
1494 for (size_t i = 0 ; i < num_entries ; ++i) {
1495 FuncRequest const func(entries[i].action,
1496 from_utf8(entries[i].arg));
1497 mac_special_menu_.add(MenuItem(MenuItem::Command,
1498 entries[i].label, func));
1502 // add the entries to a QMenu that will eventually be empty
1503 // and therefore invisible.
1504 QMenu * qMenu = qmb->addMenu("special");
1505 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1506 MenuDefinition::const_iterator end = mac_special_menu_.end();
1507 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1508 Action * action = new Action(view, QIcon(), cit->label(),
1509 cit->func(), QString(), qMenu);
1510 action->setMenuRole(entries[i].role);
1511 qMenu->addAction(action);
1516 void Menus::Impl::expand(MenuDefinition const & frommenu,
1517 MenuDefinition & tomenu, BufferView const * bv) const
1519 if (!tomenu.empty())
1522 for (MenuDefinition::const_iterator cit = frommenu.begin();
1523 cit != frommenu.end() ; ++cit) {
1524 Buffer const * buf = bv ? &bv->buffer() : 0;
1525 switch (cit->kind()) {
1526 case MenuItem::Lastfiles:
1527 tomenu.expandLastfiles();
1530 case MenuItem::Documents:
1531 tomenu.expandDocuments();
1534 case MenuItem::Bookmarks:
1535 tomenu.expandBookmarks();
1538 case MenuItem::ImportFormats:
1539 case MenuItem::ViewFormats:
1540 case MenuItem::UpdateFormats:
1541 case MenuItem::ExportFormats:
1542 tomenu.expandFormats(cit->kind(), buf);
1545 case MenuItem::CharStyles:
1546 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1549 case MenuItem::Custom:
1550 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1553 case MenuItem::Elements:
1554 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1557 case MenuItem::FloatListInsert:
1558 tomenu.expandFloatListInsert(buf);
1561 case MenuItem::FloatInsert:
1562 tomenu.expandFloatInsert(buf);
1565 case MenuItem::PasteRecent:
1566 tomenu.expandPasteRecent(buf);
1569 case MenuItem::Toolbars:
1570 tomenu.expandToolbars();
1573 case MenuItem::Branches:
1574 tomenu.expandBranches(buf);
1577 case MenuItem::Indices:
1578 tomenu.expandIndices(buf);
1581 case MenuItem::IndicesContext:
1582 tomenu.expandIndicesContext(buf);
1585 case MenuItem::IndicesLists:
1586 tomenu.expandIndices(buf, true);
1589 case MenuItem::IndicesListsContext:
1590 tomenu.expandIndicesContext(buf, true);
1593 case MenuItem::CiteStyles:
1594 tomenu.expandCiteStyles(bv);
1598 tomenu.expandToc(buf);
1601 case MenuItem::GraphicsGroups:
1602 tomenu.expandGraphicsGroups(bv);
1605 case MenuItem::SpellingSuggestions:
1606 tomenu.expandSpellingSuggestions(bv);
1609 case MenuItem::Submenu: {
1610 MenuItem item(*cit);
1611 item.setSubmenu(MenuDefinition(cit->submenuname()));
1612 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1613 tomenu.addWithStatusCheck(item);
1617 case MenuItem::Info:
1618 case MenuItem::Help:
1619 case MenuItem::Separator:
1620 tomenu.addWithStatusCheck(*cit);
1623 case MenuItem::Command:
1624 if (!mac_special_menu_.hasFunc(cit->func()))
1625 tomenu.addWithStatusCheck(*cit);
1629 // we do not want the menu to end with a separator
1630 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1631 tomenu.items_.pop_back();
1633 // Check whether the shortcuts are unique
1634 tomenu.checkShortcuts();
1638 bool Menus::Impl::hasMenu(QString const & name) const
1640 return find_if(menulist_.begin(), menulist_.end(),
1641 MenuNamesEqual(name)) != menulist_.end();
1645 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1647 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1648 MenuNamesEqual(name));
1649 if (cit == menulist_.end())
1650 LYXERR0("No submenu named " << name);
1651 LASSERT(cit != menulist_.end(), /**/);
1656 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1658 iterator it = find_if(menulist_.begin(), menulist_.end(),
1659 MenuNamesEqual(name));
1660 if (it == menulist_.end())
1661 LYXERR0("No submenu named " << name);
1662 LASSERT(it != menulist_.end(), /**/);
1667 /////////////////////////////////////////////////////////////////////
1671 /////////////////////////////////////////////////////////////////////
1673 Menus::Menus() : d(new Impl) {}
1689 void Menus::read(Lexer & lex)
1697 LexerKeyword menutags[] = {
1698 { "end", md_endmenuset },
1699 { "menu", md_menu },
1700 { "menubar", md_menubar }
1703 // consistency check
1704 if (compare_ascii_no_case(lex.getString(), "menuset"))
1705 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1707 lex.pushTable(menutags);
1708 lex.setContext("Menus::read");
1712 while (lex.isOK() && !quit) {
1713 switch (lex.lex()) {
1715 d->menubar_.read(lex);
1719 QString const name = toqstr(lex.getDocString());
1720 if (d->hasMenu(name))
1721 d->getMenu(name).read(lex);
1723 MenuDefinition menu(name);
1725 d->menulist_.push_back(menu);
1733 lex.printError("Unknown menu tag");
1741 bool Menus::searchMenu(FuncRequest const & func,
1742 docstring_list & names) const
1744 MenuDefinition menu;
1745 d->expand(d->menubar_, menu, 0);
1746 return menu.searchMenu(func, names);
1750 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1754 // setup special mac specific menu items, but only do this
1755 // the first time a QMenuBar is created. Otherwise Qt will
1756 // create duplicate items in the application menu. It seems
1757 // that Qt does not remove them when the QMenubar is cleared.
1758 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1759 d->macxMenuBarInit(view, qmb);
1762 // Clear all menubar contents before filling it.
1766 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1768 if (d->menubar_.size() == 0) {
1769 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1770 << d->menubar_.name());
1773 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1775 MenuDefinition menu;
1776 BufferView * bv = 0;
1779 d->expand(d->menubar_, menu, bv);
1781 MenuDefinition::const_iterator m = menu.begin();
1782 MenuDefinition::const_iterator end = menu.end();
1784 for (; m != end; ++m) {
1786 if (m->kind() != MenuItem::Submenu) {
1787 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1791 LYXERR(Debug::GUI, "menu bar item " << m->label()
1792 << " is a submenu named " << m->submenuname());
1794 QString name = m->submenuname();
1795 if (!d->hasMenu(name)) {
1796 LYXERR(Debug::GUI, "\tERROR: " << name
1797 << " submenu has no menu!");
1801 Menu * menu = new Menu(view, m->submenuname(), true);
1802 menu->setTitle(label(*m));
1805 d->name_map_[view][name] = menu;
1810 void Menus::updateMenu(Menu * qmenu)
1812 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1815 if (qmenu->d->name.isEmpty())
1818 // Here, We make sure that theLyXFunc points to the correct LyXView.
1819 theLyXFunc().setLyXView(qmenu->d->view);
1821 if (!d->hasMenu(qmenu->d->name)) {
1822 qmenu->addAction(qt_("No action defined!"));
1823 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1828 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1829 BufferView * bv = 0;
1831 bv = qmenu->d->view->view();
1832 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1833 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1837 Menu * Menus::menu(QString const & name, GuiView & view)
1839 LYXERR(Debug::GUI, "Context menu requested: " << name);
1840 Menu * menu = d->name_map_[&view].value(name, 0);
1841 if (!menu && !name.startsWith("context-")) {
1842 LYXERR0("requested context menu not found: " << name);
1846 menu = new Menu(&view, name, true);
1847 d->name_map_[&view][name] = menu;
1851 } // namespace frontend
1854 #include "moc_Menus.cpp"