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 "ParagraphParameters.h"
51 #include "ParIterator.h"
53 #include "SpellChecker.h"
54 #include "TextClass.h"
56 #include "TocBackend.h"
58 #include "WordLangTuple.h"
60 #include "insets/Inset.h"
61 #include "insets/InsetCitation.h"
62 #include "insets/InsetGraphics.h"
64 #include "support/lassert.h"
65 #include "support/convert.h"
66 #include "support/debug.h"
67 #include "support/docstring_list.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/lstrings.h"
77 #if QT_VERSION >= 0x040600
78 #include <QProxyStyle>
81 #include "support/shared_ptr.h"
87 using namespace lyx::support;
95 // MacOSX specific stuff is at the end.
102 /// The type of elements that can be in a menu
110 /** This type of item explains why something is unavailable. If this
111 menuitem is in a submenu, the submenu is enabled to make sure the
112 user sees the information. */
114 /** This type of item merely shows that there might be a list or
115 something alike at this position, but the list is still empty.
116 If this item is in a submenu, the submenu will not always be
119 /** This is the list of last opened file,
120 typically for the File menu. */
122 /** This is the list of opened Documents,
123 typically for the Documents menu. */
125 /** This is the bookmarks */
129 /** This is a list of viewable formats
130 typically for the File->View menu. */
132 /** This is a list of updatable formats
133 typically for the File->Update menu. */
135 /** This is a list of exportable formats
136 typically for the File->Export menu. */
138 /** This is a list of importable formats
139 typically for the File->Import menu. */
141 /** This is the list of elements available
142 * for insertion into document. */
144 /** This is the list of user-configurable
145 insets to insert into document */
147 /** This is the list of XML elements to
148 insert into the document */
150 /** This is the list of floats that we can
151 insert a list for. */
153 /** This is the list of floats that we can
156 /** This is the list of selections that can
161 /** Available branches in document */
163 /** Available indices in document */
165 /** Context menu for indices in document */
167 /** Available index lists in document */
169 /** Context menu for available indices lists in document */
171 /** Available citation styles for a given citation */
173 /** Available graphics groups */
175 /// Words suggested by the spellchecker.
177 /** Used Languages */
179 /** This is the list of arguments available
180 for insertion into the current layout. */
182 /** This is the list of arguments available
183 in the InsetArgument context menu. */
185 /** This is the list of captions available
186 in the current layout. */
188 /** This is the list of captions available
189 in the InsetCaption context menu. */
191 /** Commands to separate environments. */
192 EnvironmentSeparators
195 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
198 QString const & label,
199 QString const & submenu = QString(),
200 QString const & tooltip = QString(),
201 bool optional = false)
202 : kind_(kind), label_(label), submenuname_(submenu),
203 tooltip_(tooltip), optional_(optional)
205 LATTEST(kind == Submenu || kind == Help || kind == Info);
209 QString const & label,
210 FuncRequest const & func,
211 QString const & tooltip = QString(),
212 bool optional = false,
213 FuncRequest::Origin origin = FuncRequest::MENU)
214 : kind_(kind), label_(label), func_(func),
215 tooltip_(tooltip), optional_(optional)
217 func_.setOrigin(origin);
220 // shared_ptr<MenuDefinition> needs this apprently...
223 /// The label of a given menuitem
224 QString label() const
226 int const index = label_.lastIndexOf('|');
227 return index == -1 ? label_ : label_.left(index);
230 /// The keyboard shortcut (usually underlined in the entry)
231 QString shortcut() const
233 int const index = label_.lastIndexOf('|');
234 return index == -1 ? QString() : label_.mid(index + 1);
236 /// The complete label, with label and shortcut separated by a '|'
237 QString fulllabel() const { return label_; }
238 /// The kind of entry
239 Kind kind() const { return kind_; }
240 /// the action (if relevant)
241 FuncRequest const & func() const { return func_; }
243 QString const & tooltip() const { return tooltip_; }
244 /// returns true if the entry should be omitted when disabled
245 bool optional() const { return optional_; }
246 /// returns the status of the lfun associated with this entry
247 FuncStatus const & status() const { return status_; }
248 /// returns the status of the lfun associated with this entry
249 FuncStatus & status() { return status_; }
250 /// returns the status of the lfun associated with this entry
251 void status(FuncStatus const & status) { status_ = status; }
253 ///returns the binding associated to this action.
254 QString binding() const
256 if (kind_ != Command)
258 // Get the keys bound to this action, but keep only the
260 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
261 if (!bindings.empty())
262 return toqstr(bindings.begin()->print(KeySequence::ForGui));
264 LYXERR(Debug::KBMAP, "No binding for "
265 << lyxaction.getActionName(func_.action())
266 << '(' << func_.argument() << ')');
270 /// the description of the submenu (if relevant)
271 QString const & submenuname() const { return submenuname_; }
272 /// set the description of the submenu
273 void submenuname(QString const & name) { submenuname_ = name; }
275 bool hasSubmenu() const { return !submenu_.isEmpty(); }
277 MenuDefinition const & submenu() const { return submenu_.at(0); }
278 MenuDefinition & submenu() { return submenu_[0]; }
280 void setSubmenu(MenuDefinition const & menu)
283 submenu_.append(menu);
294 QString submenuname_;
301 /// contains 0 or 1 item.
302 QList<MenuDefinition> submenu_;
306 class MenuDefinition {
309 typedef std::vector<MenuItem> ItemList;
311 typedef ItemList::const_iterator const_iterator;
313 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
318 QString const & name() const { return name_; }
320 bool empty() const { return items_.empty(); }
321 /// Clear the menu content.
322 void clear() { items_.clear(); }
324 size_t size() const { return items_.size(); }
326 MenuItem const & operator[](size_t) const;
328 const_iterator begin() const { return items_.begin(); }
330 const_iterator end() const { return items_.end(); }
332 void cat(MenuDefinition const & other);
334 void catSub(docstring const & name);
336 // search for func in this menu iteratively, and put menu
338 bool searchMenu(FuncRequest const & func, docstring_list & names)
341 bool hasFunc(FuncRequest const &) const;
342 /// Add the menu item unconditionally
343 void add(MenuItem const & item) { items_.push_back(item); }
344 /// Checks the associated FuncRequest status before adding the
346 void addWithStatusCheck(MenuItem const &);
347 // Check whether the menu shortcuts are unique
348 void checkShortcuts() const;
350 void expandLastfiles();
351 void expandDocuments();
352 void expandBookmarks();
353 void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
354 void expandFloatListInsert(Buffer const * buf);
355 void expandFloatInsert(Buffer const * buf);
356 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
357 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
358 void expandToc(Buffer const * buf);
359 void expandPasteRecent(Buffer const * buf);
360 void expandToolbars();
361 void expandBranches(Buffer const * buf);
362 void expandIndices(Buffer const * buf, bool listof = false);
363 void expandIndicesContext(Buffer const * buf, bool listof = false);
364 void expandCiteStyles(BufferView const *);
365 void expandGraphicsGroups(BufferView const *);
366 void expandSpellingSuggestions(BufferView const *);
367 void expandLanguageSelector(Buffer const * buf);
368 void expandArguments(BufferView const *, bool switcharg = false);
369 void expandCaptions(Buffer const * buf, bool switchcap = false);
370 void expandEnvironmentSeparators(BufferView const *);
378 /// Helper for std::find_if
382 MenuNamesEqual(QString const & name) : name_(name) {}
383 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
390 typedef std::vector<MenuDefinition> MenuList;
392 typedef MenuList::const_iterator const_iterator;
394 typedef MenuList::iterator iterator;
396 /////////////////////////////////////////////////////////////////////
397 // MenuDefinition implementation
398 /////////////////////////////////////////////////////////////////////
400 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
404 case MenuItem::Command: {
405 FuncStatus status = lyx::getStatus(i.func());
406 if (status.unknown() || (!status.enabled() && i.optional()))
409 items_.back().status(status);
413 case MenuItem::Submenu: {
414 bool enabled = false;
415 if (i.hasSubmenu()) {
416 for (const_iterator cit = i.submenu().begin();
417 cit != i.submenu().end(); ++cit) {
418 // Only these kind of items affect the status of the submenu
419 if ((cit->kind() == MenuItem::Command
420 || cit->kind() == MenuItem::Submenu
421 || cit->kind() == MenuItem::Help)
422 && cit->status().enabled()) {
428 if (enabled || !i.optional()) {
430 items_.back().status().setEnabled(enabled);
435 case MenuItem::Separator:
436 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
446 void MenuDefinition::read(Lexer & lex)
463 md_indiceslistscontext,
477 md_spellingsuggestions,
486 LexerKeyword menutags[] = {
487 { "arguments", md_arguments },
488 { "bookmarks", md_bookmarks },
489 { "branches", md_branches },
490 { "captions", md_captions },
491 { "charstyles", md_charstyles },
492 { "citestyles", md_citestyles },
493 { "custom", md_custom },
494 { "documents", md_documents },
495 { "elements", md_elements },
496 { "end", md_endmenu },
497 { "environmentseparators", md_env_separators },
498 { "exportformats", md_exportformats },
499 { "floatinsert", md_floatinsert },
500 { "floatlistinsert", md_floatlistinsert },
501 { "graphicsgroups", md_graphicsgroups },
502 { "importformats", md_importformats },
503 { "indices", md_indices },
504 { "indicescontext", md_indicescontext },
505 { "indiceslists", md_indiceslists },
506 { "indiceslistscontext", md_indiceslistscontext },
508 { "languageselector", md_languageselector },
509 { "lastfiles", md_lastfiles },
510 { "optitem", md_optitem },
511 { "optsubmenu", md_optsubmenu },
512 { "pasterecent", md_pasterecent },
513 { "separator", md_separator },
514 { "spellingsuggestions", md_spellingsuggestions },
515 { "submenu", md_submenu },
516 { "switcharguments", md_switcharguments },
517 { "switchcaptions", md_switchcaptions },
519 { "toolbars", md_toolbars },
520 { "updateformats", md_updateformats },
521 { "viewformats", md_viewformats }
524 lex.pushTable(menutags);
525 lex.setContext("MenuDefinition::read: ");
528 while (lex.isOK() && md_type != md_endmenu) {
529 switch (md_type = lex.lex()) {
533 docstring const name = translateIfPossible(lex.getDocString());
535 string const command = lex.getString();
536 FuncRequest func = lyxaction.lookupFunc(command);
537 FuncRequest::Origin origin = FuncRequest::MENU;
538 if (name_.startsWith("context-toc-"))
539 origin = FuncRequest::TOC;
540 bool const optional = (md_type == md_optitem);
541 add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
546 add(MenuItem(MenuItem::Separator));
550 add(MenuItem(MenuItem::Lastfiles));
554 add(MenuItem(MenuItem::CharStyles));
558 add(MenuItem(MenuItem::Custom));
562 add(MenuItem(MenuItem::Elements));
566 add(MenuItem(MenuItem::Documents));
570 add(MenuItem(MenuItem::Bookmarks));
574 add(MenuItem(MenuItem::Toc));
578 add(MenuItem(MenuItem::ViewFormats));
581 case md_updateformats:
582 add(MenuItem(MenuItem::UpdateFormats));
585 case md_exportformats:
586 add(MenuItem(MenuItem::ExportFormats));
589 case md_importformats:
590 add(MenuItem(MenuItem::ImportFormats));
593 case md_floatlistinsert:
594 add(MenuItem(MenuItem::FloatListInsert));
598 add(MenuItem(MenuItem::FloatInsert));
602 add(MenuItem(MenuItem::PasteRecent));
606 add(MenuItem(MenuItem::Toolbars));
610 add(MenuItem(MenuItem::Branches));
614 add(MenuItem(MenuItem::CiteStyles));
617 case md_graphicsgroups:
618 add(MenuItem(MenuItem::GraphicsGroups));
621 case md_spellingsuggestions:
622 add(MenuItem(MenuItem::SpellingSuggestions));
625 case md_languageselector:
626 add(MenuItem(MenuItem::LanguageSelector));
630 add(MenuItem(MenuItem::Indices));
633 case md_indicescontext:
634 add(MenuItem(MenuItem::IndicesContext));
637 case md_indiceslists:
638 add(MenuItem(MenuItem::IndicesLists));
641 case md_indiceslistscontext:
642 add(MenuItem(MenuItem::IndicesListsContext));
646 add(MenuItem(MenuItem::Arguments));
649 case md_switcharguments:
650 add(MenuItem(MenuItem::SwitchArguments));
654 add(MenuItem(MenuItem::Captions));
657 case md_switchcaptions:
658 add(MenuItem(MenuItem::SwitchCaptions));
661 case md_env_separators:
662 add(MenuItem(MenuItem::EnvironmentSeparators));
668 docstring const mlabel = translateIfPossible(lex.getDocString());
670 docstring const mname = lex.getDocString();
671 bool const optional = (md_type == md_optsubmenu);
672 add(MenuItem(MenuItem::Submenu,
673 toqstr(mlabel), toqstr(mname), QString(), optional));
681 lex.printError("Unknown menu tag");
689 MenuItem const & MenuDefinition::operator[](size_type i) const
695 bool MenuDefinition::hasFunc(FuncRequest const & func) const
697 for (const_iterator it = begin(), et = end(); it != et; ++it)
698 if (it->func() == func)
704 void MenuDefinition::catSub(docstring const & name)
706 add(MenuItem(MenuItem::Submenu,
707 qt_("More...|M"), toqstr(name), QString(), false));
710 void MenuDefinition::cat(MenuDefinition const & other)
712 const_iterator et = other.end();
713 for (const_iterator it = other.begin(); it != et; ++it)
718 void MenuDefinition::checkShortcuts() const
720 // This is a quadratic algorithm, but we do not care because
721 // menus are short enough
722 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
723 QString shortcut = it1->shortcut();
724 if (shortcut.isEmpty())
726 if (!it1->label().contains(shortcut))
727 LYXERR0("Menu warning: menu entry \""
729 << "\" does not contain shortcut `"
730 << shortcut << "'.");
731 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
732 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
733 LYXERR0("Menu warning: menu entries "
734 << '"' << it1->fulllabel()
735 << "\" and \"" << it2->fulllabel()
736 << "\" share the same shortcut.");
743 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
745 const_iterator m = begin();
746 const_iterator m_end = end();
747 for (; m != m_end; ++m) {
748 if (m->kind() == MenuItem::Command && m->func() == func) {
749 names.push_back(qstring_to_ucs4(m->label()));
752 if (m->kind() == MenuItem::Submenu) {
753 names.push_back(qstring_to_ucs4(m->label()));
754 if (!m->hasSubmenu()) {
755 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
756 << m->label() << " name=" << m->submenuname());
760 if (m->submenu().searchMenu(func, names))
769 QString limitStringLength(docstring const & str)
771 size_t const max_item_length = 45;
773 if (str.size() > max_item_length)
774 return toqstr(str.substr(0, max_item_length - 3) + "...");
780 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
785 graphics::getGraphicsGroups(bv->buffer(), grp);
789 set<string>::const_iterator it = grp.begin();
790 set<string>::const_iterator end = grp.end();
791 add(MenuItem(MenuItem::Command, qt_("No Group"),
792 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
793 for (; it != end; ++it) {
794 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
795 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
800 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
804 Cursor const & cur = bv->cursor();
808 docstring_list suggestions;
809 Paragraph const & par = cur.paragraph();
810 pos_type from = cur.pos();
812 SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
814 case SpellChecker::UNKNOWN_WORD:
815 if (lyxrc.spellcheck_continuously) {
816 LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
817 docstring const & selection = cur.selectionAsString(false);
818 if (!cur.selection() || selection == wl.word()) {
820 size_t m = 10; // first submenu index
821 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
822 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
823 for (; i != suggestions.size(); ++i) {
824 docstring const & suggestion = suggestions[i];
825 LYXERR(Debug::GUI, suggestion);
826 MenuItem w(MenuItem::Command, toqstr(suggestion),
827 FuncRequest(LFUN_WORD_REPLACE,
828 replace2string(suggestion, selection,
829 true, // case sensitive
833 false))); // find next
837 item.submenu().add(w);
842 add(MenuItem(MenuItem::Separator));
843 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
844 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
845 FuncRequest(LFUN_SPELLING_ADD, arg)));
846 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
847 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
851 case SpellChecker::LEARNED_WORD: {
852 LYXERR(Debug::GUI, "Learned Word.");
853 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
854 add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
855 FuncRequest(LFUN_SPELLING_REMOVE, arg)));
858 case SpellChecker::NO_DICTIONARY:
859 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
861 case SpellChecker::WORD_OK:
862 case SpellChecker::COMPOUND_WORD:
863 case SpellChecker::ROOT_FOUND:
864 case SpellChecker::IGNORED_WORD:
869 struct sortLanguageByName {
870 bool operator()(const Language * a, const Language * b) const {
871 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
875 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
880 std::set<Language const *> languages_buffer =
881 buf->masterBuffer()->getLanguages();
883 if (languages_buffer.size() < 2)
886 std::set<Language const *, sortLanguageByName> languages;
888 std::set<Language const *>::const_iterator const beg =
889 languages_buffer.begin();
890 for (std::set<Language const *>::const_iterator cit = beg;
891 cit != languages_buffer.end(); ++cit) {
892 languages.insert(*cit);
895 MenuItem item(MenuItem::Submenu, qt_("Language|L"));
896 item.setSubmenu(MenuDefinition(qt_("Language")));
897 QString morelangs = qt_("More Languages ...|M");
898 QStringList accelerators;
899 if (morelangs.contains('|'))
900 accelerators.append(morelangs.section('|', -1));
901 std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
902 for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
903 cit != languages.end(); ++cit) {
904 QString label = qt_((*cit)->display());
905 // try to add an accelerator
906 bool success = false;
907 // try capitals first
908 for (int i = 0; i < label.size(); ++i) {
909 QChar const ch = label[i];
912 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
913 label = label + toqstr("|") + ch;
914 accelerators.append(ch);
919 // if all capitals are taken, try the rest
921 for (int i = 0; i < label.size(); ++i) {
922 if (label[i].isSpace())
924 QString const ch = QString(label[i]);
925 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
926 label = label + toqstr("|") + ch;
927 accelerators.append(ch);
932 MenuItem w(MenuItem::Command, label,
933 FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
934 item.submenu().addWithStatusCheck(w);
936 item.submenu().add(MenuItem(MenuItem::Separator));
937 item.submenu().add(MenuItem(MenuItem::Command, morelangs,
938 FuncRequest(LFUN_DIALOG_SHOW, "character")));
943 void MenuDefinition::expandLastfiles()
945 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
946 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
950 for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
951 string const file = lfit->absFileName();
952 QString const short_path = toqstr(makeDisplayPath(file, 30));
953 QString const long_path = toqstr(makeDisplayPath(file));
956 label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
958 label = QString("%1. %2").arg(ii).arg(short_path);
959 add(MenuItem(MenuItem::Command, label,
960 FuncRequest(LFUN_FILE_OPEN, file), long_path));
965 void MenuDefinition::expandDocuments()
967 MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
968 item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
970 Buffer * first = theBufferList().first();
972 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
978 if (!guiApp->currentView())
980 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
983 Buffer const & b = wa->bufferView().buffer();
984 QString label = toqstr(b.fileName().displayName(20));
988 label = QString::number(i) + ". " + label + '|' + QString::number(i);
989 add(MenuItem(MenuItem::Command, label,
990 FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
997 // We cannot use a for loop as the buffer list cycles.
999 if (!(guiApp->currentView()
1000 && guiApp->currentView()->workArea(*b))) {
1001 QString label = toqstr(b->fileName().displayName(20));
1005 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1006 item.submenu().add(MenuItem(MenuItem::Command, label,
1007 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1010 b = theBufferList().next(b);
1011 } while (b != first);
1013 if (!item.submenu().empty())
1018 void MenuDefinition::expandBookmarks()
1020 lyx::BookmarksSection const & bm = theSession().bookmarks();
1023 for (size_t i = 1; i <= bm.size(); ++i) {
1024 if (bm.isValid(i)) {
1025 string const file = bm.bookmark(i).filename.absFileName();
1026 QString const label = QString("%1. %2|%3").arg(i)
1027 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1028 add(MenuItem(MenuItem::Command, label,
1029 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1034 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1038 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1040 if (!buf && kind != MenuItem::ImportFormats)
1043 typedef vector<Format const *> Formats;
1045 FuncCode action = LFUN_NOACTION;
1048 case MenuItem::ImportFormats:
1049 formats = theConverters().importableFormats();
1050 action = LFUN_BUFFER_IMPORT;
1052 case MenuItem::ViewFormats:
1053 formats = buf->params().exportableFormats(true);
1054 action = LFUN_BUFFER_VIEW;
1056 case MenuItem::UpdateFormats:
1057 formats = buf->params().exportableFormats(true);
1058 action = LFUN_BUFFER_UPDATE;
1060 case MenuItem::ExportFormats:
1061 formats = buf->params().exportableFormats(false);
1062 action = LFUN_BUFFER_EXPORT;
1068 sort(formats.begin(), formats.end(), Format::formatSorter);
1070 bool const view_update = (kind == MenuItem::ViewFormats
1071 || kind == MenuItem::UpdateFormats);
1075 smenue = (kind == MenuItem::ViewFormats
1076 ? qt_("View (Other Formats)|F")
1077 : qt_("Update (Other Formats)|p"));
1078 MenuItem item(MenuItem::Submenu, smenue);
1079 item.setSubmenu(MenuDefinition(smenue));
1081 Formats::const_iterator fit = formats.begin();
1082 Formats::const_iterator end = formats.end();
1083 for (; fit != end ; ++fit) {
1084 if ((*fit)->dummy())
1087 docstring lab = from_utf8((*fit)->prettyname());
1088 docstring const scut = from_utf8((*fit)->shortcut());
1089 docstring const tmplab = lab;
1092 lab += char_type('|') + scut;
1093 docstring const lab_i18n = translateIfPossible(lab);
1094 docstring const shortcut = split(lab_i18n, lab, '|');
1096 bool const untranslated = (lab == lab_i18n);
1097 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1100 case MenuItem::ImportFormats:
1101 label += from_ascii("...");
1103 case MenuItem::ViewFormats:
1104 case MenuItem::UpdateFormats:
1105 if ((*fit)->name() == buf->params().getDefaultOutputFormat()) {
1106 docstring lbl = (kind == MenuItem::ViewFormats
1107 ? bformat(_("View [%1$s]|V"), label)
1108 : bformat(_("Update [%1$s]|U"), label));
1109 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1113 case MenuItem::ExportFormats:
1114 if (!(*fit)->inExportMenu())
1118 // we already asserted earlier in this case
1122 if (!shortcut.empty())
1123 label += '|' + shortcut;
1127 item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1128 toqstr(label), FuncRequest(action, (*fit)->name())));
1130 item.submenu().add(MenuItem(MenuItem::Command, toqstr(label),
1131 FuncRequest(action, (*fit)->name())));
1134 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1135 FuncRequest(action, (*fit)->name())));
1137 add(MenuItem(MenuItem::Command, toqstr(label),
1138 FuncRequest(action, (*fit)->name())));
1146 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1151 FloatList const & floats = buf->params().documentClass().floats();
1152 FloatList::const_iterator cit = floats.begin();
1153 FloatList::const_iterator end = floats.end();
1155 for (; cit != end; ++cit) {
1156 if (!cit->second.usesFloatPkg()) {
1157 // Different floats could declare the same ListCommand. We only
1158 // want it on the list once, though.
1159 string const & list_cmd = cit->second.listCommand();
1160 if (list_cmd.empty())
1161 // we do not know how to generate such a list
1163 // This form of insert returns an iterator pointing to the newly
1164 // inserted element OR the existing element with that value, and
1165 // a bool indicating whether we inserted a new element. So we can
1166 // see if one is there and insert it if not all at once.
1167 pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1171 string const & list_name = cit->second.listName();
1172 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1173 FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1178 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1183 FloatList const & floats = buf->params().documentClass().floats();
1184 FloatList::const_iterator cit = floats.begin();
1185 FloatList::const_iterator end = floats.end();
1186 for (; cit != end; ++cit) {
1188 QString const label = qt_(cit->second.name());
1189 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1190 FuncRequest(LFUN_FLOAT_INSERT,
1191 cit->second.floattype())));
1196 void MenuDefinition::expandFlexInsert(
1197 Buffer const * buf, InsetLayout::InsetLyXType type)
1202 TextClass::InsetLayouts const & insetLayouts =
1203 buf->params().documentClass().insetLayouts();
1204 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1205 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1206 for (; cit != end; ++cit) {
1207 if (cit->second.lyxtype() == type) {
1208 docstring label = cit->first;
1209 // we remove the "Flex:" prefix, if it is present
1210 if (prefixIs(label, from_utf8("Flex:")))
1211 label = label.substr(5);
1212 addWithStatusCheck(MenuItem(MenuItem::Command,
1213 toqstr(translateIfPossible(label)),
1214 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1217 // FIXME This is a little clunky.
1218 if (items_.empty() && type == InsetLayout::CUSTOM)
1219 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1223 size_t const max_number_of_items = 25;
1225 void MenuDefinition::expandToc2(Toc const & toc_list,
1226 size_t from, size_t to, int depth)
1228 int shortcut_count = 0;
1230 // check whether depth is smaller than the smallest depth in toc.
1231 int min_depth = 1000;
1232 for (size_t i = from; i < to; ++i)
1233 min_depth = min(min_depth, toc_list[i].depth());
1234 if (min_depth > depth)
1237 if (to - from <= max_number_of_items) {
1238 for (size_t i = from; i < to; ++i) {
1239 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1240 label += limitStringLength(toc_list[i].str());
1241 if (toc_list[i].depth() == depth) {
1243 if (shortcut_count < 9) {
1244 if (label.contains(QString::number(shortcut_count + 1)))
1245 label += QString::number(++shortcut_count);
1248 add(MenuItem(MenuItem::Command, label,
1249 FuncRequest(toc_list[i].action())));
1254 size_t new_pos = pos + 1;
1255 while (new_pos < to && toc_list[new_pos].depth() > depth)
1258 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1259 label += limitStringLength(toc_list[pos].str());
1260 if (toc_list[pos].depth() == depth) {
1262 if (shortcut_count < 9) {
1263 if (label.contains(QString::number(shortcut_count + 1)))
1264 label += QString::number(++shortcut_count);
1267 if (new_pos == pos + 1) {
1268 add(MenuItem(MenuItem::Command,
1269 label, FuncRequest(toc_list[pos].action())));
1272 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
1273 MenuItem item(MenuItem::Submenu, label);
1274 item.setSubmenu(sub);
1283 void MenuDefinition::expandToc(Buffer const * buf)
1285 // To make things very cleanly, we would have to pass buf to
1286 // all MenuItem constructors and to expandToc2. However, we
1287 // know that all the entries in a TOC will be have status_ ==
1288 // OK, so we avoid this unnecessary overhead (JMarc)
1291 add(MenuItem(MenuItem::Info, qt_("<No Document Open>")));
1295 // Add an entry for the master doc if this is a child doc
1296 Buffer const * const master = buf->masterBuffer();
1297 if (buf != master) {
1298 ParIterator const pit = par_iterator_begin(master->inset());
1299 string const arg = convert<string>(pit->id());
1300 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1301 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1304 MenuDefinition other_lists;
1306 FloatList const & floatlist = buf->params().documentClass().floats();
1307 TocList const & toc_list = buf->tocBackend().tocs();
1308 TocList::const_iterator cit = toc_list.begin();
1309 TocList::const_iterator end = toc_list.end();
1310 for (; cit != end; ++cit) {
1311 // Handle this later
1312 if (cit->first == "tableofcontents")
1315 MenuDefinition submenu;
1316 if (cit->second.size() >= 30) {
1317 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1318 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
1320 TocIterator ccit = cit->second.begin();
1321 TocIterator eend = cit->second.end();
1322 for (; ccit != eend; ++ccit) {
1323 submenu.add(MenuItem(MenuItem::Command,
1324 limitStringLength(ccit->str()) + '|',
1325 FuncRequest(ccit->action())));
1329 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1330 item.setSubmenu(submenu);
1331 if (floatlist.typeExist(cit->first) || cit->first == "child") {
1332 // Those two types deserve to be in the main menu.
1333 item.setSubmenu(submenu);
1336 other_lists.add(item);
1338 if (!other_lists.empty()) {
1339 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1340 item.setSubmenu(other_lists);
1344 // Handle normal TOC
1345 cit = toc_list.find("tableofcontents");
1347 LYXERR(Debug::GUI, "No table of contents.");
1349 if (!cit->second.empty())
1350 expandToc2(cit->second, 0, cit->second.size(), 0);
1352 add(MenuItem(MenuItem::Info, qt_("<Empty Table of Contents>")));
1357 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1359 docstring_list const sel = cap::availableSelections(buf);
1361 docstring_list::const_iterator cit = sel.begin();
1362 docstring_list::const_iterator end = sel.end();
1364 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1365 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1366 FuncRequest(LFUN_PASTE, convert<string>(index))));
1371 void MenuDefinition::expandToolbars()
1373 MenuDefinition other_lists;
1374 // extracts the toolbars from the backend
1375 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1376 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1377 for (; cit != end; ++cit) {
1378 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1379 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1380 if (guiApp->toolbars().isMainToolbar(cit->name))
1383 other_lists.add(item);
1386 if (!other_lists.empty()) {
1387 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1388 item.setSubmenu(other_lists);
1394 void MenuDefinition::expandBranches(Buffer const * buf)
1399 BufferParams const & master_params = buf->masterBuffer()->params();
1400 BufferParams const & params = buf->params();
1401 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1402 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1406 BranchList::const_iterator cit = master_params.branchlist().begin();
1407 BranchList::const_iterator end = master_params.branchlist().end();
1409 for (int ii = 1; cit != end; ++cit, ++ii) {
1410 docstring label = cit->branch();
1412 label = convert<docstring>(ii) + ". " + label
1413 + char_type('|') + convert<docstring>(ii);
1415 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1416 FuncRequest(LFUN_BRANCH_INSERT,
1420 if (buf == buf->masterBuffer())
1423 MenuDefinition child_branches;
1425 BranchList::const_iterator ccit = params.branchlist().begin();
1426 BranchList::const_iterator cend = params.branchlist().end();
1428 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1429 docstring label = ccit->branch();
1431 label = convert<docstring>(ii) + ". " + label
1432 + char_type('|') + convert<docstring>(ii);
1434 label += char_type('|');
1435 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1437 FuncRequest(LFUN_BRANCH_INSERT,
1441 if (!child_branches.empty()) {
1442 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1443 item.setSubmenu(child_branches);
1449 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1454 BufferParams const & params = buf->masterBuffer()->params();
1455 if (!params.use_indices) {
1457 addWithStatusCheck(MenuItem(MenuItem::Command,
1458 qt_("Index List|I"),
1459 FuncRequest(LFUN_INDEX_PRINT,
1460 from_ascii("idx"))));
1462 addWithStatusCheck(MenuItem(MenuItem::Command,
1463 qt_("Index Entry|d"),
1464 FuncRequest(LFUN_INDEX_INSERT,
1465 from_ascii("idx"))));
1469 if (params.indiceslist().empty())
1472 IndicesList::const_iterator cit = params.indiceslist().begin();
1473 IndicesList::const_iterator end = params.indiceslist().end();
1475 for (int ii = 1; cit != end; ++cit, ++ii) {
1477 docstring const label =
1478 bformat(_("Index: %1$s"), cit->index());
1479 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1480 FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1482 docstring const label =
1483 bformat(_("Index Entry (%1$s)"), cit->index());
1484 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1485 FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1491 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1496 BufferParams const & params = buf->masterBuffer()->params();
1497 if (!params.use_indices || params.indiceslist().empty())
1500 IndicesList::const_iterator cit = params.indiceslist().begin();
1501 IndicesList::const_iterator end = params.indiceslist().end();
1503 for (int ii = 1; cit != end; ++cit, ++ii) {
1505 InsetCommandParams p(INDEX_PRINT_CODE);
1506 p["type"] = cit->shortcut();
1507 string const data = InsetCommand::params2string(p);
1508 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1509 FuncRequest(LFUN_INSET_MODIFY, data)));
1511 docstring const label =
1512 bformat(_("Index Entry (%1$s)"), cit->index());
1513 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1514 FuncRequest(LFUN_INSET_MODIFY,
1515 from_ascii("changetype ") + cit->shortcut())));
1521 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1526 Inset const * inset = bv->cursor().nextInset();
1527 if (!inset || inset->lyxCode() != CITE_CODE) {
1528 add(MenuItem(MenuItem::Command,
1529 qt_("No Citation in Scope!"),
1530 FuncRequest(LFUN_NOACTION)));
1533 InsetCommand const * citinset =
1534 static_cast<InsetCommand const *>(inset);
1536 Buffer const * buf = &bv->buffer();
1537 string const cmd = citinset->params().getCmdName();
1539 docstring const & key = citinset->getParam("key");
1541 add(MenuItem(MenuItem::Command,
1542 qt_("No citations selected!"),
1543 FuncRequest(LFUN_NOACTION)));
1547 docstring const & before = citinset->getParam("before");
1548 docstring const & after = citinset->getParam("after");
1550 size_t const n = cmd.size();
1551 bool const force = cmd[0] == 'C';
1552 bool const full = cmd[n] == '*';
1554 vector<docstring> const keys = getVectorFromString(key);
1556 vector<CitationStyle> const citeStyleList = buf->params().citeStyles();
1557 static const size_t max_length = 40;
1558 vector<docstring> citeStrings =
1559 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(),
1560 before, after, from_utf8("dialog"), max_length);
1562 vector<docstring>::const_iterator cit = citeStrings.begin();
1563 vector<docstring>::const_iterator end = citeStrings.end();
1565 for (int ii = 1; cit != end; ++cit, ++ii) {
1566 docstring label = *cit;
1567 CitationStyle cs = citeStyleList[ii - 1];
1568 cs.forceUpperCase &= force;
1569 cs.fullAuthorList &= full;
1570 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1571 FuncRequest(LFUN_INSET_MODIFY,
1572 "changetype " + from_utf8(citationStyleToString(cs)))));
1577 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1582 if (!bv->cursor().inTexted())
1585 Inset const * inset = &bv->cursor().inset();
1586 Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1587 if (inset && args.empty())
1588 args = inset->getLayout().args();
1589 if (args.empty() || (switcharg && args.size() == 1))
1591 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1592 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1593 for (; lait != laend; ++lait) {
1594 Layout::latexarg arg = (*lait).second;
1595 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1596 QString item = toqstr(translateIfPossible(str));
1598 add(MenuItem(MenuItem::Command, item,
1599 FuncRequest(LFUN_INSET_MODIFY,
1600 from_ascii("changetype ")
1601 + from_ascii((*lait).first))));
1603 add(MenuItem(MenuItem::Command, item,
1604 FuncRequest(LFUN_ARGUMENT_INSERT,
1605 from_ascii((*lait).first))));
1610 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1615 vector<docstring> caps;
1616 DocumentClass const & dc = buf->params().documentClass();
1617 TextClass::InsetLayouts::const_iterator lit = dc.insetLayouts().begin();
1618 TextClass::InsetLayouts::const_iterator len = dc.insetLayouts().end();
1619 for (; lit != len; ++lit) {
1620 if (prefixIs(lit->first, from_ascii("Caption:")))
1621 caps.push_back(lit->first);
1624 if (caps.empty() || (switchcap && caps.size() == 1))
1626 if (caps.size() == 1) {
1628 docstring const type = split(*caps.begin(), dummy, ':');
1629 add(MenuItem(MenuItem::Command, qt_("Caption"),
1630 FuncRequest(LFUN_CAPTION_INSERT, translateIfPossible(type))));
1634 MenuDefinition captions;
1636 vector<docstring>::const_iterator cit = caps.begin();
1637 vector<docstring>::const_iterator end = caps.end();
1639 for (int ii = 1; cit != end; ++cit, ++ii) {
1641 docstring const type = split(*cit, dummy, ':');
1642 docstring const trtype = translateIfPossible(type);
1643 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1644 // make menu item optional, otherwise we would also see
1645 // forbidden caption types
1647 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cmitem),
1648 FuncRequest(LFUN_INSET_MODIFY,
1649 from_ascii("changetype ")
1650 + type), QString(), true));
1652 captions.addWithStatusCheck(MenuItem(MenuItem::Command,
1654 FuncRequest(LFUN_CAPTION_INSERT,
1655 type), QString(), true));
1657 if (!captions.empty()) {
1658 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1659 item.setSubmenu(captions);
1665 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv)
1669 Text const * text = bv->cursor().text();
1670 // no paragraphs and no separators exist in math
1674 pit_type pit = bv->cursor().selBegin().pit();
1675 Paragraph const & par = text->getPar(pit);
1676 docstring const curlayout = par.layout().name();
1677 docstring outerlayout;
1678 depth_type current_depth = par.params().depth();
1679 // check if we have an environment in our nesting hierarchy
1680 Paragraph cpar = par;
1682 if (pit == 0 || cpar.params().depth() == 0)
1685 cpar = text->getPar(pit);
1686 if (cpar.params().depth() < current_depth
1687 && cpar.layout().isEnvironment()) {
1688 outerlayout = cpar.layout().name();
1689 current_depth = cpar.params().depth();
1692 if (par.layout().isEnvironment()) {
1693 docstring const label =
1694 bformat(_("Start New Environment (%1$s)"),
1695 translateIfPossible(curlayout));
1696 add(MenuItem(MenuItem::Command, toqstr(label),
1697 FuncRequest(LFUN_ENVIRONMENT_SPLIT)));
1699 if (!outerlayout.empty()) {
1700 docstring const label =
1701 bformat(_("Start New Parent Environment (%1$s)"),
1702 translateIfPossible(outerlayout));
1703 add(MenuItem(MenuItem::Command, toqstr(label),
1704 FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1705 from_ascii("outer"))));
1712 /////////////////////////////////////////////////////////////////////
1713 // Menu::Impl definition and implementation
1714 /////////////////////////////////////////////////////////////////////
1718 /// populates the menu or one of its submenu
1719 /// This is used as a recursive function
1720 void populate(QMenu & qMenu, MenuDefinition const & menu);
1722 /// Only needed for top level menus.
1723 MenuDefinition * top_level_menu;
1726 /// the name of this menu
1732 /// Get a MenuDefinition item label from the menu backend
1733 static QString label(MenuItem const & mi)
1735 QString label = mi.label();
1736 label.replace("&", "&&");
1738 QString shortcut = mi.shortcut();
1739 if (!shortcut.isEmpty()) {
1740 int pos = label.indexOf(shortcut);
1742 //label.insert(pos, 1, char_type('&'));
1743 label.replace(pos, 0, "&");
1746 QString const binding = mi.binding();
1747 if (!binding.isEmpty())
1748 label += '\t' + binding;
1753 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1755 LYXERR(Debug::GUI, "populating menu " << menu.name());
1757 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1760 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1761 MenuDefinition::const_iterator m = menu.begin();
1762 MenuDefinition::const_iterator end = menu.end();
1763 for (; m != end; ++m) {
1764 if (m->kind() == MenuItem::Separator)
1765 qMenu.addSeparator();
1766 else if (m->kind() == MenuItem::Submenu) {
1767 QMenu * subMenu = qMenu.addMenu(label(*m));
1768 populate(*subMenu, m->submenu());
1769 subMenu->setEnabled(m->status().enabled());
1771 // we have a MenuItem::Command
1772 qMenu.addAction(new Action(QIcon(), label(*m),
1773 m->func(), m->tooltip(), &qMenu));
1778 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1779 class AlwaysMnemonicStyle : public QProxyStyle {
1781 int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1782 QStyleHintReturn *returnData = 0) const
1784 if (hint == QStyle::SH_UnderlineShortcut)
1786 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1791 /////////////////////////////////////////////////////////////////////
1792 // Menu implementation
1793 /////////////////////////////////////////////////////////////////////
1795 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1796 : QMenu(gv), d(new Menu::Impl)
1798 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1800 setStyle(new AlwaysMnemonicStyle);
1804 d->top_level_menu = top_level? new MenuDefinition : 0;
1808 if (d->top_level_menu)
1809 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1815 delete d->top_level_menu;
1820 void Menu::updateView()
1822 guiApp->menus().updateMenu(this);
1828 QList<QAction *> items = actions();
1829 for (int i = 0; i != items.size(); ++i) {
1830 // QAction::menu() returns 0 if there's no submenu.
1831 delete items.at(i)->menu();
1837 /////////////////////////////////////////////////////////////////////
1838 // Menus::Impl definition and implementation
1839 /////////////////////////////////////////////////////////////////////
1841 struct Menus::Impl {
1843 bool hasMenu(QString const &) const;
1845 MenuDefinition & getMenu(QString const &);
1847 MenuDefinition const & getMenu(QString const &) const;
1849 /// Expands some special entries of the menu
1850 /** The entries with the following kind are expanded to a
1851 sequence of Command MenuItems: Lastfiles, Documents,
1852 ViewFormats, ExportFormats, UpdateFormats, Branches,
1853 Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
1854 EnvironmentSeparators
1856 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1857 BufferView const *) const;
1859 /// Initialize specific MACOS X menubar
1860 void macxMenuBarInit(QMenuBar * qmb);
1862 /// Mac special menu.
1863 /** This defines a menu whose entries list the FuncRequests
1864 that will be removed by expand() in other menus. This is
1865 used by the Qt/Mac code.
1867 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1868 such that the items will keep accessing the FuncRequests in
1869 the MenuDefinition. While Menus::Impl might be recreated,
1870 we keep mac_special_menu_ in memory by making it static.
1872 static MenuDefinition mac_special_menu_;
1877 MenuDefinition menubar_;
1879 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1881 /// name to menu for \c menu() method.
1886 MenuDefinition Menus::Impl::mac_special_menu_;
1890 Here is what the Qt documentation says about how a menubar is chosen:
1892 1) If the window has a QMenuBar then it is used. 2) If the window
1893 is a modal then its menubar is used. If no menubar is specified
1894 then a default menubar is used (as documented below) 3) If the
1895 window has no parent then the default menubar is used (as
1898 The above 3 steps are applied all the way up the parent window
1899 chain until one of the above are satisifed. If all else fails a
1900 default menubar will be created, the default menubar on Qt/Mac is
1901 an empty menubar, however you can create a different default
1902 menubar by creating a parentless QMenuBar, the first one created
1903 will thus be designated the default menubar, and will be used
1904 whenever a default menubar is needed.
1906 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1907 that this menubar will be used also when one of LyX' dialogs has
1910 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
1912 /* Since Qt 4.2, the qt/mac menu code has special code for
1913 specifying the role of a menu entry. However, it does not
1914 work very well with our scheme of creating menus on demand,
1915 and therefore we need to put these entries in a special
1916 invisible menu. (JMarc)
1919 /* The entries of our special mac menu. If we add support for
1920 * special entries in Menus, we could imagine something
1922 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1923 * and therefore avoid hardcoding. I am not sure it is worth
1924 * the hassle, though. (JMarc)
1926 struct MacMenuEntry {
1930 QAction::MenuRole role;
1933 static MacMenuEntry entries[] = {
1934 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1935 QAction::AboutRole},
1936 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1937 QAction::PreferencesRole},
1938 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
1939 /* This doesn't work with Cocoa. */
1940 {LFUN_RECONFIGURE, "", "Reconfigure",
1941 QAction::ApplicationSpecificRole},
1943 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1945 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1946 const bool first_call = mac_special_menu_.empty();
1948 // the special menu for Menus. Fill it up only once.
1950 for (size_t i = 0 ; i < num_entries ; ++i) {
1951 FuncRequest const func(entries[i].action,
1952 from_utf8(entries[i].arg));
1953 mac_special_menu_.add(MenuItem(MenuItem::Command,
1954 entries[i].label, func));
1958 // add the entries to a QMenu that will eventually be empty
1959 // and therefore invisible.
1960 QMenu * qMenu = qmb->addMenu("special");
1961 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1962 MenuDefinition::const_iterator end = mac_special_menu_.end();
1963 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1964 Action * action = new Action(QIcon(), cit->label(),
1965 cit->func(), QString(), qMenu);
1966 action->setMenuRole(entries[i].role);
1967 qMenu->addAction(action);
1972 void Menus::Impl::expand(MenuDefinition const & frommenu,
1973 MenuDefinition & tomenu, BufferView const * bv) const
1975 if (!tomenu.empty())
1978 for (MenuDefinition::const_iterator cit = frommenu.begin();
1979 cit != frommenu.end() ; ++cit) {
1980 Buffer const * buf = bv ? &bv->buffer() : 0;
1981 switch (cit->kind()) {
1982 case MenuItem::Lastfiles:
1983 tomenu.expandLastfiles();
1986 case MenuItem::Documents:
1987 tomenu.expandDocuments();
1990 case MenuItem::Bookmarks:
1991 tomenu.expandBookmarks();
1994 case MenuItem::ImportFormats:
1995 case MenuItem::ViewFormats:
1996 case MenuItem::UpdateFormats:
1997 case MenuItem::ExportFormats:
1998 tomenu.expandFormats(cit->kind(), buf);
2001 case MenuItem::CharStyles:
2002 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2005 case MenuItem::Custom:
2006 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2009 case MenuItem::Elements:
2010 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2013 case MenuItem::FloatListInsert:
2014 tomenu.expandFloatListInsert(buf);
2017 case MenuItem::FloatInsert:
2018 tomenu.expandFloatInsert(buf);
2021 case MenuItem::PasteRecent:
2022 tomenu.expandPasteRecent(buf);
2025 case MenuItem::Toolbars:
2026 tomenu.expandToolbars();
2029 case MenuItem::Branches:
2030 tomenu.expandBranches(buf);
2033 case MenuItem::Indices:
2034 tomenu.expandIndices(buf);
2037 case MenuItem::IndicesContext:
2038 tomenu.expandIndicesContext(buf);
2041 case MenuItem::IndicesLists:
2042 tomenu.expandIndices(buf, true);
2045 case MenuItem::IndicesListsContext:
2046 tomenu.expandIndicesContext(buf, true);
2049 case MenuItem::CiteStyles:
2050 tomenu.expandCiteStyles(bv);
2054 tomenu.expandToc(buf);
2057 case MenuItem::GraphicsGroups:
2058 tomenu.expandGraphicsGroups(bv);
2061 case MenuItem::SpellingSuggestions:
2062 tomenu.expandSpellingSuggestions(bv);
2065 case MenuItem::LanguageSelector:
2066 tomenu.expandLanguageSelector(buf);
2069 case MenuItem::Arguments:
2070 tomenu.expandArguments(bv, false);
2073 case MenuItem::SwitchArguments:
2074 tomenu.expandArguments(bv, true);
2077 case MenuItem::Captions:
2078 tomenu.expandCaptions(buf, false);
2081 case MenuItem::SwitchCaptions:
2082 tomenu.expandCaptions(buf, true);
2085 case MenuItem::EnvironmentSeparators:
2086 tomenu.expandEnvironmentSeparators(bv);
2089 case MenuItem::Submenu: {
2090 MenuItem item(*cit);
2091 item.setSubmenu(MenuDefinition(cit->submenuname()));
2092 expand(getMenu(cit->submenuname()), item.submenu(), bv);
2093 tomenu.addWithStatusCheck(item);
2097 case MenuItem::Info:
2098 case MenuItem::Help:
2099 case MenuItem::Separator:
2100 tomenu.addWithStatusCheck(*cit);
2103 case MenuItem::Command:
2104 if (!mac_special_menu_.hasFunc(cit->func()))
2105 tomenu.addWithStatusCheck(*cit);
2109 // we do not want the menu to end with a separator
2110 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2111 tomenu.items_.pop_back();
2113 // Check whether the shortcuts are unique
2114 tomenu.checkShortcuts();
2118 bool Menus::Impl::hasMenu(QString const & name) const
2120 return find_if(menulist_.begin(), menulist_.end(),
2121 MenuNamesEqual(name)) != menulist_.end();
2125 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2127 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2128 MenuNamesEqual(name));
2129 if (cit == menulist_.end()) {
2130 LYXERR0("No submenu named " << name);
2131 LASSERT(false, { static const MenuDefinition m; return m; });
2137 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2139 iterator it = find_if(menulist_.begin(), menulist_.end(),
2140 MenuNamesEqual(name));
2141 if (it == menulist_.end()) {
2142 LYXERR0("No submenu named " << name);
2143 LASSERT(false, { static MenuDefinition m; return m; });
2149 /////////////////////////////////////////////////////////////////////
2153 /////////////////////////////////////////////////////////////////////
2155 Menus::Menus() : d(new Impl) {}
2171 void Menus::read(Lexer & lex)
2179 LexerKeyword menutags[] = {
2180 { "end", md_endmenuset },
2181 { "menu", md_menu },
2182 { "menubar", md_menubar }
2185 // consistency check
2186 if (compare_ascii_no_case(lex.getString(), "menuset"))
2187 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2189 lex.pushTable(menutags);
2190 lex.setContext("Menus::read");
2194 while (lex.isOK() && !quit) {
2195 switch (lex.lex()) {
2197 d->menubar_.read(lex);
2201 QString const name = toqstr(lex.getDocString());
2202 if (d->hasMenu(name))
2203 d->getMenu(name).read(lex);
2205 MenuDefinition menu(name);
2207 d->menulist_.push_back(menu);
2215 lex.printError("Unknown menu tag");
2223 bool Menus::searchMenu(FuncRequest const & func,
2224 docstring_list & names) const
2226 MenuDefinition menu;
2227 d->expand(d->menubar_, menu, 0);
2228 return menu.searchMenu(func, names);
2232 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2236 // setup special mac specific menu items, but only do this
2237 // the first time a QMenuBar is created. Otherwise Qt will
2238 // create duplicate items in the application menu. It seems
2239 // that Qt does not remove them when the QMenubar is cleared.
2240 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2241 d->macxMenuBarInit(qmb);
2244 // Clear all menubar contents before filling it.
2248 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2250 if (d->menubar_.empty()) {
2251 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2252 << d->menubar_.name());
2255 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2257 MenuDefinition menu;
2258 BufferView * bv = 0;
2260 bv = view->currentBufferView();
2261 d->expand(d->menubar_, menu, bv);
2263 MenuDefinition::const_iterator m = menu.begin();
2264 MenuDefinition::const_iterator end = menu.end();
2266 for (; m != end; ++m) {
2268 if (m->kind() != MenuItem::Submenu) {
2269 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2273 LYXERR(Debug::GUI, "menu bar item " << m->label()
2274 << " is a submenu named " << m->submenuname());
2276 QString name = m->submenuname();
2277 if (!d->hasMenu(name)) {
2278 LYXERR(Debug::GUI, "\tERROR: " << name
2279 << " submenu has no menu!");
2283 Menu * menu = new Menu(view, m->submenuname(), true);
2284 menu->setTitle(label(*m));
2286 #if defined(Q_WS_MACX) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2287 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2288 // so we create a temporary one here
2289 QAction * action = new QAction(menu);
2290 menu->addAction(action);
2295 d->name_map_[view][name] = menu;
2300 void Menus::updateMenu(Menu * qmenu)
2302 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2305 if (qmenu->d->name.isEmpty())
2308 docstring identifier = qstring_to_ucs4(qmenu->d->name);
2309 MenuDefinition fromLyxMenu(qmenu->d->name);
2310 while (!identifier.empty()) {
2311 docstring menu_name;
2312 identifier = split(identifier, menu_name, ';');
2314 if (!d->hasMenu(toqstr(menu_name))) {
2315 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2320 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2321 //FIXME: 50 is a wild guess. We should take into account here
2322 //the expansion of menu items, disabled optional items etc.
2323 bool const in_sub_menu = !fromLyxMenu.empty()
2324 && fromLyxMenu.size() + cat_menu.size() > 50 ;
2326 fromLyxMenu.catSub(menu_name);
2328 fromLyxMenu.cat(cat_menu);
2329 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2332 if (fromLyxMenu.empty()) {
2333 qmenu->addAction(qt_("No Action Defined!"));
2337 BufferView * bv = 0;
2339 bv = qmenu->d->view->currentBufferView();
2340 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2341 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2345 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2347 LYXERR(Debug::GUI, "Context menu requested: " << name);
2348 Menu * menu = d->name_map_[&view].value(name, 0);
2349 if (!menu && !name.startsWith("context-")) {
2350 LYXERR0("requested context menu not found: " << name);
2354 menu = new Menu(&view, name, true, keyboard);
2355 d->name_map_[&view][name] = menu;
2359 } // namespace frontend
2362 #include "moc_Menus.cpp"