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 "GuiWorkArea.h"
25 #include "qt_helpers.h"
27 #include "BiblioInfo.h"
28 #include "BranchList.h"
30 #include "BufferList.h"
31 #include "BufferParams.h"
32 #include "BufferView.h"
33 #include "Converter.h"
34 #include "CutAndPaste.h"
36 #include "FloatList.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "IndicesList.h"
45 #include "LyXAction.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
53 #include "SpellChecker.h"
54 #include "TextClass.h"
56 #include "TocBackend.h"
58 #include "WordLangTuple.h"
60 #include "insets/Inset.h"
61 #include "insets/InsetCitation.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetQuotes.h"
65 #include "support/lassert.h"
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/docstring_list.h"
69 #include "support/filetools.h"
70 #include "support/gettext.h"
71 #include "support/lstrings.h"
78 #if QT_VERSION >= 0x040600
79 #include <QProxyStyle>
87 using namespace lyx::support;
95 // MacOSX specific stuff is at the end.
102 /// The type of elements that can be in a menu
110 /** This type of item explains why something is unavailable. If this
111 menuitem is in a submenu, the submenu is enabled to make sure the
112 user sees the information. */
114 /** This type of item merely shows that there might be a list or
115 something alike at this position, but the list is still empty.
116 If this item is in a submenu, the submenu will not always be
119 /** This is the list of last opened file,
120 typically for the File menu. */
122 /** This is the list of opened Documents,
123 typically for the Documents menu. */
125 /** This is the bookmarks */
129 /** This is a list of viewable formats
130 typically for the File->View menu. */
132 /** This is a list of updatable formats
133 typically for the File->Update menu. */
135 /** This is a list of exportable formats
136 typically for the File->Export menu. */
138 /** This exports the document default format
139 typically for the File->Export menu. */
141 /** This is a list of importable formats
142 typically for the File->Import menu. */
144 /** This is the list of elements available
145 * for insertion into document. */
147 /** This is the list of user-configurable
148 insets to insert into document */
150 /** This is the list of XML elements to
151 insert into the document */
153 /** This is the list of floats that we can
154 insert a list for. */
156 /** This is the list of floats that we can
159 /** This is the list of selections that can
164 /** Available branches in document */
166 /** Available indices in document */
168 /** Context menu for indices in document */
170 /** Available index lists in document */
172 /** Context menu for available indices lists in document */
174 /** Available citation styles for a given citation */
176 /** Available graphics groups */
178 /// Words suggested by the spellchecker.
180 /** Used Languages */
182 /** This is the list of arguments available
183 for insertion into the current layout. */
185 /** This is the list of arguments available
186 in the InsetArgument context menu. */
188 /** This is the list of captions available
189 in the current layout. */
191 /** This is the list of captions available
192 in the InsetCaption context menu. */
194 /** Commands to separate environments. */
195 EnvironmentSeparators,
196 /** Commands to separate environments (context menu version). */
197 EnvironmentSeparatorsContext,
198 /** This is the list of quotation marks available */
202 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
205 QString const & label,
206 QString const & submenu = QString(),
207 QString const & tooltip = QString(),
208 bool optional = false)
209 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
210 submenuname_(submenu), tooltip_(tooltip), optional_(optional)
212 LATTEST(kind == Submenu || kind == Help || kind == Info);
216 QString const & label,
217 FuncRequest const & func,
218 QString const & tooltip = QString(),
219 bool optional = false,
220 FuncRequest::Origin origin = FuncRequest::MENU)
221 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
222 tooltip_(tooltip), optional_(optional)
224 func_->setOrigin(origin);
227 /// The label of a given menuitem
228 QString label() const
230 int const index = label_.lastIndexOf('|');
231 return index == -1 ? label_ : label_.left(index);
234 /// The keyboard shortcut (usually underlined in the entry)
235 QString shortcut() const
237 int const index = label_.lastIndexOf('|');
238 return index == -1 ? QString() : label_.mid(index + 1);
240 /// The complete label, with label and shortcut separated by a '|'
241 QString fulllabel() const { return label_; }
242 /// The kind of entry
243 Kind kind() const { return kind_; }
244 /// the action (if relevant)
245 shared_ptr<FuncRequest const> func() const { return func_; }
247 QString const & tooltip() const { return tooltip_; }
248 /// returns true if the entry should be omitted when disabled
249 bool optional() const { return optional_; }
250 /// returns the status of the lfun associated with this entry
251 FuncStatus const & status() const { return status_; }
252 /// returns the status of the lfun associated with this entry
253 FuncStatus & status() { return status_; }
254 /// returns the status of the lfun associated with this entry
255 void status(FuncStatus const & status) { status_ = status; }
257 ///returns the binding associated to this action.
258 QString binding() const
260 if (kind_ != Command)
262 // Get the keys bound to this action, but keep only the
264 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
265 if (!bindings.empty())
266 return toqstr(bindings.begin()->print(KeySequence::ForGui));
268 LYXERR(Debug::KBMAP, "No binding for "
269 << lyxaction.getActionName(func_->action())
270 << '(' << func_->argument() << ')');
274 /// the description of the submenu (if relevant)
275 QString const & submenuname() const { return submenuname_; }
276 /// set the description of the submenu
277 void submenuname(QString const & name) { submenuname_ = name; }
279 bool hasSubmenu() const { return !submenu_.isEmpty(); }
281 MenuDefinition const & submenu() const { return submenu_.at(0); }
282 MenuDefinition & submenu() { return submenu_[0]; }
284 void setSubmenu(MenuDefinition const & menu)
287 submenu_.append(menu);
296 shared_ptr<FuncRequest> func_;// non-null
298 QString submenuname_;
305 /// contains 0 or 1 item.
306 QList<MenuDefinition> submenu_;
310 class MenuDefinition {
313 typedef std::vector<MenuItem> ItemList;
315 typedef ItemList::const_iterator const_iterator;
317 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
322 QString const & name() const { return name_; }
324 bool empty() const { return items_.empty(); }
325 /// Clear the menu content.
326 void clear() { items_.clear(); }
328 size_t size() const { return items_.size(); }
330 const_iterator begin() const { return items_.begin(); }
332 const_iterator end() const { return items_.end(); }
334 void cat(MenuDefinition const & other);
336 void catSub(docstring const & name);
338 // search for func in this menu iteratively, and put menu
340 bool searchMenu(FuncRequest const & func, docstring_list & names)
343 bool hasFunc(FuncRequest const &) const;
344 /// Add the menu item unconditionally
345 void add(MenuItem const & item) { items_.push_back(item); }
346 /// Checks the associated FuncRequest status before adding the
348 void addWithStatusCheck(MenuItem const &);
349 // Check whether the menu shortcuts are unique
350 void checkShortcuts() const;
352 void expandLastfiles();
353 void expandDocuments();
354 void expandBookmarks();
355 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
356 void expandFloatListInsert(Buffer const * buf);
357 void expandFloatInsert(Buffer const * buf);
358 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
359 void expandTocSubmenu(std::string const & type, Toc const & toc_list);
360 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
361 void expandToc(Buffer const * buf);
362 void expandPasteRecent(Buffer const * buf);
363 void expandToolbars();
364 void expandBranches(Buffer const * buf);
365 void expandIndices(Buffer const * buf, bool listof = false);
366 void expandIndicesContext(Buffer const * buf, bool listof = false);
367 void expandCiteStyles(BufferView const *);
368 void expandGraphicsGroups(BufferView const *);
369 void expandSpellingSuggestions(BufferView const *);
370 void expandLanguageSelector(Buffer const * buf);
371 void expandArguments(BufferView const *, bool switcharg = false);
372 void expandCaptions(Buffer const * buf, bool switchcap = false);
373 void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
374 void expandQuotes(BufferView const *);
382 /// Helper for std::find_if
386 MenuNamesEqual(QString const & name) : name_(name) {}
387 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
394 typedef std::vector<MenuDefinition> MenuList;
396 typedef MenuList::const_iterator const_iterator;
398 typedef MenuList::iterator iterator;
400 /////////////////////////////////////////////////////////////////////
401 // MenuDefinition implementation
402 /////////////////////////////////////////////////////////////////////
404 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
408 case MenuItem::Command: {
409 FuncStatus status = lyx::getStatus(*i.func());
410 if (status.unknown() || (!status.enabled() && i.optional()))
413 items_.back().status(status);
417 case MenuItem::Submenu: {
418 bool enabled = false;
419 if (i.hasSubmenu()) {
420 for (const_iterator cit = i.submenu().begin();
421 cit != i.submenu().end(); ++cit) {
422 // Only these kind of items affect the status of the submenu
423 if ((cit->kind() == MenuItem::Command
424 || cit->kind() == MenuItem::Submenu
425 || cit->kind() == MenuItem::Help)
426 && cit->status().enabled()) {
432 if (enabled || !i.optional()) {
434 items_.back().status().setEnabled(enabled);
439 case MenuItem::Separator:
440 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
450 void MenuDefinition::read(Lexer & lex)
468 md_indiceslistscontext,
482 md_spellingsuggestions,
489 md_env_separatorscontext,
493 LexerKeyword menutags[] = {
494 { "arguments", md_arguments },
495 { "bookmarks", md_bookmarks },
496 { "branches", md_branches },
497 { "captions", md_captions },
498 { "charstyles", md_charstyles },
499 { "citestyles", md_citestyles },
500 { "custom", md_custom },
501 { "documents", md_documents },
502 { "elements", md_elements },
503 { "end", md_endmenu },
504 { "environmentseparators", md_env_separators },
505 { "environmentseparatorscontext", md_env_separatorscontext },
506 { "exportformat", md_exportformat },
507 { "exportformats", md_exportformats },
508 { "floatinsert", md_floatinsert },
509 { "floatlistinsert", md_floatlistinsert },
510 { "graphicsgroups", md_graphicsgroups },
511 { "importformats", md_importformats },
512 { "indices", md_indices },
513 { "indicescontext", md_indicescontext },
514 { "indiceslists", md_indiceslists },
515 { "indiceslistscontext", md_indiceslistscontext },
517 { "languageselector", md_languageselector },
518 { "lastfiles", md_lastfiles },
519 { "optitem", md_optitem },
520 { "optsubmenu", md_optsubmenu },
521 { "pasterecent", md_pasterecent },
522 { "separator", md_separator },
523 { "spellingsuggestions", md_spellingsuggestions },
524 { "submenu", md_submenu },
525 { "switcharguments", md_switcharguments },
526 { "switchcaptions", md_switchcaptions },
527 { "switchquotes", md_switchquotes },
529 { "toolbars", md_toolbars },
530 { "updateformats", md_updateformats },
531 { "viewformats", md_viewformats }
534 lex.pushTable(menutags);
535 lex.setContext("MenuDefinition::read: ");
538 while (lex.isOK() && md_type != md_endmenu) {
539 switch (md_type = lex.lex()) {
543 docstring const name = translateIfPossible(lex.getDocString());
545 string const command = lex.getString();
546 FuncRequest func = lyxaction.lookupFunc(command);
547 FuncRequest::Origin origin = FuncRequest::MENU;
548 if (name_.startsWith("context-toc-"))
549 origin = FuncRequest::TOC;
550 bool const optional = (md_type == md_optitem);
551 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
556 add(MenuItem(MenuItem::Separator));
560 add(MenuItem(MenuItem::Lastfiles));
564 add(MenuItem(MenuItem::CharStyles));
568 add(MenuItem(MenuItem::Custom));
572 add(MenuItem(MenuItem::Elements));
576 add(MenuItem(MenuItem::Documents));
580 add(MenuItem(MenuItem::Bookmarks));
584 add(MenuItem(MenuItem::Toc));
588 add(MenuItem(MenuItem::ViewFormats));
591 case md_updateformats:
592 add(MenuItem(MenuItem::UpdateFormats));
595 case md_exportformats:
596 add(MenuItem(MenuItem::ExportFormats));
599 case md_exportformat:
600 add(MenuItem(MenuItem::ExportFormat));
603 case md_importformats:
604 add(MenuItem(MenuItem::ImportFormats));
607 case md_floatlistinsert:
608 add(MenuItem(MenuItem::FloatListInsert));
612 add(MenuItem(MenuItem::FloatInsert));
616 add(MenuItem(MenuItem::PasteRecent));
620 add(MenuItem(MenuItem::Toolbars));
624 add(MenuItem(MenuItem::Branches));
628 add(MenuItem(MenuItem::CiteStyles));
631 case md_graphicsgroups:
632 add(MenuItem(MenuItem::GraphicsGroups));
635 case md_spellingsuggestions:
636 add(MenuItem(MenuItem::SpellingSuggestions));
639 case md_languageselector:
640 add(MenuItem(MenuItem::LanguageSelector));
644 add(MenuItem(MenuItem::Indices));
647 case md_indicescontext:
648 add(MenuItem(MenuItem::IndicesContext));
651 case md_indiceslists:
652 add(MenuItem(MenuItem::IndicesLists));
655 case md_indiceslistscontext:
656 add(MenuItem(MenuItem::IndicesListsContext));
660 add(MenuItem(MenuItem::Arguments));
663 case md_switcharguments:
664 add(MenuItem(MenuItem::SwitchArguments));
668 add(MenuItem(MenuItem::Captions));
671 case md_switchcaptions:
672 add(MenuItem(MenuItem::SwitchCaptions));
675 case md_env_separators:
676 add(MenuItem(MenuItem::EnvironmentSeparators));
679 case md_env_separatorscontext:
680 add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
683 case md_switchquotes:
684 add(MenuItem(MenuItem::SwitchQuotes));
690 docstring const mlabel = translateIfPossible(lex.getDocString());
692 docstring const mname = lex.getDocString();
693 bool const optional = (md_type == md_optsubmenu);
694 add(MenuItem(MenuItem::Submenu,
695 toqstr(mlabel), toqstr(mname), QString(), optional));
703 lex.printError("Unknown menu tag");
711 bool MenuDefinition::hasFunc(FuncRequest const & func) const
713 for (const_iterator it = begin(), et = end(); it != et; ++it)
714 if (*it->func() == func)
720 void MenuDefinition::catSub(docstring const & name)
722 add(MenuItem(MenuItem::Submenu,
723 qt_("More...|M"), toqstr(name), QString(), false));
726 void MenuDefinition::cat(MenuDefinition const & other)
728 const_iterator et = other.end();
729 for (const_iterator it = other.begin(); it != et; ++it)
734 void MenuDefinition::checkShortcuts() const
736 // This is a quadratic algorithm, but we do not care because
737 // menus are short enough
738 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
739 QString shortcut = it1->shortcut();
740 if (shortcut.isEmpty())
742 if (!it1->label().contains(shortcut))
743 LYXERR0("Menu warning: menu entry \""
745 << "\" does not contain shortcut `"
746 << shortcut << "'.");
747 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
748 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
749 LYXERR0("Menu warning: menu entries "
750 << '"' << it1->fulllabel()
751 << "\" and \"" << it2->fulllabel()
752 << "\" share the same shortcut.");
759 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
761 const_iterator m = begin();
762 const_iterator m_end = end();
763 for (; m != m_end; ++m) {
764 if (m->kind() == MenuItem::Command && *m->func() == func) {
765 names.push_back(qstring_to_ucs4(m->label()));
768 if (m->kind() == MenuItem::Submenu) {
769 names.push_back(qstring_to_ucs4(m->label()));
770 if (!m->hasSubmenu()) {
771 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
772 << m->label() << " name=" << m->submenuname());
776 if (m->submenu().searchMenu(func, names))
785 QString limitStringLength(docstring const & str)
787 size_t const max_item_length = 45;
788 docstring ret = str.substr(0, max_item_length + 1);
789 support::truncateWithEllipsis(ret, max_item_length);
794 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
799 graphics::getGraphicsGroups(bv->buffer(), grp);
803 set<string>::const_iterator it = grp.begin();
804 set<string>::const_iterator end = grp.end();
805 add(MenuItem(MenuItem::Command, qt_("No Group"),
806 FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
807 for (; it != end; ++it) {
808 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
809 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
814 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
818 Cursor const & cur = bv->cursor();
822 docstring_list suggestions;
823 Paragraph const & par = cur.paragraph();
824 pos_type from = cur.pos();
826 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
828 case SpellChecker::UNKNOWN_WORD:
829 if (lyxrc.spellcheck_continuously) {
830 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
831 docstring const & selection = cur.selectionAsString(false);
832 if (!cur.selection() || selection == wl.word()) {
834 size_t m = 10; // first submenu index
835 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
836 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
837 for (; i != suggestions.size(); ++i) {
838 docstring const & suggestion = suggestions[i];
839 LYXERR(Debug::GUI, suggestion);
840 MenuItem w(MenuItem::Command, toqstr(suggestion),
841 FuncRequest(LFUN_WORD_REPLACE,
842 replace2string(suggestion, selection,
843 true, // case sensitive
847 false))); // find next
851 item.submenu().add(w);
856 add(MenuItem(MenuItem::Separator));
857 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
858 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
859 FuncRequest(LFUN_SPELLING_ADD, arg)));
860 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
861 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
865 case SpellChecker::LEARNED_WORD: {
866 LYXERR(Debug::GUI, "Learned Word.");
867 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
868 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
869 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
872 case SpellChecker::NO_DICTIONARY:
873 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
875 case SpellChecker::WORD_OK:
876 case SpellChecker::COMPOUND_WORD:
877 case SpellChecker::ROOT_FOUND:
878 case SpellChecker::IGNORED_WORD:
883 struct sortLanguageByName {
884 bool operator()(const Language * a, const Language * b) const {
885 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
889 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
894 std::set<Language const *> languages_buffer =
895 buf->masterBuffer()->getLanguages();
897 if (languages_buffer.size() < 2)
900 std::set<Language const *, sortLanguageByName> languages;
902 std::set<Language const *>::const_iterator const beg =
903 languages_buffer.begin();
904 for (std::set<Language const *>::const_iterator cit = beg;
905 cit != languages_buffer.end(); ++cit) {
906 languages.insert(*cit);
909 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
910 item.setSubmenu(MenuDefinition(qt_("Language")));
911 QString morelangs = qt_("More Languages ...|M");
912 QStringList accelerators;
913 if (morelangs.contains('|'))
914 accelerators.append(morelangs.section('|', -1));
915 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
916 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
917 cit != languages.end(); ++cit) {
918 QString label = qt_((*cit)->display());
919 // try to add an accelerator
920 bool success = false;
921 // try capitals first
922 for (int i = 0; i < label.size(); ++i) {
923 QChar const ch = label[i];
926 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
927 label = label + toqstr("|") + ch;
928 accelerators.append(ch);
933 // if all capitals are taken, try the rest
935 for (int i = 0; i < label.size(); ++i) {
936 if (label[i].isSpace())
938 QString const ch = QString(label[i]);
939 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
940 label = label + toqstr("|") + ch;
941 accelerators.append(ch);
946 MenuItem w(MenuItem::Command, label,
947 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
948 item.submenu().addWithStatusCheck(w);
950 item.submenu().add(MenuItem(MenuItem::Separator));
951 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
952 FuncRequest(LFUN_DIALOG_SHOW, "character")));
957 void MenuDefinition::expandLastfiles()
959 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
960 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
964 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
965 string const file = lfit->absFileName();
966 QString const short_path = toqstr(makeDisplayPath(file, 30));
967 QString const long_path = toqstr(makeDisplayPath(file));
970 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
972 label = QString("%1. %2").arg(ii).arg(short_path);
973 add(MenuItem(MenuItem::Command, label,
974 FuncRequest(LFUN_FILE_OPEN, file), long_path));
979 void MenuDefinition::expandDocuments()
981 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
982 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
984 Buffer * first = theBufferList().first();
986 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
992 if (!guiApp->currentView())
994 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
997 Buffer const & b = wa->bufferView().buffer();
998 QString label = toqstr(b.fileName().displayName(20));
1001 if (b.notifiesExternalModification())
1002 label += QChar(0x26a0);
1004 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1005 add(MenuItem(MenuItem::Command, label,
1006 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1013 // We cannot use a for loop as the buffer list cycles.
1015 if (!(guiApp->currentView()
1016 && guiApp->currentView()->workArea(*b))) {
1017 QString label = toqstr(b->fileName().displayName(20));
1020 if (b->notifiesExternalModification())
1021 label += QChar(0x26a0);
1023 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1024 item.submenu().add(MenuItem(MenuItem::Command, label,
1025 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1028 b = theBufferList().next(b);
1029 } while (b != first);
1031 if (!item.submenu().empty())
1036 void MenuDefinition::expandBookmarks()
1038 lyx::BookmarksSection const & bm = theSession().bookmarks();
1041 for (size_t i = 1; i <= bm.size(); ++i) {
1042 if (bm.isValid(i)) {
1043 string const file = bm.bookmark(i).filename.absFileName();
1044 QString const label = QString("%1. %2|%3").arg(i)
1045 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1046 add(MenuItem(MenuItem::Command, label,
1047 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1052 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1056 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1058 if (!buf && kind != MenuItem::ImportFormats)
1062 FuncCode action = LFUN_NOACTION;
1065 case MenuItem::ImportFormats:
1066 formats = theConverters().importableFormats();
1067 action = LFUN_BUFFER_IMPORT;
1069 case MenuItem::ViewFormats:
1070 formats = buf->params().exportableFormats(true);
1071 action = LFUN_BUFFER_VIEW;
1073 case MenuItem::UpdateFormats:
1074 formats = buf->params().exportableFormats(true);
1075 action = LFUN_BUFFER_UPDATE;
1077 case MenuItem::ExportFormats:
1078 formats = buf->params().exportableFormats(false);
1079 action = LFUN_BUFFER_EXPORT;
1086 bool const view_update = (kind == MenuItem::ViewFormats
1087 || kind == MenuItem::UpdateFormats);
1091 smenue = (kind == MenuItem::ViewFormats
1092 ? qt_("View (Other Formats)|F")
1093 : qt_("Update (Other Formats)|p"));
1094 MenuItem item(MenuItem::Submenu, smenue);
1095 item.setSubmenu(MenuDefinition(smenue));
1097 for (Format const * f : formats) {
1101 docstring lab = f->prettyname();
1102 docstring const scut = from_utf8(f->shortcut());
1103 docstring const tmplab = lab;
1106 lab += char_type('|') + scut;
1107 docstring const lab_i18n = translateIfPossible(lab);
1108 docstring const shortcut = split(lab_i18n, lab, '|');
1110 bool const untranslated = (lab == lab_i18n);
1111 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1114 case MenuItem::ImportFormats:
1115 label += from_ascii("...");
1117 case MenuItem::ViewFormats:
1118 case MenuItem::UpdateFormats:
1119 if (f->name() == buf->params().getDefaultOutputFormat()) {
1120 docstring lbl = (kind == MenuItem::ViewFormats
1121 ? bformat(_("View [%1$s]|V"), label)
1122 : bformat(_("Update [%1$s]|U"), label));
1123 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1127 case MenuItem::ExportFormats:
1128 if (!f->inExportMenu())
1132 // we already asserted earlier in this case
1136 if (!shortcut.empty())
1137 label += '|' + shortcut;
1140 // note that at this point, we know that buf is not null
1142 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1143 toqstr(label), FuncRequest(action, f->name())));
1146 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1147 FuncRequest(action, f->name())));
1149 add(MenuItem(MenuItem::Command, toqstr(label),
1150 FuncRequest(action, f->name())));
1158 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1163 FloatList const & floats = buf->params().documentClass().floats();
1164 FloatList::const_iterator cit = floats.begin();
1165 FloatList::const_iterator end = floats.end();
1167 for (; cit != end; ++cit) {
1168 if (!cit->second.usesFloatPkg()) {
1169 // Different floats could declare the same ListCommand. We only
1170 // want it on the list once, though.
1171 string const & list_cmd = cit->second.listCommand();
1172 if (list_cmd.empty())
1173 // we do not know how to generate such a list
1175 // This form of insert returns an iterator pointing to the newly
1176 // inserted element OR the existing element with that value, and
1177 // a bool indicating whether we inserted a new element. So we can
1178 // see if one is there and insert it if not all at once.
1179 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1183 string const & list_name = cit->second.listName();
1184 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1185 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1190 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1195 FloatList const & floats = buf->params().documentClass().floats();
1196 FloatList::const_iterator cit = floats.begin();
1197 FloatList::const_iterator end = floats.end();
1198 for (; cit != end; ++cit) {
1200 QString const label = qt_(cit->second.name());
1201 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1202 FuncRequest(LFUN_FLOAT_INSERT,
1203 cit->second.floattype())));
1208 void MenuDefinition::expandFlexInsert(
1209 Buffer const * buf, InsetLayout::InsetLyXType type)
1214 TextClass::InsetLayouts const & insetLayouts =
1215 buf->params().documentClass().insetLayouts();
1216 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1217 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1218 for (; cit != end; ++cit) {
1219 if (cit->second.lyxtype() == type) {
1220 if (!cit->second.obsoleted_by().empty())
1222 docstring label = cit->first;
1223 // we remove the "Flex:" prefix, if it is present
1224 if (prefixIs(label, from_ascii("Flex:")))
1225 label = label.substr(5);
1226 addWithStatusCheck(MenuItem(MenuItem::Command,
1227 toqstr(translateIfPossible(label)),
1228 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1231 // FIXME This is a little clunky.
1232 if (items_.empty() && type == InsetLayout::CUSTOM && !buf->hasReadonlyFlag())
1233 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1237 // Threshold before we stop displaying sub-items alongside items
1238 // (for display purposes). Ideally this should fit on a screen.
1239 size_t const max_number_of_items = 30;
1240 // Size limit for the menu. This is for performance purposes,
1241 // because qt already displays a scrollable menu when necessary.
1242 // Ideally this should be the menu size from which scrollable
1243 // menus become unpractical.
1244 size_t const menu_size_limit = 80;
1246 void MenuDefinition::expandToc2(Toc const & toc_list,
1247 size_t from, size_t to, int depth,
1250 int shortcut_count = 0;
1252 // check whether depth is smaller than the smallest depth in toc.
1253 int min_depth = 1000;
1254 for (size_t i = from; i < to; ++i)
1255 min_depth = min(min_depth, toc_list[i].depth());
1256 if (min_depth > depth)
1259 if (to - from <= max_number_of_items) {
1260 for (size_t i = from; i < to; ++i) {
1261 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1262 label += limitStringLength(toc_list[i].asString());
1263 if (toc_list[i].depth() == depth) {
1265 if (shortcut_count < 9) {
1266 if (label.contains(QString::number(shortcut_count + 1)))
1267 label += QString::number(++shortcut_count);
1270 add(MenuItem(MenuItem::Command, label,
1271 FuncRequest(toc_list[i].action())));
1272 // separator after the menu heading
1273 if (toc_list[i].depth() < depth)
1274 add(MenuItem(MenuItem::Separator));
1280 size_t new_pos = pos + 1;
1281 while (new_pos < to && toc_list[new_pos].depth() > depth)
1284 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1285 label += limitStringLength(toc_list[pos].asString());
1286 if (toc_list[pos].depth() == depth) {
1288 if (shortcut_count < 9) {
1289 if (label.contains(QString::number(shortcut_count + 1)))
1290 label += QString::number(++shortcut_count);
1293 if (size >= menu_size_limit) {
1294 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1295 add(MenuItem(MenuItem::Command, "...", f));
1298 if (new_pos == pos + 1) {
1299 add(MenuItem(MenuItem::Command,
1300 label, FuncRequest(toc_list[pos].action())));
1303 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1304 MenuItem item(MenuItem::Submenu, label);
1305 item.setSubmenu(sub);
1315 void MenuDefinition::expandToc(Buffer const * buf)
1317 // To make things very cleanly, we would have to pass buf to
1318 // all MenuItem constructors and to expandToc2. However, we
1319 // know that all the entries in a TOC will be have status_ ==
1320 // OK, so we avoid this unnecessary overhead (JMarc)
1322 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1325 // Add an entry for the master doc if this is a child doc
1326 Buffer const * const master = buf->masterBuffer();
1327 if (buf != master) {
1328 ParIterator const pit = par_iterator_begin(master->inset());
1329 string const arg = convert<string>(pit->id());
1330 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1331 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1334 MenuDefinition other_lists;
1335 // In the navigation menu, only add tocs from this document
1336 TocBackend const & backend = buf->tocBackend();
1337 TocList const & toc_list = backend.tocs();
1338 for (pair<string, shared_ptr<Toc>> const & toc : toc_list) {
1339 // Handle table of contents later
1340 if (toc.first == "tableofcontents" || toc.second->empty())
1342 MenuDefinition submenu;
1343 submenu.expandTocSubmenu(toc.first, *toc.second);
1344 docstring const toc_name = backend.outlinerName(toc.first);
1345 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1346 item.setSubmenu(submenu);
1347 // deserves to be in the main menu?
1348 if (!TocBackend::isOther(toc.first))
1351 other_lists.add(item);
1353 if (!other_lists.empty()) {
1354 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1355 item.setSubmenu(other_lists);
1358 // Handle normal TOC
1359 add(MenuItem(MenuItem::Separator));
1360 TocList::const_iterator cit = toc_list.find("tableofcontents");
1361 if (cit == toc_list.end())
1362 LYXERR(Debug::GUI, "No table of contents.");
1364 if (!cit->second->empty())
1365 expandToc2(*cit->second, 0, cit->second->size(), 0,
1368 add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1373 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1375 // "Open outliner..." entry
1376 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1377 add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1378 add(MenuItem(MenuItem::Separator));
1380 expandToc2(toc, 0, toc.size(), 0, type);
1384 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1386 docstring_list const sel = cap::availableSelections(buf);
1388 docstring_list::const_iterator cit = sel.begin();
1389 docstring_list::const_iterator end = sel.end();
1391 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1392 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1393 FuncRequest(LFUN_PASTE, convert<string>(index))));
1398 void MenuDefinition::expandToolbars()
1400 MenuDefinition other_lists;
1401 // extracts the toolbars from the backend
1402 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1403 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1404 for (; cit != end; ++cit) {
1405 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1406 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1407 if (guiApp->toolbars().isMainToolbar(cit->name))
1410 other_lists.add(item);
1413 if (!other_lists.empty()) {
1414 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1415 item.setSubmenu(other_lists);
1421 void MenuDefinition::expandBranches(Buffer const * buf)
1423 if (!buf || buf->hasReadonlyFlag())
1426 BufferParams const & master_params = buf->masterBuffer()->params();
1427 BufferParams const & params = buf->params();
1428 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1429 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1433 BranchList::const_iterator cit = master_params.branchlist().begin();
1434 BranchList::const_iterator end = master_params.branchlist().end();
1436 for (int ii = 1; cit != end; ++cit, ++ii) {
1437 docstring label = cit->branch();
1439 label = convert<docstring>(ii) + ". " + label
1440 + char_type('|') + convert<docstring>(ii);
1442 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1443 FuncRequest(LFUN_BRANCH_INSERT,
1447 if (buf == buf->masterBuffer())
1450 MenuDefinition child_branches;
1452 BranchList::const_iterator ccit = params.branchlist().begin();
1453 BranchList::const_iterator cend = params.branchlist().end();
1455 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1456 docstring label = ccit->branch();
1458 label = convert<docstring>(ii) + ". " + label
1459 + char_type('|') + convert<docstring>(ii);
1461 label += char_type('|');
1462 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1464 FuncRequest(LFUN_BRANCH_INSERT,
1468 if (!child_branches.empty()) {
1469 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1470 item.setSubmenu(child_branches);
1476 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1481 BufferParams const & params = buf->masterBuffer()->params();
1482 if (!params.use_indices) {
1484 addWithStatusCheck(MenuItem(MenuItem::Command,
1485 qt_("Index List|I"),
1486 FuncRequest(LFUN_INDEX_PRINT,
1487 from_ascii("idx"))));
1489 addWithStatusCheck(MenuItem(MenuItem::Command,
1490 qt_("Index Entry|d"),
1491 FuncRequest(LFUN_INDEX_INSERT,
1492 from_ascii("idx"))));
1496 if (params.indiceslist().empty())
1499 IndicesList::const_iterator cit = params.indiceslist().begin();
1500 IndicesList::const_iterator end = params.indiceslist().end();
1502 for (int ii = 1; cit != end; ++cit, ++ii) {
1504 docstring const label =
1505 bformat(_("Index: %1$s"), cit->index());
1506 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1507 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1509 docstring const label =
1510 bformat(_("Index Entry (%1$s)"), cit->index());
1511 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1512 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1518 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1523 BufferParams const & params = buf->masterBuffer()->params();
1524 if (!params.use_indices || params.indiceslist().empty())
1527 IndicesList::const_iterator cit = params.indiceslist().begin();
1528 IndicesList::const_iterator end = params.indiceslist().end();
1530 for (int ii = 1; cit != end; ++cit, ++ii) {
1532 InsetCommandParams p(INDEX_PRINT_CODE);
1533 p["type"] = cit->shortcut();
1534 string const data = InsetCommand::params2string(p);
1535 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1536 FuncRequest(LFUN_INSET_MODIFY, data)));
1538 docstring const label =
1539 bformat(_("Index Entry (%1$s)"), cit->index());
1540 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1541 FuncRequest(LFUN_INSET_MODIFY,
1542 from_ascii("changetype ") + cit->shortcut())));
1548 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1553 Inset const * inset = bv->cursor().nextInset();
1554 if (!inset || inset->lyxCode() != CITE_CODE) {
1555 add(MenuItem(MenuItem::Command,
1556 qt_("No Citation in Scope!"),
1557 FuncRequest(LFUN_NOACTION)));
1560 InsetCitation const * citinset =
1561 static_cast<InsetCitation const *>(inset);
1563 Buffer const * buf = &bv->buffer();
1564 BufferParams const & bp = buf->masterParams();
1565 string const cmd = citinset->params().getCmdName();
1567 docstring const & key = citinset->getParam("key");
1569 add(MenuItem(MenuItem::Command,
1570 qt_("No citations selected!"),
1571 FuncRequest(LFUN_NOACTION)));
1575 size_t const n = cmd.size();
1576 bool const force = isUpperCase(cmd[0]);
1577 bool const star = cmd[n] == '*';
1579 vector<docstring> const keys = getVectorFromString(key);
1581 vector<CitationStyle> const citeStyleList = bp.citeStyles();
1583 CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1584 bool const qualified = cs.hasQualifiedList
1586 || !citinset->getParam("pretextlist").empty()
1587 || !citinset->getParam("posttextlist").empty());
1588 std::map<docstring, docstring> pres =
1589 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1590 std::map<docstring, docstring> posts =
1591 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1594 ci.textBefore = citinset->getParam("before");
1595 ci.textAfter = citinset->getParam("after");
1596 ci.forceUpperCase = force;
1598 ci.context = CiteItem::Dialog;
1600 ci.isQualified = qualified;
1602 ci.posttexts = posts;
1603 BiblioInfo::CiteStringMap citeStrings =
1604 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1606 BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1607 BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1609 for (int ii = 1; cit != end; ++cit, ++ii) {
1610 docstring label = cit->second;
1611 CitationStyle cs = citeStyleList[ii - 1];
1612 cs.forceUpperCase &= force;
1613 cs.hasStarredVersion &= star;
1614 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1615 FuncRequest(LFUN_INSET_MODIFY,
1616 "changetype " + from_utf8(citationStyleToString(cs)))));
1619 if (cs.hasStarredVersion) {
1620 docstring starred = _("All authors|h");
1621 // Check if we have a custom string/tooltip for the starred version
1622 if (!cs.stardesc.empty()) {
1624 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1626 starred = translateIfPossible(from_utf8(val));
1627 // Transform qt-style accelerators to menu-style
1628 int const amps = count_char(starred, '&');
1631 starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1632 size_t n = starred.find('&');
1633 char_type accel = char_type();
1634 if (n != docstring::npos && n < starred.size() - 1)
1635 accel = starred[n + 1];
1636 starred = subst(starred, from_ascii("&"), from_ascii(""));
1638 starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1639 if (accel != char_type())
1640 starred = starred + '|' + accel;
1643 add(MenuItem(MenuItem::Separator));
1644 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1645 FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1648 if (cs.forceUpperCase) {
1649 if (!cs.hasStarredVersion)
1650 add(MenuItem(MenuItem::Separator));
1651 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1652 FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1657 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1662 if (!bv->cursor().inTexted())
1665 Inset const * inset = &bv->cursor().inset();
1666 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1667 if (inset && args.empty())
1668 args = inset->getLayout().args();
1669 if (args.empty() || (switcharg && args.size() == 1))
1671 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1672 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1673 for (; lait != laend; ++lait) {
1674 Layout::latexarg arg = (*lait).second;
1675 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1676 QString item = toqstr(translateIfPossible(str));
1678 add(MenuItem(MenuItem::Command, item,
1679 FuncRequest(LFUN_INSET_MODIFY,
1680 from_ascii("changetype ")
1681 + from_ascii((*lait).first))));
1683 add(MenuItem(MenuItem::Command, item,
1684 FuncRequest(LFUN_ARGUMENT_INSERT,
1685 from_ascii((*lait).first))));
1690 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1695 DocumentClass const & dc = buf->params().documentClass();
1696 vector< pair<docstring, FuncRequest> > caps;
1697 for (pair<docstring, InsetLayout> const & il : dc.insetLayouts()) {
1699 docstring const type = split(il.first, instype, ':');
1700 if (instype == from_ascii("Caption")) {
1701 // skip forbidden caption types
1702 FuncRequest const cmd = switchcap
1703 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1704 : FuncRequest(LFUN_CAPTION_INSERT, type);
1705 if (getStatus(cmd).enabled())
1706 caps.push_back(make_pair(type, cmd));
1710 if (caps.empty() || (switchcap && caps.size() == 1))
1712 if (caps.size() == 1) {
1713 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1717 MenuDefinition captions;
1718 for (pair<docstring, FuncRequest> const & cap : caps) {
1719 docstring const type = cap.first;
1720 docstring const trtype = translateIfPossible(type);
1721 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1723 add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1725 captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1727 if (!captions.empty()) {
1728 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1729 item.setSubmenu(captions);
1735 void MenuDefinition::expandQuotes(BufferView const * bv)
1740 if (!bv->cursor().inTexted())
1743 Inset const * inset = bv->cursor().nextInset();
1744 if (!inset || inset->lyxCode() != QUOTE_CODE) {
1745 add(MenuItem(MenuItem::Command,
1746 qt_("No Quote in Scope!"),
1747 FuncRequest(LFUN_NOACTION)));
1750 InsetQuotes const * qinset =
1751 static_cast<InsetQuotes const *>(inset);
1753 map<string, docstring> styles = quoteparams.getTypes();
1754 string const qtype = qinset->getType();
1756 map<string, docstring>::const_iterator qq = styles.begin();
1757 map<string, docstring>::const_iterator end = styles.end();
1761 BufferParams const & bp = bv->buffer().masterBuffer()->params();
1763 // The global setting
1764 InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1765 char const globalqsc = quoteparams.getStyleChar(globalqs);
1767 // The current language's default
1768 InsetQuotesParams::QuoteStyle langdefqs =
1769 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1770 char const langqs = quoteparams.getStyleChar(langdefqs);
1772 bool main_global_qs = false;
1773 bool main_langdef_qs = false;
1774 bool main_dynamic_qs = false;
1775 docstring const subcmd = from_ascii("changetype ");
1776 docstring const wildcards = from_ascii("..");
1778 // First the top level menu (all glyphs of the current style) ...
1779 // Begin with dynamic (if they are current style),
1780 if (qtype[0] == 'x') {
1781 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1782 docstring desc = bformat(_("%1$s (dynamic)"),
1783 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1784 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1785 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1786 desc = bformat(_("%1$s (dynamic)"),
1787 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1788 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1789 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1790 desc = bformat(_("%1$s (dynamic)"),
1791 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1792 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1793 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1794 desc = bformat(_("%1$s (dynamic)"),
1795 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1796 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1797 main_dynamic_qs = true;
1799 // now traverse through the static styles ...
1800 for (; qq != end; ++qq) {
1801 docstring const style = from_ascii(qq->first);
1802 bool langdef = (style[0] == langqs);
1803 bool globaldef = (style[0] == globalqsc);
1805 if (prefixIs(style, qtype[0])) {
1806 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1807 docstring const desc = quoteparams.getShortGuiLabel(style);
1808 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1809 main_global_qs = globaldef;
1810 main_langdef_qs = langdef;
1812 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1813 docstring const desc =
1814 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1815 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1816 aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1820 add(MenuItem(MenuItem::Separator));
1822 bool display_static = false;
1823 // ... then potentially items to reset to the defaults and to dynamic style ...
1824 if (!main_dynamic_qs && globalqsc != 'x') {
1825 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1826 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1827 quoteparams.getGuiLabel(globalqs));
1828 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1829 display_static = true;
1831 if (!main_global_qs && langdefqs != globalqs) {
1832 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1833 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1834 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1835 quoteparams.getGuiLabel(globalqs), variant);
1836 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1838 if (!main_langdef_qs) {
1839 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1840 docstring const desc = (main_dynamic_qs || display_static)
1841 ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1842 quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1843 : bformat(_("Reset to language default (%1$s)|l"),
1844 quoteparams.getGuiLabel(langdefqs));
1845 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1848 add(MenuItem(MenuItem::Separator));
1850 // ... and a subitem with the rest
1851 MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1852 item.setSubmenu(aqs);
1857 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1862 Text const * text = bv->cursor().text();
1863 // no paragraphs and no separators exist in math
1867 pit_type pit = bv->cursor().selBegin().pit();
1868 Paragraph const & par = text->getPar(pit);
1869 docstring const curlayout = par.layout().name();
1870 docstring outerlayout;
1871 docstring prevlayout;
1872 depth_type current_depth = par.params().depth();
1873 // check if we have an environment in our scope
1874 Paragraph cpar = par;
1879 cpar = text->getPar(pit);
1880 if (cpar.layout().isEnvironment() && prevlayout.empty()
1881 && cpar.params().depth() <= current_depth)
1882 prevlayout = cpar.layout().name();
1883 if (cpar.params().depth() < current_depth
1884 && cpar.layout().isEnvironment()) {
1885 outerlayout = cpar.layout().name();
1886 current_depth = cpar.params().depth();
1888 if (cpar.params().depth() == 0)
1891 if (par.layout().isEnvironment()) {
1892 docstring label = contextmenu ?
1893 bformat(_("Insert Separated %1$s Above"),
1894 translateIfPossible(curlayout)) :
1895 bformat(_("Separated %1$s Above"),
1896 translateIfPossible(curlayout));
1897 add(MenuItem(MenuItem::Command, toqstr(label),
1898 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1899 from_ascii("before"))));
1900 label = contextmenu ?
1901 bformat(_("Insert Separated %1$s Below"),
1902 translateIfPossible(curlayout)):
1903 bformat(_("Separated %1$s Below"),
1904 translateIfPossible(curlayout));
1905 // We use command-alternatives here since this is how the binding is defined
1906 // (otherwise, the binding is not displayed in the menu)
1907 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1908 add(MenuItem(MenuItem::Command, toqstr(label),
1909 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1910 from_ascii("environment-split ; environment-split previous"))));
1912 else if (!prevlayout.empty()) {
1913 docstring const label = contextmenu ?
1914 bformat(_("Insert Separated %1$s Below"),
1915 translateIfPossible(prevlayout)) :
1916 bformat(_("Separated %1$s Below"),
1917 translateIfPossible(prevlayout));
1918 // We use command-alternatives here since this is how the binding is defined
1919 // (otherwise, the binding is not displayed in the menu)
1920 add(MenuItem(MenuItem::Command, toqstr(label),
1921 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1922 from_ascii("environment-split ; environment-split previous"))));
1924 if (!outerlayout.empty()) {
1927 label = (outerlayout == curlayout) ?
1928 bformat(_("Insert Separated Outer %1$s Below"),
1929 translateIfPossible(outerlayout)) :
1930 bformat(_("Insert Separated %1$s Below"),
1931 translateIfPossible(outerlayout));
1933 label = (outerlayout == curlayout) ?
1934 bformat(_("Separated Outer %1$s Below"),
1935 translateIfPossible(outerlayout)) :
1936 bformat(_("Separated %1$s Below"),
1937 translateIfPossible(outerlayout));
1939 add(MenuItem(MenuItem::Command, toqstr(label),
1940 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1941 from_ascii("outer"))));
1948 /////////////////////////////////////////////////////////////////////
1949 // Menu::Impl definition and implementation
1950 /////////////////////////////////////////////////////////////////////
1954 /// populates the menu or one of its submenu
1955 /// This is used as a recursive function
1956 void populate(QMenu * qMenu, MenuDefinition const & menu);
1958 /// Only needed for top level menus.
1959 MenuDefinition * top_level_menu;
1962 /// the name of this menu
1968 /// Get a MenuDefinition item label from the menu backend
1969 static QString label(MenuItem const & mi)
1971 QString label = mi.label();
1972 label.replace("&", "&&");
1974 QString shortcut = mi.shortcut();
1975 if (!shortcut.isEmpty()) {
1976 int pos = label.indexOf(shortcut);
1978 //label.insert(pos, 1, char_type('&'));
1979 label.replace(pos, 0, "&");
1982 QString const binding = mi.binding();
1983 if (!binding.isEmpty())
1984 label += '\t' + binding;
1989 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
1991 LYXERR(Debug::GUI, "populating menu " << menu.name());
1993 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1996 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1997 for (MenuItem const & m : menu)
1999 case MenuItem::Separator:
2000 qMenu->addSeparator();
2002 case MenuItem::Submenu: {
2003 QMenu * subMenu = qMenu->addMenu(label(m));
2004 populate(subMenu, m.submenu());
2005 subMenu->setEnabled(!subMenu->isEmpty());
2008 case MenuItem::Command:
2010 // FIXME: A previous comment assured that MenuItem::Command was the
2011 // only possible case in practice, but this is wrong. It would be
2012 // good to document which cases are actually treated here.
2013 qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2014 m.tooltip(), qMenu));
2019 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2020 class AlwaysMnemonicStyle : public QProxyStyle {
2022 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2023 QStyleHintReturn *returnData = 0) const
2025 if (hint == QStyle::SH_UnderlineShortcut)
2027 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2032 /////////////////////////////////////////////////////////////////////
2033 // Menu implementation
2034 /////////////////////////////////////////////////////////////////////
2036 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2037 : QMenu(gv), d(new Menu::Impl)
2039 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2041 setStyle(new AlwaysMnemonicStyle);
2045 d->top_level_menu = top_level? new MenuDefinition : 0;
2049 if (d->top_level_menu)
2050 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2056 delete d->top_level_menu;
2061 void Menu::updateView()
2063 guiApp->menus().updateMenu(this);
2069 QList<QAction *> items = actions();
2070 for (int i = 0; i != items.size(); ++i) {
2071 // QAction::menu() returns 0 if there's no submenu.
2072 delete items.at(i)->menu();
2078 /////////////////////////////////////////////////////////////////////
2079 // Menus::Impl definition and implementation
2080 /////////////////////////////////////////////////////////////////////
2082 struct Menus::Impl {
2084 bool hasMenu(QString const &) const;
2086 MenuDefinition & getMenu(QString const &);
2088 MenuDefinition const & getMenu(QString const &) const;
2090 /// Expands some special entries of the menu
2091 /** The entries with the following kind are expanded to a
2092 sequence of Command MenuItems: Lastfiles, Documents,
2093 ViewFormats, ExportFormats, UpdateFormats, Branches,
2094 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2095 EnvironmentSeparators
2097 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2098 BufferView const *) const;
2100 /// Initialize specific MACOS X menubar
2101 void macxMenuBarInit(QMenuBar * qmb);
2103 /// Mac special menu.
2104 /** This defines a menu whose entries list the FuncRequests
2105 that will be removed by expand() in other menus. This is
2106 used by the Qt/Mac code.
2108 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2109 such that the items will keep accessing the FuncRequests in
2110 the MenuDefinition. While Menus::Impl might be recreated,
2111 we keep mac_special_menu_ in memory by making it static.
2113 static MenuDefinition mac_special_menu_;
2118 MenuDefinition menubar_;
2120 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2122 /// name to menu for \c menu() method.
2127 MenuDefinition Menus::Impl::mac_special_menu_;
2131 Here is what the Qt documentation says about how a menubar is chosen:
2133 1) If the window has a QMenuBar then it is used. 2) If the window
2134 is a modal then its menubar is used. If no menubar is specified
2135 then a default menubar is used (as documented below) 3) If the
2136 window has no parent then the default menubar is used (as
2139 The above 3 steps are applied all the way up the parent window
2140 chain until one of the above are satisifed. If all else fails a
2141 default menubar will be created, the default menubar on Qt/Mac is
2142 an empty menubar, however you can create a different default
2143 menubar by creating a parentless QMenuBar, the first one created
2144 will thus be designated the default menubar, and will be used
2145 whenever a default menubar is needed.
2147 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2148 that this menubar will be used also when one of LyX' dialogs has
2151 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2153 /* Since Qt 4.2, the qt/mac menu code has special code for
2154 specifying the role of a menu entry. However, it does not
2155 work very well with our scheme of creating menus on demand,
2156 and therefore we need to put these entries in a special
2157 invisible menu. (JMarc)
2160 /* The entries of our special mac menu. If we add support for
2161 * special entries in Menus, we could imagine something
2163 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
2164 * and therefore avoid hardcoding. I am not sure it is worth
2165 * the hassle, though. (JMarc)
2167 struct MacMenuEntry {
2171 QAction::MenuRole role;
2174 static const MacMenuEntry entries[] = {
2175 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2176 QAction::AboutRole},
2177 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2178 QAction::PreferencesRole},
2179 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2180 /* This doesn't work with Cocoa. */
2181 {LFUN_RECONFIGURE, "", "Reconfigure",
2182 QAction::ApplicationSpecificRole},
2184 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2186 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2187 const bool first_call = mac_special_menu_.empty();
2189 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2190 // the special menu for Menus. Fill it up only once.
2192 for (size_t i = 0 ; i < num_entries ; ++i) {
2193 FuncRequest const func(entries[i].action,
2194 from_utf8(entries[i].arg));
2195 mac_special_menu_.add(MenuItem(MenuItem::Command,
2196 entries[i].label, func));
2200 // add the entries to a QMenu that will eventually be empty
2201 // and therefore invisible.
2202 QMenu * qMenu = qmb->addMenu("special");
2204 for (MenuItem const & m : mac_special_menu_) {
2205 Action * action = new Action(m.func(), QIcon(), m.label(),
2207 action->setMenuRole(entries[i].role);
2208 qMenu->addAction(action);
2214 void Menus::Impl::expand(MenuDefinition const & frommenu,
2215 MenuDefinition & tomenu, BufferView const * bv) const
2217 if (!tomenu.empty())
2220 for (MenuDefinition::const_iterator cit = frommenu.begin();
2221 cit != frommenu.end() ; ++cit) {
2222 Buffer const * buf = bv ? &bv->buffer() : 0;
2223 switch (cit->kind()) {
2224 case MenuItem::Lastfiles:
2225 tomenu.expandLastfiles();
2228 case MenuItem::Documents:
2229 tomenu.expandDocuments();
2232 case MenuItem::Bookmarks:
2233 tomenu.expandBookmarks();
2236 case MenuItem::ImportFormats:
2237 case MenuItem::ViewFormats:
2238 case MenuItem::UpdateFormats:
2239 case MenuItem::ExportFormats:
2240 tomenu.expandFormats(cit->kind(), buf);
2243 case MenuItem::ExportFormat: {
2246 string const format = buf->params().getDefaultOutputFormat();
2247 Format const * f = theFormats().getFormat(format);
2248 docstring const name = f ? f->prettyname() : from_utf8(format);
2249 docstring const label = bformat(_("Export [%1$s]|E"), name);
2250 MenuItem item(MenuItem::Command, toqstr(label),
2251 FuncRequest(LFUN_BUFFER_EXPORT));
2252 tomenu.addWithStatusCheck(item);
2256 case MenuItem::CharStyles:
2257 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2260 case MenuItem::Custom:
2261 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2264 case MenuItem::Elements:
2265 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2268 case MenuItem::FloatListInsert:
2269 tomenu.expandFloatListInsert(buf);
2272 case MenuItem::FloatInsert:
2273 tomenu.expandFloatInsert(buf);
2276 case MenuItem::PasteRecent:
2277 tomenu.expandPasteRecent(buf);
2280 case MenuItem::Toolbars:
2281 tomenu.expandToolbars();
2284 case MenuItem::Branches:
2285 tomenu.expandBranches(buf);
2288 case MenuItem::Indices:
2289 tomenu.expandIndices(buf);
2292 case MenuItem::IndicesContext:
2293 tomenu.expandIndicesContext(buf);
2296 case MenuItem::IndicesLists:
2297 tomenu.expandIndices(buf, true);
2300 case MenuItem::IndicesListsContext:
2301 tomenu.expandIndicesContext(buf, true);
2304 case MenuItem::CiteStyles:
2305 tomenu.expandCiteStyles(bv);
2309 tomenu.expandToc(buf);
2312 case MenuItem::GraphicsGroups:
2313 tomenu.expandGraphicsGroups(bv);
2316 case MenuItem::SpellingSuggestions:
2317 tomenu.expandSpellingSuggestions(bv);
2320 case MenuItem::LanguageSelector:
2321 tomenu.expandLanguageSelector(buf);
2324 case MenuItem::Arguments:
2325 tomenu.expandArguments(bv, false);
2328 case MenuItem::SwitchArguments:
2329 tomenu.expandArguments(bv, true);
2332 case MenuItem::Captions:
2333 tomenu.expandCaptions(buf, false);
2336 case MenuItem::SwitchCaptions:
2337 tomenu.expandCaptions(buf, true);
2340 case MenuItem::EnvironmentSeparators:
2341 tomenu.expandEnvironmentSeparators(bv);
2344 case MenuItem::EnvironmentSeparatorsContext:
2345 tomenu.expandEnvironmentSeparators(bv, true);
2348 case MenuItem::SwitchQuotes:
2349 tomenu.expandQuotes(bv);
2352 case MenuItem::Submenu: {
2353 MenuItem item(*cit);
2354 item.setSubmenu(MenuDefinition(cit->submenuname()));
2355 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2356 tomenu.addWithStatusCheck(item);
2360 case MenuItem::Info:
2361 case MenuItem::Help:
2362 case MenuItem::Separator:
2363 tomenu.addWithStatusCheck(*cit);
2366 case MenuItem::Command:
2367 if (!mac_special_menu_.hasFunc(*cit->func()))
2368 tomenu.addWithStatusCheck(*cit);
2372 // we do not want the menu to end with a separator
2373 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2374 tomenu.items_.pop_back();
2376 // Check whether the shortcuts are unique
2377 tomenu.checkShortcuts();
2381 bool Menus::Impl::hasMenu(QString const & name) const
2383 return find_if(menulist_.begin(), menulist_.end(),
2384 MenuNamesEqual(name)) != menulist_.end();
2388 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2390 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2391 MenuNamesEqual(name));
2392 if (cit == menulist_.end()) {
2393 LYXERR0("No submenu named " << name);
2394 LASSERT(false, { static const MenuDefinition m; return m; });
2400 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2402 iterator it = find_if(menulist_.begin(), menulist_.end(),
2403 MenuNamesEqual(name));
2404 if (it == menulist_.end()) {
2405 LYXERR0("No submenu named " << name);
2406 LASSERT(false, { static MenuDefinition m; return m; });
2412 /////////////////////////////////////////////////////////////////////
2416 /////////////////////////////////////////////////////////////////////
2418 Menus::Menus() : d(new Impl) {}
2434 void Menus::read(Lexer & lex)
2442 LexerKeyword menutags[] = {
2443 { "end", md_endmenuset },
2444 { "menu", md_menu },
2445 { "menubar", md_menubar }
2448 // consistency check
2449 if (compare_ascii_no_case(lex.getString(), "menuset"))
2450 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2452 lex.pushTable(menutags);
2453 lex.setContext("Menus::read");
2457 while (lex.isOK() && !quit) {
2458 switch (lex.lex()) {
2460 d->menubar_.read(lex);
2464 QString const name = toqstr(lex.getDocString());
2465 if (d->hasMenu(name))
2466 d->getMenu(name).read(lex);
2468 MenuDefinition menu(name);
2470 d->menulist_.push_back(menu);
2478 lex.printError("Unknown menu tag");
2486 bool Menus::searchMenu(FuncRequest const & func,
2487 docstring_list & names) const
2489 MenuDefinition menu;
2490 d->expand(d->menubar_, menu, 0);
2491 return menu.searchMenu(func, names);
2495 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2499 // setup special mac specific menu items, but only do this
2500 // the first time a QMenuBar is created. Otherwise Qt will
2501 // create duplicate items in the application menu. It seems
2502 // that Qt does not remove them when the QMenubar is cleared.
2503 d->macxMenuBarInit(qmb);
2506 // Clear all menubar contents before filling it.
2508 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2509 d->macxMenuBarInit(qmb);
2513 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2515 if (d->menubar_.empty()) {
2516 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2517 << d->menubar_.name());
2520 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2522 MenuDefinition menu;
2523 BufferView * bv = 0;
2525 bv = view->currentBufferView();
2526 d->expand(d->menubar_, menu, bv);
2528 MenuDefinition::const_iterator m = menu.begin();
2529 MenuDefinition::const_iterator end = menu.end();
2531 for (; m != end; ++m) {
2533 if (m->kind() != MenuItem::Submenu) {
2534 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2538 LYXERR(Debug::GUI, "menu bar item " << m->label()
2539 << " is a submenu named " << m->submenuname());
2541 QString name = m->submenuname();
2542 if (!d->hasMenu(name)) {
2543 LYXERR(Debug::GUI, "\tERROR: " << name
2544 << " submenu has no menu!");
2548 Menu * menu = new Menu(view, m->submenuname(), true);
2549 menu->setTitle(label(*m));
2551 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2552 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2553 // so we create a temporary one here
2554 QAction * action = new QAction(menu);
2555 menu->addAction(action);
2560 d->name_map_[view][name] = menu;
2565 void Menus::updateMenu(Menu * qmenu)
2567 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2570 if (qmenu->d->name.isEmpty())
2573 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2574 MenuDefinition fromLyxMenu(qmenu->d->name);
2575 while (!identifier.empty()) {
2576 docstring menu_name;
2577 identifier = split(identifier, menu_name, ';');
2579 if (!d->hasMenu(toqstr(menu_name))) {
2580 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2585 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2586 //FIXME: 50 is a wild guess. We should take into account here
2587 //the expansion of menu items, disabled optional items etc.
2588 bool const in_sub_menu = !fromLyxMenu.empty()
2589 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2591 fromLyxMenu.catSub(menu_name);
2593 fromLyxMenu.cat(cat_menu);
2594 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2597 if (fromLyxMenu.empty()) {
2598 qmenu->addAction(qt_("No Action Defined!"));
2602 BufferView * bv = 0;
2604 bv = qmenu->d->view->currentBufferView();
2605 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2606 qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2610 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2612 LYXERR(Debug::GUI, "Context menu requested: " << name);
2613 Menu * menu = d->name_map_[&view].value(name, 0);
2614 if (!menu && !name.startsWith("context-")) {
2615 LYXERR0("requested context menu not found: " << name);
2619 menu = new Menu(&view, name, true, keyboard);
2620 d->name_map_[&view][name] = menu;
2624 } // namespace frontend
2627 #include "moc_Menus.cpp"