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"
44 #include "LyXAction.h"
48 #include "Paragraph.h"
49 #include "ParIterator.h"
51 #include "SpellChecker.h"
52 #include "TextClass.h"
53 #include "TocBackend.h"
55 #include "WordLangTuple.h"
57 #include "insets/Inset.h"
58 #include "insets/InsetCitation.h"
59 #include "insets/InsetGraphics.h"
61 #include "support/lassert.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/docstring_list.h"
65 #include "support/filetools.h"
66 #include "support/gettext.h"
67 #include "support/lstrings.h"
74 #if QT_VERSION >= 0x040600
75 #include <QProxyStyle>
78 #include "support/shared_ptr.h"
84 using namespace lyx::support;
92 // MacOSX specific stuff is at the end.
99 /// The type of elements that can be in a menu
107 /** This type of item explains why something is unavailable. If this
108 menuitem is in a submenu, the submenu is enabled to make sure the
109 user sees the information. */
111 /** This type of item merely shows that there might be a list or
112 something alike at this position, but the list is still empty.
113 If this item is in a submenu, the submenu will not always be
116 /** This is the list of last opened file,
117 typically for the File menu. */
119 /** This is the list of opened Documents,
120 typically for the Documents menu. */
122 /** This is the bookmarks */
126 /** This is a list of viewable formats
127 typically for the File->View menu. */
129 /** This is a list of updatable formats
130 typically for the File->Update menu. */
132 /** This is a list of exportable formats
133 typically for the File->Export menu. */
135 /** This is a list of importable formats
136 typically for the File->Import menu. */
138 /** This is the list of elements available
139 * for insertion into document. */
141 /** This is the list of user-configurable
142 insets to insert into document */
144 /** This is the list of XML elements to
145 insert into the document */
147 /** This is the list of floats that we can
148 insert a list for. */
150 /** This is the list of floats that we can
153 /** This is the list of selections that can
158 /** Available branches in document */
160 /** Available indices in document */
162 /** Context menu for indices in document */
164 /** Available index lists in document */
166 /** Context menu for available indices lists in document */
168 /** Available citation styles for a given citation */
170 /** Available graphics groups */
172 /// Words suggested by the spellchecker.
174 /** Used Languages */
178 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
181 QString const & label,
182 QString const & submenu = QString(),
183 QString const & tooltip = QString(),
184 bool optional = false)
185 : kind_(kind), label_(label), submenuname_(submenu),
186 tooltip_(tooltip), optional_(optional)
188 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
192 QString const & label,
193 FuncRequest const & func,
194 QString const & tooltip = QString(),
195 bool optional = false,
196 FuncRequest::Origin origin = FuncRequest::MENU)
197 : kind_(kind), label_(label), func_(func),
198 tooltip_(tooltip), optional_(optional)
200 func_.setOrigin(origin);
203 // shared_ptr<MenuDefinition> needs this apprently...
206 /// The label of a given menuitem
207 QString label() const
209 int const index = label_.lastIndexOf('|');
210 return index == -1 ? label_ : label_.left(index);
213 /// The keyboard shortcut (usually underlined in the entry)
214 QString shortcut() const
216 int const index = label_.lastIndexOf('|');
217 return index == -1 ? QString() : label_.mid(index + 1);
219 /// The complete label, with label and shortcut separated by a '|'
220 QString fulllabel() const { return label_; }
221 /// The kind of entry
222 Kind kind() const { return kind_; }
223 /// the action (if relevant)
224 FuncRequest const & func() const { return func_; }
226 QString const & tooltip() const { return tooltip_; }
227 /// returns true if the entry should be omitted when disabled
228 bool optional() const { return optional_; }
229 /// returns the status of the lfun associated with this entry
230 FuncStatus const & status() const { return status_; }
231 /// returns the status of the lfun associated with this entry
232 FuncStatus & status() { return status_; }
233 /// returns the status of the lfun associated with this entry
234 void status(FuncStatus const & status) { status_ = status; }
236 ///returns the binding associated to this action.
237 QString binding() const
239 if (kind_ != Command)
241 // Get the keys bound to this action, but keep only the
243 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
245 return toqstr(bindings.begin()->print(KeySequence::ForGui));
247 LYXERR(Debug::KBMAP, "No binding for "
248 << lyxaction.getActionName(func_.action())
249 << '(' << func_.argument() << ')');
253 /// the description of the submenu (if relevant)
254 QString const & submenuname() const { return submenuname_; }
255 /// set the description of the submenu
256 void submenuname(QString const & name) { submenuname_ = name; }
258 bool hasSubmenu() const { return !submenu_.isEmpty(); }
260 MenuDefinition const & submenu() const { return submenu_.at(0); }
261 MenuDefinition & submenu() { return submenu_[0]; }
263 void setSubmenu(MenuDefinition const & menu)
266 submenu_.append(menu);
277 QString submenuname_;
284 /// contains 0 or 1 item.
285 QList<MenuDefinition> submenu_;
289 class MenuDefinition {
292 typedef std::vector<MenuItem> ItemList;
294 typedef ItemList::const_iterator const_iterator;
296 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
301 QString const & name() const { return name_; }
303 bool empty() const { return items_.empty(); }
304 /// Clear the menu content.
305 void clear() { items_.clear(); }
307 size_t size() const { return items_.size(); }
309 MenuItem const & operator[](size_t) const;
311 const_iterator begin() const { return items_.begin(); }
313 const_iterator end() const { return items_.end(); }
315 void cat(MenuDefinition const & other);
317 void catSub(docstring const & name);
319 // search for func in this menu iteratively, and put menu
321 bool searchMenu(FuncRequest const & func, docstring_list & names)
324 bool hasFunc(FuncRequest const &) const;
325 /// Add the menu item unconditionally
326 void add(MenuItem const & item) { items_.push_back(item); }
327 /// Checks the associated FuncRequest status before adding the
329 void addWithStatusCheck(MenuItem const &);
330 // Check whether the menu shortcuts are unique
331 void checkShortcuts() const;
333 void expandLastfiles();
334 void expandDocuments();
335 void expandBookmarks();
336 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
337 void expandFloatListInsert(Buffer const * buf);
338 void expandFloatInsert(Buffer const * buf);
339 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
340 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
341 void expandToc(Buffer const * buf);
342 void expandPasteRecent(Buffer const * buf);
343 void expandToolbars();
344 void expandBranches(Buffer const * buf);
345 void expandIndices(Buffer const * buf, bool listof = false);
346 void expandIndicesContext(Buffer const * buf, bool listof = false);
347 void expandCiteStyles(BufferView const *);
348 void expandGraphicsGroups(BufferView const *);
349 void expandSpellingSuggestions(BufferView const *);
350 void expandLanguageSelector(Buffer const * buf);
358 /// Helper for std::find_if
362 MenuNamesEqual(QString const & name) : name_(name) {}
363 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
370 typedef std::vector<MenuDefinition> MenuList;
372 typedef MenuList::const_iterator const_iterator;
374 typedef MenuList::iterator iterator;
376 /////////////////////////////////////////////////////////////////////
377 // MenuDefinition implementation
378 /////////////////////////////////////////////////////////////////////
380 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
384 case MenuItem::Command: {
385 FuncStatus status = lyx::getStatus(i.func());
386 if (status.unknown() || (!status.enabled() && i.optional()))
389 items_.back().status(status);
393 case MenuItem::Submenu: {
394 bool enabled = false;
395 if (i.hasSubmenu()) {
396 for (const_iterator cit = i.submenu().begin();
397 cit != i.submenu().end(); ++cit) {
398 // Only these kind of items affect the status of the submenu
399 if ((cit->kind() == MenuItem::Command
400 || cit->kind() == MenuItem::Submenu
401 || cit->kind() == MenuItem::Help)
402 && cit->status().enabled()) {
408 if (enabled || !i.optional()) {
410 items_.back().status().setEnabled(enabled);
415 case MenuItem::Separator:
416 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
426 void MenuDefinition::read(Lexer & lex)
443 md_indiceslistscontext,
457 md_spellingsuggestions,
461 LexerKeyword menutags[] = {
462 { "bookmarks", md_bookmarks },
463 { "branches", md_branches },
464 { "charstyles", md_charstyles },
465 { "citestyles", md_citestyles },
466 { "custom", md_custom },
467 { "documents", md_documents },
468 { "elements", md_elements },
469 { "end", md_endmenu },
470 { "exportformats", md_exportformats },
471 { "floatinsert", md_floatinsert },
472 { "floatlistinsert", md_floatlistinsert },
473 { "graphicsgroups", md_graphicsgroups },
474 { "importformats", md_importformats },
475 { "indices", md_indices },
476 { "indicescontext", md_indicescontext },
477 { "indiceslists", md_indiceslists },
478 { "indiceslistscontext", md_indiceslistscontext },
480 { "languageselector", md_languageselector },
481 { "lastfiles", md_lastfiles },
482 { "optitem", md_optitem },
483 { "optsubmenu", md_optsubmenu },
484 { "pasterecent", md_pasterecent },
485 { "separator", md_separator },
486 { "spellingsuggestions", md_spellingsuggestions },
487 { "submenu", md_submenu },
489 { "toolbars", md_toolbars },
490 { "updateformats", md_updateformats },
491 { "viewformats", md_viewformats }
494 lex.pushTable(menutags);
495 lex.setContext("MenuDefinition::read: ");
498 bool optional = false;
500 while (lex.isOK() && !quit) {
504 // fallback to md_item
507 docstring const name = translateIfPossible(lex.getDocString());
509 string const command = lex.getString();
510 FuncRequest func = lyxaction.lookupFunc(command);
511 FuncRequest::Origin origin = FuncRequest::MENU;
512 if (name_.startsWith("context-toc-"))
513 origin = FuncRequest::TOC;
514 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
520 add(MenuItem(MenuItem::Separator));
524 add(MenuItem(MenuItem::Lastfiles));
528 add(MenuItem(MenuItem::CharStyles));
532 add(MenuItem(MenuItem::Custom));
536 add(MenuItem(MenuItem::Elements));
540 add(MenuItem(MenuItem::Documents));
544 add(MenuItem(MenuItem::Bookmarks));
548 add(MenuItem(MenuItem::Toc));
552 add(MenuItem(MenuItem::ViewFormats));
555 case md_updateformats:
556 add(MenuItem(MenuItem::UpdateFormats));
559 case md_exportformats:
560 add(MenuItem(MenuItem::ExportFormats));
563 case md_importformats:
564 add(MenuItem(MenuItem::ImportFormats));
567 case md_floatlistinsert:
568 add(MenuItem(MenuItem::FloatListInsert));
572 add(MenuItem(MenuItem::FloatInsert));
576 add(MenuItem(MenuItem::PasteRecent));
580 add(MenuItem(MenuItem::Toolbars));
584 add(MenuItem(MenuItem::Branches));
588 add(MenuItem(MenuItem::CiteStyles));
591 case md_graphicsgroups:
592 add(MenuItem(MenuItem::GraphicsGroups));
595 case md_spellingsuggestions:
596 add(MenuItem(MenuItem::SpellingSuggestions));
599 case md_languageselector:
600 add(MenuItem(MenuItem::LanguageSelector));
604 add(MenuItem(MenuItem::Indices));
607 case md_indicescontext:
608 add(MenuItem(MenuItem::IndicesContext));
611 case md_indiceslists:
612 add(MenuItem(MenuItem::IndicesLists));
615 case md_indiceslistscontext:
616 add(MenuItem(MenuItem::IndicesListsContext));
621 // fallback to md_submenu
624 docstring const mlabel = translateIfPossible(lex.getDocString());
626 docstring const mname = lex.getDocString();
627 add(MenuItem(MenuItem::Submenu,
628 toqstr(mlabel), toqstr(mname), QString(), optional));
638 lex.printError("Unknown menu tag");
646 MenuItem const & MenuDefinition::operator[](size_type i) const
652 bool MenuDefinition::hasFunc(FuncRequest const & func) const
654 for (const_iterator it = begin(), et = end(); it != et; ++it)
655 if (it->func() == func)
661 void MenuDefinition::catSub(docstring const & name)
663 add(MenuItem(MenuItem::Submenu,
664 qt_("More...|M"), toqstr(name), QString(), false));
667 void MenuDefinition::cat(MenuDefinition const & other)
669 const_iterator et = other.end();
670 for (const_iterator it = other.begin(); it != et; ++it)
675 void MenuDefinition::checkShortcuts() const
677 // This is a quadratic algorithm, but we do not care because
678 // menus are short enough
679 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
680 QString shortcut = it1->shortcut();
681 if (shortcut.isEmpty())
683 if (!it1->label().contains(shortcut))
684 LYXERR0("Menu warning: menu entry \""
686 << "\" does not contain shortcut `"
687 << shortcut << "'.");
688 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
689 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
690 LYXERR0("Menu warning: menu entries "
691 << '"' << it1->fulllabel()
692 << "\" and \"" << it2->fulllabel()
693 << "\" share the same shortcut.");
700 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
702 const_iterator m = begin();
703 const_iterator m_end = end();
704 for (; m != m_end; ++m) {
705 if (m->kind() == MenuItem::Command && m->func() == func) {
706 names.push_back(qstring_to_ucs4(m->label()));
709 if (m->kind() == MenuItem::Submenu) {
710 names.push_back(qstring_to_ucs4(m->label()));
711 if (!m->hasSubmenu()) {
712 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
713 << m->label() << " name=" << m->submenuname());
717 if (m->submenu().searchMenu(func, names))
726 bool compareFormat(Format const * p1, Format const * p2)
732 QString limitStringLength(docstring const & str)
734 size_t const max_item_length = 45;
736 if (str.size() > max_item_length)
737 return toqstr(str.substr(0, max_item_length - 3) + "...");
743 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
748 graphics::getGraphicsGroups(bv->buffer(), grp);
752 set<string>::const_iterator it = grp.begin();
753 set<string>::const_iterator end = grp.end();
754 add(MenuItem(MenuItem::Command, qt_("No Group"),
755 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
756 for (; it != end; it++) {
757 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
758 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
763 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
767 Cursor const & cur = bv->cursor();
771 docstring_list suggestions;
772 Paragraph const & par = cur.paragraph();
773 pos_type from = cur.pos();
775 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
777 case SpellChecker::UNKNOWN_WORD:
778 if (lyxrc.spellcheck_continuously) {
779 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
780 docstring const & selection = cur.selectionAsString(false);
781 if (!cur.selection() || selection == wl.word()) {
783 size_t m = 10; // first submenu index
784 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
785 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
786 for (; i != suggestions.size(); ++i) {
787 docstring const & suggestion = suggestions[i];
788 LYXERR(Debug::GUI, suggestion);
789 MenuItem w(MenuItem::Command, toqstr(suggestion),
790 FuncRequest(LFUN_WORD_REPLACE,
791 replace2string(suggestion, selection,
792 true, true, false, true, false)));
796 item.submenu().add(w);
801 add(MenuItem(MenuItem::Separator));
802 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
803 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
804 FuncRequest(LFUN_SPELLING_ADD, arg)));
805 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
806 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
810 case SpellChecker::LEARNED_WORD: {
811 LYXERR(Debug::GUI, "Learned Word.");
812 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
813 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
814 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
817 case SpellChecker::WORD_OK:
818 case SpellChecker::COMPOUND_WORD:
819 case SpellChecker::ROOT_FOUND:
820 case SpellChecker::IGNORED_WORD:
825 struct sortLanguageByName {
826 bool operator()(const Language * a, const Language * b) const {
827 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
831 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
836 std::set<Language const *> languages_buffer =
837 buf->masterBuffer()->getLanguages();
839 if (languages_buffer.size() < 2)
842 std::set<Language const *, sortLanguageByName> languages;
844 std::set<Language const *>::const_iterator const beg =
845 languages_buffer.begin();
846 for (std::set<Language const *>::const_iterator cit = beg;
847 cit != languages_buffer.end(); ++cit) {
848 languages.insert(*cit);
851 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
852 item.setSubmenu(MenuDefinition(qt_("Language")));
853 QString morelangs = qt_("More Languages ...|M");
854 QStringList accelerators;
855 if (morelangs.contains('|'))
856 accelerators.append(morelangs.section('|', -1));
857 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
858 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
859 cit != languages.end(); ++cit) {
860 QString label = qt_((*cit)->display());
861 // try to add an accelerator
862 bool success = false;
863 // try capitals first
864 for (int i = 0; i < label.size(); ++i) {
865 QChar const ch = label[i];
868 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
869 label = label + toqstr("|") + ch;
870 accelerators.append(ch);
875 // if all capitals are taken, try the rest
877 for (int i = 0; i < label.size(); ++i) {
878 if (label[i].isSpace())
880 QString const ch = QString(label[i]);
881 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
882 label = label + toqstr("|") + ch;
883 accelerators.append(ch);
888 MenuItem w(MenuItem::Command, label,
889 FuncRequest(LFUN_LANGUAGE, (*cit)->lang()));
890 item.submenu().addWithStatusCheck(w);
892 item.submenu().add(MenuItem(MenuItem::Separator));
893 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
894 FuncRequest(LFUN_DIALOG_SHOW, "character")));
899 void MenuDefinition::expandLastfiles()
901 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
902 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
906 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
907 string const file = lfit->absFileName();
908 QString const short_path = toqstr(makeDisplayPath(file, 30));
909 QString const long_path = toqstr(makeDisplayPath(file));
912 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
914 label = QString("%1. %2").arg(ii).arg(short_path);
915 add(MenuItem(MenuItem::Command, label,
916 FuncRequest(LFUN_FILE_OPEN, file), long_path));
921 void MenuDefinition::expandDocuments()
923 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
924 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
926 Buffer * first = theBufferList().first();
928 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
934 if (!guiApp->currentView())
936 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
939 Buffer const & b = wa->bufferView().buffer();
940 QString label = toqstr(b.fileName().displayName(20));
944 label = QString::number(i) + ". " + label + '|' + QString::number(i);
945 add(MenuItem(MenuItem::Command, label,
946 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
953 // We cannot use a for loop as the buffer list cycles.
955 bool const shown = guiApp->currentView()
956 ? guiApp->currentView()->workArea(*b) : false;
958 QString label = toqstr(b->fileName().displayName(20));
962 label = QString::number(i) + ". " + label + '|' + QString::number(i);
963 item.submenu().add(MenuItem(MenuItem::Command, label,
964 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
967 b = theBufferList().next(b);
968 } while (b != first);
970 if (!item.submenu().empty())
975 void MenuDefinition::expandBookmarks()
977 lyx::BookmarksSection const & bm = theSession().bookmarks();
980 for (size_t i = 1; i <= bm.size(); ++i) {
982 string const file = bm.bookmark(i).filename.absFileName();
983 QString const label = QString("%1. %2|%3").arg(i)
984 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
985 add(MenuItem(MenuItem::Command, label,
986 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
991 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
995 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
997 if (!buf && kind != MenuItem::ImportFormats)
1000 typedef vector<Format const *> Formats;
1002 FuncCode action = LFUN_NOACTION;
1005 case MenuItem::ImportFormats:
1006 formats = theConverters().importableFormats();
1007 action = LFUN_BUFFER_IMPORT;
1009 case MenuItem::ViewFormats:
1010 formats = buf->params().exportableFormats(true);
1011 action = LFUN_BUFFER_VIEW;
1013 case MenuItem::UpdateFormats:
1014 formats = buf->params().exportableFormats(true);
1015 action = LFUN_BUFFER_UPDATE;
1017 case MenuItem::ExportFormats:
1018 formats = buf->params().exportableFormats(false);
1019 action = LFUN_BUFFER_EXPORT;
1022 LASSERT(false, /* */);
1026 sort(formats.begin(), formats.end(), &compareFormat);
1028 bool const view_update = (kind == MenuItem::ViewFormats
1029 || kind == MenuItem::UpdateFormats);
1033 smenue = (kind == MenuItem::ViewFormats
1034 ? qt_("View (Other Formats)|F")
1035 : qt_("Update (Other Formats)|p"));
1036 MenuItem item(MenuItem::Submenu, smenue);
1037 item.setSubmenu(MenuDefinition(smenue));
1039 Formats::const_iterator fit = formats.begin();
1040 Formats::const_iterator end = formats.end();
1041 for (; fit != end ; ++fit) {
1042 if ((*fit)->dummy())
1045 docstring lab = from_utf8((*fit)->prettyname());
1046 docstring const scut = from_utf8((*fit)->shortcut());
1047 docstring const tmplab = lab;
1050 lab += char_type('|') + scut;
1051 docstring const lab_i18n = translateIfPossible(lab);
1052 docstring const shortcut = split(lab_i18n, lab, '|');
1054 bool const untranslated = (lab == lab_i18n);
1055 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1058 case MenuItem::ImportFormats:
1059 label += from_ascii("...");
1061 case MenuItem::ViewFormats:
1062 case MenuItem::UpdateFormats:
1063 if ((*fit)->name() == buf->params().getDefaultOutputFormat()) {
1064 docstring lbl = (kind == MenuItem::ViewFormats
1065 ? bformat(_("View [%1$s]|V"), label)
1066 : bformat(_("Update [%1$s]|U"), label));
1067 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1071 case MenuItem::ExportFormats:
1072 if (!(*fit)->inExportMenu())
1076 LASSERT(false, /* */);
1079 if (!shortcut.empty())
1080 label += '|' + shortcut;
1084 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1085 toqstr(label), FuncRequest(action, (*fit)->name())));
1087 item.submenu().add(MenuItem(MenuItem::Command, toqstr(label),
1088 FuncRequest(action, (*fit)->name())));
1091 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1092 FuncRequest(action, (*fit)->name())));
1094 add(MenuItem(MenuItem::Command, toqstr(label),
1095 FuncRequest(action, (*fit)->name())));
1103 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1108 FloatList const & floats = buf->params().documentClass().floats();
1109 FloatList::const_iterator cit = floats.begin();
1110 FloatList::const_iterator end = floats.end();
1112 for (; cit != end; ++cit) {
1113 if (!cit->second.usesFloatPkg()) {
1114 // Different floats could declare the same ListCommand. We only
1115 // want it on the list once, though.
1116 string const & list_cmd = cit->second.listCommand();
1117 if (list_cmd.empty())
1118 // we do not know how to generate such a list
1120 // This form of insert returns an iterator pointing to the newly
1121 // inserted element OR the existing element with that value, and
1122 // a bool indicating whether we inserted a new element. So we can
1123 // see if one is there and insert it if not all at once.
1124 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1128 string const & list_name = cit->second.listName();
1129 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1130 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1135 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1140 FloatList const & floats = buf->params().documentClass().floats();
1141 FloatList::const_iterator cit = floats.begin();
1142 FloatList::const_iterator end = floats.end();
1143 for (; cit != end; ++cit) {
1145 QString const label = qt_(cit->second.name());
1146 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1147 FuncRequest(LFUN_FLOAT_INSERT,
1148 cit->second.floattype())));
1153 void MenuDefinition::expandFlexInsert(
1154 Buffer const * buf, InsetLayout::InsetLyXType type)
1159 TextClass::InsetLayouts const & insetLayouts =
1160 buf->params().documentClass().insetLayouts();
1161 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1162 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1163 for (; cit != end; ++cit) {
1164 if (cit->second.lyxtype() == type) {
1165 docstring label = cit->first;
1166 // we remove the "Flex:" prefix, if it is present
1167 if (prefixIs(label, from_utf8("Flex:")))
1168 label = label.substr(5);
1169 addWithStatusCheck(MenuItem(MenuItem::Command,
1170 toqstr(translateIfPossible(label)),
1171 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1174 // FIXME This is a little clunky.
1175 if (items_.empty() && type == InsetLayout::CUSTOM)
1176 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1180 size_t const max_number_of_items = 25;
1182 void MenuDefinition::expandToc2(Toc const & toc_list,
1183 size_t from, size_t to, int depth)
1185 int shortcut_count = 0;
1187 // check whether depth is smaller than the smallest depth in toc.
1188 int min_depth = 1000;
1189 for (size_t i = from; i < to; ++i)
1190 min_depth = min(min_depth, toc_list[i].depth());
1191 if (min_depth > depth)
1194 if (to - from <= max_number_of_items) {
1195 for (size_t i = from; i < to; ++i) {
1196 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1197 label += limitStringLength(toc_list[i].str());
1198 if (toc_list[i].depth() == depth) {
1200 if (shortcut_count < 9) {
1201 if (label.contains(QString::number(shortcut_count + 1)))
1202 label += QString::number(++shortcut_count);
1205 add(MenuItem(MenuItem::Command, label,
1206 FuncRequest(toc_list[i].action())));
1211 size_t new_pos = pos + 1;
1212 while (new_pos < to && toc_list[new_pos].depth() > depth)
1215 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1216 label += limitStringLength(toc_list[pos].str());
1217 if (toc_list[pos].depth() == depth) {
1219 if (shortcut_count < 9) {
1220 if (label.contains(QString::number(shortcut_count + 1)))
1221 label += QString::number(++shortcut_count);
1224 if (new_pos == pos + 1) {
1225 add(MenuItem(MenuItem::Command,
1226 label, FuncRequest(toc_list[pos].action())));
1229 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
1230 MenuItem item(MenuItem::Submenu, label);
1231 item.setSubmenu(sub);
1240 void MenuDefinition::expandToc(Buffer const * buf)
1242 // To make things very cleanly, we would have to pass buf to
1243 // all MenuItem constructors and to expandToc2. However, we
1244 // know that all the entries in a TOC will be have status_ ==
1245 // OK, so we avoid this unnecessary overhead (JMarc)
1248 add(MenuItem(MenuItem::Info, qt_("<No Document Open>")));
1252 // Add an entry for the master doc if this is a child doc
1253 Buffer const * const master = buf->masterBuffer();
1254 if (buf != master) {
1255 ParIterator const pit = par_iterator_begin(master->inset());
1256 string const arg = convert<string>(pit->id());
1257 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1258 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1261 MenuDefinition other_lists;
1263 FloatList const & floatlist = buf->params().documentClass().floats();
1264 TocList const & toc_list = buf->tocBackend().tocs();
1265 TocList::const_iterator cit = toc_list.begin();
1266 TocList::const_iterator end = toc_list.end();
1267 for (; cit != end; ++cit) {
1268 // Handle this later
1269 if (cit->first == "tableofcontents")
1272 MenuDefinition submenu;
1273 if (cit->second.size() >= 30) {
1274 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1275 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1277 TocIterator ccit = cit->second.begin();
1278 TocIterator eend = cit->second.end();
1279 for (; ccit != eend; ++ccit) {
1280 submenu.add(MenuItem(MenuItem::Command,
1281 limitStringLength(ccit->str()) + '|',
1282 FuncRequest(ccit->action())));
1286 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1287 item.setSubmenu(submenu);
1288 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1289 // Those two types deserve to be in the main menu.
1290 item.setSubmenu(submenu);
1293 other_lists.add(item);
1295 if (!other_lists.empty()) {
1296 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1297 item.setSubmenu(other_lists);
1301 // Handle normal TOC
1302 cit = toc_list.find("tableofcontents");
1304 LYXERR(Debug::GUI, "No table of contents.");
1306 if (cit->second.size() > 0 )
1307 expandToc2(cit->second, 0, cit->second.size(), 0);
1309 add(MenuItem(MenuItem::Info, qt_("<Empty Table of Contents>")));
1314 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1316 docstring_list const sel = cap::availableSelections(buf);
1318 docstring_list::const_iterator cit = sel.begin();
1319 docstring_list::const_iterator end = sel.end();
1321 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1322 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1323 FuncRequest(LFUN_PASTE, convert<string>(index))));
1328 void MenuDefinition::expandToolbars()
1330 MenuDefinition other_lists;
1331 // extracts the toolbars from the backend
1332 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1333 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1334 for (; cit != end; ++cit) {
1335 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1336 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1337 if (guiApp->toolbars().isMainToolbar(cit->name))
1340 other_lists.add(item);
1343 if (!other_lists.empty()) {
1344 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1345 item.setSubmenu(other_lists);
1351 void MenuDefinition::expandBranches(Buffer const * buf)
1356 BufferParams const & master_params = buf->masterBuffer()->params();
1357 BufferParams const & params = buf->params();
1358 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1359 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1363 BranchList::const_iterator cit = master_params.branchlist().begin();
1364 BranchList::const_iterator end = master_params.branchlist().end();
1366 for (int ii = 1; cit != end; ++cit, ++ii) {
1367 docstring label = cit->branch();
1369 label = convert<docstring>(ii) + ". " + label
1370 + char_type('|') + convert<docstring>(ii);
1372 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1373 FuncRequest(LFUN_BRANCH_INSERT,
1377 if (buf == buf->masterBuffer())
1380 MenuDefinition child_branches;
1382 BranchList::const_iterator ccit = params.branchlist().begin();
1383 BranchList::const_iterator cend = params.branchlist().end();
1385 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1386 docstring label = ccit->branch();
1388 label = convert<docstring>(ii) + ". " + label
1389 + char_type('|') + convert<docstring>(ii);
1391 label += char_type('|');
1392 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1394 FuncRequest(LFUN_BRANCH_INSERT,
1398 if (!child_branches.empty()) {
1399 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1400 item.setSubmenu(child_branches);
1406 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1411 BufferParams const & params = buf->masterBuffer()->params();
1412 if (!params.use_indices) {
1414 addWithStatusCheck(MenuItem(MenuItem::Command,
1415 qt_("Index List|I"),
1416 FuncRequest(LFUN_INDEX_PRINT,
1417 from_ascii("idx"))));
1419 addWithStatusCheck(MenuItem(MenuItem::Command,
1420 qt_("Index Entry|d"),
1421 FuncRequest(LFUN_INDEX_INSERT,
1422 from_ascii("idx"))));
1426 if (params.indiceslist().empty())
1429 IndicesList::const_iterator cit = params.indiceslist().begin();
1430 IndicesList::const_iterator end = params.indiceslist().end();
1432 for (int ii = 1; cit != end; ++cit, ++ii) {
1434 docstring const label =
1435 bformat(_("Index: %1$s"), cit->index());
1436 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1437 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1439 docstring const label =
1440 bformat(_("Index Entry (%1$s)"), cit->index());
1441 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1442 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1448 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1453 BufferParams const & params = buf->masterBuffer()->params();
1454 if (!params.use_indices || params.indiceslist().empty())
1457 IndicesList::const_iterator cit = params.indiceslist().begin();
1458 IndicesList::const_iterator end = params.indiceslist().end();
1460 for (int ii = 1; cit != end; ++cit, ++ii) {
1462 InsetCommandParams p(INDEX_PRINT_CODE);
1463 p["type"] = cit->shortcut();
1464 string const data = InsetCommand::params2string(p);
1465 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1466 FuncRequest(LFUN_INSET_MODIFY, data)));
1468 docstring const label =
1469 bformat(_("Index Entry (%1$s)"), cit->index());
1470 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1471 FuncRequest(LFUN_INSET_MODIFY,
1472 from_ascii("changetype ") + cit->shortcut())));
1478 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1483 Inset const * inset = bv->cursor().nextInset();
1484 if (!inset || inset->lyxCode() != CITE_CODE) {
1485 add(MenuItem(MenuItem::Command,
1486 qt_("No Citation in Scope!"),
1487 FuncRequest(LFUN_NOACTION)));
1490 InsetCommand const * citinset =
1491 static_cast<InsetCommand const *>(inset);
1493 Buffer const * buf = &bv->buffer();
1494 docstring key = citinset->getParam("key");
1495 // we can only handle one key currently
1496 if (contains(key, ','))
1497 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1499 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1500 docstring_list citeStrings =
1501 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1503 docstring_list::const_iterator cit = citeStrings.begin();
1504 docstring_list::const_iterator end = citeStrings.end();
1506 for (int ii = 1; cit != end; ++cit, ++ii) {
1507 docstring label = *cit;
1509 CiteStyle cst = citeStyleList[ii - 1];
1511 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1512 FuncRequest(LFUN_INSET_MODIFY,
1513 "changetype " + from_utf8(citationStyleToString(cs)))));
1520 /////////////////////////////////////////////////////////////////////
1521 // Menu::Impl definition and implementation
1522 /////////////////////////////////////////////////////////////////////
1526 /// populates the menu or one of its submenu
1527 /// This is used as a recursive function
1528 void populate(QMenu & qMenu, MenuDefinition const & menu);
1530 /// Only needed for top level menus.
1531 MenuDefinition * top_level_menu;
1534 /// the name of this menu
1540 /// Get a MenuDefinition item label from the menu backend
1541 static QString label(MenuItem const & mi)
1543 QString label = mi.label();
1544 label.replace("&", "&&");
1546 QString shortcut = mi.shortcut();
1547 if (!shortcut.isEmpty()) {
1548 int pos = label.indexOf(shortcut);
1550 //label.insert(pos, 1, char_type('&'));
1551 label.replace(pos, 0, "&");
1554 QString const binding = mi.binding();
1555 if (!binding.isEmpty())
1556 label += '\t' + binding;
1561 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1563 LYXERR(Debug::GUI, "populating menu " << menu.name());
1564 if (menu.size() == 0) {
1565 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1568 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1569 MenuDefinition::const_iterator m = menu.begin();
1570 MenuDefinition::const_iterator end = menu.end();
1571 for (; m != end; ++m) {
1572 if (m->kind() == MenuItem::Separator)
1573 qMenu.addSeparator();
1574 else if (m->kind() == MenuItem::Submenu) {
1575 QMenu * subMenu = qMenu.addMenu(label(*m));
1576 populate(*subMenu, m->submenu());
1577 subMenu->setEnabled(m->status().enabled());
1579 // we have a MenuItem::Command
1580 qMenu.addAction(new Action(view, QIcon(), label(*m),
1581 m->func(), m->tooltip(), &qMenu));
1586 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1587 class AlwaysMnemonicStyle : public QProxyStyle {
1589 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1590 QStyleHintReturn *returnData = 0) const
1592 if (hint == QStyle::SH_UnderlineShortcut)
1594 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1599 /////////////////////////////////////////////////////////////////////
1600 // Menu implementation
1601 /////////////////////////////////////////////////////////////////////
1603 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1604 : QMenu(gv), d(new Menu::Impl)
1606 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1608 setStyle(new AlwaysMnemonicStyle);
1612 d->top_level_menu = top_level? new MenuDefinition : 0;
1616 if (d->top_level_menu)
1617 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1623 delete d->top_level_menu;
1628 void Menu::updateView()
1630 guiApp->menus().updateMenu(this);
1636 QList<QAction *> items = actions();
1637 for (int i = 0; i != items.size(); ++i) {
1638 // QAction::menu() returns 0 if there's no submenu.
1639 delete items.at(i)->menu();
1645 /////////////////////////////////////////////////////////////////////
1646 // Menus::Impl definition and implementation
1647 /////////////////////////////////////////////////////////////////////
1649 struct Menus::Impl {
1651 bool hasMenu(QString const &) const;
1653 MenuDefinition & getMenu(QString const &);
1655 MenuDefinition const & getMenu(QString const &) const;
1657 /// Expands some special entries of the menu
1658 /** The entries with the following kind are expanded to a
1659 sequence of Command MenuItems: Lastfiles, Documents,
1660 ViewFormats, ExportFormats, UpdateFormats, Branches, Indices
1662 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1663 BufferView const *) const;
1665 /// Initialize specific MACOS X menubar
1666 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1668 /// Mac special menu.
1669 /** This defines a menu whose entries list the FuncRequests
1670 that will be removed by expand() in other menus. This is
1671 used by the Qt/Mac code.
1673 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1674 such that the items will keep accessing the FuncRequests in
1675 the MenuDefinition. While Menus::Impl might be recreated,
1676 we keep mac_special_menu_ in memory by making it static.
1678 static MenuDefinition mac_special_menu_;
1683 MenuDefinition menubar_;
1685 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1687 /// name to menu for \c menu() method.
1692 MenuDefinition Menus::Impl::mac_special_menu_;
1696 Here is what the Qt documentation says about how a menubar is chosen:
1698 1) If the window has a QMenuBar then it is used. 2) If the window
1699 is a modal then its menubar is used. If no menubar is specified
1700 then a default menubar is used (as documented below) 3) If the
1701 window has no parent then the default menubar is used (as
1704 The above 3 steps are applied all the way up the parent window
1705 chain until one of the above are satisifed. If all else fails a
1706 default menubar will be created, the default menubar on Qt/Mac is
1707 an empty menubar, however you can create a different default
1708 menubar by creating a parentless QMenuBar, the first one created
1709 will thus be designated the default menubar, and will be used
1710 whenever a default menubar is needed.
1712 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1713 that this menubar will be used also when one of LyX' dialogs has
1716 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1718 /* Since Qt 4.2, the qt/mac menu code has special code for
1719 specifying the role of a menu entry. However, it does not
1720 work very well with our scheme of creating menus on demand,
1721 and therefore we need to put these entries in a special
1722 invisible menu. (JMarc)
1725 /* The entries of our special mac menu. If we add support for
1726 * special entries in Menus, we could imagine something
1728 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1729 * and therefore avoid hardcoding. I am not sure it is worth
1730 * the hassle, though. (JMarc)
1732 struct MacMenuEntry {
1736 QAction::MenuRole role;
1739 MacMenuEntry entries[] = {
1740 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1741 QAction::AboutRole},
1742 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1743 QAction::PreferencesRole},
1744 {LFUN_RECONFIGURE, "", "Reconfigure",
1745 QAction::ApplicationSpecificRole},
1746 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1748 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1749 const bool first_call = mac_special_menu_.size() == 0;
1751 // the special menu for Menus. Fill it up only once.
1753 for (size_t i = 0 ; i < num_entries ; ++i) {
1754 FuncRequest const func(entries[i].action,
1755 from_utf8(entries[i].arg));
1756 mac_special_menu_.add(MenuItem(MenuItem::Command,
1757 entries[i].label, func));
1761 // add the entries to a QMenu that will eventually be empty
1762 // and therefore invisible.
1763 QMenu * qMenu = qmb->addMenu("special");
1764 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1765 MenuDefinition::const_iterator end = mac_special_menu_.end();
1766 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1767 #if defined(QT_MAC_USE_COCOA) && (QT_MAC_USE_COCOA > 0)
1768 if (first_call || entries[i].role != QAction::ApplicationSpecificRole) {
1769 Action * action = new Action(view, QIcon(), cit->label(),
1770 cit->func(), QString(), qMenu);
1771 action->setMenuRole(entries[i].role);
1772 qMenu->addAction(action);
1775 Action * action = new Action(view, QIcon(), cit->label(),
1776 cit->func(), QString(), qMenu);
1777 action->setMenuRole(entries[i].role);
1778 qMenu->addAction(action);
1784 void Menus::Impl::expand(MenuDefinition const & frommenu,
1785 MenuDefinition & tomenu, BufferView const * bv) const
1787 if (!tomenu.empty())
1790 for (MenuDefinition::const_iterator cit = frommenu.begin();
1791 cit != frommenu.end() ; ++cit) {
1792 Buffer const * buf = bv ? &bv->buffer() : 0;
1793 switch (cit->kind()) {
1794 case MenuItem::Lastfiles:
1795 tomenu.expandLastfiles();
1798 case MenuItem::Documents:
1799 tomenu.expandDocuments();
1802 case MenuItem::Bookmarks:
1803 tomenu.expandBookmarks();
1806 case MenuItem::ImportFormats:
1807 case MenuItem::ViewFormats:
1808 case MenuItem::UpdateFormats:
1809 case MenuItem::ExportFormats:
1810 tomenu.expandFormats(cit->kind(), buf);
1813 case MenuItem::CharStyles:
1814 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1817 case MenuItem::Custom:
1818 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1821 case MenuItem::Elements:
1822 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1825 case MenuItem::FloatListInsert:
1826 tomenu.expandFloatListInsert(buf);
1829 case MenuItem::FloatInsert:
1830 tomenu.expandFloatInsert(buf);
1833 case MenuItem::PasteRecent:
1834 tomenu.expandPasteRecent(buf);
1837 case MenuItem::Toolbars:
1838 tomenu.expandToolbars();
1841 case MenuItem::Branches:
1842 tomenu.expandBranches(buf);
1845 case MenuItem::Indices:
1846 tomenu.expandIndices(buf);
1849 case MenuItem::IndicesContext:
1850 tomenu.expandIndicesContext(buf);
1853 case MenuItem::IndicesLists:
1854 tomenu.expandIndices(buf, true);
1857 case MenuItem::IndicesListsContext:
1858 tomenu.expandIndicesContext(buf, true);
1861 case MenuItem::CiteStyles:
1862 tomenu.expandCiteStyles(bv);
1866 tomenu.expandToc(buf);
1869 case MenuItem::GraphicsGroups:
1870 tomenu.expandGraphicsGroups(bv);
1873 case MenuItem::SpellingSuggestions:
1874 tomenu.expandSpellingSuggestions(bv);
1877 case MenuItem::LanguageSelector:
1878 tomenu.expandLanguageSelector(buf);
1881 case MenuItem::Submenu: {
1882 MenuItem item(*cit);
1883 item.setSubmenu(MenuDefinition(cit->submenuname()));
1884 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1885 tomenu.addWithStatusCheck(item);
1889 case MenuItem::Info:
1890 case MenuItem::Help:
1891 case MenuItem::Separator:
1892 tomenu.addWithStatusCheck(*cit);
1895 case MenuItem::Command:
1896 if (!mac_special_menu_.hasFunc(cit->func()))
1897 tomenu.addWithStatusCheck(*cit);
1901 // we do not want the menu to end with a separator
1902 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1903 tomenu.items_.pop_back();
1905 // Check whether the shortcuts are unique
1906 tomenu.checkShortcuts();
1910 bool Menus::Impl::hasMenu(QString const & name) const
1912 return find_if(menulist_.begin(), menulist_.end(),
1913 MenuNamesEqual(name)) != menulist_.end();
1917 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1919 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1920 MenuNamesEqual(name));
1921 if (cit == menulist_.end())
1922 LYXERR0("No submenu named " << name);
1923 LASSERT(cit != menulist_.end(), /**/);
1928 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1930 iterator it = find_if(menulist_.begin(), menulist_.end(),
1931 MenuNamesEqual(name));
1932 if (it == menulist_.end())
1933 LYXERR0("No submenu named " << name);
1934 LASSERT(it != menulist_.end(), /**/);
1939 /////////////////////////////////////////////////////////////////////
1943 /////////////////////////////////////////////////////////////////////
1945 Menus::Menus() : d(new Impl) {}
1961 void Menus::read(Lexer & lex)
1969 LexerKeyword menutags[] = {
1970 { "end", md_endmenuset },
1971 { "menu", md_menu },
1972 { "menubar", md_menubar }
1975 // consistency check
1976 if (compare_ascii_no_case(lex.getString(), "menuset"))
1977 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1979 lex.pushTable(menutags);
1980 lex.setContext("Menus::read");
1984 while (lex.isOK() && !quit) {
1985 switch (lex.lex()) {
1987 d->menubar_.read(lex);
1991 QString const name = toqstr(lex.getDocString());
1992 if (d->hasMenu(name))
1993 d->getMenu(name).read(lex);
1995 MenuDefinition menu(name);
1997 d->menulist_.push_back(menu);
2005 lex.printError("Unknown menu tag");
2013 bool Menus::searchMenu(FuncRequest const & func,
2014 docstring_list & names) const
2016 MenuDefinition menu;
2017 d->expand(d->menubar_, menu, 0);
2018 return menu.searchMenu(func, names);
2022 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2026 // setup special mac specific menu items, but only do this
2027 // the first time a QMenuBar is created. Otherwise Qt will
2028 // create duplicate items in the application menu. It seems
2029 // that Qt does not remove them when the QMenubar is cleared.
2030 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2031 d->macxMenuBarInit(view, qmb);
2034 // Clear all menubar contents before filling it.
2038 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2040 if (d->menubar_.size() == 0) {
2041 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2042 << d->menubar_.name());
2045 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2047 MenuDefinition menu;
2048 BufferView * bv = 0;
2050 bv = view->currentBufferView();
2051 d->expand(d->menubar_, menu, bv);
2053 MenuDefinition::const_iterator m = menu.begin();
2054 MenuDefinition::const_iterator end = menu.end();
2056 for (; m != end; ++m) {
2058 if (m->kind() != MenuItem::Submenu) {
2059 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2063 LYXERR(Debug::GUI, "menu bar item " << m->label()
2064 << " is a submenu named " << m->submenuname());
2066 QString name = m->submenuname();
2067 if (!d->hasMenu(name)) {
2068 LYXERR(Debug::GUI, "\tERROR: " << name
2069 << " submenu has no menu!");
2073 Menu * menu = new Menu(view, m->submenuname(), true);
2074 menu->setTitle(label(*m));
2077 d->name_map_[view][name] = menu;
2082 void Menus::updateMenu(Menu * qmenu)
2084 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2087 if (qmenu->d->name.isEmpty())
2090 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2091 MenuDefinition fromLyxMenu(qmenu->d->name);
2092 while (!identifier.empty()) {
2093 docstring menu_name;
2094 identifier = split(identifier, menu_name, ';');
2096 if (!d->hasMenu(toqstr(menu_name))) {
2097 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2102 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2103 //FIXME: 50 is a wild guess. We should take into account here
2104 //the expansion of menu items, disabled optional items etc.
2105 bool const in_sub_menu = fromLyxMenu.size() > 0
2106 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2108 fromLyxMenu.catSub(menu_name);
2110 fromLyxMenu.cat(cat_menu);
2111 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2114 if (fromLyxMenu.empty()) {
2115 qmenu->addAction(qt_("No Action Defined!"));
2119 BufferView * bv = 0;
2121 bv = qmenu->d->view->currentBufferView();
2122 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2123 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2127 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2129 LYXERR(Debug::GUI, "Context menu requested: " << name);
2130 Menu * menu = d->name_map_[&view].value(name, 0);
2131 if (!menu && !name.startsWith("context-")) {
2132 LYXERR0("requested context menu not found: " << name);
2136 menu = new Menu(&view, name, true, keyboard);
2137 d->name_map_[&view][name] = menu;
2141 } // namespace frontend
2144 #include "moc_Menus.cpp"