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. */
180 /** This is the list of arguments available
181 in the InsetArgument context menu. */
183 /** This is the list of captions available
184 in the current layout. */
186 /** This is the list of captions available
187 in the InsetCaption context menu. */
191 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
194 QString const & label,
195 QString const & submenu = QString(),
196 QString const & tooltip = QString(),
197 bool optional = false)
198 : kind_(kind), label_(label), submenuname_(submenu),
199 tooltip_(tooltip), optional_(optional)
201 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
205 QString const & label,
206 FuncRequest const & func,
207 QString const & tooltip = QString(),
208 bool optional = false,
209 FuncRequest::Origin origin = FuncRequest::MENU)
210 : kind_(kind), label_(label), func_(func),
211 tooltip_(tooltip), optional_(optional)
213 func_.setOrigin(origin);
216 // shared_ptr<MenuDefinition> needs this apprently...
219 /// The label of a given menuitem
220 QString label() const
222 int const index = label_.lastIndexOf('|');
223 return index == -1 ? label_ : label_.left(index);
226 /// The keyboard shortcut (usually underlined in the entry)
227 QString shortcut() const
229 int const index = label_.lastIndexOf('|');
230 return index == -1 ? QString() : label_.mid(index + 1);
232 /// The complete label, with label and shortcut separated by a '|'
233 QString fulllabel() const { return label_; }
234 /// The kind of entry
235 Kind kind() const { return kind_; }
236 /// the action (if relevant)
237 FuncRequest const & func() const { return func_; }
239 QString const & tooltip() const { return tooltip_; }
240 /// returns true if the entry should be omitted when disabled
241 bool optional() const { return optional_; }
242 /// returns the status of the lfun associated with this entry
243 FuncStatus const & status() const { return status_; }
244 /// returns the status of the lfun associated with this entry
245 FuncStatus & status() { return status_; }
246 /// returns the status of the lfun associated with this entry
247 void status(FuncStatus const & status) { status_ = status; }
249 ///returns the binding associated to this action.
250 QString binding() const
252 if (kind_ != Command)
254 // Get the keys bound to this action, but keep only the
256 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
257 if (!bindings.empty())
258 return toqstr(bindings.begin()->print(KeySequence::ForGui));
260 LYXERR(Debug::KBMAP, "No binding for "
261 << lyxaction.getActionName(func_.action())
262 << '(' << func_.argument() << ')');
266 /// the description of the submenu (if relevant)
267 QString const & submenuname() const { return submenuname_; }
268 /// set the description of the submenu
269 void submenuname(QString const & name) { submenuname_ = name; }
271 bool hasSubmenu() const { return !submenu_.isEmpty(); }
273 MenuDefinition const & submenu() const { return submenu_.at(0); }
274 MenuDefinition & submenu() { return submenu_[0]; }
276 void setSubmenu(MenuDefinition const & menu)
279 submenu_.append(menu);
290 QString submenuname_;
297 /// contains 0 or 1 item.
298 QList<MenuDefinition> submenu_;
302 class MenuDefinition {
305 typedef std::vector<MenuItem> ItemList;
307 typedef ItemList::const_iterator const_iterator;
309 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
314 QString const & name() const { return name_; }
316 bool empty() const { return items_.empty(); }
317 /// Clear the menu content.
318 void clear() { items_.clear(); }
320 size_t size() const { return items_.size(); }
322 MenuItem const & operator[](size_t) const;
324 const_iterator begin() const { return items_.begin(); }
326 const_iterator end() const { return items_.end(); }
328 void cat(MenuDefinition const & other);
330 void catSub(docstring const & name);
332 // search for func in this menu iteratively, and put menu
334 bool searchMenu(FuncRequest const & func, docstring_list & names)
337 bool hasFunc(FuncRequest const &) const;
338 /// Add the menu item unconditionally
339 void add(MenuItem const & item) { items_.push_back(item); }
340 /// Checks the associated FuncRequest status before adding the
342 void addWithStatusCheck(MenuItem const &);
343 // Check whether the menu shortcuts are unique
344 void checkShortcuts() const;
346 void expandLastfiles();
347 void expandDocuments();
348 void expandBookmarks();
349 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
350 void expandFloatListInsert(Buffer const * buf);
351 void expandFloatInsert(Buffer const * buf);
352 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
353 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
354 void expandToc(Buffer const * buf);
355 void expandPasteRecent(Buffer const * buf);
356 void expandToolbars();
357 void expandBranches(Buffer const * buf);
358 void expandIndices(Buffer const * buf, bool listof = false);
359 void expandIndicesContext(Buffer const * buf, bool listof = false);
360 void expandCiteStyles(BufferView const *);
361 void expandGraphicsGroups(BufferView const *);
362 void expandSpellingSuggestions(BufferView const *);
363 void expandLanguageSelector(Buffer const * buf);
364 void expandArguments(BufferView const *, bool switcharg = false);
365 void expandCaptions(Buffer const * buf, bool switchcap = false);
373 /// Helper for std::find_if
377 MenuNamesEqual(QString const & name) : name_(name) {}
378 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
385 typedef std::vector<MenuDefinition> MenuList;
387 typedef MenuList::const_iterator const_iterator;
389 typedef MenuList::iterator iterator;
391 /////////////////////////////////////////////////////////////////////
392 // MenuDefinition implementation
393 /////////////////////////////////////////////////////////////////////
395 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
399 case MenuItem::Command: {
400 FuncStatus status = lyx::getStatus(i.func());
401 if (status.unknown() || (!status.enabled() && i.optional()))
404 items_.back().status(status);
408 case MenuItem::Submenu: {
409 bool enabled = false;
410 if (i.hasSubmenu()) {
411 for (const_iterator cit = i.submenu().begin();
412 cit != i.submenu().end(); ++cit) {
413 // Only these kind of items affect the status of the submenu
414 if ((cit->kind() == MenuItem::Command
415 || cit->kind() == MenuItem::Submenu
416 || cit->kind() == MenuItem::Help)
417 && cit->status().enabled()) {
423 if (enabled || !i.optional()) {
425 items_.back().status().setEnabled(enabled);
430 case MenuItem::Separator:
431 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
441 void MenuDefinition::read(Lexer & lex)
458 md_indiceslistscontext,
472 md_spellingsuggestions,
480 LexerKeyword menutags[] = {
481 { "arguments", md_arguments },
482 { "bookmarks", md_bookmarks },
483 { "branches", md_branches },
484 { "captions", md_captions },
485 { "charstyles", md_charstyles },
486 { "citestyles", md_citestyles },
487 { "custom", md_custom },
488 { "documents", md_documents },
489 { "elements", md_elements },
490 { "end", md_endmenu },
491 { "exportformats", md_exportformats },
492 { "floatinsert", md_floatinsert },
493 { "floatlistinsert", md_floatlistinsert },
494 { "graphicsgroups", md_graphicsgroups },
495 { "importformats", md_importformats },
496 { "indices", md_indices },
497 { "indicescontext", md_indicescontext },
498 { "indiceslists", md_indiceslists },
499 { "indiceslistscontext", md_indiceslistscontext },
501 { "languageselector", md_languageselector },
502 { "lastfiles", md_lastfiles },
503 { "optitem", md_optitem },
504 { "optsubmenu", md_optsubmenu },
505 { "pasterecent", md_pasterecent },
506 { "separator", md_separator },
507 { "spellingsuggestions", md_spellingsuggestions },
508 { "submenu", md_submenu },
509 { "switcharguments", md_switcharguments },
510 { "switchcaptions", md_switchcaptions },
512 { "toolbars", md_toolbars },
513 { "updateformats", md_updateformats },
514 { "viewformats", md_viewformats }
517 lex.pushTable(menutags);
518 lex.setContext("MenuDefinition::read: ");
521 bool optional = false;
523 while (lex.isOK() && !quit) {
527 // fallback to md_item
530 docstring const name = translateIfPossible(lex.getDocString());
532 string const command = lex.getString();
533 FuncRequest func = lyxaction.lookupFunc(command);
534 FuncRequest::Origin origin = FuncRequest::MENU;
535 if (name_.startsWith("context-toc-"))
536 origin = FuncRequest::TOC;
537 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
543 add(MenuItem(MenuItem::Separator));
547 add(MenuItem(MenuItem::Lastfiles));
551 add(MenuItem(MenuItem::CharStyles));
555 add(MenuItem(MenuItem::Custom));
559 add(MenuItem(MenuItem::Elements));
563 add(MenuItem(MenuItem::Documents));
567 add(MenuItem(MenuItem::Bookmarks));
571 add(MenuItem(MenuItem::Toc));
575 add(MenuItem(MenuItem::ViewFormats));
578 case md_updateformats:
579 add(MenuItem(MenuItem::UpdateFormats));
582 case md_exportformats:
583 add(MenuItem(MenuItem::ExportFormats));
586 case md_importformats:
587 add(MenuItem(MenuItem::ImportFormats));
590 case md_floatlistinsert:
591 add(MenuItem(MenuItem::FloatListInsert));
595 add(MenuItem(MenuItem::FloatInsert));
599 add(MenuItem(MenuItem::PasteRecent));
603 add(MenuItem(MenuItem::Toolbars));
607 add(MenuItem(MenuItem::Branches));
611 add(MenuItem(MenuItem::CiteStyles));
614 case md_graphicsgroups:
615 add(MenuItem(MenuItem::GraphicsGroups));
618 case md_spellingsuggestions:
619 add(MenuItem(MenuItem::SpellingSuggestions));
622 case md_languageselector:
623 add(MenuItem(MenuItem::LanguageSelector));
627 add(MenuItem(MenuItem::Indices));
630 case md_indicescontext:
631 add(MenuItem(MenuItem::IndicesContext));
634 case md_indiceslists:
635 add(MenuItem(MenuItem::IndicesLists));
638 case md_indiceslistscontext:
639 add(MenuItem(MenuItem::IndicesListsContext));
643 add(MenuItem(MenuItem::Arguments));
646 case md_switcharguments:
647 add(MenuItem(MenuItem::SwitchArguments));
651 add(MenuItem(MenuItem::Captions));
654 case md_switchcaptions:
655 add(MenuItem(MenuItem::SwitchCaptions));
660 // fallback to md_submenu
663 docstring const mlabel = translateIfPossible(lex.getDocString());
665 docstring const mname = lex.getDocString();
666 add(MenuItem(MenuItem::Submenu,
667 toqstr(mlabel), toqstr(mname), QString(), optional));
677 lex.printError("Unknown menu tag");
685 MenuItem const & MenuDefinition::operator[](size_type i) const
691 bool MenuDefinition::hasFunc(FuncRequest const & func) const
693 for (const_iterator it = begin(), et = end(); it != et; ++it)
694 if (it->func() == func)
700 void MenuDefinition::catSub(docstring const & name)
702 add(MenuItem(MenuItem::Submenu,
703 qt_("More...|M"), toqstr(name), QString(), false));
706 void MenuDefinition::cat(MenuDefinition const & other)
708 const_iterator et = other.end();
709 for (const_iterator it = other.begin(); it != et; ++it)
714 void MenuDefinition::checkShortcuts() const
716 // This is a quadratic algorithm, but we do not care because
717 // menus are short enough
718 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
719 QString shortcut = it1->shortcut();
720 if (shortcut.isEmpty())
722 if (!it1->label().contains(shortcut))
723 LYXERR0("Menu warning: menu entry \""
725 << "\" does not contain shortcut `"
726 << shortcut << "'.");
727 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
728 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
729 LYXERR0("Menu warning: menu entries "
730 << '"' << it1->fulllabel()
731 << "\" and \"" << it2->fulllabel()
732 << "\" share the same shortcut.");
739 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
741 const_iterator m = begin();
742 const_iterator m_end = end();
743 for (; m != m_end; ++m) {
744 if (m->kind() == MenuItem::Command && m->func() == func) {
745 names.push_back(qstring_to_ucs4(m->label()));
748 if (m->kind() == MenuItem::Submenu) {
749 names.push_back(qstring_to_ucs4(m->label()));
750 if (!m->hasSubmenu()) {
751 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
752 << m->label() << " name=" << m->submenuname());
756 if (m->submenu().searchMenu(func, names))
765 QString limitStringLength(docstring const & str)
767 size_t const max_item_length = 45;
769 if (str.size() > max_item_length)
770 return toqstr(str.substr(0, max_item_length - 3) + "...");
776 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
781 graphics::getGraphicsGroups(bv->buffer(), grp);
785 set<string>::const_iterator it = grp.begin();
786 set<string>::const_iterator end = grp.end();
787 add(MenuItem(MenuItem::Command, qt_("No Group"),
788 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
789 for (; it != end; ++it) {
790 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
791 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
796 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
800 Cursor const & cur = bv->cursor();
804 docstring_list suggestions;
805 Paragraph const & par = cur.paragraph();
806 pos_type from = cur.pos();
808 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
810 case SpellChecker::UNKNOWN_WORD:
811 if (lyxrc.spellcheck_continuously) {
812 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
813 docstring const & selection = cur.selectionAsString(false);
814 if (!cur.selection() || selection == wl.word()) {
816 size_t m = 10; // first submenu index
817 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
818 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
819 for (; i != suggestions.size(); ++i) {
820 docstring const & suggestion = suggestions[i];
821 LYXERR(Debug::GUI, suggestion);
822 MenuItem w(MenuItem::Command, toqstr(suggestion),
823 FuncRequest(LFUN_WORD_REPLACE,
824 replace2string(suggestion, selection,
825 true, // case sensitive
829 false))); // find next
833 item.submenu().add(w);
838 add(MenuItem(MenuItem::Separator));
839 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
840 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
841 FuncRequest(LFUN_SPELLING_ADD, arg)));
842 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
843 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
847 case SpellChecker::LEARNED_WORD: {
848 LYXERR(Debug::GUI, "Learned Word.");
849 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
850 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
851 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
854 case SpellChecker::NO_DICTIONARY:
855 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
857 case SpellChecker::WORD_OK:
858 case SpellChecker::COMPOUND_WORD:
859 case SpellChecker::ROOT_FOUND:
860 case SpellChecker::IGNORED_WORD:
865 struct sortLanguageByName {
866 bool operator()(const Language * a, const Language * b) const {
867 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
871 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
876 std::set<Language const *> languages_buffer =
877 buf->masterBuffer()->getLanguages();
879 if (languages_buffer.size() < 2)
882 std::set<Language const *, sortLanguageByName> languages;
884 std::set<Language const *>::const_iterator const beg =
885 languages_buffer.begin();
886 for (std::set<Language const *>::const_iterator cit = beg;
887 cit != languages_buffer.end(); ++cit) {
888 languages.insert(*cit);
891 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
892 item.setSubmenu(MenuDefinition(qt_("Language")));
893 QString morelangs = qt_("More Languages ...|M");
894 QStringList accelerators;
895 if (morelangs.contains('|'))
896 accelerators.append(morelangs.section('|', -1));
897 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
898 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
899 cit != languages.end(); ++cit) {
900 QString label = qt_((*cit)->display());
901 // try to add an accelerator
902 bool success = false;
903 // try capitals first
904 for (int i = 0; i < label.size(); ++i) {
905 QChar const ch = label[i];
908 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
909 label = label + toqstr("|") + ch;
910 accelerators.append(ch);
915 // if all capitals are taken, try the rest
917 for (int i = 0; i < label.size(); ++i) {
918 if (label[i].isSpace())
920 QString const ch = QString(label[i]);
921 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
922 label = label + toqstr("|") + ch;
923 accelerators.append(ch);
928 MenuItem w(MenuItem::Command, label,
929 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
930 item.submenu().addWithStatusCheck(w);
932 item.submenu().add(MenuItem(MenuItem::Separator));
933 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
934 FuncRequest(LFUN_DIALOG_SHOW, "character")));
939 void MenuDefinition::expandLastfiles()
941 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
942 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
946 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
947 string const file = lfit->absFileName();
948 QString const short_path = toqstr(makeDisplayPath(file, 30));
949 QString const long_path = toqstr(makeDisplayPath(file));
952 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
954 label = QString("%1. %2").arg(ii).arg(short_path);
955 add(MenuItem(MenuItem::Command, label,
956 FuncRequest(LFUN_FILE_OPEN, file), long_path));
961 void MenuDefinition::expandDocuments()
963 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
964 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
966 Buffer * first = theBufferList().first();
968 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
974 if (!guiApp->currentView())
976 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
979 Buffer const & b = wa->bufferView().buffer();
980 QString label = toqstr(b.fileName().displayName(20));
984 label = QString::number(i) + ". " + label + '|' + QString::number(i);
985 add(MenuItem(MenuItem::Command, label,
986 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
993 // We cannot use a for loop as the buffer list cycles.
995 if (!(guiApp->currentView()
996 && guiApp->currentView()->workArea(*b))) {
997 QString label = toqstr(b->fileName().displayName(20));
1001 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1002 item.submenu().add(MenuItem(MenuItem::Command, label,
1003 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1006 b = theBufferList().next(b);
1007 } while (b != first);
1009 if (!item.submenu().empty())
1014 void MenuDefinition::expandBookmarks()
1016 lyx::BookmarksSection const & bm = theSession().bookmarks();
1019 for (size_t i = 1; i <= bm.size(); ++i) {
1020 if (bm.isValid(i)) {
1021 string const file = bm.bookmark(i).filename.absFileName();
1022 QString const label = QString("%1. %2|%3").arg(i)
1023 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1024 add(MenuItem(MenuItem::Command, label,
1025 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1030 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1034 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1036 if (!buf && kind != MenuItem::ImportFormats)
1039 typedef vector<Format const *> Formats;
1041 FuncCode action = LFUN_NOACTION;
1044 case MenuItem::ImportFormats:
1045 formats = theConverters().importableFormats();
1046 action = LFUN_BUFFER_IMPORT;
1048 case MenuItem::ViewFormats:
1049 formats = buf->params().exportableFormats(true);
1050 action = LFUN_BUFFER_VIEW;
1052 case MenuItem::UpdateFormats:
1053 formats = buf->params().exportableFormats(true);
1054 action = LFUN_BUFFER_UPDATE;
1056 case MenuItem::ExportFormats:
1057 formats = buf->params().exportableFormats(false);
1058 action = LFUN_BUFFER_EXPORT;
1061 LASSERT(false, /* */);
1065 bool const view_update = (kind == MenuItem::ViewFormats
1066 || kind == MenuItem::UpdateFormats);
1070 smenue = (kind == MenuItem::ViewFormats
1071 ? qt_("View (Other Formats)|F")
1072 : qt_("Update (Other Formats)|p"));
1073 MenuItem item(MenuItem::Submenu, smenue);
1074 item.setSubmenu(MenuDefinition(smenue));
1076 Formats::const_iterator fit = formats.begin();
1077 Formats::const_iterator end = formats.end();
1078 for (; fit != end ; ++fit) {
1079 if ((*fit)->dummy())
1082 docstring lab = from_utf8((*fit)->prettyname());
1083 docstring const scut = from_utf8((*fit)->shortcut());
1084 docstring const tmplab = lab;
1087 lab += char_type('|') + scut;
1088 docstring const lab_i18n = translateIfPossible(lab);
1089 docstring const shortcut = split(lab_i18n, lab, '|');
1091 bool const untranslated = (lab == lab_i18n);
1092 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1095 case MenuItem::ImportFormats:
1096 label += from_ascii("...");
1098 case MenuItem::ViewFormats:
1099 case MenuItem::UpdateFormats:
1100 if ((*fit)->name() == buf->params().getDefaultOutputFormat()) {
1101 docstring lbl = (kind == MenuItem::ViewFormats
1102 ? bformat(_("View [%1$s]|V"), label)
1103 : bformat(_("Update [%1$s]|U"), label));
1104 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1108 case MenuItem::ExportFormats:
1109 if (!(*fit)->inExportMenu())
1113 LASSERT(false, /* */);
1116 if (!shortcut.empty())
1117 label += '|' + shortcut;
1121 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1122 toqstr(label), FuncRequest(action, (*fit)->name())));
1124 item.submenu().add(MenuItem(MenuItem::Command, toqstr(label),
1125 FuncRequest(action, (*fit)->name())));
1128 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1129 FuncRequest(action, (*fit)->name())));
1131 add(MenuItem(MenuItem::Command, toqstr(label),
1132 FuncRequest(action, (*fit)->name())));
1140 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1145 FloatList const & floats = buf->params().documentClass().floats();
1146 FloatList::const_iterator cit = floats.begin();
1147 FloatList::const_iterator end = floats.end();
1149 for (; cit != end; ++cit) {
1150 if (!cit->second.usesFloatPkg()) {
1151 // Different floats could declare the same ListCommand. We only
1152 // want it on the list once, though.
1153 string const & list_cmd = cit->second.listCommand();
1154 if (list_cmd.empty())
1155 // we do not know how to generate such a list
1157 // This form of insert returns an iterator pointing to the newly
1158 // inserted element OR the existing element with that value, and
1159 // a bool indicating whether we inserted a new element. So we can
1160 // see if one is there and insert it if not all at once.
1161 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1165 string const & list_name = cit->second.listName();
1166 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1167 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1172 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1177 FloatList const & floats = buf->params().documentClass().floats();
1178 FloatList::const_iterator cit = floats.begin();
1179 FloatList::const_iterator end = floats.end();
1180 for (; cit != end; ++cit) {
1182 QString const label = qt_(cit->second.name());
1183 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1184 FuncRequest(LFUN_FLOAT_INSERT,
1185 cit->second.floattype())));
1190 void MenuDefinition::expandFlexInsert(
1191 Buffer const * buf, InsetLayout::InsetLyXType type)
1196 TextClass::InsetLayouts const & insetLayouts =
1197 buf->params().documentClass().insetLayouts();
1198 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1199 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1200 for (; cit != end; ++cit) {
1201 if (cit->second.lyxtype() == type) {
1202 docstring label = cit->first;
1203 // we remove the "Flex:" prefix, if it is present
1204 if (prefixIs(label, from_utf8("Flex:")))
1205 label = label.substr(5);
1206 addWithStatusCheck(MenuItem(MenuItem::Command,
1207 toqstr(translateIfPossible(label)),
1208 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1211 // FIXME This is a little clunky.
1212 if (items_.empty() && type == InsetLayout::CUSTOM)
1213 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1217 size_t const max_number_of_items = 25;
1219 void MenuDefinition::expandToc2(Toc const & toc_list,
1220 size_t from, size_t to, int depth)
1222 int shortcut_count = 0;
1224 // check whether depth is smaller than the smallest depth in toc.
1225 int min_depth = 1000;
1226 for (size_t i = from; i < to; ++i)
1227 min_depth = min(min_depth, toc_list[i].depth());
1228 if (min_depth > depth)
1231 if (to - from <= max_number_of_items) {
1232 for (size_t i = from; i < to; ++i) {
1233 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1234 label += limitStringLength(toc_list[i].str());
1235 if (toc_list[i].depth() == depth) {
1237 if (shortcut_count < 9) {
1238 if (label.contains(QString::number(shortcut_count + 1)))
1239 label += QString::number(++shortcut_count);
1242 add(MenuItem(MenuItem::Command, label,
1243 FuncRequest(toc_list[i].action())));
1248 size_t new_pos = pos + 1;
1249 while (new_pos < to && toc_list[new_pos].depth() > depth)
1252 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1253 label += limitStringLength(toc_list[pos].str());
1254 if (toc_list[pos].depth() == depth) {
1256 if (shortcut_count < 9) {
1257 if (label.contains(QString::number(shortcut_count + 1)))
1258 label += QString::number(++shortcut_count);
1261 if (new_pos == pos + 1) {
1262 add(MenuItem(MenuItem::Command,
1263 label, FuncRequest(toc_list[pos].action())));
1266 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
1267 MenuItem item(MenuItem::Submenu, label);
1268 item.setSubmenu(sub);
1277 void MenuDefinition::expandToc(Buffer const * buf)
1279 // To make things very cleanly, we would have to pass buf to
1280 // all MenuItem constructors and to expandToc2. However, we
1281 // know that all the entries in a TOC will be have status_ ==
1282 // OK, so we avoid this unnecessary overhead (JMarc)
1285 add(MenuItem(MenuItem::Info, qt_("<No Document Open>")));
1289 // Add an entry for the master doc if this is a child doc
1290 Buffer const * const master = buf->masterBuffer();
1291 if (buf != master) {
1292 ParIterator const pit = par_iterator_begin(master->inset());
1293 string const arg = convert<string>(pit->id());
1294 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1295 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1298 MenuDefinition other_lists;
1300 FloatList const & floatlist = buf->params().documentClass().floats();
1301 TocList const & toc_list = buf->tocBackend().tocs();
1302 TocList::const_iterator cit = toc_list.begin();
1303 TocList::const_iterator end = toc_list.end();
1304 for (; cit != end; ++cit) {
1305 // Handle this later
1306 if (cit->first == "tableofcontents")
1309 MenuDefinition submenu;
1310 if (cit->second.size() >= 30) {
1311 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1312 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1314 TocIterator ccit = cit->second.begin();
1315 TocIterator eend = cit->second.end();
1316 for (; ccit != eend; ++ccit) {
1317 submenu.add(MenuItem(MenuItem::Command,
1318 limitStringLength(ccit->str()) + '|',
1319 FuncRequest(ccit->action())));
1323 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1324 item.setSubmenu(submenu);
1325 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1326 // Those two types deserve to be in the main menu.
1327 item.setSubmenu(submenu);
1330 other_lists.add(item);
1332 if (!other_lists.empty()) {
1333 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1334 item.setSubmenu(other_lists);
1338 // Handle normal TOC
1339 cit = toc_list.find("tableofcontents");
1341 LYXERR(Debug::GUI, "No table of contents.");
1343 if (!cit->second.empty())
1344 expandToc2(cit->second, 0, cit->second.size(), 0);
1346 add(MenuItem(MenuItem::Info, qt_("<Empty Table of Contents>")));
1351 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1353 docstring_list const sel = cap::availableSelections(buf);
1355 docstring_list::const_iterator cit = sel.begin();
1356 docstring_list::const_iterator end = sel.end();
1358 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1359 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1360 FuncRequest(LFUN_PASTE, convert<string>(index))));
1365 void MenuDefinition::expandToolbars()
1367 MenuDefinition other_lists;
1368 // extracts the toolbars from the backend
1369 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1370 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1371 for (; cit != end; ++cit) {
1372 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1373 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1374 if (guiApp->toolbars().isMainToolbar(cit->name))
1377 other_lists.add(item);
1380 if (!other_lists.empty()) {
1381 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1382 item.setSubmenu(other_lists);
1388 void MenuDefinition::expandBranches(Buffer const * buf)
1393 BufferParams const & master_params = buf->masterBuffer()->params();
1394 BufferParams const & params = buf->params();
1395 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1396 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1400 BranchList::const_iterator cit = master_params.branchlist().begin();
1401 BranchList::const_iterator end = master_params.branchlist().end();
1403 for (int ii = 1; cit != end; ++cit, ++ii) {
1404 docstring label = cit->branch();
1406 label = convert<docstring>(ii) + ". " + label
1407 + char_type('|') + convert<docstring>(ii);
1409 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1410 FuncRequest(LFUN_BRANCH_INSERT,
1414 if (buf == buf->masterBuffer())
1417 MenuDefinition child_branches;
1419 BranchList::const_iterator ccit = params.branchlist().begin();
1420 BranchList::const_iterator cend = params.branchlist().end();
1422 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1423 docstring label = ccit->branch();
1425 label = convert<docstring>(ii) + ". " + label
1426 + char_type('|') + convert<docstring>(ii);
1428 label += char_type('|');
1429 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1431 FuncRequest(LFUN_BRANCH_INSERT,
1435 if (!child_branches.empty()) {
1436 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1437 item.setSubmenu(child_branches);
1443 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1448 BufferParams const & params = buf->masterBuffer()->params();
1449 if (!params.use_indices) {
1451 addWithStatusCheck(MenuItem(MenuItem::Command,
1452 qt_("Index List|I"),
1453 FuncRequest(LFUN_INDEX_PRINT,
1454 from_ascii("idx"))));
1456 addWithStatusCheck(MenuItem(MenuItem::Command,
1457 qt_("Index Entry|d"),
1458 FuncRequest(LFUN_INDEX_INSERT,
1459 from_ascii("idx"))));
1463 if (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 docstring const label =
1472 bformat(_("Index: %1$s"), cit->index());
1473 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1474 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1476 docstring const label =
1477 bformat(_("Index Entry (%1$s)"), cit->index());
1478 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1479 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1485 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1490 BufferParams const & params = buf->masterBuffer()->params();
1491 if (!params.use_indices || params.indiceslist().empty())
1494 IndicesList::const_iterator cit = params.indiceslist().begin();
1495 IndicesList::const_iterator end = params.indiceslist().end();
1497 for (int ii = 1; cit != end; ++cit, ++ii) {
1499 InsetCommandParams p(INDEX_PRINT_CODE);
1500 p["type"] = cit->shortcut();
1501 string const data = InsetCommand::params2string(p);
1502 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1503 FuncRequest(LFUN_INSET_MODIFY, data)));
1505 docstring const label =
1506 bformat(_("Index Entry (%1$s)"), cit->index());
1507 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1508 FuncRequest(LFUN_INSET_MODIFY,
1509 from_ascii("changetype ") + cit->shortcut())));
1515 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1520 Inset const * inset = bv->cursor().nextInset();
1521 if (!inset || inset->lyxCode() != CITE_CODE) {
1522 add(MenuItem(MenuItem::Command,
1523 qt_("No Citation in Scope!"),
1524 FuncRequest(LFUN_NOACTION)));
1527 InsetCommand const * citinset =
1528 static_cast<InsetCommand const *>(inset);
1530 Buffer const * buf = &bv->buffer();
1531 string const cmd = citinset->params().getCmdName();
1533 docstring const & key = citinset->getParam("key");
1535 add(MenuItem(MenuItem::Command,
1536 qt_("No citations selected!"),
1537 FuncRequest(LFUN_NOACTION)));
1541 docstring const & before = citinset->getParam("before");
1542 docstring const & after = citinset->getParam("after");
1544 size_t const n = cmd.size();
1545 bool const force = cmd[0] == 'C';
1546 bool const full = cmd[n] == '*';
1548 vector<docstring> const keys = getVectorFromString(key);
1550 vector<CitationStyle> const citeStyleList = buf->params().citeStyles();
1551 vector<docstring> citeStrings =
1552 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(),
1553 false, before, after, from_utf8("dialog"));
1555 vector<docstring>::const_iterator cit = citeStrings.begin();
1556 vector<docstring>::const_iterator end = citeStrings.end();
1558 for (int ii = 1; cit != end; ++cit, ++ii) {
1559 docstring label = *cit;
1560 CitationStyle cs = citeStyleList[ii - 1];
1561 cs.forceUpperCase &= force;
1562 cs.fullAuthorList &= full;
1563 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1564 FuncRequest(LFUN_INSET_MODIFY,
1565 "changetype " + from_utf8(citationStyleToString(cs)))));
1570 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1575 if (!bv->cursor().inTexted())
1578 Inset const * inset = &bv->cursor().inset();
1579 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1580 if (inset && args.empty())
1581 args = inset->getLayout().args();
1582 if (args.empty() || (switcharg && args.size() == 1))
1584 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1585 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1586 for (; lait != laend; ++lait) {
1587 Layout::latexarg arg = (*lait).second;
1588 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1589 QString item = toqstr(translateIfPossible(str));
1591 add(MenuItem(MenuItem::Command, item,
1592 FuncRequest(LFUN_INSET_MODIFY,
1593 from_ascii("changetype ")
1594 + from_ascii((*lait).first))));
1596 add(MenuItem(MenuItem::Command, item,
1597 FuncRequest(LFUN_ARGUMENT_INSERT,
1598 from_ascii((*lait).first))));
1603 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1608 vector<docstring> caps;
1609 DocumentClass const & dc = buf->params().documentClass();
1610 TextClass::InsetLayouts::const_iterator lit = dc.insetLayouts().begin();
1611 TextClass::InsetLayouts::const_iterator len = dc.insetLayouts().end();
1612 for (; lit != len; ++lit) {
1613 if (prefixIs(lit->first, from_ascii("Caption:")))
1614 caps.push_back(lit->first);
1617 if (caps.empty() || (switchcap && caps.size() == 1))
1619 if (caps.size() == 1) {
1621 docstring const type = split(*caps.begin(), dummy, ':');
1622 add(MenuItem(MenuItem::Command, qt_("Caption"),
1623 FuncRequest(LFUN_CAPTION_INSERT, translateIfPossible(type))));
1627 MenuDefinition captions;
1629 vector<docstring>::const_iterator cit = caps.begin();
1630 vector<docstring>::const_iterator end = caps.end();
1632 for (int ii = 1; cit != end; ++cit, ++ii) {
1634 docstring const type = split(*cit, dummy, ':');
1635 docstring const trtype = translateIfPossible(type);
1636 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1638 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cmitem),
1639 FuncRequest(LFUN_INSET_MODIFY,
1640 from_ascii("changetype ")
1641 + type), QString(), true));
1643 captions.addWithStatusCheck(MenuItem(MenuItem::Command,
1645 FuncRequest(LFUN_CAPTION_INSERT,
1646 type), QString(), true));
1648 if (!captions.empty()) {
1649 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1650 item.setSubmenu(captions);
1658 /////////////////////////////////////////////////////////////////////
1659 // Menu::Impl definition and implementation
1660 /////////////////////////////////////////////////////////////////////
1664 /// populates the menu or one of its submenu
1665 /// This is used as a recursive function
1666 void populate(QMenu & qMenu, MenuDefinition const & menu);
1668 /// Only needed for top level menus.
1669 MenuDefinition * top_level_menu;
1672 /// the name of this menu
1678 /// Get a MenuDefinition item label from the menu backend
1679 static QString label(MenuItem const & mi)
1681 QString label = mi.label();
1682 label.replace("&", "&&");
1684 QString shortcut = mi.shortcut();
1685 if (!shortcut.isEmpty()) {
1686 int pos = label.indexOf(shortcut);
1688 //label.insert(pos, 1, char_type('&'));
1689 label.replace(pos, 0, "&");
1692 QString const binding = mi.binding();
1693 if (!binding.isEmpty())
1694 label += '\t' + binding;
1699 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1701 LYXERR(Debug::GUI, "populating menu " << menu.name());
1703 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1706 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1707 MenuDefinition::const_iterator m = menu.begin();
1708 MenuDefinition::const_iterator end = menu.end();
1709 for (; m != end; ++m) {
1710 if (m->kind() == MenuItem::Separator)
1711 qMenu.addSeparator();
1712 else if (m->kind() == MenuItem::Submenu) {
1713 QMenu * subMenu = qMenu.addMenu(label(*m));
1714 populate(*subMenu, m->submenu());
1715 subMenu->setEnabled(m->status().enabled());
1717 // we have a MenuItem::Command
1718 qMenu.addAction(new Action(view, QIcon(), label(*m),
1719 m->func(), m->tooltip(), &qMenu));
1724 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1725 class AlwaysMnemonicStyle : public QProxyStyle {
1727 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1728 QStyleHintReturn *returnData = 0) const
1730 if (hint == QStyle::SH_UnderlineShortcut)
1732 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1737 /////////////////////////////////////////////////////////////////////
1738 // Menu implementation
1739 /////////////////////////////////////////////////////////////////////
1741 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1742 : QMenu(gv), d(new Menu::Impl)
1744 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1746 setStyle(new AlwaysMnemonicStyle);
1750 d->top_level_menu = top_level? new MenuDefinition : 0;
1754 if (d->top_level_menu)
1755 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1761 delete d->top_level_menu;
1766 void Menu::updateView()
1768 guiApp->menus().updateMenu(this);
1774 QList<QAction *> items = actions();
1775 for (int i = 0; i != items.size(); ++i) {
1776 // QAction::menu() returns 0 if there's no submenu.
1777 delete items.at(i)->menu();
1783 /////////////////////////////////////////////////////////////////////
1784 // Menus::Impl definition and implementation
1785 /////////////////////////////////////////////////////////////////////
1787 struct Menus::Impl {
1789 bool hasMenu(QString const &) const;
1791 MenuDefinition & getMenu(QString const &);
1793 MenuDefinition const & getMenu(QString const &) const;
1795 /// Expands some special entries of the menu
1796 /** The entries with the following kind are expanded to a
1797 sequence of Command MenuItems: Lastfiles, Documents,
1798 ViewFormats, ExportFormats, UpdateFormats, Branches,
1799 Indices, Arguments, SwitchArguments, Captions, Switchcaptions
1801 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1802 BufferView const *) const;
1804 /// Initialize specific MACOS X menubar
1805 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1807 /// Mac special menu.
1808 /** This defines a menu whose entries list the FuncRequests
1809 that will be removed by expand() in other menus. This is
1810 used by the Qt/Mac code.
1812 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1813 such that the items will keep accessing the FuncRequests in
1814 the MenuDefinition. While Menus::Impl might be recreated,
1815 we keep mac_special_menu_ in memory by making it static.
1817 static MenuDefinition mac_special_menu_;
1822 MenuDefinition menubar_;
1824 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1826 /// name to menu for \c menu() method.
1831 MenuDefinition Menus::Impl::mac_special_menu_;
1835 Here is what the Qt documentation says about how a menubar is chosen:
1837 1) If the window has a QMenuBar then it is used. 2) If the window
1838 is a modal then its menubar is used. If no menubar is specified
1839 then a default menubar is used (as documented below) 3) If the
1840 window has no parent then the default menubar is used (as
1843 The above 3 steps are applied all the way up the parent window
1844 chain until one of the above are satisifed. If all else fails a
1845 default menubar will be created, the default menubar on Qt/Mac is
1846 an empty menubar, however you can create a different default
1847 menubar by creating a parentless QMenuBar, the first one created
1848 will thus be designated the default menubar, and will be used
1849 whenever a default menubar is needed.
1851 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1852 that this menubar will be used also when one of LyX' dialogs has
1855 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1857 /* Since Qt 4.2, the qt/mac menu code has special code for
1858 specifying the role of a menu entry. However, it does not
1859 work very well with our scheme of creating menus on demand,
1860 and therefore we need to put these entries in a special
1861 invisible menu. (JMarc)
1864 /* The entries of our special mac menu. If we add support for
1865 * special entries in Menus, we could imagine something
1867 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1868 * and therefore avoid hardcoding. I am not sure it is worth
1869 * the hassle, though. (JMarc)
1871 struct MacMenuEntry {
1875 QAction::MenuRole role;
1878 static MacMenuEntry entries[] = {
1879 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1880 QAction::AboutRole},
1881 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1882 QAction::PreferencesRole},
1883 /* {LFUN_RECONFIGURE, "", "Reconfigure",
1884 QAction::ApplicationSpecificRole}, */
1885 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1887 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1888 const bool first_call = mac_special_menu_.empty();
1890 // the special menu for Menus. Fill it up only once.
1892 for (size_t i = 0 ; i < num_entries ; ++i) {
1893 FuncRequest const func(entries[i].action,
1894 from_utf8(entries[i].arg));
1895 mac_special_menu_.add(MenuItem(MenuItem::Command,
1896 entries[i].label, func));
1900 // add the entries to a QMenu that will eventually be empty
1901 // and therefore invisible.
1902 QMenu * qMenu = qmb->addMenu("special");
1903 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1904 MenuDefinition::const_iterator end = mac_special_menu_.end();
1905 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1906 #if defined(QT_MAC_USE_COCOA) && (QT_MAC_USE_COCOA > 0)
1907 if (first_call || entries[i].role != QAction::ApplicationSpecificRole) {
1908 Action * action = new Action(view, QIcon(), cit->label(),
1909 cit->func(), QString(), qMenu);
1910 action->setMenuRole(entries[i].role);
1911 qMenu->addAction(action);
1914 Action * action = new Action(view, QIcon(), cit->label(),
1915 cit->func(), QString(), qMenu);
1916 action->setMenuRole(entries[i].role);
1917 qMenu->addAction(action);
1923 void Menus::Impl::expand(MenuDefinition const & frommenu,
1924 MenuDefinition & tomenu, BufferView const * bv) const
1926 if (!tomenu.empty())
1929 for (MenuDefinition::const_iterator cit = frommenu.begin();
1930 cit != frommenu.end() ; ++cit) {
1931 Buffer const * buf = bv ? &bv->buffer() : 0;
1932 switch (cit->kind()) {
1933 case MenuItem::Lastfiles:
1934 tomenu.expandLastfiles();
1937 case MenuItem::Documents:
1938 tomenu.expandDocuments();
1941 case MenuItem::Bookmarks:
1942 tomenu.expandBookmarks();
1945 case MenuItem::ImportFormats:
1946 case MenuItem::ViewFormats:
1947 case MenuItem::UpdateFormats:
1948 case MenuItem::ExportFormats:
1949 tomenu.expandFormats(cit->kind(), buf);
1952 case MenuItem::CharStyles:
1953 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1956 case MenuItem::Custom:
1957 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1960 case MenuItem::Elements:
1961 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1964 case MenuItem::FloatListInsert:
1965 tomenu.expandFloatListInsert(buf);
1968 case MenuItem::FloatInsert:
1969 tomenu.expandFloatInsert(buf);
1972 case MenuItem::PasteRecent:
1973 tomenu.expandPasteRecent(buf);
1976 case MenuItem::Toolbars:
1977 tomenu.expandToolbars();
1980 case MenuItem::Branches:
1981 tomenu.expandBranches(buf);
1984 case MenuItem::Indices:
1985 tomenu.expandIndices(buf);
1988 case MenuItem::IndicesContext:
1989 tomenu.expandIndicesContext(buf);
1992 case MenuItem::IndicesLists:
1993 tomenu.expandIndices(buf, true);
1996 case MenuItem::IndicesListsContext:
1997 tomenu.expandIndicesContext(buf, true);
2000 case MenuItem::CiteStyles:
2001 tomenu.expandCiteStyles(bv);
2005 tomenu.expandToc(buf);
2008 case MenuItem::GraphicsGroups:
2009 tomenu.expandGraphicsGroups(bv);
2012 case MenuItem::SpellingSuggestions:
2013 tomenu.expandSpellingSuggestions(bv);
2016 case MenuItem::LanguageSelector:
2017 tomenu.expandLanguageSelector(buf);
2020 case MenuItem::Arguments:
2021 tomenu.expandArguments(bv, false);
2024 case MenuItem::SwitchArguments:
2025 tomenu.expandArguments(bv, true);
2028 case MenuItem::Captions:
2029 tomenu.expandCaptions(buf, false);
2032 case MenuItem::SwitchCaptions:
2033 tomenu.expandCaptions(buf, true);
2036 case MenuItem::Submenu: {
2037 MenuItem item(*cit);
2038 item.setSubmenu(MenuDefinition(cit->submenuname()));
2039 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2040 tomenu.addWithStatusCheck(item);
2044 case MenuItem::Info:
2045 case MenuItem::Help:
2046 case MenuItem::Separator:
2047 tomenu.addWithStatusCheck(*cit);
2050 case MenuItem::Command:
2051 if (!mac_special_menu_.hasFunc(cit->func()))
2052 tomenu.addWithStatusCheck(*cit);
2056 // we do not want the menu to end with a separator
2057 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2058 tomenu.items_.pop_back();
2060 // Check whether the shortcuts are unique
2061 tomenu.checkShortcuts();
2065 bool Menus::Impl::hasMenu(QString const & name) const
2067 return find_if(menulist_.begin(), menulist_.end(),
2068 MenuNamesEqual(name)) != menulist_.end();
2072 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2074 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2075 MenuNamesEqual(name));
2076 if (cit == menulist_.end())
2077 LYXERR0("No submenu named " << name);
2078 LASSERT(cit != menulist_.end(), /**/);
2083 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2085 iterator it = find_if(menulist_.begin(), menulist_.end(),
2086 MenuNamesEqual(name));
2087 if (it == menulist_.end())
2088 LYXERR0("No submenu named " << name);
2089 LASSERT(it != menulist_.end(), /**/);
2094 /////////////////////////////////////////////////////////////////////
2098 /////////////////////////////////////////////////////////////////////
2100 Menus::Menus() : d(new Impl) {}
2116 void Menus::read(Lexer & lex)
2124 LexerKeyword menutags[] = {
2125 { "end", md_endmenuset },
2126 { "menu", md_menu },
2127 { "menubar", md_menubar }
2130 // consistency check
2131 if (compare_ascii_no_case(lex.getString(), "menuset"))
2132 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2134 lex.pushTable(menutags);
2135 lex.setContext("Menus::read");
2139 while (lex.isOK() && !quit) {
2140 switch (lex.lex()) {
2142 d->menubar_.read(lex);
2146 QString const name = toqstr(lex.getDocString());
2147 if (d->hasMenu(name))
2148 d->getMenu(name).read(lex);
2150 MenuDefinition menu(name);
2152 d->menulist_.push_back(menu);
2160 lex.printError("Unknown menu tag");
2168 bool Menus::searchMenu(FuncRequest const & func,
2169 docstring_list & names) const
2171 MenuDefinition menu;
2172 d->expand(d->menubar_, menu, 0);
2173 return menu.searchMenu(func, names);
2177 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2181 // setup special mac specific menu items, but only do this
2182 // the first time a QMenuBar is created. Otherwise Qt will
2183 // create duplicate items in the application menu. It seems
2184 // that Qt does not remove them when the QMenubar is cleared.
2185 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2186 d->macxMenuBarInit(view, qmb);
2189 // Clear all menubar contents before filling it.
2193 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2195 if (d->menubar_.empty()) {
2196 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2197 << d->menubar_.name());
2200 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2202 MenuDefinition menu;
2203 BufferView * bv = 0;
2205 bv = view->currentBufferView();
2206 d->expand(d->menubar_, menu, bv);
2208 MenuDefinition::const_iterator m = menu.begin();
2209 MenuDefinition::const_iterator end = menu.end();
2211 for (; m != end; ++m) {
2213 if (m->kind() != MenuItem::Submenu) {
2214 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2218 LYXERR(Debug::GUI, "menu bar item " << m->label()
2219 << " is a submenu named " << m->submenuname());
2221 QString name = m->submenuname();
2222 if (!d->hasMenu(name)) {
2223 LYXERR(Debug::GUI, "\tERROR: " << name
2224 << " submenu has no menu!");
2228 Menu * menu = new Menu(view, m->submenuname(), true);
2229 menu->setTitle(label(*m));
2232 d->name_map_[view][name] = menu;
2237 void Menus::updateMenu(Menu * qmenu)
2239 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2242 if (qmenu->d->name.isEmpty())
2245 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2246 MenuDefinition fromLyxMenu(qmenu->d->name);
2247 while (!identifier.empty()) {
2248 docstring menu_name;
2249 identifier = split(identifier, menu_name, ';');
2251 if (!d->hasMenu(toqstr(menu_name))) {
2252 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2257 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2258 //FIXME: 50 is a wild guess. We should take into account here
2259 //the expansion of menu items, disabled optional items etc.
2260 bool const in_sub_menu = !fromLyxMenu.empty()
2261 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2263 fromLyxMenu.catSub(menu_name);
2265 fromLyxMenu.cat(cat_menu);
2266 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2269 if (fromLyxMenu.empty()) {
2270 qmenu->addAction(qt_("No Action Defined!"));
2274 BufferView * bv = 0;
2276 bv = qmenu->d->view->currentBufferView();
2277 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2278 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2282 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2284 LYXERR(Debug::GUI, "Context menu requested: " << name);
2285 Menu * menu = d->name_map_[&view].value(name, 0);
2286 if (!menu && !name.startsWith("context-")) {
2287 LYXERR0("requested context menu not found: " << name);
2291 menu = new Menu(&view, name, true, keyboard);
2292 d->name_map_[&view][name] = menu;
2296 } // namespace frontend
2299 #include "moc_Menus.cpp"