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 "ParIterator.h"
52 #include "SpellChecker.h"
53 #include "TextClass.h"
54 #include "TocBackend.h"
56 #include "WordLangTuple.h"
58 #include "insets/Inset.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetGraphics.h"
62 #include "support/lassert.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/docstring_list.h"
66 #include "support/filetools.h"
67 #include "support/gettext.h"
68 #include "support/lstrings.h"
75 #if QT_VERSION >= 0x040600
76 #include <QProxyStyle>
79 #include "support/shared_ptr.h"
85 using namespace lyx::support;
93 // MacOSX specific stuff is at the end.
100 /// The type of elements that can be in a menu
108 /** This type of item explains why something is unavailable. If this
109 menuitem is in a submenu, the submenu is enabled to make sure the
110 user sees the information. */
112 /** This type of item merely shows that there might be a list or
113 something alike at this position, but the list is still empty.
114 If this item is in a submenu, the submenu will not always be
117 /** This is the list of last opened file,
118 typically for the File menu. */
120 /** This is the list of opened Documents,
121 typically for the Documents menu. */
123 /** This is the bookmarks */
127 /** This is a list of viewable formats
128 typically for the File->View menu. */
130 /** This is a list of updatable formats
131 typically for the File->Update menu. */
133 /** This is a list of exportable formats
134 typically for the File->Export menu. */
136 /** This is a list of importable formats
137 typically for the File->Import menu. */
139 /** This is the list of elements available
140 * for insertion into document. */
142 /** This is the list of user-configurable
143 insets to insert into document */
145 /** This is the list of XML elements to
146 insert into the document */
148 /** This is the list of floats that we can
149 insert a list for. */
151 /** This is the list of floats that we can
154 /** This is the list of selections that can
159 /** Available branches in document */
161 /** Available indices in document */
163 /** Context menu for indices in document */
165 /** Available index lists in document */
167 /** Context menu for available indices lists in document */
169 /** Available citation styles for a given citation */
171 /** Available graphics groups */
173 /// Words suggested by the spellchecker.
175 /** Used Languages */
177 /** This is the list of arguments available
178 for insertion into the current layout. */
182 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
185 QString const & label,
186 QString const & submenu = QString(),
187 QString const & tooltip = QString(),
188 bool optional = false)
189 : kind_(kind), label_(label), submenuname_(submenu),
190 tooltip_(tooltip), optional_(optional)
192 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
196 QString const & label,
197 FuncRequest const & func,
198 QString const & tooltip = QString(),
199 bool optional = false,
200 FuncRequest::Origin origin = FuncRequest::MENU)
201 : kind_(kind), label_(label), func_(func),
202 tooltip_(tooltip), optional_(optional)
204 func_.setOrigin(origin);
207 // shared_ptr<MenuDefinition> needs this apprently...
210 /// The label of a given menuitem
211 QString label() const
213 int const index = label_.lastIndexOf('|');
214 return index == -1 ? label_ : label_.left(index);
217 /// The keyboard shortcut (usually underlined in the entry)
218 QString shortcut() const
220 int const index = label_.lastIndexOf('|');
221 return index == -1 ? QString() : label_.mid(index + 1);
223 /// The complete label, with label and shortcut separated by a '|'
224 QString fulllabel() const { return label_; }
225 /// The kind of entry
226 Kind kind() const { return kind_; }
227 /// the action (if relevant)
228 FuncRequest const & func() const { return func_; }
230 QString const & tooltip() const { return tooltip_; }
231 /// returns true if the entry should be omitted when disabled
232 bool optional() const { return optional_; }
233 /// returns the status of the lfun associated with this entry
234 FuncStatus const & status() const { return status_; }
235 /// returns the status of the lfun associated with this entry
236 FuncStatus & status() { return status_; }
237 /// returns the status of the lfun associated with this entry
238 void status(FuncStatus const & status) { status_ = status; }
240 ///returns the binding associated to this action.
241 QString binding() const
243 if (kind_ != Command)
245 // Get the keys bound to this action, but keep only the
247 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
248 if (!bindings.empty())
249 return toqstr(bindings.begin()->print(KeySequence::ForGui));
251 LYXERR(Debug::KBMAP, "No binding for "
252 << lyxaction.getActionName(func_.action())
253 << '(' << func_.argument() << ')');
257 /// the description of the submenu (if relevant)
258 QString const & submenuname() const { return submenuname_; }
259 /// set the description of the submenu
260 void submenuname(QString const & name) { submenuname_ = name; }
262 bool hasSubmenu() const { return !submenu_.isEmpty(); }
264 MenuDefinition const & submenu() const { return submenu_.at(0); }
265 MenuDefinition & submenu() { return submenu_[0]; }
267 void setSubmenu(MenuDefinition const & menu)
270 submenu_.append(menu);
281 QString submenuname_;
288 /// contains 0 or 1 item.
289 QList<MenuDefinition> submenu_;
293 class MenuDefinition {
296 typedef std::vector<MenuItem> ItemList;
298 typedef ItemList::const_iterator const_iterator;
300 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
305 QString const & name() const { return name_; }
307 bool empty() const { return items_.empty(); }
308 /// Clear the menu content.
309 void clear() { items_.clear(); }
311 size_t size() const { return items_.size(); }
313 MenuItem const & operator[](size_t) const;
315 const_iterator begin() const { return items_.begin(); }
317 const_iterator end() const { return items_.end(); }
319 void cat(MenuDefinition const & other);
321 void catSub(docstring const & name);
323 // search for func in this menu iteratively, and put menu
325 bool searchMenu(FuncRequest const & func, docstring_list & names)
328 bool hasFunc(FuncRequest const &) const;
329 /// Add the menu item unconditionally
330 void add(MenuItem const & item) { items_.push_back(item); }
331 /// Checks the associated FuncRequest status before adding the
333 void addWithStatusCheck(MenuItem const &);
334 // Check whether the menu shortcuts are unique
335 void checkShortcuts() const;
337 void expandLastfiles();
338 void expandDocuments();
339 void expandBookmarks();
340 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
341 void expandFloatListInsert(Buffer const * buf);
342 void expandFloatInsert(Buffer const * buf);
343 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
344 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
345 void expandToc(Buffer const * buf);
346 void expandPasteRecent(Buffer const * buf);
347 void expandToolbars();
348 void expandBranches(Buffer const * buf);
349 void expandIndices(Buffer const * buf, bool listof = false);
350 void expandIndicesContext(Buffer const * buf, bool listof = false);
351 void expandCiteStyles(BufferView const *);
352 void expandGraphicsGroups(BufferView const *);
353 void expandSpellingSuggestions(BufferView const *);
354 void expandLanguageSelector(Buffer const * buf);
355 void expandArguments(BufferView const *);
363 /// Helper for std::find_if
367 MenuNamesEqual(QString const & name) : name_(name) {}
368 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
375 typedef std::vector<MenuDefinition> MenuList;
377 typedef MenuList::const_iterator const_iterator;
379 typedef MenuList::iterator iterator;
381 /////////////////////////////////////////////////////////////////////
382 // MenuDefinition implementation
383 /////////////////////////////////////////////////////////////////////
385 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
389 case MenuItem::Command: {
390 FuncStatus status = lyx::getStatus(i.func());
391 if (status.unknown() || (!status.enabled() && i.optional()))
394 items_.back().status(status);
398 case MenuItem::Submenu: {
399 bool enabled = false;
400 if (i.hasSubmenu()) {
401 for (const_iterator cit = i.submenu().begin();
402 cit != i.submenu().end(); ++cit) {
403 // Only these kind of items affect the status of the submenu
404 if ((cit->kind() == MenuItem::Command
405 || cit->kind() == MenuItem::Submenu
406 || cit->kind() == MenuItem::Help)
407 && cit->status().enabled()) {
413 if (enabled || !i.optional()) {
415 items_.back().status().setEnabled(enabled);
420 case MenuItem::Separator:
421 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
431 void MenuDefinition::read(Lexer & lex)
448 md_indiceslistscontext,
462 md_spellingsuggestions,
467 LexerKeyword menutags[] = {
468 { "arguments", md_arguments },
469 { "bookmarks", md_bookmarks },
470 { "branches", md_branches },
471 { "charstyles", md_charstyles },
472 { "citestyles", md_citestyles },
473 { "custom", md_custom },
474 { "documents", md_documents },
475 { "elements", md_elements },
476 { "end", md_endmenu },
477 { "exportformats", md_exportformats },
478 { "floatinsert", md_floatinsert },
479 { "floatlistinsert", md_floatlistinsert },
480 { "graphicsgroups", md_graphicsgroups },
481 { "importformats", md_importformats },
482 { "indices", md_indices },
483 { "indicescontext", md_indicescontext },
484 { "indiceslists", md_indiceslists },
485 { "indiceslistscontext", md_indiceslistscontext },
487 { "languageselector", md_languageselector },
488 { "lastfiles", md_lastfiles },
489 { "optitem", md_optitem },
490 { "optsubmenu", md_optsubmenu },
491 { "pasterecent", md_pasterecent },
492 { "separator", md_separator },
493 { "spellingsuggestions", md_spellingsuggestions },
494 { "submenu", md_submenu },
496 { "toolbars", md_toolbars },
497 { "updateformats", md_updateformats },
498 { "viewformats", md_viewformats }
501 lex.pushTable(menutags);
502 lex.setContext("MenuDefinition::read: ");
505 bool optional = false;
507 while (lex.isOK() && !quit) {
511 // fallback to md_item
514 docstring const name = translateIfPossible(lex.getDocString());
516 string const command = lex.getString();
517 FuncRequest func = lyxaction.lookupFunc(command);
518 FuncRequest::Origin origin = FuncRequest::MENU;
519 if (name_.startsWith("context-toc-"))
520 origin = FuncRequest::TOC;
521 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
527 add(MenuItem(MenuItem::Separator));
531 add(MenuItem(MenuItem::Lastfiles));
535 add(MenuItem(MenuItem::CharStyles));
539 add(MenuItem(MenuItem::Custom));
543 add(MenuItem(MenuItem::Elements));
547 add(MenuItem(MenuItem::Documents));
551 add(MenuItem(MenuItem::Bookmarks));
555 add(MenuItem(MenuItem::Toc));
559 add(MenuItem(MenuItem::ViewFormats));
562 case md_updateformats:
563 add(MenuItem(MenuItem::UpdateFormats));
566 case md_exportformats:
567 add(MenuItem(MenuItem::ExportFormats));
570 case md_importformats:
571 add(MenuItem(MenuItem::ImportFormats));
574 case md_floatlistinsert:
575 add(MenuItem(MenuItem::FloatListInsert));
579 add(MenuItem(MenuItem::FloatInsert));
583 add(MenuItem(MenuItem::PasteRecent));
587 add(MenuItem(MenuItem::Toolbars));
591 add(MenuItem(MenuItem::Branches));
595 add(MenuItem(MenuItem::CiteStyles));
598 case md_graphicsgroups:
599 add(MenuItem(MenuItem::GraphicsGroups));
602 case md_spellingsuggestions:
603 add(MenuItem(MenuItem::SpellingSuggestions));
606 case md_languageselector:
607 add(MenuItem(MenuItem::LanguageSelector));
611 add(MenuItem(MenuItem::Indices));
614 case md_indicescontext:
615 add(MenuItem(MenuItem::IndicesContext));
618 case md_indiceslists:
619 add(MenuItem(MenuItem::IndicesLists));
622 case md_indiceslistscontext:
623 add(MenuItem(MenuItem::IndicesListsContext));
627 add(MenuItem(MenuItem::Arguments));
632 // fallback to md_submenu
635 docstring const mlabel = translateIfPossible(lex.getDocString());
637 docstring const mname = lex.getDocString();
638 add(MenuItem(MenuItem::Submenu,
639 toqstr(mlabel), toqstr(mname), QString(), optional));
649 lex.printError("Unknown menu tag");
657 MenuItem const & MenuDefinition::operator[](size_type i) const
663 bool MenuDefinition::hasFunc(FuncRequest const & func) const
665 for (const_iterator it = begin(), et = end(); it != et; ++it)
666 if (it->func() == func)
672 void MenuDefinition::catSub(docstring const & name)
674 add(MenuItem(MenuItem::Submenu,
675 qt_("More...|M"), toqstr(name), QString(), false));
678 void MenuDefinition::cat(MenuDefinition const & other)
680 const_iterator et = other.end();
681 for (const_iterator it = other.begin(); it != et; ++it)
686 void MenuDefinition::checkShortcuts() const
688 // This is a quadratic algorithm, but we do not care because
689 // menus are short enough
690 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
691 QString shortcut = it1->shortcut();
692 if (shortcut.isEmpty())
694 if (!it1->label().contains(shortcut))
695 LYXERR0("Menu warning: menu entry \""
697 << "\" does not contain shortcut `"
698 << shortcut << "'.");
699 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
700 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
701 LYXERR0("Menu warning: menu entries "
702 << '"' << it1->fulllabel()
703 << "\" and \"" << it2->fulllabel()
704 << "\" share the same shortcut.");
711 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
713 const_iterator m = begin();
714 const_iterator m_end = end();
715 for (; m != m_end; ++m) {
716 if (m->kind() == MenuItem::Command && m->func() == func) {
717 names.push_back(qstring_to_ucs4(m->label()));
720 if (m->kind() == MenuItem::Submenu) {
721 names.push_back(qstring_to_ucs4(m->label()));
722 if (!m->hasSubmenu()) {
723 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
724 << m->label() << " name=" << m->submenuname());
728 if (m->submenu().searchMenu(func, names))
737 QString limitStringLength(docstring const & str)
739 size_t const max_item_length = 45;
741 if (str.size() > max_item_length)
742 return toqstr(str.substr(0, max_item_length - 3) + "...");
748 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
753 graphics::getGraphicsGroups(bv->buffer(), grp);
757 set<string>::const_iterator it = grp.begin();
758 set<string>::const_iterator end = grp.end();
759 add(MenuItem(MenuItem::Command, qt_("No Group"),
760 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
761 for (; it != end; ++it) {
762 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
763 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
768 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
772 Cursor const & cur = bv->cursor();
776 docstring_list suggestions;
777 Paragraph const & par = cur.paragraph();
778 pos_type from = cur.pos();
780 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
782 case SpellChecker::UNKNOWN_WORD:
783 if (lyxrc.spellcheck_continuously) {
784 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
785 docstring const & selection = cur.selectionAsString(false);
786 if (!cur.selection() || selection == wl.word()) {
788 size_t m = 10; // first submenu index
789 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
790 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
791 for (; i != suggestions.size(); ++i) {
792 docstring const & suggestion = suggestions[i];
793 LYXERR(Debug::GUI, suggestion);
794 MenuItem w(MenuItem::Command, toqstr(suggestion),
795 FuncRequest(LFUN_WORD_REPLACE,
796 replace2string(suggestion, selection,
797 true, // case sensitive
801 false))); // find next
805 item.submenu().add(w);
810 add(MenuItem(MenuItem::Separator));
811 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
812 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
813 FuncRequest(LFUN_SPELLING_ADD, arg)));
814 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
815 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
819 case SpellChecker::LEARNED_WORD: {
820 LYXERR(Debug::GUI, "Learned Word.");
821 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
822 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
823 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
826 case SpellChecker::NO_DICTIONARY:
827 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
829 case SpellChecker::WORD_OK:
830 case SpellChecker::COMPOUND_WORD:
831 case SpellChecker::ROOT_FOUND:
832 case SpellChecker::IGNORED_WORD:
837 struct sortLanguageByName {
838 bool operator()(const Language * a, const Language * b) const {
839 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
843 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
848 std::set<Language const *> languages_buffer =
849 buf->masterBuffer()->getLanguages();
851 if (languages_buffer.size() < 2)
854 std::set<Language const *, sortLanguageByName> languages;
856 std::set<Language const *>::const_iterator const beg =
857 languages_buffer.begin();
858 for (std::set<Language const *>::const_iterator cit = beg;
859 cit != languages_buffer.end(); ++cit) {
860 languages.insert(*cit);
863 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
864 item.setSubmenu(MenuDefinition(qt_("Language")));
865 QString morelangs = qt_("More Languages ...|M");
866 QStringList accelerators;
867 if (morelangs.contains('|'))
868 accelerators.append(morelangs.section('|', -1));
869 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
870 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
871 cit != languages.end(); ++cit) {
872 QString label = qt_((*cit)->display());
873 // try to add an accelerator
874 bool success = false;
875 // try capitals first
876 for (int i = 0; i < label.size(); ++i) {
877 QChar const ch = label[i];
880 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
881 label = label + toqstr("|") + ch;
882 accelerators.append(ch);
887 // if all capitals are taken, try the rest
889 for (int i = 0; i < label.size(); ++i) {
890 if (label[i].isSpace())
892 QString const ch = QString(label[i]);
893 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
894 label = label + toqstr("|") + ch;
895 accelerators.append(ch);
900 MenuItem w(MenuItem::Command, label,
901 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
902 item.submenu().addWithStatusCheck(w);
904 item.submenu().add(MenuItem(MenuItem::Separator));
905 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
906 FuncRequest(LFUN_DIALOG_SHOW, "character")));
911 void MenuDefinition::expandLastfiles()
913 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
914 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
918 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
919 string const file = lfit->absFileName();
920 QString const short_path = toqstr(makeDisplayPath(file, 30));
921 QString const long_path = toqstr(makeDisplayPath(file));
924 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
926 label = QString("%1. %2").arg(ii).arg(short_path);
927 add(MenuItem(MenuItem::Command, label,
928 FuncRequest(LFUN_FILE_OPEN, file), long_path));
933 void MenuDefinition::expandDocuments()
935 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
936 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
938 Buffer * first = theBufferList().first();
940 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
946 if (!guiApp->currentView())
948 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
951 Buffer const & b = wa->bufferView().buffer();
952 QString label = toqstr(b.fileName().displayName(20));
956 label = QString::number(i) + ". " + label + '|' + QString::number(i);
957 add(MenuItem(MenuItem::Command, label,
958 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
965 // We cannot use a for loop as the buffer list cycles.
967 if (!(guiApp->currentView()
968 && guiApp->currentView()->workArea(*b))) {
969 QString label = toqstr(b->fileName().displayName(20));
973 label = QString::number(i) + ". " + label + '|' + QString::number(i);
974 item.submenu().add(MenuItem(MenuItem::Command, label,
975 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
978 b = theBufferList().next(b);
979 } while (b != first);
981 if (!item.submenu().empty())
986 void MenuDefinition::expandBookmarks()
988 lyx::BookmarksSection const & bm = theSession().bookmarks();
991 for (size_t i = 1; i <= bm.size(); ++i) {
993 string const file = bm.bookmark(i).filename.absFileName();
994 QString const label = QString("%1. %2|%3").arg(i)
995 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
996 add(MenuItem(MenuItem::Command, label,
997 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1002 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1006 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1008 if (!buf && kind != MenuItem::ImportFormats)
1011 typedef vector<Format const *> Formats;
1013 FuncCode action = LFUN_NOACTION;
1016 case MenuItem::ImportFormats:
1017 formats = theConverters().importableFormats();
1018 action = LFUN_BUFFER_IMPORT;
1020 case MenuItem::ViewFormats:
1021 formats = buf->params().exportableFormats(true);
1022 action = LFUN_BUFFER_VIEW;
1024 case MenuItem::UpdateFormats:
1025 formats = buf->params().exportableFormats(true);
1026 action = LFUN_BUFFER_UPDATE;
1028 case MenuItem::ExportFormats:
1029 formats = buf->params().exportableFormats(false);
1030 action = LFUN_BUFFER_EXPORT;
1033 LASSERT(false, /* */);
1037 bool const view_update = (kind == MenuItem::ViewFormats
1038 || kind == MenuItem::UpdateFormats);
1042 smenue = (kind == MenuItem::ViewFormats
1043 ? qt_("View (Other Formats)|F")
1044 : qt_("Update (Other Formats)|p"));
1045 MenuItem item(MenuItem::Submenu, smenue);
1046 item.setSubmenu(MenuDefinition(smenue));
1048 Formats::const_iterator fit = formats.begin();
1049 Formats::const_iterator end = formats.end();
1050 for (; fit != end ; ++fit) {
1051 if ((*fit)->dummy())
1054 docstring lab = from_utf8((*fit)->prettyname());
1055 docstring const scut = from_utf8((*fit)->shortcut());
1056 docstring const tmplab = lab;
1059 lab += char_type('|') + scut;
1060 docstring const lab_i18n = translateIfPossible(lab);
1061 docstring const shortcut = split(lab_i18n, lab, '|');
1063 bool const untranslated = (lab == lab_i18n);
1064 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1067 case MenuItem::ImportFormats:
1068 label += from_ascii("...");
1070 case MenuItem::ViewFormats:
1071 case MenuItem::UpdateFormats:
1072 if ((*fit)->name() == buf->params().getDefaultOutputFormat()) {
1073 docstring lbl = (kind == MenuItem::ViewFormats
1074 ? bformat(_("View [%1$s]|V"), label)
1075 : bformat(_("Update [%1$s]|U"), label));
1076 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1080 case MenuItem::ExportFormats:
1081 if (!(*fit)->inExportMenu())
1085 LASSERT(false, /* */);
1088 if (!shortcut.empty())
1089 label += '|' + shortcut;
1093 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1094 toqstr(label), FuncRequest(action, (*fit)->name())));
1096 item.submenu().add(MenuItem(MenuItem::Command, toqstr(label),
1097 FuncRequest(action, (*fit)->name())));
1100 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1101 FuncRequest(action, (*fit)->name())));
1103 add(MenuItem(MenuItem::Command, toqstr(label),
1104 FuncRequest(action, (*fit)->name())));
1112 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1117 FloatList const & floats = buf->params().documentClass().floats();
1118 FloatList::const_iterator cit = floats.begin();
1119 FloatList::const_iterator end = floats.end();
1121 for (; cit != end; ++cit) {
1122 if (!cit->second.usesFloatPkg()) {
1123 // Different floats could declare the same ListCommand. We only
1124 // want it on the list once, though.
1125 string const & list_cmd = cit->second.listCommand();
1126 if (list_cmd.empty())
1127 // we do not know how to generate such a list
1129 // This form of insert returns an iterator pointing to the newly
1130 // inserted element OR the existing element with that value, and
1131 // a bool indicating whether we inserted a new element. So we can
1132 // see if one is there and insert it if not all at once.
1133 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1137 string const & list_name = cit->second.listName();
1138 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1139 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1144 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1149 FloatList const & floats = buf->params().documentClass().floats();
1150 FloatList::const_iterator cit = floats.begin();
1151 FloatList::const_iterator end = floats.end();
1152 for (; cit != end; ++cit) {
1154 QString const label = qt_(cit->second.name());
1155 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1156 FuncRequest(LFUN_FLOAT_INSERT,
1157 cit->second.floattype())));
1162 void MenuDefinition::expandFlexInsert(
1163 Buffer const * buf, InsetLayout::InsetLyXType type)
1168 TextClass::InsetLayouts const & insetLayouts =
1169 buf->params().documentClass().insetLayouts();
1170 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1171 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1172 for (; cit != end; ++cit) {
1173 if (cit->second.lyxtype() == type) {
1174 docstring label = cit->first;
1175 // we remove the "Flex:" prefix, if it is present
1176 if (prefixIs(label, from_utf8("Flex:")))
1177 label = label.substr(5);
1178 addWithStatusCheck(MenuItem(MenuItem::Command,
1179 toqstr(translateIfPossible(label)),
1180 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1183 // FIXME This is a little clunky.
1184 if (items_.empty() && type == InsetLayout::CUSTOM)
1185 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1189 size_t const max_number_of_items = 25;
1191 void MenuDefinition::expandToc2(Toc const & toc_list,
1192 size_t from, size_t to, int depth)
1194 int shortcut_count = 0;
1196 // check whether depth is smaller than the smallest depth in toc.
1197 int min_depth = 1000;
1198 for (size_t i = from; i < to; ++i)
1199 min_depth = min(min_depth, toc_list[i].depth());
1200 if (min_depth > depth)
1203 if (to - from <= max_number_of_items) {
1204 for (size_t i = from; i < to; ++i) {
1205 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1206 label += limitStringLength(toc_list[i].str());
1207 if (toc_list[i].depth() == depth) {
1209 if (shortcut_count < 9) {
1210 if (label.contains(QString::number(shortcut_count + 1)))
1211 label += QString::number(++shortcut_count);
1214 add(MenuItem(MenuItem::Command, label,
1215 FuncRequest(toc_list[i].action())));
1220 size_t new_pos = pos + 1;
1221 while (new_pos < to && toc_list[new_pos].depth() > depth)
1224 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1225 label += limitStringLength(toc_list[pos].str());
1226 if (toc_list[pos].depth() == depth) {
1228 if (shortcut_count < 9) {
1229 if (label.contains(QString::number(shortcut_count + 1)))
1230 label += QString::number(++shortcut_count);
1233 if (new_pos == pos + 1) {
1234 add(MenuItem(MenuItem::Command,
1235 label, FuncRequest(toc_list[pos].action())));
1238 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
1239 MenuItem item(MenuItem::Submenu, label);
1240 item.setSubmenu(sub);
1249 void MenuDefinition::expandToc(Buffer const * buf)
1251 // To make things very cleanly, we would have to pass buf to
1252 // all MenuItem constructors and to expandToc2. However, we
1253 // know that all the entries in a TOC will be have status_ ==
1254 // OK, so we avoid this unnecessary overhead (JMarc)
1257 add(MenuItem(MenuItem::Info, qt_("<No Document Open>")));
1261 // Add an entry for the master doc if this is a child doc
1262 Buffer const * const master = buf->masterBuffer();
1263 if (buf != master) {
1264 ParIterator const pit = par_iterator_begin(master->inset());
1265 string const arg = convert<string>(pit->id());
1266 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1267 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1270 MenuDefinition other_lists;
1272 FloatList const & floatlist = buf->params().documentClass().floats();
1273 TocList const & toc_list = buf->tocBackend().tocs();
1274 TocList::const_iterator cit = toc_list.begin();
1275 TocList::const_iterator end = toc_list.end();
1276 for (; cit != end; ++cit) {
1277 // Handle this later
1278 if (cit->first == "tableofcontents")
1281 MenuDefinition submenu;
1282 if (cit->second.size() >= 30) {
1283 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1284 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1286 TocIterator ccit = cit->second.begin();
1287 TocIterator eend = cit->second.end();
1288 for (; ccit != eend; ++ccit) {
1289 submenu.add(MenuItem(MenuItem::Command,
1290 limitStringLength(ccit->str()) + '|',
1291 FuncRequest(ccit->action())));
1295 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1296 item.setSubmenu(submenu);
1297 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1298 // Those two types deserve to be in the main menu.
1299 item.setSubmenu(submenu);
1302 other_lists.add(item);
1304 if (!other_lists.empty()) {
1305 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1306 item.setSubmenu(other_lists);
1310 // Handle normal TOC
1311 cit = toc_list.find("tableofcontents");
1313 LYXERR(Debug::GUI, "No table of contents.");
1315 if (!cit->second.empty())
1316 expandToc2(cit->second, 0, cit->second.size(), 0);
1318 add(MenuItem(MenuItem::Info, qt_("<Empty Table of Contents>")));
1323 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1325 docstring_list const sel = cap::availableSelections(buf);
1327 docstring_list::const_iterator cit = sel.begin();
1328 docstring_list::const_iterator end = sel.end();
1330 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1331 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1332 FuncRequest(LFUN_PASTE, convert<string>(index))));
1337 void MenuDefinition::expandToolbars()
1339 MenuDefinition other_lists;
1340 // extracts the toolbars from the backend
1341 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1342 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1343 for (; cit != end; ++cit) {
1344 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1345 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1346 if (guiApp->toolbars().isMainToolbar(cit->name))
1349 other_lists.add(item);
1352 if (!other_lists.empty()) {
1353 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1354 item.setSubmenu(other_lists);
1360 void MenuDefinition::expandBranches(Buffer const * buf)
1365 BufferParams const & master_params = buf->masterBuffer()->params();
1366 BufferParams const & params = buf->params();
1367 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1368 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1372 BranchList::const_iterator cit = master_params.branchlist().begin();
1373 BranchList::const_iterator end = master_params.branchlist().end();
1375 for (int ii = 1; cit != end; ++cit, ++ii) {
1376 docstring label = cit->branch();
1378 label = convert<docstring>(ii) + ". " + label
1379 + char_type('|') + convert<docstring>(ii);
1381 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1382 FuncRequest(LFUN_BRANCH_INSERT,
1386 if (buf == buf->masterBuffer())
1389 MenuDefinition child_branches;
1391 BranchList::const_iterator ccit = params.branchlist().begin();
1392 BranchList::const_iterator cend = params.branchlist().end();
1394 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1395 docstring label = ccit->branch();
1397 label = convert<docstring>(ii) + ". " + label
1398 + char_type('|') + convert<docstring>(ii);
1400 label += char_type('|');
1401 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1403 FuncRequest(LFUN_BRANCH_INSERT,
1407 if (!child_branches.empty()) {
1408 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1409 item.setSubmenu(child_branches);
1415 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1420 BufferParams const & params = buf->masterBuffer()->params();
1421 if (!params.use_indices) {
1423 addWithStatusCheck(MenuItem(MenuItem::Command,
1424 qt_("Index List|I"),
1425 FuncRequest(LFUN_INDEX_PRINT,
1426 from_ascii("idx"))));
1428 addWithStatusCheck(MenuItem(MenuItem::Command,
1429 qt_("Index Entry|d"),
1430 FuncRequest(LFUN_INDEX_INSERT,
1431 from_ascii("idx"))));
1435 if (params.indiceslist().empty())
1438 IndicesList::const_iterator cit = params.indiceslist().begin();
1439 IndicesList::const_iterator end = params.indiceslist().end();
1441 for (int ii = 1; cit != end; ++cit, ++ii) {
1443 docstring const label =
1444 bformat(_("Index: %1$s"), cit->index());
1445 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1446 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1448 docstring const label =
1449 bformat(_("Index Entry (%1$s)"), cit->index());
1450 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1451 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1457 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1462 BufferParams const & params = buf->masterBuffer()->params();
1463 if (!params.use_indices || params.indiceslist().empty())
1466 IndicesList::const_iterator cit = params.indiceslist().begin();
1467 IndicesList::const_iterator end = params.indiceslist().end();
1469 for (int ii = 1; cit != end; ++cit, ++ii) {
1471 InsetCommandParams p(INDEX_PRINT_CODE);
1472 p["type"] = cit->shortcut();
1473 string const data = InsetCommand::params2string(p);
1474 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1475 FuncRequest(LFUN_INSET_MODIFY, data)));
1477 docstring const label =
1478 bformat(_("Index Entry (%1$s)"), cit->index());
1479 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1480 FuncRequest(LFUN_INSET_MODIFY,
1481 from_ascii("changetype ") + cit->shortcut())));
1487 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1492 Inset const * inset = bv->cursor().nextInset();
1493 if (!inset || inset->lyxCode() != CITE_CODE) {
1494 add(MenuItem(MenuItem::Command,
1495 qt_("No Citation in Scope!"),
1496 FuncRequest(LFUN_NOACTION)));
1499 InsetCommand const * citinset =
1500 static_cast<InsetCommand const *>(inset);
1502 Buffer const * buf = &bv->buffer();
1503 string const cmd = citinset->params().getCmdName();
1505 docstring const & key = citinset->getParam("key");
1507 add(MenuItem(MenuItem::Command,
1508 qt_("No citations selected!"),
1509 FuncRequest(LFUN_NOACTION)));
1513 docstring const & before = citinset->getParam("before");
1514 docstring const & after = citinset->getParam("after");
1516 size_t const n = cmd.size();
1517 bool const force = cmd[0] == 'C';
1518 bool const full = cmd[n] == '*';
1520 vector<docstring> const keys = getVectorFromString(key);
1522 vector<CitationStyle> const citeStyleList = buf->params().citeStyles();
1523 vector<docstring> citeStrings =
1524 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(),
1525 false, before, after, from_utf8("dialog"));
1527 vector<docstring>::const_iterator cit = citeStrings.begin();
1528 vector<docstring>::const_iterator end = citeStrings.end();
1530 for (int ii = 1; cit != end; ++cit, ++ii) {
1531 docstring label = *cit;
1532 CitationStyle cs = citeStyleList[ii - 1];
1533 cs.forceUpperCase &= force;
1534 cs.fullAuthorList &= full;
1535 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1536 FuncRequest(LFUN_INSET_MODIFY,
1537 "changetype " + from_utf8(citationStyleToString(cs)))));
1542 void MenuDefinition::expandArguments(BufferView const * bv)
1547 Inset const * inset = &bv->cursor().inset();
1548 Layout::LaTeXArgMap args;
1549 if (inset && bv->cursor().paragraph().layout().latexargs().empty())
1550 args = inset->getLayout().latexargs();
1552 args = bv->cursor().paragraph().layout().latexargs();
1555 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1556 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1557 for (; lait != laend; ++lait) {
1558 Layout::latexarg arg = (*lait).second;
1559 QString item = toqstr(translateIfPossible(arg.labelstring));
1560 if (!arg.shortcut.empty())
1561 item += "|" + toqstr(arg.shortcut);
1562 add(MenuItem(MenuItem::Command, item,
1563 FuncRequest(LFUN_ARGUMENT_INSERT,
1564 convert<docstring>((*lait).first))));
1571 /////////////////////////////////////////////////////////////////////
1572 // Menu::Impl definition and implementation
1573 /////////////////////////////////////////////////////////////////////
1577 /// populates the menu or one of its submenu
1578 /// This is used as a recursive function
1579 void populate(QMenu & qMenu, MenuDefinition const & menu);
1581 /// Only needed for top level menus.
1582 MenuDefinition * top_level_menu;
1585 /// the name of this menu
1591 /// Get a MenuDefinition item label from the menu backend
1592 static QString label(MenuItem const & mi)
1594 QString label = mi.label();
1595 label.replace("&", "&&");
1597 QString shortcut = mi.shortcut();
1598 if (!shortcut.isEmpty()) {
1599 int pos = label.indexOf(shortcut);
1601 //label.insert(pos, 1, char_type('&'));
1602 label.replace(pos, 0, "&");
1605 QString const binding = mi.binding();
1606 if (!binding.isEmpty())
1607 label += '\t' + binding;
1612 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1614 LYXERR(Debug::GUI, "populating menu " << menu.name());
1616 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1619 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1620 MenuDefinition::const_iterator m = menu.begin();
1621 MenuDefinition::const_iterator end = menu.end();
1622 for (; m != end; ++m) {
1623 if (m->kind() == MenuItem::Separator)
1624 qMenu.addSeparator();
1625 else if (m->kind() == MenuItem::Submenu) {
1626 QMenu * subMenu = qMenu.addMenu(label(*m));
1627 populate(*subMenu, m->submenu());
1628 subMenu->setEnabled(m->status().enabled());
1630 // we have a MenuItem::Command
1631 qMenu.addAction(new Action(view, QIcon(), label(*m),
1632 m->func(), m->tooltip(), &qMenu));
1637 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1638 class AlwaysMnemonicStyle : public QProxyStyle {
1640 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1641 QStyleHintReturn *returnData = 0) const
1643 if (hint == QStyle::SH_UnderlineShortcut)
1645 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1650 /////////////////////////////////////////////////////////////////////
1651 // Menu implementation
1652 /////////////////////////////////////////////////////////////////////
1654 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1655 : QMenu(gv), d(new Menu::Impl)
1657 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1659 setStyle(new AlwaysMnemonicStyle);
1663 d->top_level_menu = top_level? new MenuDefinition : 0;
1667 if (d->top_level_menu)
1668 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1674 delete d->top_level_menu;
1679 void Menu::updateView()
1681 guiApp->menus().updateMenu(this);
1687 QList<QAction *> items = actions();
1688 for (int i = 0; i != items.size(); ++i) {
1689 // QAction::menu() returns 0 if there's no submenu.
1690 delete items.at(i)->menu();
1696 /////////////////////////////////////////////////////////////////////
1697 // Menus::Impl definition and implementation
1698 /////////////////////////////////////////////////////////////////////
1700 struct Menus::Impl {
1702 bool hasMenu(QString const &) const;
1704 MenuDefinition & getMenu(QString const &);
1706 MenuDefinition const & getMenu(QString const &) const;
1708 /// Expands some special entries of the menu
1709 /** The entries with the following kind are expanded to a
1710 sequence of Command MenuItems: Lastfiles, Documents,
1711 ViewFormats, ExportFormats, UpdateFormats, Branches,
1714 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1715 BufferView const *) const;
1717 /// Initialize specific MACOS X menubar
1718 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1720 /// Mac special menu.
1721 /** This defines a menu whose entries list the FuncRequests
1722 that will be removed by expand() in other menus. This is
1723 used by the Qt/Mac code.
1725 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1726 such that the items will keep accessing the FuncRequests in
1727 the MenuDefinition. While Menus::Impl might be recreated,
1728 we keep mac_special_menu_ in memory by making it static.
1730 static MenuDefinition mac_special_menu_;
1735 MenuDefinition menubar_;
1737 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1739 /// name to menu for \c menu() method.
1744 MenuDefinition Menus::Impl::mac_special_menu_;
1748 Here is what the Qt documentation says about how a menubar is chosen:
1750 1) If the window has a QMenuBar then it is used. 2) If the window
1751 is a modal then its menubar is used. If no menubar is specified
1752 then a default menubar is used (as documented below) 3) If the
1753 window has no parent then the default menubar is used (as
1756 The above 3 steps are applied all the way up the parent window
1757 chain until one of the above are satisifed. If all else fails a
1758 default menubar will be created, the default menubar on Qt/Mac is
1759 an empty menubar, however you can create a different default
1760 menubar by creating a parentless QMenuBar, the first one created
1761 will thus be designated the default menubar, and will be used
1762 whenever a default menubar is needed.
1764 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1765 that this menubar will be used also when one of LyX' dialogs has
1768 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1770 /* Since Qt 4.2, the qt/mac menu code has special code for
1771 specifying the role of a menu entry. However, it does not
1772 work very well with our scheme of creating menus on demand,
1773 and therefore we need to put these entries in a special
1774 invisible menu. (JMarc)
1777 /* The entries of our special mac menu. If we add support for
1778 * special entries in Menus, we could imagine something
1780 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1781 * and therefore avoid hardcoding. I am not sure it is worth
1782 * the hassle, though. (JMarc)
1784 struct MacMenuEntry {
1788 QAction::MenuRole role;
1791 MacMenuEntry entries[] = {
1792 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1793 QAction::AboutRole},
1794 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1795 QAction::PreferencesRole},
1796 /* {LFUN_RECONFIGURE, "", "Reconfigure",
1797 QAction::ApplicationSpecificRole}, */
1798 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1800 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1801 const bool first_call = mac_special_menu_.empty();
1803 // the special menu for Menus. Fill it up only once.
1805 for (size_t i = 0 ; i < num_entries ; ++i) {
1806 FuncRequest const func(entries[i].action,
1807 from_utf8(entries[i].arg));
1808 mac_special_menu_.add(MenuItem(MenuItem::Command,
1809 entries[i].label, func));
1813 // add the entries to a QMenu that will eventually be empty
1814 // and therefore invisible.
1815 QMenu * qMenu = qmb->addMenu("special");
1816 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1817 MenuDefinition::const_iterator end = mac_special_menu_.end();
1818 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1819 #if defined(QT_MAC_USE_COCOA) && (QT_MAC_USE_COCOA > 0)
1820 if (first_call || entries[i].role != QAction::ApplicationSpecificRole) {
1821 Action * action = new Action(view, QIcon(), cit->label(),
1822 cit->func(), QString(), qMenu);
1823 action->setMenuRole(entries[i].role);
1824 qMenu->addAction(action);
1827 Action * action = new Action(view, QIcon(), cit->label(),
1828 cit->func(), QString(), qMenu);
1829 action->setMenuRole(entries[i].role);
1830 qMenu->addAction(action);
1836 void Menus::Impl::expand(MenuDefinition const & frommenu,
1837 MenuDefinition & tomenu, BufferView const * bv) const
1839 if (!tomenu.empty())
1842 for (MenuDefinition::const_iterator cit = frommenu.begin();
1843 cit != frommenu.end() ; ++cit) {
1844 Buffer const * buf = bv ? &bv->buffer() : 0;
1845 switch (cit->kind()) {
1846 case MenuItem::Lastfiles:
1847 tomenu.expandLastfiles();
1850 case MenuItem::Documents:
1851 tomenu.expandDocuments();
1854 case MenuItem::Bookmarks:
1855 tomenu.expandBookmarks();
1858 case MenuItem::ImportFormats:
1859 case MenuItem::ViewFormats:
1860 case MenuItem::UpdateFormats:
1861 case MenuItem::ExportFormats:
1862 tomenu.expandFormats(cit->kind(), buf);
1865 case MenuItem::CharStyles:
1866 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1869 case MenuItem::Custom:
1870 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1873 case MenuItem::Elements:
1874 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1877 case MenuItem::FloatListInsert:
1878 tomenu.expandFloatListInsert(buf);
1881 case MenuItem::FloatInsert:
1882 tomenu.expandFloatInsert(buf);
1885 case MenuItem::PasteRecent:
1886 tomenu.expandPasteRecent(buf);
1889 case MenuItem::Toolbars:
1890 tomenu.expandToolbars();
1893 case MenuItem::Branches:
1894 tomenu.expandBranches(buf);
1897 case MenuItem::Indices:
1898 tomenu.expandIndices(buf);
1901 case MenuItem::IndicesContext:
1902 tomenu.expandIndicesContext(buf);
1905 case MenuItem::IndicesLists:
1906 tomenu.expandIndices(buf, true);
1909 case MenuItem::IndicesListsContext:
1910 tomenu.expandIndicesContext(buf, true);
1913 case MenuItem::CiteStyles:
1914 tomenu.expandCiteStyles(bv);
1918 tomenu.expandToc(buf);
1921 case MenuItem::GraphicsGroups:
1922 tomenu.expandGraphicsGroups(bv);
1925 case MenuItem::SpellingSuggestions:
1926 tomenu.expandSpellingSuggestions(bv);
1929 case MenuItem::LanguageSelector:
1930 tomenu.expandLanguageSelector(buf);
1933 case MenuItem::Arguments:
1934 tomenu.expandArguments(bv);
1937 case MenuItem::Submenu: {
1938 MenuItem item(*cit);
1939 item.setSubmenu(MenuDefinition(cit->submenuname()));
1940 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1941 tomenu.addWithStatusCheck(item);
1945 case MenuItem::Info:
1946 case MenuItem::Help:
1947 case MenuItem::Separator:
1948 tomenu.addWithStatusCheck(*cit);
1951 case MenuItem::Command:
1952 if (!mac_special_menu_.hasFunc(cit->func()))
1953 tomenu.addWithStatusCheck(*cit);
1957 // we do not want the menu to end with a separator
1958 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1959 tomenu.items_.pop_back();
1961 // Check whether the shortcuts are unique
1962 tomenu.checkShortcuts();
1966 bool Menus::Impl::hasMenu(QString const & name) const
1968 return find_if(menulist_.begin(), menulist_.end(),
1969 MenuNamesEqual(name)) != menulist_.end();
1973 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1975 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1976 MenuNamesEqual(name));
1977 if (cit == menulist_.end())
1978 LYXERR0("No submenu named " << name);
1979 LASSERT(cit != menulist_.end(), /**/);
1984 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1986 iterator it = find_if(menulist_.begin(), menulist_.end(),
1987 MenuNamesEqual(name));
1988 if (it == menulist_.end())
1989 LYXERR0("No submenu named " << name);
1990 LASSERT(it != menulist_.end(), /**/);
1995 /////////////////////////////////////////////////////////////////////
1999 /////////////////////////////////////////////////////////////////////
2001 Menus::Menus() : d(new Impl) {}
2017 void Menus::read(Lexer & lex)
2025 LexerKeyword menutags[] = {
2026 { "end", md_endmenuset },
2027 { "menu", md_menu },
2028 { "menubar", md_menubar }
2031 // consistency check
2032 if (compare_ascii_no_case(lex.getString(), "menuset"))
2033 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2035 lex.pushTable(menutags);
2036 lex.setContext("Menus::read");
2040 while (lex.isOK() && !quit) {
2041 switch (lex.lex()) {
2043 d->menubar_.read(lex);
2047 QString const name = toqstr(lex.getDocString());
2048 if (d->hasMenu(name))
2049 d->getMenu(name).read(lex);
2051 MenuDefinition menu(name);
2053 d->menulist_.push_back(menu);
2061 lex.printError("Unknown menu tag");
2069 bool Menus::searchMenu(FuncRequest const & func,
2070 docstring_list & names) const
2072 MenuDefinition menu;
2073 d->expand(d->menubar_, menu, 0);
2074 return menu.searchMenu(func, names);
2078 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2082 // setup special mac specific menu items, but only do this
2083 // the first time a QMenuBar is created. Otherwise Qt will
2084 // create duplicate items in the application menu. It seems
2085 // that Qt does not remove them when the QMenubar is cleared.
2086 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2087 d->macxMenuBarInit(view, qmb);
2090 // Clear all menubar contents before filling it.
2094 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2096 if (d->menubar_.empty()) {
2097 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2098 << d->menubar_.name());
2101 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2103 MenuDefinition menu;
2104 BufferView * bv = 0;
2106 bv = view->currentBufferView();
2107 d->expand(d->menubar_, menu, bv);
2109 MenuDefinition::const_iterator m = menu.begin();
2110 MenuDefinition::const_iterator end = menu.end();
2112 for (; m != end; ++m) {
2114 if (m->kind() != MenuItem::Submenu) {
2115 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2119 LYXERR(Debug::GUI, "menu bar item " << m->label()
2120 << " is a submenu named " << m->submenuname());
2122 QString name = m->submenuname();
2123 if (!d->hasMenu(name)) {
2124 LYXERR(Debug::GUI, "\tERROR: " << name
2125 << " submenu has no menu!");
2129 Menu * menu = new Menu(view, m->submenuname(), true);
2130 menu->setTitle(label(*m));
2133 d->name_map_[view][name] = menu;
2138 void Menus::updateMenu(Menu * qmenu)
2140 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2143 if (qmenu->d->name.isEmpty())
2146 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2147 MenuDefinition fromLyxMenu(qmenu->d->name);
2148 while (!identifier.empty()) {
2149 docstring menu_name;
2150 identifier = split(identifier, menu_name, ';');
2152 if (!d->hasMenu(toqstr(menu_name))) {
2153 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2158 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2159 //FIXME: 50 is a wild guess. We should take into account here
2160 //the expansion of menu items, disabled optional items etc.
2161 bool const in_sub_menu = !fromLyxMenu.empty()
2162 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2164 fromLyxMenu.catSub(menu_name);
2166 fromLyxMenu.cat(cat_menu);
2167 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2170 if (fromLyxMenu.empty()) {
2171 qmenu->addAction(qt_("No Action Defined!"));
2175 BufferView * bv = 0;
2177 bv = qmenu->d->view->currentBufferView();
2178 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2179 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2183 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2185 LYXERR(Debug::GUI, "Context menu requested: " << name);
2186 Menu * menu = d->name_map_[&view].value(name, 0);
2187 if (!menu && !name.startsWith("context-")) {
2188 LYXERR0("requested context menu not found: " << name);
2192 menu = new Menu(&view, name, true, keyboard);
2193 d->name_map_[&view][name] = menu;
2197 } // namespace frontend
2200 #include "moc_Menus.cpp"