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 "qt_helpers.h"
26 #include "BiblioInfo.h"
27 #include "BranchList.h"
29 #include "BufferList.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "Converter.h"
33 #include "CutAndPaste.h"
35 #include "FloatList.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
41 #include "LyXAction.h"
42 #include "LyX.h" // for lastfiles
44 #include "Paragraph.h"
45 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TocBackend.h"
51 #include "insets/Inset.h"
52 #include "insets/InsetCitation.h"
53 #include "insets/InsetGraphics.h"
55 #include "support/lassert.h"
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/docstring_list.h"
59 #include "support/filetools.h"
60 #include "support/gettext.h"
61 #include "support/lstrings.h"
69 #include <boost/shared_ptr.hpp>
75 using namespace lyx::support;
83 // MacOSX specific stuff is at the end.
90 /// The type of elements that can be in a menu
98 /** This type of item explains why something is unavailable. If this
99 menuitem is in a submenu, the submenu is enabled to make sure the
100 user sees the information. */
102 /** This type of item merely shows that there might be a list or
103 something alike at this position, but the list is still empty.
104 If this item is in a submenu, the submenu will not always be
107 /** This is the list of last opened file,
108 typically for the File menu. */
110 /** This is the list of opened Documents,
111 typically for the Documents menu. */
113 /** This is the bookmarks */
117 /** This is a list of viewable formats
118 typically for the File->View menu. */
120 /** This is a list of updatable formats
121 typically for the File->Update menu. */
123 /** This is a list of exportable formats
124 typically for the File->Export menu. */
126 /** This is a list of importable formats
127 typically for the File->Export menu. */
129 /** This is the list of elements available
130 * for insertion into document. */
132 /** This is the list of user-configurable
133 insets to insert into document */
135 /** This is the list of XML elements to
136 insert into the document */
138 /** This is the list of floats that we can
139 insert a list for. */
141 /** This is the list of floats that we can
144 /** This is the list of selections that can
149 /** Available branches in document */
151 /** Available citation styles for a given citation */
153 /** Available graphics groups */
157 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
160 QString const & label,
161 QString const & submenu = QString(),
162 bool optional = false)
163 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
165 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
169 QString const & label,
170 FuncRequest const & func,
171 bool optional = false,
172 FuncRequest::Origin origin = FuncRequest::MENU)
173 : kind_(kind), label_(label), func_(func), optional_(optional)
175 func_.origin = origin;
178 // boost::shared_ptr<MenuDefinition> needs this apprently...
181 /// The label of a given menuitem
182 QString label() const { return label_.split('|')[0]; }
184 /// The keyboard shortcut (usually underlined in the entry)
185 QString shortcut() const
187 return label_.contains('|') ? label_.split('|')[1] : QString();
189 /// The complete label, with label and shortcut separated by a '|'
190 QString fulllabel() const { return label_;}
191 /// The kind of entry
192 Kind kind() const { return kind_; }
193 /// the action (if relevant)
194 FuncRequest const & func() const { return func_; }
195 /// returns true if the entry should be ommited when disabled
196 bool optional() const { return optional_; }
197 /// returns the status of the lfun associated with this entry
198 FuncStatus const & status() const { return status_; }
199 /// returns the status of the lfun associated with this entry
200 FuncStatus & status() { return status_; }
201 /// returns the status of the lfun associated with this entry
202 void status(FuncStatus const & status) { status_ = status; }
204 ///returns the binding associated to this action.
205 QString binding() const
207 if (kind_ != Command)
209 // Get the keys bound to this action, but keep only the
211 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
213 return toqstr(bindings.begin()->print(KeySequence::ForGui));
215 LYXERR(Debug::KBMAP, "No binding for "
216 << lyxaction.getActionName(func_.action)
217 << '(' << func_.argument() << ')');
221 /// the description of the submenu (if relevant)
222 QString const & submenuname() const { return submenuname_; }
223 /// set the description of the submenu
224 void submenuname(QString const & name) { submenuname_ = name; }
226 bool hasSubmenu() const { return !submenu_.isEmpty(); }
228 MenuDefinition const & submenu() const { return submenu_.at(0); }
229 MenuDefinition & submenu() { return submenu_[0]; }
231 void setSubmenu(MenuDefinition const & menu)
234 submenu_.append(menu);
245 QString submenuname_;
250 /// contains 0 or 1 item.
251 QList<MenuDefinition> submenu_;
255 class MenuDefinition {
258 typedef std::vector<MenuItem> ItemList;
260 typedef ItemList::const_iterator const_iterator;
262 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
267 QString const & name() const { return name_; }
269 bool empty() const { return items_.empty(); }
270 /// Clear the menu content.
271 void clear() { items_.clear(); }
273 size_t size() const { return items_.size(); }
275 MenuItem const & operator[](size_t) const;
277 const_iterator begin() const { return items_.begin(); }
279 const_iterator end() const { return items_.end(); }
281 // search for func in this menu iteratively, and put menu
283 bool searchMenu(FuncRequest const & func, docstring_list & names)
286 bool hasFunc(FuncRequest const &) const;
287 /// Add the menu item unconditionally
288 void add(MenuItem const & item) { items_.push_back(item); }
289 /// Checks the associated FuncRequest status before adding the
291 void addWithStatusCheck(MenuItem const &);
292 // Check whether the menu shortcuts are unique
293 void checkShortcuts() const;
295 void expandLastfiles();
296 void expandDocuments();
297 void expandBookmarks();
298 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
299 void expandFloatListInsert(Buffer const * buf);
300 void expandFloatInsert(Buffer const * buf);
301 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
302 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
303 void expandToc(Buffer const * buf);
304 void expandPasteRecent(Buffer const * buf);
305 void expandToolbars();
306 void expandBranches(Buffer const * buf);
307 void expandCiteStyles(BufferView const *);
308 void expandGraphicsGroups(BufferView const *);
316 /// Helper for std::find_if
320 MenuNamesEqual(QString const & name) : name_(name) {}
321 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
328 typedef std::vector<MenuDefinition> MenuList;
330 typedef MenuList::const_iterator const_iterator;
332 typedef MenuList::iterator iterator;
334 /////////////////////////////////////////////////////////////////////
335 // MenuDefinition implementation
336 /////////////////////////////////////////////////////////////////////
338 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
342 case MenuItem::Command: {
343 FuncStatus status = lyx::getStatus(i.func());
344 if (status.unknown() || (!status.enabled() && i.optional()))
347 items_.back().status(status);
351 case MenuItem::Submenu: {
352 bool enabled = false;
353 if (i.hasSubmenu()) {
354 for (const_iterator cit = i.submenu().begin();
355 cit != i.submenu().end(); ++cit) {
356 // Only these kind of items affect the status of the submenu
357 if ((cit->kind() == MenuItem::Command
358 || cit->kind() == MenuItem::Submenu
359 || cit->kind() == MenuItem::Help)
360 && cit->status().enabled()) {
366 if (enabled || !i.optional()) {
368 items_.back().status().setEnabled(enabled);
373 case MenuItem::Separator:
374 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
384 void MenuDefinition::read(Lexer & lex)
413 LexerKeyword menutags[] = {
414 { "bookmarks", md_bookmarks },
415 { "branches", md_branches },
416 { "charstyles", md_charstyles },
417 { "citestyles", md_citestyles },
418 { "custom", md_custom },
419 { "documents", md_documents },
420 { "elements", md_elements },
421 { "end", md_endmenu },
422 { "exportformats", md_exportformats },
423 { "floatinsert", md_floatinsert },
424 { "floatlistinsert", md_floatlistinsert },
425 { "graphicsgroups", md_graphicsgroups },
426 { "importformats", md_importformats },
428 { "lastfiles", md_lastfiles },
429 { "optitem", md_optitem },
430 { "optsubmenu", md_optsubmenu },
431 { "pasterecent", md_pasterecent },
432 { "separator", md_separator },
433 { "submenu", md_submenu },
435 { "toolbars", md_toolbars },
436 { "updateformats", md_updateformats },
437 { "viewformats", md_viewformats }
440 lex.pushTable(menutags);
441 lex.setContext("MenuDefinition::read: ");
444 bool optional = false;
446 while (lex.isOK() && !quit) {
450 // fallback to md_item
453 docstring const name = translateIfPossible(lex.getDocString());
455 string const command = lex.getString();
456 FuncRequest func = lyxaction.lookupFunc(command);
457 FuncRequest::Origin origin = FuncRequest::MENU;
458 if (name_.startsWith("context-toc-"))
459 origin = FuncRequest::TOC;
460 add(MenuItem(MenuItem::Command, toqstr(name), func, optional, origin));
466 add(MenuItem(MenuItem::Separator));
470 add(MenuItem(MenuItem::Lastfiles));
474 add(MenuItem(MenuItem::CharStyles));
478 add(MenuItem(MenuItem::Custom));
482 add(MenuItem(MenuItem::Elements));
486 add(MenuItem(MenuItem::Documents));
490 add(MenuItem(MenuItem::Bookmarks));
494 add(MenuItem(MenuItem::Toc));
498 add(MenuItem(MenuItem::ViewFormats));
501 case md_updateformats:
502 add(MenuItem(MenuItem::UpdateFormats));
505 case md_exportformats:
506 add(MenuItem(MenuItem::ExportFormats));
509 case md_importformats:
510 add(MenuItem(MenuItem::ImportFormats));
513 case md_floatlistinsert:
514 add(MenuItem(MenuItem::FloatListInsert));
518 add(MenuItem(MenuItem::FloatInsert));
522 add(MenuItem(MenuItem::PasteRecent));
526 add(MenuItem(MenuItem::Toolbars));
530 add(MenuItem(MenuItem::Branches));
534 add(MenuItem(MenuItem::CiteStyles));
537 case md_graphicsgroups:
538 add(MenuItem(MenuItem::GraphicsGroups));
543 // fallback to md_submenu
546 docstring const mlabel = translateIfPossible(lex.getDocString());
548 docstring const mname = lex.getDocString();
549 add(MenuItem(MenuItem::Submenu,
550 toqstr(mlabel), toqstr(mname), optional));
560 lex.printError("Unknown menu tag");
568 MenuItem const & MenuDefinition::operator[](size_type i) const
574 bool MenuDefinition::hasFunc(FuncRequest const & func) const
576 for (const_iterator it = begin(), et = end(); it != et; ++it)
577 if (it->func() == func)
583 void MenuDefinition::checkShortcuts() const
585 // This is a quadratic algorithm, but we do not care because
586 // menus are short enough
587 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
588 QString shortcut = it1->shortcut();
589 if (shortcut.isEmpty())
591 if (!it1->label().contains(shortcut))
592 LYXERR0("Menu warning: menu entry \""
594 << "\" does not contain shortcut `"
595 << shortcut << "'.");
596 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
597 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
598 LYXERR0("Menu warning: menu entries "
599 << '"' << it1->fulllabel()
600 << "\" and \"" << it2->fulllabel()
601 << "\" share the same shortcut.");
608 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
610 const_iterator m = begin();
611 const_iterator m_end = end();
612 for (; m != m_end; ++m) {
613 if (m->kind() == MenuItem::Command && m->func() == func) {
614 names.push_back(qstring_to_ucs4(m->label()));
617 if (m->kind() == MenuItem::Submenu) {
618 names.push_back(qstring_to_ucs4(m->label()));
619 if (!m->hasSubmenu()) {
620 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
621 << m->label() << " name=" << m->submenuname());
625 if (m->submenu().searchMenu(func, names))
634 bool compareFormat(Format const * p1, Format const * p2)
640 QString limitStringLength(docstring const & str)
642 size_t const max_item_length = 45;
644 if (str.size() > max_item_length)
645 return toqstr(str.substr(0, max_item_length - 3) + "...");
651 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
656 graphics::getGraphicsGroups(bv->buffer(), grp);
660 set<string>::const_iterator it = grp.begin();
661 set<string>::const_iterator end = grp.end();
662 add(MenuItem(MenuItem::Command, qt_("No Group"),
663 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
664 for (; it != end; it++) {
665 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
666 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
670 void MenuDefinition::expandLastfiles()
672 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
673 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
677 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
678 string const file = lfit->absFilename();
679 QString const label = QString("%1. %2|%3").arg(ii)
680 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
681 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
686 void MenuDefinition::expandDocuments()
688 MenuItem item(MenuItem::Submenu, qt_("Invisible"));
689 item.setSubmenu(MenuDefinition(qt_("Invisible")));
691 Buffer * first = theBufferList().first();
697 // We cannot use a for loop as the buffer list cycles.
699 QString label = toqstr(b->fileName().displayName(20));
702 bool const shown = guiApp->currentView()->workArea(*b);
703 int ii = shown ? vis : invis;
705 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
707 add(MenuItem(MenuItem::Command, label,
708 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
711 item.submenu().add(MenuItem(MenuItem::Command, label,
712 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
715 b = theBufferList().next(b);
716 } while (b != first);
717 if (!item.submenu().empty())
720 add(MenuItem(MenuItem::Info, qt_("<No documents open>")));
724 void MenuDefinition::expandBookmarks()
726 lyx::BookmarksSection const & bm = theSession().bookmarks();
729 for (size_t i = 1; i <= bm.size(); ++i) {
731 string const file = bm.bookmark(i).filename.absFilename();
732 QString const label = QString("%1. %2|%3").arg(i)
733 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
734 add(MenuItem(MenuItem::Command, label,
735 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
740 add(MenuItem(MenuItem::Info, qt_("<No bookmarks saved yet>")));
744 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
746 if (!buf && kind != MenuItem::ImportFormats)
749 typedef vector<Format const *> Formats;
754 case MenuItem::ImportFormats:
755 formats = theConverters().importableFormats();
756 action = LFUN_BUFFER_IMPORT;
758 case MenuItem::ViewFormats:
759 formats = buf->exportableFormats(true);
760 action = LFUN_BUFFER_VIEW;
762 case MenuItem::UpdateFormats:
763 formats = buf->exportableFormats(true);
764 action = LFUN_BUFFER_UPDATE;
767 formats = buf->exportableFormats(false);
768 action = LFUN_BUFFER_EXPORT;
770 sort(formats.begin(), formats.end(), &compareFormat);
772 Formats::const_iterator fit = formats.begin();
773 Formats::const_iterator end = formats.end();
774 for (; fit != end ; ++fit) {
778 docstring lab = from_utf8((*fit)->prettyname());
779 docstring scut = from_utf8((*fit)->shortcut());
780 docstring const tmplab = lab;
783 lab += char_type('|') + scut;
784 docstring lab_i18n = translateIfPossible(lab);
785 bool const untranslated = (lab == lab_i18n);
786 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
787 QString label = toqstr(lab);
789 // this might happen if the shortcut
790 // has been redefined
791 label = toqstr(translateIfPossible(tmplab));
794 case MenuItem::ImportFormats:
797 case MenuItem::ViewFormats:
798 case MenuItem::UpdateFormats:
799 if ((*fit)->name() == buf->getDefaultOutputFormat())
801 case MenuItem::ExportFormats:
802 if (!(*fit)->documentFormat())
806 LASSERT(false, /**/);
809 if (!shortcut.isEmpty())
810 label += '|' + shortcut;
813 addWithStatusCheck(MenuItem(MenuItem::Command, label,
814 FuncRequest(action, (*fit)->name())));
816 add(MenuItem(MenuItem::Command, label,
817 FuncRequest(action, (*fit)->name())));
822 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
827 FloatList const & floats = buf->params().documentClass().floats();
828 FloatList::const_iterator cit = floats.begin();
829 FloatList::const_iterator end = floats.end();
830 for (; cit != end; ++cit) {
831 addWithStatusCheck(MenuItem(MenuItem::Command,
832 qt_(cit->second.listName()),
833 FuncRequest(LFUN_FLOAT_LIST_INSERT,
834 cit->second.type())));
839 void MenuDefinition::expandFloatInsert(Buffer const * buf)
844 FloatList const & floats = buf->params().documentClass().floats();
845 FloatList::const_iterator cit = floats.begin();
846 FloatList::const_iterator end = floats.end();
847 for (; cit != end; ++cit) {
849 QString const label = qt_(cit->second.name());
850 addWithStatusCheck(MenuItem(MenuItem::Command, label,
851 FuncRequest(LFUN_FLOAT_INSERT,
852 cit->second.type())));
857 void MenuDefinition::expandFlexInsert(
858 Buffer const * buf, InsetLayout::InsetLyXType type)
863 TextClass::InsetLayouts const & insetLayouts =
864 buf->params().documentClass().insetLayouts();
865 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
866 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
867 for (; cit != end; ++cit) {
868 if (cit->second.lyxtype() == type) {
869 docstring const label = cit->first;
870 addWithStatusCheck(MenuItem(MenuItem::Command,
871 toqstr(translateIfPossible(label)),
872 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
875 // FIXME This is a little clunky.
876 if (items_.empty() && type == InsetLayout::CUSTOM)
877 add(MenuItem(MenuItem::Help, qt_("No custom insets defined!")));
881 size_t const max_number_of_items = 25;
883 void MenuDefinition::expandToc2(Toc const & toc_list,
884 size_t from, size_t to, int depth)
886 int shortcut_count = 0;
888 // check whether depth is smaller than the smallest depth in toc.
889 int min_depth = 1000;
890 for (size_t i = from; i < to; ++i)
891 min_depth = min(min_depth, toc_list[i].depth());
892 if (min_depth > depth)
895 if (to - from <= max_number_of_items) {
896 for (size_t i = from; i < to; ++i) {
897 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
898 label += limitStringLength(toc_list[i].str());
899 if (toc_list[i].depth() == depth
900 && shortcut_count < 9) {
901 if (label.contains(QString::number(shortcut_count + 1)))
902 label += '|' + QString::number(++shortcut_count);
904 add(MenuItem(MenuItem::Command, label,
905 FuncRequest(toc_list[i].action())));
910 size_t new_pos = pos + 1;
911 while (new_pos < to && toc_list[new_pos].depth() > depth)
914 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
915 label += limitStringLength(toc_list[pos].str());
916 if (toc_list[pos].depth() == depth &&
917 shortcut_count < 9) {
918 if (label.contains(QString::number(shortcut_count + 1)))
919 label += '|' + QString::number(++shortcut_count);
921 if (new_pos == pos + 1) {
922 add(MenuItem(MenuItem::Command,
923 label, FuncRequest(toc_list[pos].action())));
926 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
927 MenuItem item(MenuItem::Submenu, label);
928 item.setSubmenu(sub);
937 void MenuDefinition::expandToc(Buffer const * buf)
939 // To make things very cleanly, we would have to pass buf to
940 // all MenuItem constructors and to expandToc2. However, we
941 // know that all the entries in a TOC will be have status_ ==
942 // OK, so we avoid this unnecessary overhead (JMarc)
945 add(MenuItem(MenuItem::Info, qt_("<No document open>")));
949 // Add an entry for the master doc if this is a child doc
950 Buffer const * const master = buf->masterBuffer();
952 ParIterator const pit = par_iterator_begin(master->inset());
953 string const arg = convert<string>(pit->id());
954 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
955 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
958 MenuDefinition other_lists;
960 FloatList const & floatlist = buf->params().documentClass().floats();
961 TocList const & toc_list = buf->tocBackend().tocs();
962 TocList::const_iterator cit = toc_list.begin();
963 TocList::const_iterator end = toc_list.end();
964 for (; cit != end; ++cit) {
966 if (cit->first == "tableofcontents")
969 MenuDefinition submenu;
970 if (cit->second.size() >= 30) {
971 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
972 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
974 TocIterator ccit = cit->second.begin();
975 TocIterator eend = cit->second.end();
976 for (; ccit != eend; ++ccit) {
977 submenu.add(MenuItem(MenuItem::Command,
978 limitStringLength(ccit->str()),
979 FuncRequest(ccit->action())));
983 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
984 item.setSubmenu(submenu);
985 if (floatlist.typeExist(cit->first) || cit->first == "child") {
986 // Those two types deserve to be in the main menu.
987 item.setSubmenu(submenu);
990 other_lists.add(item);
992 if (!other_lists.empty()) {
993 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
994 item.setSubmenu(other_lists);
999 cit = toc_list.find("tableofcontents");
1001 LYXERR(Debug::GUI, "No table of contents.");
1003 if (cit->second.size() > 0 )
1004 expandToc2(cit->second, 0, cit->second.size(), 0);
1006 add(MenuItem(MenuItem::Info, qt_("<Empty table of contents>")));
1011 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1013 docstring_list const sel = cap::availableSelections(buf);
1015 docstring_list::const_iterator cit = sel.begin();
1016 docstring_list::const_iterator end = sel.end();
1018 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1019 add(MenuItem(MenuItem::Command, toqstr(*cit),
1020 FuncRequest(LFUN_PASTE, convert<string>(index))));
1025 void MenuDefinition::expandToolbars()
1027 MenuDefinition other_lists;
1028 // extracts the toolbars from the backend
1029 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1030 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1031 for (; cit != end; ++cit) {
1032 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1033 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1034 if (guiApp->toolbars().isMainToolbar(cit->name))
1037 other_lists.add(item);
1040 if (!other_lists.empty()) {
1041 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1042 item.setSubmenu(other_lists);
1048 void MenuDefinition::expandBranches(Buffer const * buf)
1053 BufferParams const & master_params = buf->masterBuffer()->params();
1054 BufferParams const & params = buf->params();
1055 if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1056 add(MenuItem(MenuItem::Help, qt_("No branches set for document!")));
1060 BranchList::const_iterator cit = master_params.branchlist().begin();
1061 BranchList::const_iterator end = master_params.branchlist().end();
1063 for (int ii = 1; cit != end; ++cit, ++ii) {
1064 docstring label = cit->branch();
1066 label = convert<docstring>(ii) + ". " + label
1067 + char_type('|') + convert<docstring>(ii);
1069 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1070 FuncRequest(LFUN_BRANCH_INSERT,
1074 if (buf == buf->masterBuffer())
1077 MenuDefinition child_branches;
1079 BranchList::const_iterator ccit = params.branchlist().begin();
1080 BranchList::const_iterator cend = params.branchlist().end();
1082 for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1083 docstring label = ccit->branch();
1085 label = convert<docstring>(ii) + ". " + label
1086 + char_type('|') + convert<docstring>(ii);
1088 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1090 FuncRequest(LFUN_BRANCH_INSERT,
1094 if (!child_branches.empty()) {
1095 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1096 item.setSubmenu(child_branches);
1102 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1107 Inset const * inset = bv->cursor().nextInset();
1108 if (!inset || inset->lyxCode() != CITE_CODE) {
1109 add(MenuItem(MenuItem::Command,
1110 qt_("No Citation in Scope!"),
1111 FuncRequest(LFUN_NOACTION)));
1114 InsetCommand const * citinset =
1115 static_cast<InsetCommand const *>(inset);
1117 Buffer const * buf = &bv->buffer();
1118 docstring key = citinset->getParam("key");
1119 // we can only handle one key currently
1120 if (contains(key, ','))
1121 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1123 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1124 docstring_list citeStrings =
1125 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1127 docstring_list::const_iterator cit = citeStrings.begin();
1128 docstring_list::const_iterator end = citeStrings.end();
1130 for (int ii = 1; cit != end; ++cit, ++ii) {
1131 docstring label = *cit;
1133 CiteStyle cst = citeStyleList[ii - 1];
1135 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1136 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1137 "changetype " + from_utf8(citationStyleToString(cs)))));
1144 /////////////////////////////////////////////////////////////////////
1145 // Menu::Impl definition and implementation
1146 /////////////////////////////////////////////////////////////////////
1150 /// populates the menu or one of its submenu
1151 /// This is used as a recursive function
1152 void populate(QMenu & qMenu, MenuDefinition const & menu);
1154 /// Only needed for top level menus.
1155 MenuDefinition * top_level_menu;
1158 /// the name of this menu
1164 /// Get a MenuDefinition item label from the menu backend
1165 static QString label(MenuItem const & mi)
1167 QString label = mi.label();
1168 label.replace("&", "&&");
1170 QString shortcut = mi.shortcut();
1171 if (!shortcut.isEmpty()) {
1172 int pos = label.indexOf(shortcut);
1174 //label.insert(pos, 1, char_type('&'));
1175 label.replace(pos, 0, "&");
1178 QString const binding = mi.binding();
1179 if (!binding.isEmpty())
1180 label += '\t' + binding;
1185 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1187 LYXERR(Debug::GUI, "populating menu " << menu.name());
1188 if (menu.size() == 0) {
1189 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1192 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1193 MenuDefinition::const_iterator m = menu.begin();
1194 MenuDefinition::const_iterator end = menu.end();
1195 for (; m != end; ++m) {
1196 if (m->kind() == MenuItem::Separator)
1197 qMenu.addSeparator();
1198 else if (m->kind() == MenuItem::Submenu) {
1199 QMenu * subMenu = qMenu.addMenu(label(*m));
1200 populate(*subMenu, m->submenu());
1201 subMenu->setEnabled(m->status().enabled());
1203 // we have a MenuItem::Command
1204 qMenu.addAction(new Action(view, QIcon(), label(*m),
1205 m->func(), QString(), &qMenu));
1210 /////////////////////////////////////////////////////////////////////
1211 // Menu implementation
1212 /////////////////////////////////////////////////////////////////////
1214 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1215 : QMenu(gv), d(new Menu::Impl)
1217 d->top_level_menu = top_level? new MenuDefinition : 0;
1221 if (d->top_level_menu)
1222 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1228 delete d->top_level_menu;
1233 void Menu::updateView()
1235 guiApp->menus().updateMenu(this);
1239 /////////////////////////////////////////////////////////////////////
1240 // Menus::Impl definition and implementation
1241 /////////////////////////////////////////////////////////////////////
1243 struct Menus::Impl {
1245 bool hasMenu(QString const &) const;
1247 MenuDefinition & getMenu(QString const &);
1249 MenuDefinition const & getMenu(QString const &) const;
1251 /// Expands some special entries of the menu
1252 /** The entries with the following kind are expanded to a
1253 sequence of Command MenuItems: Lastfiles, Documents,
1254 ViewFormats, ExportFormats, UpdateFormats, Branches
1256 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1257 BufferView const *) const;
1259 /// Initialize specific MACOS X menubar
1260 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1262 /// Mac special menu.
1263 /** This defines a menu whose entries list the FuncRequests
1264 that will be removed by expand() in other menus. This is
1265 used by the Qt/Mac code.
1267 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1268 such that the items will keep accessing the FuncRequests in
1269 the MenuDefinition. While Menus::Impl might be recreated,
1270 we keep mac_special_menu_ in memory by making it static.
1272 static MenuDefinition mac_special_menu_;
1277 MenuDefinition menubar_;
1279 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1281 /// name to menu for \c menu() method.
1286 MenuDefinition Menus::Impl::mac_special_menu_;
1290 Here is what the Qt documentation says about how a menubar is chosen:
1292 1) If the window has a QMenuBar then it is used. 2) If the window
1293 is a modal then its menubar is used. If no menubar is specified
1294 then a default menubar is used (as documented below) 3) If the
1295 window has no parent then the default menubar is used (as
1298 The above 3 steps are applied all the way up the parent window
1299 chain until one of the above are satisifed. If all else fails a
1300 default menubar will be created, the default menubar on Qt/Mac is
1301 an empty menubar, however you can create a different default
1302 menubar by creating a parentless QMenuBar, the first one created
1303 will thus be designated the default menubar, and will be used
1304 whenever a default menubar is needed.
1306 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1307 that this menubar will be used also when one of LyX' dialogs has
1310 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1312 /* Since Qt 4.2, the qt/mac menu code has special code for
1313 specifying the role of a menu entry. However, it does not
1314 work very well with our scheme of creating menus on demand,
1315 and therefore we need to put these entries in a special
1316 invisible menu. (JMarc)
1319 /* The entries of our special mac menu. If we add support for
1320 * special entries in Menus, we could imagine something
1322 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1323 * and therefore avoid hardcoding. I am not sure it is worth
1324 * the hassle, though. (JMarc)
1326 struct MacMenuEntry {
1330 QAction::MenuRole role;
1333 MacMenuEntry entries[] = {
1334 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1335 QAction::AboutRole},
1336 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1337 QAction::PreferencesRole},
1338 {LFUN_RECONFIGURE, "", "Reconfigure",
1339 QAction::ApplicationSpecificRole},
1340 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1342 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1344 // the special menu for Menus. Fill it up only once.
1345 if (mac_special_menu_.size() == 0) {
1346 for (size_t i = 0 ; i < num_entries ; ++i) {
1347 FuncRequest const func(entries[i].action,
1348 from_utf8(entries[i].arg));
1349 mac_special_menu_.add(MenuItem(MenuItem::Command,
1350 entries[i].label, func));
1354 // add the entries to a QMenu that will eventually be empty
1355 // and therefore invisible.
1356 QMenu * qMenu = qmb->addMenu("special");
1357 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1358 MenuDefinition::const_iterator end = mac_special_menu_.end();
1359 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1360 Action * action = new Action(view, QIcon(), cit->label(),
1361 cit->func(), QString(), qMenu);
1362 action->setMenuRole(entries[i].role);
1363 qMenu->addAction(action);
1368 void Menus::Impl::expand(MenuDefinition const & frommenu,
1369 MenuDefinition & tomenu, BufferView const * bv) const
1371 if (!tomenu.empty())
1374 for (MenuDefinition::const_iterator cit = frommenu.begin();
1375 cit != frommenu.end() ; ++cit) {
1376 Buffer const * buf = bv ? &bv->buffer() : 0;
1377 switch (cit->kind()) {
1378 case MenuItem::Lastfiles:
1379 tomenu.expandLastfiles();
1382 case MenuItem::Documents:
1383 tomenu.expandDocuments();
1386 case MenuItem::Bookmarks:
1387 tomenu.expandBookmarks();
1390 case MenuItem::ImportFormats:
1391 case MenuItem::ViewFormats:
1392 case MenuItem::UpdateFormats:
1393 case MenuItem::ExportFormats:
1394 tomenu.expandFormats(cit->kind(), buf);
1397 case MenuItem::CharStyles:
1398 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1401 case MenuItem::Custom:
1402 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1405 case MenuItem::Elements:
1406 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1409 case MenuItem::FloatListInsert:
1410 tomenu.expandFloatListInsert(buf);
1413 case MenuItem::FloatInsert:
1414 tomenu.expandFloatInsert(buf);
1417 case MenuItem::PasteRecent:
1418 tomenu.expandPasteRecent(buf);
1421 case MenuItem::Toolbars:
1422 tomenu.expandToolbars();
1425 case MenuItem::Branches:
1426 tomenu.expandBranches(buf);
1429 case MenuItem::CiteStyles:
1430 tomenu.expandCiteStyles(bv);
1434 tomenu.expandToc(buf);
1437 case MenuItem::GraphicsGroups:
1438 tomenu.expandGraphicsGroups(bv);
1441 case MenuItem::Submenu: {
1442 MenuItem item(*cit);
1443 item.setSubmenu(MenuDefinition(cit->submenuname()));
1444 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1445 tomenu.addWithStatusCheck(item);
1449 case MenuItem::Info:
1450 case MenuItem::Help:
1451 case MenuItem::Separator:
1452 tomenu.addWithStatusCheck(*cit);
1455 case MenuItem::Command:
1456 if (!mac_special_menu_.hasFunc(cit->func()))
1457 tomenu.addWithStatusCheck(*cit);
1461 // we do not want the menu to end with a separator
1462 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1463 tomenu.items_.pop_back();
1465 // Check whether the shortcuts are unique
1466 tomenu.checkShortcuts();
1470 bool Menus::Impl::hasMenu(QString const & name) const
1472 return find_if(menulist_.begin(), menulist_.end(),
1473 MenuNamesEqual(name)) != menulist_.end();
1477 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1479 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1480 MenuNamesEqual(name));
1481 if (cit == menulist_.end())
1482 LYXERR0("No submenu named " << name);
1483 LASSERT(cit != menulist_.end(), /**/);
1488 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1490 iterator it = find_if(menulist_.begin(), menulist_.end(),
1491 MenuNamesEqual(name));
1492 if (it == menulist_.end())
1493 LYXERR0("No submenu named " << name);
1494 LASSERT(it != menulist_.end(), /**/);
1499 /////////////////////////////////////////////////////////////////////
1503 /////////////////////////////////////////////////////////////////////
1505 Menus::Menus() : d(new Impl) {}
1521 void Menus::read(Lexer & lex)
1529 LexerKeyword menutags[] = {
1530 { "end", md_endmenuset },
1531 { "menu", md_menu },
1532 { "menubar", md_menubar }
1535 // consistency check
1536 if (compare_ascii_no_case(lex.getString(), "menuset"))
1537 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1539 lex.pushTable(menutags);
1540 lex.setContext("Menus::read");
1544 while (lex.isOK() && !quit) {
1545 switch (lex.lex()) {
1547 d->menubar_.read(lex);
1551 QString const name = toqstr(lex.getDocString());
1552 if (d->hasMenu(name))
1553 d->getMenu(name).read(lex);
1555 MenuDefinition menu(name);
1557 d->menulist_.push_back(menu);
1565 lex.printError("Unknown menu tag");
1573 bool Menus::searchMenu(FuncRequest const & func,
1574 docstring_list & names) const
1576 MenuDefinition menu;
1577 d->expand(d->menubar_, menu, 0);
1578 return menu.searchMenu(func, names);
1582 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1586 // setup special mac specific menu items, but only do this
1587 // the first time a QMenuBar is created. Otherwise Qt will
1588 // create duplicate items in the application menu. It seems
1589 // that Qt does not remove them when the QMenubar is cleared.
1590 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1591 d->macxMenuBarInit(view, qmb);
1594 // Clear all menubar contents before filling it.
1598 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1600 if (d->menubar_.size() == 0) {
1601 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1602 << d->menubar_.name());
1605 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1607 MenuDefinition menu;
1608 BufferView * bv = 0;
1611 d->expand(d->menubar_, menu, bv);
1613 MenuDefinition::const_iterator m = menu.begin();
1614 MenuDefinition::const_iterator end = menu.end();
1616 for (; m != end; ++m) {
1618 if (m->kind() != MenuItem::Submenu) {
1619 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1623 LYXERR(Debug::GUI, "menu bar item " << m->label()
1624 << " is a submenu named " << m->submenuname());
1626 QString name = m->submenuname();
1627 if (!d->hasMenu(name)) {
1628 LYXERR(Debug::GUI, "\tERROR: " << name
1629 << " submenu has no menu!");
1633 Menu * menu = new Menu(view, m->submenuname(), true);
1634 menu->setTitle(label(*m));
1637 d->name_map_[view][name] = menu;
1642 void Menus::updateMenu(Menu * qmenu)
1644 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1647 if (qmenu->d->name.isEmpty())
1650 // Here, We make sure that theLyXFunc points to the correct LyXView.
1651 theLyXFunc().setLyXView(qmenu->d->view);
1653 if (!d->hasMenu(qmenu->d->name)) {
1654 qmenu->addAction(qt_("No action defined!"));
1655 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1660 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1661 BufferView * bv = 0;
1663 bv = qmenu->d->view->view();
1664 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1665 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1669 Menu * Menus::menu(QString const & name, GuiView & view)
1671 LYXERR(Debug::GUI, "Context menu requested: " << name);
1672 Menu * menu = d->name_map_[&view].value(name, 0);
1673 if (!menu && !name.startsWith("context-")) {
1674 LYXERR0("requested context menu not found: " << name);
1678 menu = new Menu(&view, name, true);
1679 d->name_map_[&view][name] = menu;
1683 } // namespace frontend
1686 #include "moc_Menus.cpp"