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 for in the InsetArgument context menu. */
185 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
188 QString const & label,
189 QString const & submenu = QString(),
190 QString const & tooltip = QString(),
191 bool optional = false)
192 : kind_(kind), label_(label), submenuname_(submenu),
193 tooltip_(tooltip), optional_(optional)
195 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
199 QString const & label,
200 FuncRequest const & func,
201 QString const & tooltip = QString(),
202 bool optional = false,
203 FuncRequest::Origin origin = FuncRequest::MENU)
204 : kind_(kind), label_(label), func_(func),
205 tooltip_(tooltip), optional_(optional)
207 func_.setOrigin(origin);
210 // shared_ptr<MenuDefinition> needs this apprently...
213 /// The label of a given menuitem
214 QString label() const
216 int const index = label_.lastIndexOf('|');
217 return index == -1 ? label_ : label_.left(index);
220 /// The keyboard shortcut (usually underlined in the entry)
221 QString shortcut() const
223 int const index = label_.lastIndexOf('|');
224 return index == -1 ? QString() : label_.mid(index + 1);
226 /// The complete label, with label and shortcut separated by a '|'
227 QString fulllabel() const { return label_; }
228 /// The kind of entry
229 Kind kind() const { return kind_; }
230 /// the action (if relevant)
231 FuncRequest const & func() const { return func_; }
233 QString const & tooltip() const { return tooltip_; }
234 /// returns true if the entry should be omitted when disabled
235 bool optional() const { return optional_; }
236 /// returns the status of the lfun associated with this entry
237 FuncStatus const & status() const { return status_; }
238 /// returns the status of the lfun associated with this entry
239 FuncStatus & status() { return status_; }
240 /// returns the status of the lfun associated with this entry
241 void status(FuncStatus const & status) { status_ = status; }
243 ///returns the binding associated to this action.
244 QString binding() const
246 if (kind_ != Command)
248 // Get the keys bound to this action, but keep only the
250 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
251 if (!bindings.empty())
252 return toqstr(bindings.begin()->print(KeySequence::ForGui));
254 LYXERR(Debug::KBMAP, "No binding for "
255 << lyxaction.getActionName(func_.action())
256 << '(' << func_.argument() << ')');
260 /// the description of the submenu (if relevant)
261 QString const & submenuname() const { return submenuname_; }
262 /// set the description of the submenu
263 void submenuname(QString const & name) { submenuname_ = name; }
265 bool hasSubmenu() const { return !submenu_.isEmpty(); }
267 MenuDefinition const & submenu() const { return submenu_.at(0); }
268 MenuDefinition & submenu() { return submenu_[0]; }
270 void setSubmenu(MenuDefinition const & menu)
273 submenu_.append(menu);
284 QString submenuname_;
291 /// contains 0 or 1 item.
292 QList<MenuDefinition> submenu_;
296 class MenuDefinition {
299 typedef std::vector<MenuItem> ItemList;
301 typedef ItemList::const_iterator const_iterator;
303 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
308 QString const & name() const { return name_; }
310 bool empty() const { return items_.empty(); }
311 /// Clear the menu content.
312 void clear() { items_.clear(); }
314 size_t size() const { return items_.size(); }
316 MenuItem const & operator[](size_t) const;
318 const_iterator begin() const { return items_.begin(); }
320 const_iterator end() const { return items_.end(); }
322 void cat(MenuDefinition const & other);
324 void catSub(docstring const & name);
326 // search for func in this menu iteratively, and put menu
328 bool searchMenu(FuncRequest const & func, docstring_list & names)
331 bool hasFunc(FuncRequest const &) const;
332 /// Add the menu item unconditionally
333 void add(MenuItem const & item) { items_.push_back(item); }
334 /// Checks the associated FuncRequest status before adding the
336 void addWithStatusCheck(MenuItem const &);
337 // Check whether the menu shortcuts are unique
338 void checkShortcuts() const;
340 void expandLastfiles();
341 void expandDocuments();
342 void expandBookmarks();
343 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
344 void expandFloatListInsert(Buffer const * buf);
345 void expandFloatInsert(Buffer const * buf);
346 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
347 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
348 void expandToc(Buffer const * buf);
349 void expandPasteRecent(Buffer const * buf);
350 void expandToolbars();
351 void expandBranches(Buffer const * buf);
352 void expandIndices(Buffer const * buf, bool listof = false);
353 void expandIndicesContext(Buffer const * buf, bool listof = false);
354 void expandCiteStyles(BufferView const *);
355 void expandGraphicsGroups(BufferView const *);
356 void expandSpellingSuggestions(BufferView const *);
357 void expandLanguageSelector(Buffer const * buf);
358 void expandArguments(BufferView const *, bool switcharg = false);
366 /// Helper for std::find_if
370 MenuNamesEqual(QString const & name) : name_(name) {}
371 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
378 typedef std::vector<MenuDefinition> MenuList;
380 typedef MenuList::const_iterator const_iterator;
382 typedef MenuList::iterator iterator;
384 /////////////////////////////////////////////////////////////////////
385 // MenuDefinition implementation
386 /////////////////////////////////////////////////////////////////////
388 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
392 case MenuItem::Command: {
393 FuncStatus status = lyx::getStatus(i.func());
394 if (status.unknown() || (!status.enabled() && i.optional()))
397 items_.back().status(status);
401 case MenuItem::Submenu: {
402 bool enabled = false;
403 if (i.hasSubmenu()) {
404 for (const_iterator cit = i.submenu().begin();
405 cit != i.submenu().end(); ++cit) {
406 // Only these kind of items affect the status of the submenu
407 if ((cit->kind() == MenuItem::Command
408 || cit->kind() == MenuItem::Submenu
409 || cit->kind() == MenuItem::Help)
410 && cit->status().enabled()) {
416 if (enabled || !i.optional()) {
418 items_.back().status().setEnabled(enabled);
423 case MenuItem::Separator:
424 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
434 void MenuDefinition::read(Lexer & lex)
451 md_indiceslistscontext,
465 md_spellingsuggestions,
471 LexerKeyword menutags[] = {
472 { "arguments", md_arguments },
473 { "bookmarks", md_bookmarks },
474 { "branches", md_branches },
475 { "charstyles", md_charstyles },
476 { "citestyles", md_citestyles },
477 { "custom", md_custom },
478 { "documents", md_documents },
479 { "elements", md_elements },
480 { "end", md_endmenu },
481 { "exportformats", md_exportformats },
482 { "floatinsert", md_floatinsert },
483 { "floatlistinsert", md_floatlistinsert },
484 { "graphicsgroups", md_graphicsgroups },
485 { "importformats", md_importformats },
486 { "indices", md_indices },
487 { "indicescontext", md_indicescontext },
488 { "indiceslists", md_indiceslists },
489 { "indiceslistscontext", md_indiceslistscontext },
491 { "languageselector", md_languageselector },
492 { "lastfiles", md_lastfiles },
493 { "optitem", md_optitem },
494 { "optsubmenu", md_optsubmenu },
495 { "pasterecent", md_pasterecent },
496 { "separator", md_separator },
497 { "spellingsuggestions", md_spellingsuggestions },
498 { "submenu", md_submenu },
499 { "switcharguments", md_switcharguments },
501 { "toolbars", md_toolbars },
502 { "updateformats", md_updateformats },
503 { "viewformats", md_viewformats }
506 lex.pushTable(menutags);
507 lex.setContext("MenuDefinition::read: ");
510 bool optional = false;
512 while (lex.isOK() && !quit) {
516 // fallback to md_item
519 docstring const name = translateIfPossible(lex.getDocString());
521 string const command = lex.getString();
522 FuncRequest func = lyxaction.lookupFunc(command);
523 FuncRequest::Origin origin = FuncRequest::MENU;
524 if (name_.startsWith("context-toc-"))
525 origin = FuncRequest::TOC;
526 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
532 add(MenuItem(MenuItem::Separator));
536 add(MenuItem(MenuItem::Lastfiles));
540 add(MenuItem(MenuItem::CharStyles));
544 add(MenuItem(MenuItem::Custom));
548 add(MenuItem(MenuItem::Elements));
552 add(MenuItem(MenuItem::Documents));
556 add(MenuItem(MenuItem::Bookmarks));
560 add(MenuItem(MenuItem::Toc));
564 add(MenuItem(MenuItem::ViewFormats));
567 case md_updateformats:
568 add(MenuItem(MenuItem::UpdateFormats));
571 case md_exportformats:
572 add(MenuItem(MenuItem::ExportFormats));
575 case md_importformats:
576 add(MenuItem(MenuItem::ImportFormats));
579 case md_floatlistinsert:
580 add(MenuItem(MenuItem::FloatListInsert));
584 add(MenuItem(MenuItem::FloatInsert));
588 add(MenuItem(MenuItem::PasteRecent));
592 add(MenuItem(MenuItem::Toolbars));
596 add(MenuItem(MenuItem::Branches));
600 add(MenuItem(MenuItem::CiteStyles));
603 case md_graphicsgroups:
604 add(MenuItem(MenuItem::GraphicsGroups));
607 case md_spellingsuggestions:
608 add(MenuItem(MenuItem::SpellingSuggestions));
611 case md_languageselector:
612 add(MenuItem(MenuItem::LanguageSelector));
616 add(MenuItem(MenuItem::Indices));
619 case md_indicescontext:
620 add(MenuItem(MenuItem::IndicesContext));
623 case md_indiceslists:
624 add(MenuItem(MenuItem::IndicesLists));
627 case md_indiceslistscontext:
628 add(MenuItem(MenuItem::IndicesListsContext));
632 add(MenuItem(MenuItem::Arguments));
635 case md_switcharguments:
636 add(MenuItem(MenuItem::SwitchArguments));
641 // fallback to md_submenu
644 docstring const mlabel = translateIfPossible(lex.getDocString());
646 docstring const mname = lex.getDocString();
647 add(MenuItem(MenuItem::Submenu,
648 toqstr(mlabel), toqstr(mname), QString(), optional));
658 lex.printError("Unknown menu tag");
666 MenuItem const & MenuDefinition::operator[](size_type i) const
672 bool MenuDefinition::hasFunc(FuncRequest const & func) const
674 for (const_iterator it = begin(), et = end(); it != et; ++it)
675 if (it->func() == func)
681 void MenuDefinition::catSub(docstring const & name)
683 add(MenuItem(MenuItem::Submenu,
684 qt_("More...|M"), toqstr(name), QString(), false));
687 void MenuDefinition::cat(MenuDefinition const & other)
689 const_iterator et = other.end();
690 for (const_iterator it = other.begin(); it != et; ++it)
695 void MenuDefinition::checkShortcuts() const
697 // This is a quadratic algorithm, but we do not care because
698 // menus are short enough
699 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
700 QString shortcut = it1->shortcut();
701 if (shortcut.isEmpty())
703 if (!it1->label().contains(shortcut))
704 LYXERR0("Menu warning: menu entry \""
706 << "\" does not contain shortcut `"
707 << shortcut << "'.");
708 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
709 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
710 LYXERR0("Menu warning: menu entries "
711 << '"' << it1->fulllabel()
712 << "\" and \"" << it2->fulllabel()
713 << "\" share the same shortcut.");
720 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
722 const_iterator m = begin();
723 const_iterator m_end = end();
724 for (; m != m_end; ++m) {
725 if (m->kind() == MenuItem::Command && m->func() == func) {
726 names.push_back(qstring_to_ucs4(m->label()));
729 if (m->kind() == MenuItem::Submenu) {
730 names.push_back(qstring_to_ucs4(m->label()));
731 if (!m->hasSubmenu()) {
732 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
733 << m->label() << " name=" << m->submenuname());
737 if (m->submenu().searchMenu(func, names))
746 QString limitStringLength(docstring const & str)
748 size_t const max_item_length = 45;
750 if (str.size() > max_item_length)
751 return toqstr(str.substr(0, max_item_length - 3) + "...");
757 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
762 graphics::getGraphicsGroups(bv->buffer(), grp);
766 set<string>::const_iterator it = grp.begin();
767 set<string>::const_iterator end = grp.end();
768 add(MenuItem(MenuItem::Command, qt_("No Group"),
769 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
770 for (; it != end; ++it) {
771 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
772 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
777 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
781 Cursor const & cur = bv->cursor();
785 docstring_list suggestions;
786 Paragraph const & par = cur.paragraph();
787 pos_type from = cur.pos();
789 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
791 case SpellChecker::UNKNOWN_WORD:
792 if (lyxrc.spellcheck_continuously) {
793 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
794 docstring const & selection = cur.selectionAsString(false);
795 if (!cur.selection() || selection == wl.word()) {
797 size_t m = 10; // first submenu index
798 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
799 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
800 for (; i != suggestions.size(); ++i) {
801 docstring const & suggestion = suggestions[i];
802 LYXERR(Debug::GUI, suggestion);
803 MenuItem w(MenuItem::Command, toqstr(suggestion),
804 FuncRequest(LFUN_WORD_REPLACE,
805 replace2string(suggestion, selection,
806 true, // case sensitive
810 false))); // find next
814 item.submenu().add(w);
819 add(MenuItem(MenuItem::Separator));
820 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
821 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
822 FuncRequest(LFUN_SPELLING_ADD, arg)));
823 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
824 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
828 case SpellChecker::LEARNED_WORD: {
829 LYXERR(Debug::GUI, "Learned Word.");
830 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
831 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
832 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
835 case SpellChecker::NO_DICTIONARY:
836 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
838 case SpellChecker::WORD_OK:
839 case SpellChecker::COMPOUND_WORD:
840 case SpellChecker::ROOT_FOUND:
841 case SpellChecker::IGNORED_WORD:
846 struct sortLanguageByName {
847 bool operator()(const Language * a, const Language * b) const {
848 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
852 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
857 std::set<Language const *> languages_buffer =
858 buf->masterBuffer()->getLanguages();
860 if (languages_buffer.size() < 2)
863 std::set<Language const *, sortLanguageByName> languages;
865 std::set<Language const *>::const_iterator const beg =
866 languages_buffer.begin();
867 for (std::set<Language const *>::const_iterator cit = beg;
868 cit != languages_buffer.end(); ++cit) {
869 languages.insert(*cit);
872 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
873 item.setSubmenu(MenuDefinition(qt_("Language")));
874 QString morelangs = qt_("More Languages ...|M");
875 QStringList accelerators;
876 if (morelangs.contains('|'))
877 accelerators.append(morelangs.section('|', -1));
878 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
879 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
880 cit != languages.end(); ++cit) {
881 QString label = qt_((*cit)->display());
882 // try to add an accelerator
883 bool success = false;
884 // try capitals first
885 for (int i = 0; i < label.size(); ++i) {
886 QChar const ch = label[i];
889 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
890 label = label + toqstr("|") + ch;
891 accelerators.append(ch);
896 // if all capitals are taken, try the rest
898 for (int i = 0; i < label.size(); ++i) {
899 if (label[i].isSpace())
901 QString const ch = QString(label[i]);
902 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
903 label = label + toqstr("|") + ch;
904 accelerators.append(ch);
909 MenuItem w(MenuItem::Command, label,
910 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
911 item.submenu().addWithStatusCheck(w);
913 item.submenu().add(MenuItem(MenuItem::Separator));
914 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
915 FuncRequest(LFUN_DIALOG_SHOW, "character")));
920 void MenuDefinition::expandLastfiles()
922 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
923 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
927 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
928 string const file = lfit->absFileName();
929 QString const short_path = toqstr(makeDisplayPath(file, 30));
930 QString const long_path = toqstr(makeDisplayPath(file));
933 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
935 label = QString("%1. %2").arg(ii).arg(short_path);
936 add(MenuItem(MenuItem::Command, label,
937 FuncRequest(LFUN_FILE_OPEN, file), long_path));
942 void MenuDefinition::expandDocuments()
944 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
945 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
947 Buffer * first = theBufferList().first();
949 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
955 if (!guiApp->currentView())
957 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
960 Buffer const & b = wa->bufferView().buffer();
961 QString label = toqstr(b.fileName().displayName(20));
965 label = QString::number(i) + ". " + label + '|' + QString::number(i);
966 add(MenuItem(MenuItem::Command, label,
967 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
974 // We cannot use a for loop as the buffer list cycles.
976 if (!(guiApp->currentView()
977 && guiApp->currentView()->workArea(*b))) {
978 QString label = toqstr(b->fileName().displayName(20));
982 label = QString::number(i) + ". " + label + '|' + QString::number(i);
983 item.submenu().add(MenuItem(MenuItem::Command, label,
984 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
987 b = theBufferList().next(b);
988 } while (b != first);
990 if (!item.submenu().empty())
995 void MenuDefinition::expandBookmarks()
997 lyx::BookmarksSection const & bm = theSession().bookmarks();
1000 for (size_t i = 1; i <= bm.size(); ++i) {
1001 if (bm.isValid(i)) {
1002 string const file = bm.bookmark(i).filename.absFileName();
1003 QString const label = QString("%1. %2|%3").arg(i)
1004 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1005 add(MenuItem(MenuItem::Command, label,
1006 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1011 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1015 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1017 if (!buf && kind != MenuItem::ImportFormats)
1020 typedef vector<Format const *> Formats;
1022 FuncCode action = LFUN_NOACTION;
1025 case MenuItem::ImportFormats:
1026 formats = theConverters().importableFormats();
1027 action = LFUN_BUFFER_IMPORT;
1029 case MenuItem::ViewFormats:
1030 formats = buf->params().exportableFormats(true);
1031 action = LFUN_BUFFER_VIEW;
1033 case MenuItem::UpdateFormats:
1034 formats = buf->params().exportableFormats(true);
1035 action = LFUN_BUFFER_UPDATE;
1037 case MenuItem::ExportFormats:
1038 formats = buf->params().exportableFormats(false);
1039 action = LFUN_BUFFER_EXPORT;
1042 LASSERT(false, /* */);
1046 bool const view_update = (kind == MenuItem::ViewFormats
1047 || kind == MenuItem::UpdateFormats);
1051 smenue = (kind == MenuItem::ViewFormats
1052 ? qt_("View (Other Formats)|F")
1053 : qt_("Update (Other Formats)|p"));
1054 MenuItem item(MenuItem::Submenu, smenue);
1055 item.setSubmenu(MenuDefinition(smenue));
1057 Formats::const_iterator fit = formats.begin();
1058 Formats::const_iterator end = formats.end();
1059 for (; fit != end ; ++fit) {
1060 if ((*fit)->dummy())
1063 docstring lab = from_utf8((*fit)->prettyname());
1064 docstring const scut = from_utf8((*fit)->shortcut());
1065 docstring const tmplab = lab;
1068 lab += char_type('|') + scut;
1069 docstring const lab_i18n = translateIfPossible(lab);
1070 docstring const shortcut = split(lab_i18n, lab, '|');
1072 bool const untranslated = (lab == lab_i18n);
1073 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1076 case MenuItem::ImportFormats:
1077 label += from_ascii("...");
1079 case MenuItem::ViewFormats:
1080 case MenuItem::UpdateFormats:
1081 if ((*fit)->name() == buf->params().getDefaultOutputFormat()) {
1082 docstring lbl = (kind == MenuItem::ViewFormats
1083 ? bformat(_("View [%1$s]|V"), label)
1084 : bformat(_("Update [%1$s]|U"), label));
1085 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1089 case MenuItem::ExportFormats:
1090 if (!(*fit)->inExportMenu())
1094 LASSERT(false, /* */);
1097 if (!shortcut.empty())
1098 label += '|' + shortcut;
1102 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1103 toqstr(label), FuncRequest(action, (*fit)->name())));
1105 item.submenu().add(MenuItem(MenuItem::Command, toqstr(label),
1106 FuncRequest(action, (*fit)->name())));
1109 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1110 FuncRequest(action, (*fit)->name())));
1112 add(MenuItem(MenuItem::Command, toqstr(label),
1113 FuncRequest(action, (*fit)->name())));
1121 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1126 FloatList const & floats = buf->params().documentClass().floats();
1127 FloatList::const_iterator cit = floats.begin();
1128 FloatList::const_iterator end = floats.end();
1130 for (; cit != end; ++cit) {
1131 if (!cit->second.usesFloatPkg()) {
1132 // Different floats could declare the same ListCommand. We only
1133 // want it on the list once, though.
1134 string const & list_cmd = cit->second.listCommand();
1135 if (list_cmd.empty())
1136 // we do not know how to generate such a list
1138 // This form of insert returns an iterator pointing to the newly
1139 // inserted element OR the existing element with that value, and
1140 // a bool indicating whether we inserted a new element. So we can
1141 // see if one is there and insert it if not all at once.
1142 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1146 string const & list_name = cit->second.listName();
1147 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1148 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1153 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1158 FloatList const & floats = buf->params().documentClass().floats();
1159 FloatList::const_iterator cit = floats.begin();
1160 FloatList::const_iterator end = floats.end();
1161 for (; cit != end; ++cit) {
1163 QString const label = qt_(cit->second.name());
1164 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1165 FuncRequest(LFUN_FLOAT_INSERT,
1166 cit->second.floattype())));
1171 void MenuDefinition::expandFlexInsert(
1172 Buffer const * buf, InsetLayout::InsetLyXType type)
1177 TextClass::InsetLayouts const & insetLayouts =
1178 buf->params().documentClass().insetLayouts();
1179 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1180 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1181 for (; cit != end; ++cit) {
1182 if (cit->second.lyxtype() == type) {
1183 docstring label = cit->first;
1184 // we remove the "Flex:" prefix, if it is present
1185 if (prefixIs(label, from_utf8("Flex:")))
1186 label = label.substr(5);
1187 addWithStatusCheck(MenuItem(MenuItem::Command,
1188 toqstr(translateIfPossible(label)),
1189 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1192 // FIXME This is a little clunky.
1193 if (items_.empty() && type == InsetLayout::CUSTOM)
1194 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1198 size_t const max_number_of_items = 25;
1200 void MenuDefinition::expandToc2(Toc const & toc_list,
1201 size_t from, size_t to, int depth)
1203 int shortcut_count = 0;
1205 // check whether depth is smaller than the smallest depth in toc.
1206 int min_depth = 1000;
1207 for (size_t i = from; i < to; ++i)
1208 min_depth = min(min_depth, toc_list[i].depth());
1209 if (min_depth > depth)
1212 if (to - from <= max_number_of_items) {
1213 for (size_t i = from; i < to; ++i) {
1214 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1215 label += limitStringLength(toc_list[i].str());
1216 if (toc_list[i].depth() == depth) {
1218 if (shortcut_count < 9) {
1219 if (label.contains(QString::number(shortcut_count + 1)))
1220 label += QString::number(++shortcut_count);
1223 add(MenuItem(MenuItem::Command, label,
1224 FuncRequest(toc_list[i].action())));
1229 size_t new_pos = pos + 1;
1230 while (new_pos < to && toc_list[new_pos].depth() > depth)
1233 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1234 label += limitStringLength(toc_list[pos].str());
1235 if (toc_list[pos].depth() == depth) {
1237 if (shortcut_count < 9) {
1238 if (label.contains(QString::number(shortcut_count + 1)))
1239 label += QString::number(++shortcut_count);
1242 if (new_pos == pos + 1) {
1243 add(MenuItem(MenuItem::Command,
1244 label, FuncRequest(toc_list[pos].action())));
1247 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
1248 MenuItem item(MenuItem::Submenu, label);
1249 item.setSubmenu(sub);
1258 void MenuDefinition::expandToc(Buffer const * buf)
1260 // To make things very cleanly, we would have to pass buf to
1261 // all MenuItem constructors and to expandToc2. However, we
1262 // know that all the entries in a TOC will be have status_ ==
1263 // OK, so we avoid this unnecessary overhead (JMarc)
1266 add(MenuItem(MenuItem::Info, qt_("<No Document Open>")));
1270 // Add an entry for the master doc if this is a child doc
1271 Buffer const * const master = buf->masterBuffer();
1272 if (buf != master) {
1273 ParIterator const pit = par_iterator_begin(master->inset());
1274 string const arg = convert<string>(pit->id());
1275 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1276 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1279 MenuDefinition other_lists;
1281 FloatList const & floatlist = buf->params().documentClass().floats();
1282 TocList const & toc_list = buf->tocBackend().tocs();
1283 TocList::const_iterator cit = toc_list.begin();
1284 TocList::const_iterator end = toc_list.end();
1285 for (; cit != end; ++cit) {
1286 // Handle this later
1287 if (cit->first == "tableofcontents")
1290 MenuDefinition submenu;
1291 if (cit->second.size() >= 30) {
1292 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1293 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1295 TocIterator ccit = cit->second.begin();
1296 TocIterator eend = cit->second.end();
1297 for (; ccit != eend; ++ccit) {
1298 submenu.add(MenuItem(MenuItem::Command,
1299 limitStringLength(ccit->str()) + '|',
1300 FuncRequest(ccit->action())));
1304 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1305 item.setSubmenu(submenu);
1306 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1307 // Those two types deserve to be in the main menu.
1308 item.setSubmenu(submenu);
1311 other_lists.add(item);
1313 if (!other_lists.empty()) {
1314 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1315 item.setSubmenu(other_lists);
1319 // Handle normal TOC
1320 cit = toc_list.find("tableofcontents");
1322 LYXERR(Debug::GUI, "No table of contents.");
1324 if (!cit->second.empty())
1325 expandToc2(cit->second, 0, cit->second.size(), 0);
1327 add(MenuItem(MenuItem::Info, qt_("<Empty Table of Contents>")));
1332 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1334 docstring_list const sel = cap::availableSelections(buf);
1336 docstring_list::const_iterator cit = sel.begin();
1337 docstring_list::const_iterator end = sel.end();
1339 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1340 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1341 FuncRequest(LFUN_PASTE, convert<string>(index))));
1346 void MenuDefinition::expandToolbars()
1348 MenuDefinition other_lists;
1349 // extracts the toolbars from the backend
1350 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1351 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1352 for (; cit != end; ++cit) {
1353 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1354 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1355 if (guiApp->toolbars().isMainToolbar(cit->name))
1358 other_lists.add(item);
1361 if (!other_lists.empty()) {
1362 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1363 item.setSubmenu(other_lists);
1369 void MenuDefinition::expandBranches(Buffer const * buf)
1374 BufferParams const & master_params = buf->masterBuffer()->params();
1375 BufferParams const & params = buf->params();
1376 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1377 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1381 BranchList::const_iterator cit = master_params.branchlist().begin();
1382 BranchList::const_iterator end = master_params.branchlist().end();
1384 for (int ii = 1; cit != end; ++cit, ++ii) {
1385 docstring label = cit->branch();
1387 label = convert<docstring>(ii) + ". " + label
1388 + char_type('|') + convert<docstring>(ii);
1390 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1391 FuncRequest(LFUN_BRANCH_INSERT,
1395 if (buf == buf->masterBuffer())
1398 MenuDefinition child_branches;
1400 BranchList::const_iterator ccit = params.branchlist().begin();
1401 BranchList::const_iterator cend = params.branchlist().end();
1403 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1404 docstring label = ccit->branch();
1406 label = convert<docstring>(ii) + ". " + label
1407 + char_type('|') + convert<docstring>(ii);
1409 label += char_type('|');
1410 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1412 FuncRequest(LFUN_BRANCH_INSERT,
1416 if (!child_branches.empty()) {
1417 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1418 item.setSubmenu(child_branches);
1424 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1429 BufferParams const & params = buf->masterBuffer()->params();
1430 if (!params.use_indices) {
1432 addWithStatusCheck(MenuItem(MenuItem::Command,
1433 qt_("Index List|I"),
1434 FuncRequest(LFUN_INDEX_PRINT,
1435 from_ascii("idx"))));
1437 addWithStatusCheck(MenuItem(MenuItem::Command,
1438 qt_("Index Entry|d"),
1439 FuncRequest(LFUN_INDEX_INSERT,
1440 from_ascii("idx"))));
1444 if (params.indiceslist().empty())
1447 IndicesList::const_iterator cit = params.indiceslist().begin();
1448 IndicesList::const_iterator end = params.indiceslist().end();
1450 for (int ii = 1; cit != end; ++cit, ++ii) {
1452 docstring const label =
1453 bformat(_("Index: %1$s"), cit->index());
1454 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1455 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1457 docstring const label =
1458 bformat(_("Index Entry (%1$s)"), cit->index());
1459 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1460 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1466 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1471 BufferParams const & params = buf->masterBuffer()->params();
1472 if (!params.use_indices || params.indiceslist().empty())
1475 IndicesList::const_iterator cit = params.indiceslist().begin();
1476 IndicesList::const_iterator end = params.indiceslist().end();
1478 for (int ii = 1; cit != end; ++cit, ++ii) {
1480 InsetCommandParams p(INDEX_PRINT_CODE);
1481 p["type"] = cit->shortcut();
1482 string const data = InsetCommand::params2string(p);
1483 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1484 FuncRequest(LFUN_INSET_MODIFY, data)));
1486 docstring const label =
1487 bformat(_("Index Entry (%1$s)"), cit->index());
1488 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1489 FuncRequest(LFUN_INSET_MODIFY,
1490 from_ascii("changetype ") + cit->shortcut())));
1496 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1501 Inset const * inset = bv->cursor().nextInset();
1502 if (!inset || inset->lyxCode() != CITE_CODE) {
1503 add(MenuItem(MenuItem::Command,
1504 qt_("No Citation in Scope!"),
1505 FuncRequest(LFUN_NOACTION)));
1508 InsetCommand const * citinset =
1509 static_cast<InsetCommand const *>(inset);
1511 Buffer const * buf = &bv->buffer();
1512 string const cmd = citinset->params().getCmdName();
1514 docstring const & key = citinset->getParam("key");
1516 add(MenuItem(MenuItem::Command,
1517 qt_("No citations selected!"),
1518 FuncRequest(LFUN_NOACTION)));
1522 docstring const & before = citinset->getParam("before");
1523 docstring const & after = citinset->getParam("after");
1525 size_t const n = cmd.size();
1526 bool const force = cmd[0] == 'C';
1527 bool const full = cmd[n] == '*';
1529 vector<docstring> const keys = getVectorFromString(key);
1531 vector<CitationStyle> const citeStyleList = buf->params().citeStyles();
1532 vector<docstring> citeStrings =
1533 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(),
1534 false, before, after, from_utf8("dialog"));
1536 vector<docstring>::const_iterator cit = citeStrings.begin();
1537 vector<docstring>::const_iterator end = citeStrings.end();
1539 for (int ii = 1; cit != end; ++cit, ++ii) {
1540 docstring label = *cit;
1541 CitationStyle cs = citeStyleList[ii - 1];
1542 cs.forceUpperCase &= force;
1543 cs.fullAuthorList &= full;
1544 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1545 FuncRequest(LFUN_INSET_MODIFY,
1546 "changetype " + from_utf8(citationStyleToString(cs)))));
1551 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1556 Inset const * inset = &bv->cursor().inset();
1557 Layout::LaTeXArgMap args;
1558 if (inset && bv->cursor().paragraph().layout().latexargs().empty()
1559 && bv->cursor().paragraph().layout().itemargs().empty())
1560 args = inset->getLayout().latexargs();
1562 args = bv->cursor().paragraph().layout().latexargs();
1563 Layout::LaTeXArgMap itemargs = bv->cursor().paragraph().layout().itemargs();
1564 if (!itemargs.empty())
1565 args.insert(itemargs.begin(), itemargs.end());
1567 if (args.empty() || (switcharg && args.size() == 1))
1569 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1570 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1571 for (; lait != laend; ++lait) {
1572 Layout::latexarg arg = (*lait).second;
1573 QString item = toqstr(translateIfPossible(arg.labelstring));
1575 add(MenuItem(MenuItem::Command, item,
1576 FuncRequest(LFUN_INSET_MODIFY,
1577 from_ascii("changetype ")
1578 + from_ascii((*lait).first))));
1580 add(MenuItem(MenuItem::Command, item,
1581 FuncRequest(LFUN_ARGUMENT_INSERT,
1582 from_ascii((*lait).first))));
1589 /////////////////////////////////////////////////////////////////////
1590 // Menu::Impl definition and implementation
1591 /////////////////////////////////////////////////////////////////////
1595 /// populates the menu or one of its submenu
1596 /// This is used as a recursive function
1597 void populate(QMenu & qMenu, MenuDefinition const & menu);
1599 /// Only needed for top level menus.
1600 MenuDefinition * top_level_menu;
1603 /// the name of this menu
1609 /// Get a MenuDefinition item label from the menu backend
1610 static QString label(MenuItem const & mi)
1612 QString label = mi.label();
1613 label.replace("&", "&&");
1615 QString shortcut = mi.shortcut();
1616 if (!shortcut.isEmpty()) {
1617 int pos = label.indexOf(shortcut);
1619 //label.insert(pos, 1, char_type('&'));
1620 label.replace(pos, 0, "&");
1623 QString const binding = mi.binding();
1624 if (!binding.isEmpty())
1625 label += '\t' + binding;
1630 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1632 LYXERR(Debug::GUI, "populating menu " << menu.name());
1634 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1637 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1638 MenuDefinition::const_iterator m = menu.begin();
1639 MenuDefinition::const_iterator end = menu.end();
1640 for (; m != end; ++m) {
1641 if (m->kind() == MenuItem::Separator)
1642 qMenu.addSeparator();
1643 else if (m->kind() == MenuItem::Submenu) {
1644 QMenu * subMenu = qMenu.addMenu(label(*m));
1645 populate(*subMenu, m->submenu());
1646 subMenu->setEnabled(m->status().enabled());
1648 // we have a MenuItem::Command
1649 qMenu.addAction(new Action(view, QIcon(), label(*m),
1650 m->func(), m->tooltip(), &qMenu));
1655 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1656 class AlwaysMnemonicStyle : public QProxyStyle {
1658 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1659 QStyleHintReturn *returnData = 0) const
1661 if (hint == QStyle::SH_UnderlineShortcut)
1663 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1668 /////////////////////////////////////////////////////////////////////
1669 // Menu implementation
1670 /////////////////////////////////////////////////////////////////////
1672 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1673 : QMenu(gv), d(new Menu::Impl)
1675 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1677 setStyle(new AlwaysMnemonicStyle);
1681 d->top_level_menu = top_level? new MenuDefinition : 0;
1685 if (d->top_level_menu)
1686 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1692 delete d->top_level_menu;
1697 void Menu::updateView()
1699 guiApp->menus().updateMenu(this);
1705 QList<QAction *> items = actions();
1706 for (int i = 0; i != items.size(); ++i) {
1707 // QAction::menu() returns 0 if there's no submenu.
1708 delete items.at(i)->menu();
1714 /////////////////////////////////////////////////////////////////////
1715 // Menus::Impl definition and implementation
1716 /////////////////////////////////////////////////////////////////////
1718 struct Menus::Impl {
1720 bool hasMenu(QString const &) const;
1722 MenuDefinition & getMenu(QString const &);
1724 MenuDefinition const & getMenu(QString const &) const;
1726 /// Expands some special entries of the menu
1727 /** The entries with the following kind are expanded to a
1728 sequence of Command MenuItems: Lastfiles, Documents,
1729 ViewFormats, ExportFormats, UpdateFormats, Branches,
1730 Indices, Arguments, SwitchArguments
1732 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1733 BufferView const *) const;
1735 /// Initialize specific MACOS X menubar
1736 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1738 /// Mac special menu.
1739 /** This defines a menu whose entries list the FuncRequests
1740 that will be removed by expand() in other menus. This is
1741 used by the Qt/Mac code.
1743 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1744 such that the items will keep accessing the FuncRequests in
1745 the MenuDefinition. While Menus::Impl might be recreated,
1746 we keep mac_special_menu_ in memory by making it static.
1748 static MenuDefinition mac_special_menu_;
1753 MenuDefinition menubar_;
1755 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1757 /// name to menu for \c menu() method.
1762 MenuDefinition Menus::Impl::mac_special_menu_;
1766 Here is what the Qt documentation says about how a menubar is chosen:
1768 1) If the window has a QMenuBar then it is used. 2) If the window
1769 is a modal then its menubar is used. If no menubar is specified
1770 then a default menubar is used (as documented below) 3) If the
1771 window has no parent then the default menubar is used (as
1774 The above 3 steps are applied all the way up the parent window
1775 chain until one of the above are satisifed. If all else fails a
1776 default menubar will be created, the default menubar on Qt/Mac is
1777 an empty menubar, however you can create a different default
1778 menubar by creating a parentless QMenuBar, the first one created
1779 will thus be designated the default menubar, and will be used
1780 whenever a default menubar is needed.
1782 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1783 that this menubar will be used also when one of LyX' dialogs has
1786 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1788 /* Since Qt 4.2, the qt/mac menu code has special code for
1789 specifying the role of a menu entry. However, it does not
1790 work very well with our scheme of creating menus on demand,
1791 and therefore we need to put these entries in a special
1792 invisible menu. (JMarc)
1795 /* The entries of our special mac menu. If we add support for
1796 * special entries in Menus, we could imagine something
1798 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1799 * and therefore avoid hardcoding. I am not sure it is worth
1800 * the hassle, though. (JMarc)
1802 struct MacMenuEntry {
1806 QAction::MenuRole role;
1809 MacMenuEntry entries[] = {
1810 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1811 QAction::AboutRole},
1812 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1813 QAction::PreferencesRole},
1814 /* {LFUN_RECONFIGURE, "", "Reconfigure",
1815 QAction::ApplicationSpecificRole}, */
1816 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1818 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1819 const bool first_call = mac_special_menu_.empty();
1821 // the special menu for Menus. Fill it up only once.
1823 for (size_t i = 0 ; i < num_entries ; ++i) {
1824 FuncRequest const func(entries[i].action,
1825 from_utf8(entries[i].arg));
1826 mac_special_menu_.add(MenuItem(MenuItem::Command,
1827 entries[i].label, func));
1831 // add the entries to a QMenu that will eventually be empty
1832 // and therefore invisible.
1833 QMenu * qMenu = qmb->addMenu("special");
1834 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1835 MenuDefinition::const_iterator end = mac_special_menu_.end();
1836 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1837 #if defined(QT_MAC_USE_COCOA) && (QT_MAC_USE_COCOA > 0)
1838 if (first_call || entries[i].role != QAction::ApplicationSpecificRole) {
1839 Action * action = new Action(view, QIcon(), cit->label(),
1840 cit->func(), QString(), qMenu);
1841 action->setMenuRole(entries[i].role);
1842 qMenu->addAction(action);
1845 Action * action = new Action(view, QIcon(), cit->label(),
1846 cit->func(), QString(), qMenu);
1847 action->setMenuRole(entries[i].role);
1848 qMenu->addAction(action);
1854 void Menus::Impl::expand(MenuDefinition const & frommenu,
1855 MenuDefinition & tomenu, BufferView const * bv) const
1857 if (!tomenu.empty())
1860 for (MenuDefinition::const_iterator cit = frommenu.begin();
1861 cit != frommenu.end() ; ++cit) {
1862 Buffer const * buf = bv ? &bv->buffer() : 0;
1863 switch (cit->kind()) {
1864 case MenuItem::Lastfiles:
1865 tomenu.expandLastfiles();
1868 case MenuItem::Documents:
1869 tomenu.expandDocuments();
1872 case MenuItem::Bookmarks:
1873 tomenu.expandBookmarks();
1876 case MenuItem::ImportFormats:
1877 case MenuItem::ViewFormats:
1878 case MenuItem::UpdateFormats:
1879 case MenuItem::ExportFormats:
1880 tomenu.expandFormats(cit->kind(), buf);
1883 case MenuItem::CharStyles:
1884 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1887 case MenuItem::Custom:
1888 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1891 case MenuItem::Elements:
1892 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1895 case MenuItem::FloatListInsert:
1896 tomenu.expandFloatListInsert(buf);
1899 case MenuItem::FloatInsert:
1900 tomenu.expandFloatInsert(buf);
1903 case MenuItem::PasteRecent:
1904 tomenu.expandPasteRecent(buf);
1907 case MenuItem::Toolbars:
1908 tomenu.expandToolbars();
1911 case MenuItem::Branches:
1912 tomenu.expandBranches(buf);
1915 case MenuItem::Indices:
1916 tomenu.expandIndices(buf);
1919 case MenuItem::IndicesContext:
1920 tomenu.expandIndicesContext(buf);
1923 case MenuItem::IndicesLists:
1924 tomenu.expandIndices(buf, true);
1927 case MenuItem::IndicesListsContext:
1928 tomenu.expandIndicesContext(buf, true);
1931 case MenuItem::CiteStyles:
1932 tomenu.expandCiteStyles(bv);
1936 tomenu.expandToc(buf);
1939 case MenuItem::GraphicsGroups:
1940 tomenu.expandGraphicsGroups(bv);
1943 case MenuItem::SpellingSuggestions:
1944 tomenu.expandSpellingSuggestions(bv);
1947 case MenuItem::LanguageSelector:
1948 tomenu.expandLanguageSelector(buf);
1951 case MenuItem::Arguments:
1952 tomenu.expandArguments(bv, false);
1955 case MenuItem::SwitchArguments:
1956 tomenu.expandArguments(bv, true);
1959 case MenuItem::Submenu: {
1960 MenuItem item(*cit);
1961 item.setSubmenu(MenuDefinition(cit->submenuname()));
1962 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1963 tomenu.addWithStatusCheck(item);
1967 case MenuItem::Info:
1968 case MenuItem::Help:
1969 case MenuItem::Separator:
1970 tomenu.addWithStatusCheck(*cit);
1973 case MenuItem::Command:
1974 if (!mac_special_menu_.hasFunc(cit->func()))
1975 tomenu.addWithStatusCheck(*cit);
1979 // we do not want the menu to end with a separator
1980 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1981 tomenu.items_.pop_back();
1983 // Check whether the shortcuts are unique
1984 tomenu.checkShortcuts();
1988 bool Menus::Impl::hasMenu(QString const & name) const
1990 return find_if(menulist_.begin(), menulist_.end(),
1991 MenuNamesEqual(name)) != menulist_.end();
1995 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1997 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1998 MenuNamesEqual(name));
1999 if (cit == menulist_.end())
2000 LYXERR0("No submenu named " << name);
2001 LASSERT(cit != menulist_.end(), /**/);
2006 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2008 iterator it = find_if(menulist_.begin(), menulist_.end(),
2009 MenuNamesEqual(name));
2010 if (it == menulist_.end())
2011 LYXERR0("No submenu named " << name);
2012 LASSERT(it != menulist_.end(), /**/);
2017 /////////////////////////////////////////////////////////////////////
2021 /////////////////////////////////////////////////////////////////////
2023 Menus::Menus() : d(new Impl) {}
2039 void Menus::read(Lexer & lex)
2047 LexerKeyword menutags[] = {
2048 { "end", md_endmenuset },
2049 { "menu", md_menu },
2050 { "menubar", md_menubar }
2053 // consistency check
2054 if (compare_ascii_no_case(lex.getString(), "menuset"))
2055 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2057 lex.pushTable(menutags);
2058 lex.setContext("Menus::read");
2062 while (lex.isOK() && !quit) {
2063 switch (lex.lex()) {
2065 d->menubar_.read(lex);
2069 QString const name = toqstr(lex.getDocString());
2070 if (d->hasMenu(name))
2071 d->getMenu(name).read(lex);
2073 MenuDefinition menu(name);
2075 d->menulist_.push_back(menu);
2083 lex.printError("Unknown menu tag");
2091 bool Menus::searchMenu(FuncRequest const & func,
2092 docstring_list & names) const
2094 MenuDefinition menu;
2095 d->expand(d->menubar_, menu, 0);
2096 return menu.searchMenu(func, names);
2100 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2104 // setup special mac specific menu items, but only do this
2105 // the first time a QMenuBar is created. Otherwise Qt will
2106 // create duplicate items in the application menu. It seems
2107 // that Qt does not remove them when the QMenubar is cleared.
2108 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2109 d->macxMenuBarInit(view, qmb);
2112 // Clear all menubar contents before filling it.
2116 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2118 if (d->menubar_.empty()) {
2119 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2120 << d->menubar_.name());
2123 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2125 MenuDefinition menu;
2126 BufferView * bv = 0;
2128 bv = view->currentBufferView();
2129 d->expand(d->menubar_, menu, bv);
2131 MenuDefinition::const_iterator m = menu.begin();
2132 MenuDefinition::const_iterator end = menu.end();
2134 for (; m != end; ++m) {
2136 if (m->kind() != MenuItem::Submenu) {
2137 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2141 LYXERR(Debug::GUI, "menu bar item " << m->label()
2142 << " is a submenu named " << m->submenuname());
2144 QString name = m->submenuname();
2145 if (!d->hasMenu(name)) {
2146 LYXERR(Debug::GUI, "\tERROR: " << name
2147 << " submenu has no menu!");
2151 Menu * menu = new Menu(view, m->submenuname(), true);
2152 menu->setTitle(label(*m));
2155 d->name_map_[view][name] = menu;
2160 void Menus::updateMenu(Menu * qmenu)
2162 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2165 if (qmenu->d->name.isEmpty())
2168 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2169 MenuDefinition fromLyxMenu(qmenu->d->name);
2170 while (!identifier.empty()) {
2171 docstring menu_name;
2172 identifier = split(identifier, menu_name, ';');
2174 if (!d->hasMenu(toqstr(menu_name))) {
2175 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2180 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2181 //FIXME: 50 is a wild guess. We should take into account here
2182 //the expansion of menu items, disabled optional items etc.
2183 bool const in_sub_menu = !fromLyxMenu.empty()
2184 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2186 fromLyxMenu.catSub(menu_name);
2188 fromLyxMenu.cat(cat_menu);
2189 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2192 if (fromLyxMenu.empty()) {
2193 qmenu->addAction(qt_("No Action Defined!"));
2197 BufferView * bv = 0;
2199 bv = qmenu->d->view->currentBufferView();
2200 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2201 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2205 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2207 LYXERR(Debug::GUI, "Context menu requested: " << name);
2208 Menu * menu = d->name_map_[&view].value(name, 0);
2209 if (!menu && !name.startsWith("context-")) {
2210 LYXERR0("requested context menu not found: " << name);
2214 menu = new Menu(&view, name, true, keyboard);
2215 d->name_map_[&view][name] = menu;
2219 } // namespace frontend
2222 #include "moc_Menus.cpp"