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"
35 #include "CutAndPaste.h"
37 #include "FloatList.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "IndicesList.h"
46 #include "LyXAction.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
54 #include "SpellChecker.h"
55 #include "TextClass.h"
57 #include "TocBackend.h"
59 #include "WordLangTuple.h"
61 #include "insets/Inset.h"
62 #include "insets/InsetCitation.h"
63 #include "insets/InsetGraphics.h"
64 #include "insets/InsetInfo.h"
65 #include "insets/InsetQuotes.h"
67 #include "support/lassert.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/docstring_list.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
80 #if QT_VERSION >= 0x040600
81 #include <QProxyStyle>
89 using namespace lyx::support;
97 // MacOSX specific stuff is at the end.
104 /// The type of elements that can be in a menu
112 /** This type of item explains why something is unavailable. If this
113 menuitem is in a submenu, the submenu is enabled to make sure the
114 user sees the information. */
116 /** This type of item merely shows that there might be a list or
117 something alike at this position, but the list is still empty.
118 If this item is in a submenu, the submenu will not always be
121 /** This is the list of last opened file,
122 typically for the File menu. */
124 /** This is the list of opened Documents,
125 typically for the Documents menu. */
127 /** This is the bookmarks */
131 /** This is a list of viewable formats
132 typically for the File->View menu. */
134 /** This is a list of updatable formats
135 typically for the File->Update menu. */
137 /** This is a list of exportable formats
138 typically for the File->Export menu. */
140 /** This exports the document default format
141 typically for the File->Export menu. */
143 /** This is a list of importable formats
144 typically for the File->Import menu. */
146 /** This is the list of elements available
147 * for insertion into document. */
149 /** This is the list of user-configurable
150 insets to insert into document */
152 /** This is the list of floats that we can
153 insert a list for. */
155 /** This is the list of floats that we can
158 /** This is the list of selections that can
163 /** Available branches in document */
165 /** Available indices in document */
167 /** Context menu for indices in document */
169 /** Available index lists in document */
171 /** Context menu for available indices lists in document */
173 /** Available citation styles for a given citation */
175 /** Available arguments for a given info inset */
177 /** Available graphics groups */
179 /// Words suggested by the spellchecker.
181 /** Used Languages */
183 /** This is the list of arguments available
184 for insertion into the current layout. */
186 /** This is the list of arguments available
187 in the InsetArgument context menu. */
189 /** This is the list of captions available
190 in the current layout. */
192 /** This is the list of captions available
193 in the InsetCaption context menu. */
195 /** Commands to separate environments. */
196 EnvironmentSeparators,
197 /** Commands to separate environments (context menu version). */
198 EnvironmentSeparatorsContext,
199 /** This is the list of quotation marks available */
203 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
206 QString const & label,
207 QString const & submenu = QString(),
208 QString const & tooltip = QString(),
209 bool optional = false)
210 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
211 submenuname_(submenu), tooltip_(tooltip), optional_(optional)
213 LATTEST(kind == Submenu || kind == Help || kind == Info);
217 QString const & label,
218 FuncRequest const & func,
219 QString const & tooltip = QString(),
220 bool optional = false,
221 FuncRequest::Origin origin = FuncRequest::MENU)
222 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
223 tooltip_(tooltip), optional_(optional)
225 func_->setOrigin(origin);
228 /// The label of a given menuitem
229 QString label() const
231 int const index = label_.lastIndexOf('|');
232 return index == -1 ? label_ : label_.left(index);
235 /// The keyboard shortcut (usually underlined in the entry)
236 QString shortcut() const
238 int const index = label_.lastIndexOf('|');
239 return index == -1 ? QString() : label_.mid(index + 1);
241 /// The complete label, with label and shortcut separated by a '|'
242 QString fulllabel() const { return label_; }
243 /// The kind of entry
244 Kind kind() const { return kind_; }
245 /// the action (if relevant)
246 shared_ptr<FuncRequest const> func() const { return func_; }
248 QString const & tooltip() const { return tooltip_; }
249 /// returns true if the entry should be omitted when disabled
250 bool optional() const { return optional_; }
251 /// returns the status of the lfun associated with this entry
252 FuncStatus const & status() const { return status_; }
253 /// returns the status of the lfun associated with this entry
254 FuncStatus & status() { return status_; }
255 /// returns the status of the lfun associated with this entry
256 void status(FuncStatus const & status) { status_ = status; }
258 ///returns the binding associated to this action.
259 QString binding() const
261 if (kind_ != Command)
263 // Get the keys bound to this action, but keep only the
265 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
266 if (!bindings.empty())
267 return toqstr(bindings.begin()->print(KeySequence::ForGui));
269 LYXERR(Debug::KBMAP, "No binding for "
270 << lyxaction.getActionName(func_->action())
271 << '(' << func_->argument() << ')');
275 /// the description of the submenu (if relevant)
276 QString const & submenuname() const { return submenuname_; }
277 /// set the description of the submenu
278 void submenuname(QString const & name) { submenuname_ = name; }
280 bool hasSubmenu() const { return !submenu_.isEmpty(); }
282 MenuDefinition const & submenu() const { return submenu_.at(0); }
283 MenuDefinition & submenu() { return submenu_[0]; }
285 void setSubmenu(MenuDefinition const & menu)
288 submenu_.append(menu);
297 shared_ptr<FuncRequest> func_;// non-null
299 QString submenuname_;
306 /// contains 0 or 1 item.
307 QList<MenuDefinition> submenu_;
311 class MenuDefinition {
314 typedef std::vector<MenuItem> ItemList;
316 typedef ItemList::const_iterator const_iterator;
318 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
323 QString const & name() const { return name_; }
325 bool empty() const { return items_.empty(); }
326 /// Clear the menu content.
327 void clear() { items_.clear(); }
329 size_t size() const { return items_.size(); }
331 const_iterator begin() const { return items_.begin(); }
333 const_iterator end() const { return items_.end(); }
335 void cat(MenuDefinition const & other);
337 void catSub(docstring const & name);
339 // search for func in this menu iteratively, and put menu
341 bool searchMenu(FuncRequest const & func, docstring_list & names)
344 bool hasFunc(FuncRequest const &) const;
345 /// Add the menu item unconditionally
346 void add(MenuItem const & item) { items_.push_back(item); }
347 /// Checks the associated FuncRequest status before adding the
349 void addWithStatusCheck(MenuItem const &);
350 // Check whether the menu shortcuts are unique
351 void checkShortcuts() const;
353 void expandLastfiles();
354 void expandDocuments();
355 void expandBookmarks();
356 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
357 void expandFloatListInsert(Buffer const * buf);
358 void expandFloatInsert(Buffer const * buf);
359 void expandFlexInsert(Buffer const * buf, InsetLyXType type);
360 void expandTocSubmenu(std::string const & type, Toc const & toc_list);
361 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, const string & toc_type);
362 void expandToc(Buffer const * buf);
363 void expandPasteRecent(Buffer const * buf);
364 void expandToolbars();
365 void expandBranches(Buffer const * buf);
366 void expandIndices(Buffer const * buf, bool listof = false);
367 void expandIndicesContext(Buffer const * buf, bool listof = false);
368 void expandCiteStyles(BufferView const *);
369 void expandInfoArguments(BufferView const *);
370 void expandGraphicsGroups(BufferView const *);
371 void expandSpellingSuggestions(BufferView const *);
372 void expandLanguageSelector(Buffer const * buf);
373 void expandArguments(BufferView const *, bool switcharg = false);
374 void expandCaptions(Buffer const * buf, bool switchcap = false);
375 void expandEnvironmentSeparators(BufferView const *, bool contextmenu = false);
376 void expandQuotes(BufferView const *);
384 /// Helper for std::find_if
388 MenuNamesEqual(QString const & name) : name_(name) {}
389 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
396 typedef std::vector<MenuDefinition> MenuList;
398 typedef MenuList::const_iterator const_iterator;
400 typedef MenuList::iterator iterator;
402 /////////////////////////////////////////////////////////////////////
403 // MenuDefinition implementation
404 /////////////////////////////////////////////////////////////////////
406 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
410 case MenuItem::Command: {
411 FuncStatus status = lyx::getStatus(*i.func());
412 if (status.unknown() || (!status.enabled() && i.optional()))
415 items_.back().status(status);
419 case MenuItem::Submenu: {
420 bool enabled = false;
421 if (i.hasSubmenu()) {
422 for (const_iterator cit = i.submenu().begin();
423 cit != i.submenu().end(); ++cit) {
424 // Only these kind of items affect the status of the submenu
425 if ((cit->kind() == MenuItem::Command
426 || cit->kind() == MenuItem::Submenu
427 || cit->kind() == MenuItem::Help)
428 && cit->status().enabled()) {
434 if (enabled || !i.optional()) {
436 items_.back().status().setEnabled(enabled);
441 case MenuItem::Separator:
442 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
452 void MenuDefinition::read(Lexer & lex)
469 md_indiceslistscontext,
484 md_spellingsuggestions,
491 md_env_separatorscontext,
495 LexerKeyword menutags[] = {
496 { "arguments", md_arguments },
497 { "bookmarks", md_bookmarks },
498 { "branches", md_branches },
499 { "captions", md_captions },
500 { "charstyles", md_charstyles },
501 { "citestyles", md_citestyles },
502 { "custom", md_custom },
503 { "documents", md_documents },
504 { "end", md_endmenu },
505 { "environmentseparators", md_env_separators },
506 { "environmentseparatorscontext", md_env_separatorscontext },
507 { "exportformat", md_exportformat },
508 { "exportformats", md_exportformats },
509 { "floatinsert", md_floatinsert },
510 { "floatlistinsert", md_floatlistinsert },
511 { "graphicsgroups", md_graphicsgroups },
512 { "importformats", md_importformats },
513 { "indices", md_indices },
514 { "indicescontext", md_indicescontext },
515 { "indiceslists", md_indiceslists },
516 { "indiceslistscontext", md_indiceslistscontext },
517 { "infoarguments", md_infoarguments },
519 { "languageselector", md_languageselector },
520 { "lastfiles", md_lastfiles },
521 { "optitem", md_optitem },
522 { "optsubmenu", md_optsubmenu },
523 { "pasterecent", md_pasterecent },
524 { "separator", md_separator },
525 { "spellingsuggestions", md_spellingsuggestions },
526 { "submenu", md_submenu },
527 { "switcharguments", md_switcharguments },
528 { "switchcaptions", md_switchcaptions },
529 { "switchquotes", md_switchquotes },
531 { "toolbars", md_toolbars },
532 { "updateformats", md_updateformats },
533 { "viewformats", md_viewformats }
536 lex.pushTable(menutags);
537 lex.setContext("MenuDefinition::read: ");
540 while (lex.isOK() && md_type != md_endmenu) {
541 switch (md_type = lex.lex()) {
545 docstring const name = translateIfPossible(lex.getDocString());
547 string const command = lex.getString();
548 FuncRequest func = lyxaction.lookupFunc(command);
549 FuncRequest::Origin origin = FuncRequest::MENU;
550 if (name_.startsWith("context-toc-"))
551 origin = FuncRequest::TOC;
552 bool const optional = (md_type == md_optitem);
553 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
558 add(MenuItem(MenuItem::Separator));
562 add(MenuItem(MenuItem::Lastfiles));
566 add(MenuItem(MenuItem::CharStyles));
570 add(MenuItem(MenuItem::Custom));
574 add(MenuItem(MenuItem::Documents));
578 add(MenuItem(MenuItem::Bookmarks));
582 add(MenuItem(MenuItem::Toc));
586 add(MenuItem(MenuItem::ViewFormats));
589 case md_updateformats:
590 add(MenuItem(MenuItem::UpdateFormats));
593 case md_exportformats:
594 add(MenuItem(MenuItem::ExportFormats));
597 case md_exportformat:
598 add(MenuItem(MenuItem::ExportFormat));
601 case md_importformats:
602 add(MenuItem(MenuItem::ImportFormats));
605 case md_floatlistinsert:
606 add(MenuItem(MenuItem::FloatListInsert));
610 add(MenuItem(MenuItem::FloatInsert));
614 add(MenuItem(MenuItem::PasteRecent));
618 add(MenuItem(MenuItem::Toolbars));
622 add(MenuItem(MenuItem::Branches));
626 add(MenuItem(MenuItem::CiteStyles));
629 case md_infoarguments:
630 add(MenuItem(MenuItem::InfoArguments));
634 case md_graphicsgroups:
635 add(MenuItem(MenuItem::GraphicsGroups));
638 case md_spellingsuggestions:
639 add(MenuItem(MenuItem::SpellingSuggestions));
642 case md_languageselector:
643 add(MenuItem(MenuItem::LanguageSelector));
647 add(MenuItem(MenuItem::Indices));
650 case md_indicescontext:
651 add(MenuItem(MenuItem::IndicesContext));
654 case md_indiceslists:
655 add(MenuItem(MenuItem::IndicesLists));
658 case md_indiceslistscontext:
659 add(MenuItem(MenuItem::IndicesListsContext));
663 add(MenuItem(MenuItem::Arguments));
666 case md_switcharguments:
667 add(MenuItem(MenuItem::SwitchArguments));
671 add(MenuItem(MenuItem::Captions));
674 case md_switchcaptions:
675 add(MenuItem(MenuItem::SwitchCaptions));
678 case md_env_separators:
679 add(MenuItem(MenuItem::EnvironmentSeparators));
682 case md_env_separatorscontext:
683 add(MenuItem(MenuItem::EnvironmentSeparatorsContext));
686 case md_switchquotes:
687 add(MenuItem(MenuItem::SwitchQuotes));
693 docstring const mlabel = translateIfPossible(lex.getDocString());
695 docstring const mname = lex.getDocString();
696 bool const optional = (md_type == md_optsubmenu);
697 add(MenuItem(MenuItem::Submenu,
698 toqstr(mlabel), toqstr(mname), QString(), optional));
706 lex.printError("Unknown menu tag");
714 bool MenuDefinition::hasFunc(FuncRequest const & func) const
716 for (auto const & it : *this)
717 if (*it.func() == func)
723 void MenuDefinition::catSub(docstring const & name)
725 add(MenuItem(MenuItem::Submenu,
726 qt_("More...|M"), toqstr(name), QString(), false));
729 void MenuDefinition::cat(MenuDefinition const & other)
731 const_iterator et = other.end();
732 for (const_iterator it = other.begin(); it != et; ++it)
737 void MenuDefinition::checkShortcuts() const
739 // This is a quadratic algorithm, but we do not care because
740 // menus are short enough
741 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
742 QString shortcut = it1->shortcut();
743 if (shortcut.isEmpty())
745 if (!it1->label().contains(shortcut))
746 LYXERR0("Menu warning: menu entry \""
748 << "\" does not contain shortcut `"
749 << shortcut << "'.");
750 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
751 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
752 LYXERR0("Menu warning: menu entries "
753 << '"' << it1->fulllabel()
754 << "\" and \"" << it2->fulllabel()
755 << "\" share the same shortcut.");
762 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
764 const_iterator m = begin();
765 const_iterator m_end = end();
766 for (; m != m_end; ++m) {
767 if (m->kind() == MenuItem::Command && *m->func() == func) {
768 names.push_back(qstring_to_ucs4(m->label()));
771 if (m->kind() == MenuItem::Submenu) {
772 names.push_back(qstring_to_ucs4(m->label()));
773 if (!m->hasSubmenu()) {
774 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
775 << m->label() << " name=" << m->submenuname());
779 if (m->submenu().searchMenu(func, names))
788 QString limitStringLength(docstring const & str)
790 size_t const max_item_length = 45;
791 docstring ret = str.substr(0, max_item_length + 1);
792 support::truncateWithEllipsis(ret, max_item_length);
797 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
802 graphics::getGraphicsGroups(bv->buffer(), grp);
806 set<string>::const_iterator it = grp.begin();
807 set<string>::const_iterator end = grp.end();
808 add(MenuItem(MenuItem::Command, qt_("No Group"),
809 FuncRequest(LFUN_GRAPHICS_SET_GROUP)));
810 for (; it != end; ++it) {
811 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
812 FuncRequest(LFUN_GRAPHICS_SET_GROUP, *it)));
817 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
821 Cursor const & cur = bv->cursor();
825 docstring_list suggestions;
826 Paragraph const & par = cur.paragraph();
827 pos_type from = cur.pos();
829 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
831 case SpellChecker::UNKNOWN_WORD:
832 if (lyxrc.spellcheck_continuously) {
833 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
834 docstring const & selection = cur.selectionAsString(false);
835 if (!cur.selection() || selection == wl.word()) {
837 size_t m = 10; // first submenu index
838 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
839 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
840 for (; i != suggestions.size(); ++i) {
841 docstring const & suggestion = suggestions[i];
842 LYXERR(Debug::GUI, suggestion);
843 MenuItem w(MenuItem::Command, toqstr(suggestion),
844 FuncRequest(LFUN_WORD_REPLACE,
845 replace2string(suggestion, selection,
846 true, // case sensitive
850 false))); // find next
854 item.submenu().add(w);
859 add(MenuItem(MenuItem::Separator));
860 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
861 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
862 FuncRequest(LFUN_SPELLING_ADD, arg)));
863 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
864 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
868 case SpellChecker::LEARNED_WORD: {
869 LYXERR(Debug::GUI, "Learned Word.");
870 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
871 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
872 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
875 case SpellChecker::NO_DICTIONARY:
876 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
878 case SpellChecker::WORD_OK:
879 case SpellChecker::COMPOUND_WORD:
880 case SpellChecker::ROOT_FOUND:
881 case SpellChecker::IGNORED_WORD:
886 struct sortLanguageByName {
887 bool operator()(const Language * a, const Language * b) const {
888 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
892 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
897 std::set<Language const *> languages_buffer =
898 buf->masterBuffer()->getLanguages();
900 if (languages_buffer.size() < 2) {
901 add(MenuItem(MenuItem::Command, qt_("Switch Language...|L"),
902 FuncRequest(LFUN_DIALOG_SHOW, "character")));
906 std::set<Language const *, sortLanguageByName> langs;
908 std::set<Language const *>::const_iterator const beg =
909 languages_buffer.begin();
910 for (std::set<Language const *>::const_iterator cit = beg;
911 cit != languages_buffer.end(); ++cit) {
915 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
916 item.setSubmenu(MenuDefinition(qt_("Language")));
917 QString morelangs = qt_("More Languages ...|M");
918 QStringList accelerators;
919 if (morelangs.contains('|'))
920 accelerators.append(morelangs.section('|', -1));
921 std::set<Language const *, sortLanguageByName>::const_iterator const begin = langs.begin();
922 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
923 cit != langs.end(); ++cit) {
924 QString label = qt_((*cit)->display());
925 // try to add an accelerator
926 bool success = false;
927 // try capitals first
928 for (int i = 0; i < label.size(); ++i) {
929 QChar const ch = label[i];
932 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
933 label = label + toqstr("|") + ch;
934 accelerators.append(ch);
939 // if all capitals are taken, try the rest
941 for (int i = 0; i < label.size(); ++i) {
942 if (label[i].isSpace())
944 QString const ch = QString(label[i]);
945 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
946 label = label + toqstr("|") + ch;
947 accelerators.append(ch);
952 MenuItem w(MenuItem::Command, label,
953 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
954 item.submenu().addWithStatusCheck(w);
956 item.submenu().add(MenuItem(MenuItem::Separator));
957 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
958 FuncRequest(LFUN_DIALOG_SHOW, "character")));
963 void MenuDefinition::expandLastfiles()
965 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
966 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
970 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
971 string const file = lfit->absFileName();
972 QString const short_path = toqstr(makeDisplayPath(file, 30));
973 QString const long_path = toqstr(makeDisplayPath(file));
976 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
978 label = QString("%1. %2").arg(ii).arg(short_path);
979 add(MenuItem(MenuItem::Command, label,
980 FuncRequest(LFUN_FILE_OPEN, file), long_path));
985 void MenuDefinition::expandDocuments()
987 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
988 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
990 Buffer * first = theBufferList().first();
992 add(MenuItem(MenuItem::Info, qt_("(No Documents Open)")));
998 if (!guiApp->currentView())
1000 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
1003 Buffer const & b = wa->bufferView().buffer();
1004 QString label = toqstr(b.fileName().displayName(20));
1007 if (b.notifiesExternalModification())
1008 label += QChar(0x26a0);
1010 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1011 add(MenuItem(MenuItem::Command, label,
1012 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
1019 // We cannot use a for loop as the buffer list cycles.
1021 if (!(guiApp->currentView()
1022 && guiApp->currentView()->workArea(*b))) {
1023 QString label = toqstr(b->fileName().displayName(20));
1026 if (b->notifiesExternalModification())
1027 label += QChar(0x26a0);
1029 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1030 item.submenu().add(MenuItem(MenuItem::Command, label,
1031 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1034 b = theBufferList().next(b);
1035 } while (b != first);
1037 if (!item.submenu().empty())
1042 void MenuDefinition::expandBookmarks()
1044 lyx::BookmarksSection const & bm = theSession().bookmarks();
1047 for (size_t i = 1; i <= bm.size(); ++i) {
1048 if (bm.isValid(i)) {
1049 string const file = bm.bookmark(i).filename.absFileName();
1050 QString const label = QString("%1. %2|%3").arg(i)
1051 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1052 add(MenuItem(MenuItem::Command, label,
1053 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1058 add(MenuItem(MenuItem::Info, qt_("(No Bookmarks Saved Yet)")));
1062 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1064 if (!buf && kind != MenuItem::ImportFormats)
1068 FuncCode action = LFUN_NOACTION;
1071 case MenuItem::ImportFormats:
1072 formats = theConverters().importableFormats();
1073 action = LFUN_BUFFER_IMPORT;
1075 case MenuItem::ViewFormats:
1076 formats = buf->params().exportableFormats(true);
1077 action = LFUN_BUFFER_VIEW;
1079 case MenuItem::UpdateFormats:
1080 formats = buf->params().exportableFormats(true);
1081 action = LFUN_BUFFER_UPDATE;
1083 case MenuItem::ExportFormats:
1084 formats = buf->params().exportableFormats(false);
1085 action = LFUN_BUFFER_EXPORT;
1092 bool const view_update = (kind == MenuItem::ViewFormats
1093 || kind == MenuItem::UpdateFormats);
1097 smenue = (kind == MenuItem::ViewFormats
1098 ? qt_("View (Other Formats)|F")
1099 : qt_("Update (Other Formats)|p"));
1100 MenuItem item(MenuItem::Submenu, smenue);
1101 item.setSubmenu(MenuDefinition(smenue));
1103 for (Format const * f : formats) {
1107 docstring lab = f->prettyname();
1108 docstring const scut = from_utf8(f->shortcut());
1109 docstring const tmplab = lab;
1112 lab += char_type('|') + scut;
1113 docstring const lab_i18n = translateIfPossible(lab);
1114 docstring const shortcut = split(lab_i18n, lab, '|');
1116 bool const untranslated = (lab == lab_i18n);
1117 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1120 case MenuItem::ImportFormats:
1123 label += from_ascii("...");
1125 case MenuItem::ViewFormats:
1126 case MenuItem::UpdateFormats:
1127 if (f->name() == buf->params().getDefaultOutputFormat()) {
1128 docstring lbl = (kind == MenuItem::ViewFormats
1129 ? bformat(_("View [%1$s]|V"), label)
1130 : bformat(_("Update [%1$s]|U"), label));
1131 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1135 case MenuItem::ExportFormats:
1136 if (!f->inExportMenu())
1140 // we already asserted earlier in this case
1144 if (!shortcut.empty())
1145 label += '|' + shortcut;
1148 // note that at this point, we know that buf is not null
1150 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1151 toqstr(label), FuncRequest(action, f->name())));
1154 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1155 FuncRequest(action, f->name())));
1157 add(MenuItem(MenuItem::Command, toqstr(label),
1158 FuncRequest(action, f->name())));
1166 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1171 FloatList const & floats = buf->params().documentClass().floats();
1172 FloatList::const_iterator cit = floats.begin();
1173 FloatList::const_iterator end = floats.end();
1175 for (; cit != end; ++cit) {
1176 if (!cit->second.usesFloatPkg()) {
1177 // Different floats could declare the same ListCommand. We only
1178 // want it on the list once, though.
1179 string const & list_cmd = cit->second.listCommand();
1180 if (list_cmd.empty())
1181 // we do not know how to generate such a list
1183 // This form of insert returns an iterator pointing to the newly
1184 // inserted element OR the existing element with that value, and
1185 // a bool indicating whether we inserted a new element. So we can
1186 // see if one is there and insert it if not all at once.
1187 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1191 string const & list_name = cit->second.listName();
1192 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1193 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1198 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1203 FloatList const & floats = buf->params().documentClass().floats();
1204 FloatList::const_iterator cit = floats.begin();
1205 FloatList::const_iterator end = floats.end();
1206 for (; cit != end; ++cit) {
1208 if (cit->second.name().empty())
1210 QString const label = qt_(cit->second.name());
1211 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1212 FuncRequest(LFUN_FLOAT_INSERT,
1213 cit->second.floattype())));
1218 void MenuDefinition::expandFlexInsert(
1219 Buffer const * buf, InsetLyXType type)
1224 TextClass::InsetLayouts const & insetLayouts =
1225 buf->params().documentClass().insetLayouts();
1226 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1227 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1228 for (; cit != end; ++cit) {
1229 if (cit->second.lyxtype() == type) {
1230 if (!cit->second.obsoleted_by().empty())
1232 docstring name = cit->first;
1233 // we remove the "Flex:" prefix, if it is present
1234 if (prefixIs(name, from_ascii("Flex:")))
1235 name = name.substr(5);
1236 docstring const label = (cit->second.menustring().empty()) ?
1238 : cit->second.menustring();
1239 addWithStatusCheck(MenuItem(MenuItem::Command,
1240 toqstr(translateIfPossible(label)),
1241 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(name))));
1244 // FIXME This is a little clunky.
1245 if (items_.empty() && type == InsetLyXType::CUSTOM && !buf->hasReadonlyFlag())
1246 add(MenuItem(MenuItem::Help, qt_("(No Custom Insets Defined)")));
1250 // Threshold before we stop displaying sub-items alongside items
1251 // (for display purposes). Ideally this should fit on a screen.
1252 size_t const max_number_of_items = 30;
1253 // Size limit for the menu. This is for performance purposes,
1254 // because qt already displays a scrollable menu when necessary.
1255 // Ideally this should be the menu size from which scrollable
1256 // menus become unpractical.
1257 size_t const menu_size_limit = 80;
1259 void MenuDefinition::expandToc2(Toc const & toc_list,
1260 size_t from, size_t to, int depth,
1261 string const & toc_type)
1263 int shortcut_count = 0;
1265 // check whether depth is smaller than the smallest depth in toc.
1266 int min_depth = 1000;
1267 for (size_t i = from; i < to; ++i)
1268 min_depth = min(min_depth, toc_list[i].depth());
1269 if (min_depth > depth)
1272 if (to - from <= max_number_of_items) {
1273 for (size_t i = from; i < to; ++i) {
1274 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1275 label += limitStringLength(toc_list[i].asString());
1276 if (toc_list[i].depth() == depth) {
1278 if (shortcut_count < 9) {
1279 if (label.contains(QString::number(shortcut_count + 1)))
1280 label += QString::number(++shortcut_count);
1283 add(MenuItem(MenuItem::Command, label,
1284 FuncRequest(toc_list[i].action())));
1285 // separator after the menu heading
1286 if (toc_list[i].depth() < depth)
1287 add(MenuItem(MenuItem::Separator));
1293 size_t new_pos = pos + 1;
1294 while (new_pos < to && toc_list[new_pos].depth() > depth)
1297 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1298 label += limitStringLength(toc_list[pos].asString());
1299 if (toc_list[pos].depth() == depth) {
1301 if (shortcut_count < 9) {
1302 if (label.contains(QString::number(shortcut_count + 1)))
1303 label += QString::number(++shortcut_count);
1306 if (size >= menu_size_limit) {
1307 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1308 add(MenuItem(MenuItem::Command, "...", f));
1311 if (new_pos == pos + 1) {
1312 add(MenuItem(MenuItem::Command,
1313 label, FuncRequest(toc_list[pos].action())));
1316 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1317 MenuItem item(MenuItem::Submenu, label);
1318 item.setSubmenu(sub);
1328 void MenuDefinition::expandToc(Buffer const * buf)
1330 // To make things very cleanly, we would have to pass buf to
1331 // all MenuItem constructors and to expandToc2. However, we
1332 // know that all the entries in a TOC will be have status_ ==
1333 // OK, so we avoid this unnecessary overhead (JMarc)
1335 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1338 // Add an entry for the master doc if this is a child doc
1339 Buffer const * const master = buf->masterBuffer();
1340 if (buf != master) {
1341 ParIterator const pit = par_iterator_begin(master->inset());
1342 string const arg = convert<string>(pit->id());
1343 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1344 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1347 MenuDefinition other_lists;
1348 // In the navigation menu, only add tocs from this document
1349 TocBackend const & backend = buf->tocBackend();
1350 TocList const & toc_list = backend.tocs();
1351 for (pair<const string, shared_ptr<Toc>> const & toc : toc_list) {
1352 // Handle table of contents later
1353 if (toc.first == "tableofcontents" || toc.second->empty())
1355 MenuDefinition submenu;
1356 submenu.expandTocSubmenu(toc.first, *toc.second);
1357 docstring const toc_name = backend.outlinerName(toc.first);
1358 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1359 item.setSubmenu(submenu);
1360 // deserves to be in the main menu?
1361 if (!TocBackend::isOther(toc.first))
1364 other_lists.add(item);
1366 if (!other_lists.empty()) {
1367 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1368 item.setSubmenu(other_lists);
1371 // Handle normal TOC
1372 add(MenuItem(MenuItem::Separator));
1373 TocList::const_iterator const cit = toc_list.find("tableofcontents");
1374 if (cit == toc_list.end())
1375 LYXERR(Debug::GUI, "No table of contents.");
1377 if (!cit->second->empty())
1378 expandToc2(*cit->second, 0, cit->second->size(), 0,
1381 add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1386 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1388 // "Open outliner..." entry
1389 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1390 add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1391 add(MenuItem(MenuItem::Separator));
1393 expandToc2(toc, 0, toc.size(), 0, type);
1397 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1399 docstring_list const sel = cap::availableSelections(buf);
1401 docstring_list::const_iterator cit = sel.begin();
1402 docstring_list::const_iterator end = sel.end();
1404 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1405 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1406 FuncRequest(LFUN_PASTE, convert<string>(index))));
1411 void MenuDefinition::expandToolbars()
1413 MenuDefinition other_lists;
1414 // extracts the toolbars from the backend
1415 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1416 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1417 for (; cit != end; ++cit) {
1418 MenuItem item(MenuItem::Command, toqstr(cit->gui_name),
1419 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1420 if (cit->allow_auto) {
1421 MenuDefinition tristate;
1422 tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]On|O"),
1423 FuncRequest(LFUN_TOOLBAR_SET, cit->name + " on")));
1424 tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]Off|f"),
1425 FuncRequest(LFUN_TOOLBAR_SET, cit->name + " off")));
1426 tristate.add(MenuItem(MenuItem::Command, qt_("[[Toolbar]]Automatic|A"),
1427 FuncRequest(LFUN_TOOLBAR_SET, cit->name + " auto")));
1428 item = MenuItem(MenuItem::Submenu,toqstr(cit->gui_name));
1429 item.setSubmenu(tristate);
1431 if (guiApp->toolbars().isMainToolbar(cit->name))
1434 other_lists.add(item);
1437 if (!other_lists.empty()) {
1438 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1439 item.setSubmenu(other_lists);
1445 void MenuDefinition::expandBranches(Buffer const * buf)
1447 if (!buf || buf->hasReadonlyFlag())
1450 BranchList const & child_list = buf->params().branchlist();
1451 set<docstring> brset;
1453 for (auto const & b : child_list) {
1454 docstring const & bname = b.branch();
1455 // NUM. Branch Name + "|", which triggers an empty shortcut in
1456 // case that character should be in the branch name.
1457 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1458 // Add NUM as a keyboard shortcut if it's a single digit
1460 label += convert<docstring>(ii);
1462 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1463 FuncRequest(LFUN_BRANCH_INSERT, bname)));
1465 brset.insert(bname);
1469 set<Buffer const *> bufset;
1470 Buffer const * nextbuf = buf->parent();
1471 MenuDefinition master_branches;
1474 // recursive includes are a bad idea, but let's not crash
1476 if (bufset.count(nextbuf))
1479 for (auto const & b : nextbuf->params().branchlist()) {
1480 docstring const & bname = b.branch();
1481 // do not add it if we've already seen it
1482 if (brset.count(bname))
1485 docstring label = convert<docstring>(ii) + ". " + bname + char_type('|');
1487 label += convert<docstring>(ii);
1489 master_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1490 toqstr(label), FuncRequest(LFUN_BRANCH_INSERT, bname)));
1492 bufset.insert(nextbuf);
1493 brset.insert(bname);
1497 nextbuf = nextbuf->parent();
1500 if (!master_branches.empty()) {
1501 MenuItem item(MenuItem::Submenu, qt_("Master Documents"));
1502 item.setSubmenu(master_branches);
1508 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1513 BufferParams const & params = buf->masterBuffer()->params();
1514 if (!params.use_indices) {
1516 addWithStatusCheck(MenuItem(MenuItem::Command,
1517 qt_("Index List|I"),
1518 FuncRequest(LFUN_INDEX_PRINT,
1519 from_ascii("idx"))));
1521 addWithStatusCheck(MenuItem(MenuItem::Command,
1522 qt_("Index Entry|d"),
1523 FuncRequest(LFUN_INDEX_INSERT,
1524 from_ascii("idx"))));
1528 if (params.indiceslist().empty())
1531 IndicesList::const_iterator cit = params.indiceslist().begin();
1532 IndicesList::const_iterator end = params.indiceslist().end();
1534 for (int ii = 1; cit != end; ++cit, ++ii) {
1536 docstring const label =
1537 bformat(_("Index: %1$s"), cit->index());
1538 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1539 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1541 docstring const label =
1542 bformat(_("Index Entry (%1$s)"), cit->index());
1543 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1544 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1550 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1555 BufferParams const & params = buf->masterBuffer()->params();
1556 if (!params.use_indices || params.indiceslist().empty())
1559 IndicesList::const_iterator cit = params.indiceslist().begin();
1560 IndicesList::const_iterator end = params.indiceslist().end();
1562 for (int ii = 1; cit != end; ++cit, ++ii) {
1564 InsetCommandParams p(INDEX_PRINT_CODE);
1565 p["type"] = cit->shortcut();
1566 string const data = InsetCommand::params2string(p);
1567 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1568 FuncRequest(LFUN_INSET_MODIFY, data)));
1570 docstring const label =
1571 bformat(_("Index Entry (%1$s)"), cit->index());
1572 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1573 FuncRequest(LFUN_INSET_MODIFY,
1574 from_ascii("changetype ") + cit->shortcut())));
1580 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1585 Inset const * inset = bv->cursor().nextInset();
1586 if (!inset || inset->lyxCode() != CITE_CODE) {
1587 add(MenuItem(MenuItem::Command,
1588 qt_("No Citation in Scope!"),
1589 FuncRequest(LFUN_NOACTION)));
1592 InsetCitation const * citinset =
1593 static_cast<InsetCitation const *>(inset);
1595 Buffer const * buf = &bv->buffer();
1596 BufferParams const & bp = buf->masterParams();
1597 string const cmd = citinset->params().getCmdName();
1599 docstring const & key = citinset->getParam("key");
1601 add(MenuItem(MenuItem::Command,
1602 qt_("No citations selected!"),
1603 FuncRequest(LFUN_NOACTION)));
1607 bool const force = isUpperCase(cmd[0]);
1608 bool const star = suffixIs(cmd, '*');
1610 vector<docstring> const keys = getVectorFromString(key);
1612 vector<CitationStyle> const citeStyleList = bp.citeStyles();
1614 CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1615 bool const qualified = cs.hasQualifiedList
1617 || !citinset->getParam("pretextlist").empty()
1618 || !citinset->getParam("posttextlist").empty());
1619 vector<pair<docstring, docstring>> pres =
1620 citinset->getQualifiedLists(citinset->getParam("pretextlist"));
1621 vector<pair<docstring, docstring>> posts =
1622 citinset->getQualifiedLists(citinset->getParam("posttextlist"));
1625 ci.textBefore = citinset->getParam("before");
1626 ci.textAfter = citinset->getParam("after");
1627 ci.forceUpperCase = force;
1629 ci.context = CiteItem::Dialog;
1631 ci.isQualified = qualified;
1633 ci.posttexts = posts;
1634 BiblioInfo::CiteStringMap citeStrings =
1635 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1637 BiblioInfo::CiteStringMap::const_iterator cit = citeStrings.begin();
1638 BiblioInfo::CiteStringMap::const_iterator end = citeStrings.end();
1640 for (int ii = 1; cit != end; ++cit, ++ii) {
1641 docstring label = cit->second;
1642 CitationStyle ccs = citeStyleList[ii - 1];
1643 ccs.forceUpperCase &= force;
1644 ccs.hasStarredVersion &= star;
1645 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1646 FuncRequest(LFUN_INSET_MODIFY,
1647 "changetype " + from_utf8(citationStyleToString(ccs)))));
1650 if (cs.hasStarredVersion) {
1651 docstring starred = _("All authors|h");
1652 // Check if we have a custom string/tooltip for the starred version
1653 if (!cs.stardesc.empty()) {
1655 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1657 starred = translateIfPossible(from_utf8(val));
1658 // Transform qt-style accelerators to menu-style
1659 int const amps = count_char(starred, '&');
1662 starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1663 size_t nn = starred.find('&');
1664 char_type accel = char_type();
1665 if (nn != docstring::npos && nn < starred.size() - 1)
1666 accel = starred[nn + 1];
1667 starred = subst(starred, from_ascii("&"), from_ascii(""));
1669 starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1670 if (accel != char_type())
1671 starred = starred + '|' + accel;
1674 add(MenuItem(MenuItem::Separator));
1675 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1676 FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1679 if (cs.forceUpperCase) {
1680 if (!cs.hasStarredVersion)
1681 add(MenuItem(MenuItem::Separator));
1682 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1683 FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1688 void MenuDefinition::expandInfoArguments(BufferView const * bv)
1693 Inset const * inset = bv->cursor().nextInset();
1694 if (!inset || inset->lyxCode() != INFO_CODE) {
1695 add(MenuItem(MenuItem::Command,
1696 qt_("No Text Field in Scope!"),
1697 FuncRequest(LFUN_NOACTION)));
1700 InsetInfo const * iinset = static_cast<InsetInfo const *>(inset);
1702 string const type = iinset->params().infoType();
1703 vector<pair<string,docstring>> const args =
1704 iinset->params().getArguments(&bv->buffer(), type);
1706 // Don't generate a menu for big lists (such as lfuns and rcs)
1707 if (args.size() > 15)
1710 for (auto const & p : args) {
1711 if (p.first == "invalid")
1714 if (p.first == "custom") {
1715 add(MenuItem(MenuItem::Command, qt_("Custom..."),
1716 FuncRequest(LFUN_INSET_SETTINGS, "info")));
1719 docstring label = p.second;
1720 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1721 FuncRequest(LFUN_INSET_MODIFY, type + " " + p.first)));
1727 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1732 if (!bv->cursor().inTexted())
1735 Inset const * inset = &bv->cursor().inset();
1736 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1737 if (inset && args.empty())
1738 args = inset->getLayout().args();
1739 if (args.empty() || (switcharg && args.size() == 1))
1741 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1742 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1743 for (; lait != laend; ++lait) {
1744 Layout::latexarg arg = (*lait).second;
1745 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1746 QString item = toqstr(translateIfPossible(str));
1748 add(MenuItem(MenuItem::Command, item,
1749 FuncRequest(LFUN_INSET_MODIFY,
1750 from_ascii("changetype ")
1751 + from_ascii((*lait).first))));
1753 add(MenuItem(MenuItem::Command, item,
1754 FuncRequest(LFUN_ARGUMENT_INSERT,
1755 from_ascii((*lait).first))));
1760 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1765 DocumentClass const & dc = buf->params().documentClass();
1766 vector< pair<docstring, FuncRequest> > caps;
1767 for (pair<const docstring, InsetLayout> const & il : dc.insetLayouts()) {
1769 docstring const type = split(il.first, instype, ':');
1770 if (instype == from_ascii("Caption")) {
1771 // skip forbidden caption types
1772 FuncRequest const cmd = switchcap
1773 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1774 : FuncRequest(LFUN_CAPTION_INSERT, type);
1775 if (getStatus(cmd).enabled())
1776 caps.push_back(make_pair(type, cmd));
1780 if (caps.empty() || (switchcap && caps.size() == 1))
1782 if (caps.size() == 1) {
1783 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1787 MenuDefinition captions;
1788 for (pair<docstring, FuncRequest> const & cap : caps) {
1789 docstring const type = cap.first;
1790 docstring const trtype = translateIfPossible(type);
1791 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1793 add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1795 captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1797 if (!captions.empty()) {
1798 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1799 item.setSubmenu(captions);
1805 void MenuDefinition::expandQuotes(BufferView const * bv)
1810 if (!bv->cursor().inTexted())
1813 Inset const * inset = bv->cursor().nextInset();
1814 if (!inset || inset->lyxCode() != QUOTE_CODE) {
1815 add(MenuItem(MenuItem::Command,
1816 qt_("No Quote in Scope!"),
1817 FuncRequest(LFUN_NOACTION)));
1820 InsetQuotes const * qinset =
1821 static_cast<InsetQuotes const *>(inset);
1823 string const qtype = qinset->getType();
1827 BufferParams const & bp = bv->buffer().masterBuffer()->params();
1829 // The global setting
1830 QuoteStyle globalqs = bp.quotes_style;
1831 char const globalqsc = quoteparams.getStyleChar(globalqs);
1833 // The current language's default
1834 QuoteStyle langdefqs =
1835 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1836 char const langqs = quoteparams.getStyleChar(langdefqs);
1838 bool main_global_qs = false;
1839 bool main_langdef_qs = false;
1840 bool main_dynamic_qs = false;
1841 docstring const subcmd = from_ascii("changetype ");
1842 docstring const wildcards = from_ascii("..");
1844 // First the top level menu (all glyphs of the current style) ...
1845 // Begin with dynamic (if they are current style),
1846 if (qtype[0] == 'x') {
1847 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1848 docstring desc = bformat(_("%1$s (dynamic)"),
1849 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1850 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1851 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1852 desc = bformat(_("%1$s (dynamic)"),
1853 quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1854 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1855 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1856 desc = bformat(_("%1$s (dynamic)"),
1857 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1858 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1859 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1860 desc = bformat(_("%1$s (dynamic)"),
1861 quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1862 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1863 main_dynamic_qs = true;
1865 // now traverse through the static styles ...
1866 map<string, docstring> styles = quoteparams.getTypes();
1867 for (auto const & s : styles) {
1868 char style_char = (s.first)[0];
1869 bool langdef = (style_char == langqs);
1870 bool globaldef = (style_char == globalqsc);
1871 docstring const style = from_ascii(s.first);
1873 if (prefixIs(style, qtype[0])) {
1874 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1875 docstring const desc = quoteparams.getShortGuiLabel(style);
1876 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1877 main_global_qs = globaldef;
1878 main_langdef_qs = langdef;
1880 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1881 docstring const desc =
1882 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1883 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1884 aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1888 add(MenuItem(MenuItem::Separator));
1890 bool display_static = false;
1891 // ... then potentially items to reset to the defaults and to dynamic style ...
1892 if (!main_dynamic_qs && globalqsc != 'x') {
1893 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1894 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1895 quoteparams.getGuiLabel(globalqs));
1896 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1897 display_static = true;
1899 if (!main_global_qs && langdefqs != globalqs) {
1900 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1901 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1902 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1903 quoteparams.getGuiLabel(globalqs), variant);
1904 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1906 if (!main_langdef_qs) {
1907 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1908 docstring const desc = (main_dynamic_qs || display_static)
1909 ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1910 quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1911 : bformat(_("Reset to language default (%1$s)|l"),
1912 quoteparams.getGuiLabel(langdefqs));
1913 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1916 add(MenuItem(MenuItem::Separator));
1918 // ... and a subitem with the rest
1919 MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1920 item.setSubmenu(aqs);
1925 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv,
1930 Text const * text = bv->cursor().text();
1931 // no paragraphs and no separators exist in math
1935 pit_type pit = bv->cursor().selBegin().pit();
1936 Paragraph const & par = text->getPar(pit);
1937 docstring const curlayout = par.layout().name();
1938 docstring outerlayout;
1939 docstring prevlayout;
1940 depth_type current_depth = par.params().depth();
1941 // check if we have an environment in our scope
1946 Paragraph cpar = text->getPar(pit);
1947 if (cpar.layout().isEnvironment() && prevlayout.empty()
1948 && cpar.params().depth() <= current_depth)
1949 prevlayout = cpar.layout().name();
1950 if (cpar.params().depth() < current_depth
1951 && cpar.layout().isEnvironment()) {
1952 outerlayout = cpar.layout().name();
1953 current_depth = cpar.params().depth();
1955 if (cpar.params().depth() == 0)
1958 if (par.layout().isEnvironment()) {
1959 docstring label = contextmenu ?
1960 bformat(_("Insert Separated %1$s Above"),
1961 translateIfPossible(curlayout)) :
1962 bformat(_("Separated %1$s Above"),
1963 translateIfPossible(curlayout));
1964 add(MenuItem(MenuItem::Command, toqstr(label),
1965 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1966 from_ascii("before"))));
1967 label = contextmenu ?
1968 bformat(_("Insert Separated %1$s Below"),
1969 translateIfPossible(curlayout)):
1970 bformat(_("Separated %1$s Below"),
1971 translateIfPossible(curlayout));
1972 // We use command-alternatives here since this is how the binding is defined
1973 // (otherwise, the binding is not displayed in the menu)
1974 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1975 add(MenuItem(MenuItem::Command, toqstr(label),
1976 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1977 from_ascii("environment-split ; environment-split previous"))));
1979 else if (!prevlayout.empty()) {
1980 docstring const label = contextmenu ?
1981 bformat(_("Insert Separated %1$s Below"),
1982 translateIfPossible(prevlayout)) :
1983 bformat(_("Separated %1$s Below"),
1984 translateIfPossible(prevlayout));
1985 // We use command-alternatives here since this is how the binding is defined
1986 // (otherwise, the binding is not displayed in the menu)
1987 if (getStatus(FuncRequest(LFUN_ENVIRONMENT_SPLIT)).enabled())
1988 add(MenuItem(MenuItem::Command, toqstr(label),
1989 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1990 from_ascii("environment-split ; environment-split previous"))));
1992 if (!outerlayout.empty()) {
1995 label = (outerlayout == curlayout) ?
1996 bformat(_("Insert Separated Outer %1$s Below"),
1997 translateIfPossible(outerlayout)) :
1998 bformat(_("Insert Separated %1$s Below"),
1999 translateIfPossible(outerlayout));
2001 label = (outerlayout == curlayout) ?
2002 bformat(_("Separated Outer %1$s Below"),
2003 translateIfPossible(outerlayout)) :
2004 bformat(_("Separated %1$s Below"),
2005 translateIfPossible(outerlayout));
2007 add(MenuItem(MenuItem::Command, toqstr(label),
2008 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
2009 from_ascii("outer"))));
2016 /////////////////////////////////////////////////////////////////////
2017 // Menu::Impl definition and implementation
2018 /////////////////////////////////////////////////////////////////////
2022 /// populates the menu or one of its submenu
2023 /// This is used as a recursive function
2024 void populate(QMenu * qMenu, MenuDefinition const & menu);
2026 /// Only needed for top level menus.
2027 MenuDefinition * top_level_menu;
2030 /// the name of this menu
2036 /// Get a MenuDefinition item label from the menu backend
2037 static QString label(MenuItem const & mi)
2039 QString label = mi.label();
2040 label.replace("&", "&&");
2042 QString shortcut = mi.shortcut();
2043 if (!shortcut.isEmpty()) {
2044 int pos = label.indexOf(shortcut);
2046 //label.insert(pos, 1, char_type('&'));
2047 label.replace(pos, 0, "&");
2050 QString const binding = mi.binding();
2051 if (!binding.isEmpty())
2052 label += '\t' + binding;
2057 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
2059 LYXERR(Debug::GUI, "populating menu " << menu.name());
2061 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
2064 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
2065 for (MenuItem const & m : menu)
2067 case MenuItem::Separator:
2068 qMenu->addSeparator();
2070 case MenuItem::Submenu: {
2071 QMenu * subMenu = qMenu->addMenu(label(m));
2072 populate(subMenu, m.submenu());
2073 subMenu->setEnabled(!subMenu->isEmpty());
2076 case MenuItem::Command:
2078 // FIXME: A previous comment assured that MenuItem::Command was the
2079 // only possible case in practice, but this is wrong. It would be
2080 // good to document which cases are actually treated here.
2081 qMenu->addAction(new Action(m.func(), QIcon(), label(m),
2082 m.tooltip(), qMenu));
2087 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2088 class AlwaysMnemonicStyle : public QProxyStyle {
2090 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
2091 QStyleHintReturn *returnData = 0) const override
2093 if (hint == QStyle::SH_UnderlineShortcut)
2095 return QProxyStyle::styleHint(hint, opt, widget, returnData);
2100 /////////////////////////////////////////////////////////////////////
2101 // Menu implementation
2102 /////////////////////////////////////////////////////////////////////
2104 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
2105 : QMenu(gv), d(new Menu::Impl)
2107 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
2109 setStyle(new AlwaysMnemonicStyle);
2113 d->top_level_menu = top_level? new MenuDefinition : 0;
2117 if (d->top_level_menu)
2118 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
2124 delete d->top_level_menu;
2129 void Menu::updateView()
2131 guiApp->menus().updateMenu(this);
2137 QList<QAction *> items = actions();
2138 for (int i = 0; i != items.size(); ++i) {
2139 // QAction::menu() returns 0 if there's no submenu.
2140 delete items.at(i)->menu();
2146 /////////////////////////////////////////////////////////////////////
2147 // Menus::Impl definition and implementation
2148 /////////////////////////////////////////////////////////////////////
2150 struct Menus::Impl {
2152 bool hasMenu(QString const &) const;
2154 MenuDefinition & getMenu(QString const &);
2156 MenuDefinition const & getMenu(QString const &) const;
2158 /// Expands some special entries of the menu
2159 /** The entries with the following kind are expanded to a
2160 sequence of Command MenuItems: Lastfiles, Documents,
2161 ViewFormats, ExportFormats, UpdateFormats, Branches,
2162 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2163 EnvironmentSeparators
2165 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2166 BufferView const *) const;
2168 /// Initialize specific MACOS X menubar
2169 void macxMenuBarInit(QMenuBar * qmb);
2171 /// Mac special menu.
2172 /** This defines a menu whose entries list the FuncRequests
2173 that will be removed by expand() in other menus. This is
2174 used by the Qt/Mac code.
2176 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2177 such that the items will keep accessing the FuncRequests in
2178 the MenuDefinition. While Menus::Impl might be recreated,
2179 we keep mac_special_menu_ in memory by making it static.
2181 static MenuDefinition mac_special_menu_;
2186 MenuDefinition menubar_;
2188 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2190 /// name to menu for \c menu() method.
2195 MenuDefinition Menus::Impl::mac_special_menu_;
2199 Here is what the Qt documentation says about how a menubar is chosen:
2201 1) If the window has a QMenuBar then it is used. 2) If the window
2202 is a modal then its menubar is used. If no menubar is specified
2203 then a default menubar is used (as documented below) 3) If the
2204 window has no parent then the default menubar is used (as
2207 The above 3 steps are applied all the way up the parent window
2208 chain until one of the above are satisfied. If all else fails a
2209 default menubar will be created, the default menubar on Qt/Mac is
2210 an empty menubar, however you can create a different default
2211 menubar by creating a parentless QMenuBar, the first one created
2212 will thus be designated the default menubar, and will be used
2213 whenever a default menubar is needed.
2215 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2216 that this menubar will be used also when one of LyX' dialogs has
2219 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2221 /* Since Qt 4.2, the qt/mac menu code has special code for
2222 specifying the role of a menu entry. However, it does not
2223 work very well with our scheme of creating menus on demand,
2224 and therefore we need to put these entries in a special
2225 invisible menu. (JMarc)
2228 /* The entries of our special mac menu. If we add support for
2229 * special entries in Menus, we could imagine something
2231 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
2232 * and therefore avoid hardcoding. I am not sure it is worth
2233 * the hassle, though. (JMarc)
2235 struct MacMenuEntry {
2239 QAction::MenuRole role;
2242 static const MacMenuEntry entries[] = {
2243 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2244 QAction::AboutRole},
2245 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2246 QAction::PreferencesRole},
2247 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2248 /* This doesn't work with Cocoa. */
2249 {LFUN_RECONFIGURE, "", "Reconfigure",
2250 QAction::ApplicationSpecificRole},
2252 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2254 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2255 const bool first_call = mac_special_menu_.empty();
2257 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2258 // the special menu for Menus. Fill it up only once.
2260 for (size_t i = 0 ; i < num_entries ; ++i) {
2261 FuncRequest const func(entries[i].action,
2262 from_utf8(entries[i].arg));
2263 mac_special_menu_.add(MenuItem(MenuItem::Command,
2264 entries[i].label, func));
2268 // add the entries to a QMenu that will eventually be empty
2269 // and therefore invisible.
2270 QMenu * qMenu = qmb->addMenu("special");
2272 for (MenuItem const & m : mac_special_menu_) {
2273 Action * action = new Action(m.func(), QIcon(), m.label(),
2275 action->setMenuRole(entries[i].role);
2276 qMenu->addAction(action);
2282 void Menus::Impl::expand(MenuDefinition const & frommenu,
2283 MenuDefinition & tomenu, BufferView const * bv) const
2285 if (!tomenu.empty())
2288 for (MenuDefinition::const_iterator cit = frommenu.begin();
2289 cit != frommenu.end() ; ++cit) {
2290 Buffer const * buf = bv ? &bv->buffer() : 0;
2291 switch (cit->kind()) {
2292 case MenuItem::Lastfiles:
2293 tomenu.expandLastfiles();
2296 case MenuItem::Documents:
2297 tomenu.expandDocuments();
2300 case MenuItem::Bookmarks:
2301 tomenu.expandBookmarks();
2304 case MenuItem::ImportFormats:
2305 case MenuItem::ViewFormats:
2306 case MenuItem::UpdateFormats:
2307 case MenuItem::ExportFormats:
2308 tomenu.expandFormats(cit->kind(), buf);
2311 case MenuItem::ExportFormat: {
2314 string const format = buf->params().getDefaultOutputFormat();
2315 Format const * f = theFormats().getFormat(format);
2316 docstring const name = f ? translateIfPossible(f->prettyname())
2317 : from_utf8(format);
2318 docstring const label = bformat(_("Export [%1$s]|E"), name);
2319 MenuItem item(MenuItem::Command, toqstr(label),
2320 FuncRequest(LFUN_BUFFER_EXPORT));
2321 tomenu.addWithStatusCheck(item);
2325 case MenuItem::CharStyles:
2326 tomenu.expandFlexInsert(buf, InsetLyXType::CHARSTYLE);
2329 case MenuItem::Custom:
2330 tomenu.expandFlexInsert(buf, InsetLyXType::CUSTOM);
2333 case MenuItem::FloatListInsert:
2334 tomenu.expandFloatListInsert(buf);
2337 case MenuItem::FloatInsert:
2338 tomenu.expandFloatInsert(buf);
2341 case MenuItem::PasteRecent:
2342 tomenu.expandPasteRecent(buf);
2345 case MenuItem::Toolbars:
2346 tomenu.expandToolbars();
2349 case MenuItem::Branches:
2350 tomenu.expandBranches(buf);
2353 case MenuItem::Indices:
2354 tomenu.expandIndices(buf);
2357 case MenuItem::IndicesContext:
2358 tomenu.expandIndicesContext(buf);
2361 case MenuItem::IndicesLists:
2362 tomenu.expandIndices(buf, true);
2365 case MenuItem::IndicesListsContext:
2366 tomenu.expandIndicesContext(buf, true);
2369 case MenuItem::CiteStyles:
2370 tomenu.expandCiteStyles(bv);
2373 case MenuItem::InfoArguments:
2374 tomenu.expandInfoArguments(bv);
2379 tomenu.expandToc(buf);
2382 case MenuItem::GraphicsGroups:
2383 tomenu.expandGraphicsGroups(bv);
2386 case MenuItem::SpellingSuggestions:
2387 tomenu.expandSpellingSuggestions(bv);
2390 case MenuItem::LanguageSelector:
2391 tomenu.expandLanguageSelector(buf);
2394 case MenuItem::Arguments:
2395 tomenu.expandArguments(bv, false);
2398 case MenuItem::SwitchArguments:
2399 tomenu.expandArguments(bv, true);
2402 case MenuItem::Captions:
2403 tomenu.expandCaptions(buf, false);
2406 case MenuItem::SwitchCaptions:
2407 tomenu.expandCaptions(buf, true);
2410 case MenuItem::EnvironmentSeparators:
2411 tomenu.expandEnvironmentSeparators(bv);
2414 case MenuItem::EnvironmentSeparatorsContext:
2415 tomenu.expandEnvironmentSeparators(bv, true);
2418 case MenuItem::SwitchQuotes:
2419 tomenu.expandQuotes(bv);
2422 case MenuItem::Submenu: {
2423 MenuItem item(*cit);
2424 item.setSubmenu(MenuDefinition(cit->submenuname()));
2425 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2426 tomenu.addWithStatusCheck(item);
2430 case MenuItem::Info:
2431 case MenuItem::Help:
2432 case MenuItem::Separator:
2433 tomenu.addWithStatusCheck(*cit);
2436 case MenuItem::Command:
2437 if (!mac_special_menu_.hasFunc(*cit->func()))
2438 tomenu.addWithStatusCheck(*cit);
2442 // we do not want the menu to end with a separator
2443 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2444 tomenu.items_.pop_back();
2446 // Check whether the shortcuts are unique
2447 tomenu.checkShortcuts();
2451 bool Menus::Impl::hasMenu(QString const & name) const
2453 return find_if(menulist_.begin(), menulist_.end(),
2454 MenuNamesEqual(name)) != menulist_.end();
2458 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2460 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2461 MenuNamesEqual(name));
2462 if (cit == menulist_.end()) {
2463 LYXERR0("No submenu named " << name);
2464 LASSERT(false, { static const MenuDefinition m; return m; });
2470 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2472 iterator it = find_if(menulist_.begin(), menulist_.end(),
2473 MenuNamesEqual(name));
2474 if (it == menulist_.end()) {
2475 LYXERR0("No submenu named " << name);
2476 LASSERT(false, { static MenuDefinition m; return m; });
2482 /////////////////////////////////////////////////////////////////////
2486 /////////////////////////////////////////////////////////////////////
2488 Menus::Menus() : d(new Impl) {}
2504 void Menus::read(Lexer & lex)
2512 LexerKeyword menutags[] = {
2513 { "end", md_endmenuset },
2514 { "menu", md_menu },
2515 { "menubar", md_menubar }
2518 // consistency check
2519 if (compare_ascii_no_case(lex.getString(), "menuset"))
2520 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2522 lex.pushTable(menutags);
2523 lex.setContext("Menus::read");
2527 while (lex.isOK() && !quit) {
2528 switch (lex.lex()) {
2530 d->menubar_.read(lex);
2534 QString const name = toqstr(lex.getDocString());
2535 if (d->hasMenu(name))
2536 d->getMenu(name).read(lex);
2538 MenuDefinition menu(name);
2540 d->menulist_.push_back(menu);
2548 lex.printError("Unknown menu tag");
2556 bool Menus::searchMenu(FuncRequest const & func,
2557 docstring_list & names, BufferView const * bv) const
2559 MenuDefinition menu;
2560 d->expand(d->menubar_, menu, bv);
2561 return menu.searchMenu(func, names);
2565 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2569 // setup special mac specific menu items, but only do this
2570 // the first time a QMenuBar is created. Otherwise Qt will
2571 // create duplicate items in the application menu. It seems
2572 // that Qt does not remove them when the QMenubar is cleared.
2573 d->macxMenuBarInit(qmb);
2576 // Clear all menubar contents before filling it.
2578 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2579 d->macxMenuBarInit(qmb);
2583 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2585 if (d->menubar_.empty()) {
2586 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2587 << d->menubar_.name());
2590 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2592 MenuDefinition menu;
2593 BufferView * bv = 0;
2595 bv = view->currentBufferView();
2596 d->expand(d->menubar_, menu, bv);
2598 MenuDefinition::const_iterator m = menu.begin();
2599 MenuDefinition::const_iterator end = menu.end();
2601 for (; m != end; ++m) {
2603 if (m->kind() != MenuItem::Submenu) {
2604 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2608 LYXERR(Debug::GUI, "menu bar item " << m->label()
2609 << " is a submenu named " << m->submenuname());
2611 QString name = m->submenuname();
2612 if (!d->hasMenu(name)) {
2613 LYXERR(Debug::GUI, "\tERROR: " << name
2614 << " submenu has no menu!");
2618 Menu * menuptr = new Menu(view, m->submenuname(), true);
2619 menuptr->setTitle(label(*m));
2621 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2622 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2623 // so we create a temporary one here
2624 QAction * action = new QAction(menuptr);
2625 menuptr->addAction(action);
2628 qmb->addMenu(menuptr);
2630 d->name_map_[view][name] = menuptr;
2635 void Menus::updateMenu(Menu * qmenu)
2637 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2640 if (qmenu->d->name.isEmpty())
2643 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2644 MenuDefinition fromLyxMenu(qmenu->d->name);
2645 while (!identifier.empty()) {
2646 docstring menu_name;
2647 identifier = split(identifier, menu_name, ';');
2649 if (!d->hasMenu(toqstr(menu_name))) {
2650 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2655 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2656 //FIXME: 50 is a wild guess. We should take into account here
2657 //the expansion of menu items, disabled optional items etc.
2658 bool const in_sub_menu = !fromLyxMenu.empty()
2659 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2661 fromLyxMenu.catSub(menu_name);
2663 fromLyxMenu.cat(cat_menu);
2664 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2667 if (fromLyxMenu.empty()) {
2668 qmenu->addAction(qt_("No Action Defined!"));
2672 BufferView * bv = 0;
2674 bv = qmenu->d->view->currentBufferView();
2675 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2676 qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2680 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2682 LYXERR(Debug::GUI, "Context menu requested: " << name);
2683 Menu * menu = d->name_map_[&view].value(name, 0);
2684 if (!menu && !name.startsWith("context-")) {
2685 LYXERR0("requested context menu not found: " << name);
2689 menu = new Menu(&view, name, true, keyboard);
2690 d->name_map_[&view][name] = menu;
2694 } // namespace frontend
2697 #include "moc_Menus.cpp"