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"
49 #include "ToolbarBackend.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/filetools.h"
59 #include "support/gettext.h"
60 #include "support/lstrings.h"
68 #include <boost/shared_ptr.hpp>
74 using namespace lyx::support;
82 // MacOSX specific stuff is at the end.
89 /// The type of elements that can be in a menu
97 /** This is the list of last opened file,
98 typically for the File menu. */
100 /** This is the list of opened Documents,
101 typically for the Documents menu. */
103 /** This is the bookmarks */
107 /** This is a list of viewable formats
108 typically for the File->View menu. */
110 /** This is a list of updatable formats
111 typically for the File->Update menu. */
113 /** This is a list of exportable formats
114 typically for the File->Export menu. */
116 /** This is a list of importable formats
117 typically for the File->Export menu. */
119 /** This is the list of elements available
120 * for insertion into document. */
122 /** This is the list of user-configurable
123 insets to insert into document */
125 /** This is the list of XML elements to
126 insert into the document */
128 /** This is the list of floats that we can
129 insert a list for. */
131 /** This is the list of floats that we can
134 /** This is the list of selections that can
139 /** Available branches in document */
141 /** Available citation styles for a given citation */
143 /** Available graphics groups */
147 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
150 QString const & label,
151 QString const & submenu = QString(),
152 bool optional = false)
153 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
155 LASSERT(kind == Submenu, /**/);
159 QString const & label,
160 FuncRequest const & func,
161 bool optional = false)
162 : kind_(kind), label_(label), func_(func), optional_(optional)
164 func_.origin = FuncRequest::MENU;
167 // boost::shared_ptr<MenuDefinition> needs this apprently...
170 /// The label of a given menuitem
171 QString label() const { return label_.split('|')[0]; }
173 /// The keyboard shortcut (usually underlined in the entry)
174 QString shortcut() const
176 return label_.contains('|') ? label_.split('|')[1] : QString();
178 /// The complete label, with label and shortcut separated by a '|'
179 QString fulllabel() const { return label_;}
180 /// The kind of entry
181 Kind kind() const { return kind_; }
182 /// the action (if relevant)
183 FuncRequest const & func() const { return func_; }
184 /// returns true if the entry should be ommited when disabled
185 bool optional() const { return optional_; }
186 /// returns the status of the lfun associated with this entry
187 FuncStatus const & status() const { return status_; }
188 /// returns the status of the lfun associated with this entry
189 FuncStatus & status() { return status_; }
190 /// returns the status of the lfun associated with this entry
191 void status(FuncStatus const & status) { status_ = status; }
193 ///returns the binding associated to this action.
194 QString binding() const
196 if (kind_ != Command)
198 // Get the keys bound to this action, but keep only the
200 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
202 return toqstr(bindings.begin()->print(KeySequence::ForGui));
204 LYXERR(Debug::KBMAP, "No binding for "
205 << lyxaction.getActionName(func_.action)
206 << '(' << func_.argument() << ')');
210 /// the description of the submenu (if relevant)
211 QString const & submenuname() const { return submenuname_; }
212 /// set the description of the submenu
213 void submenuname(QString const & name) { submenuname_ = name; }
215 bool hasSubmenu() const { return !submenu_.isEmpty(); }
217 MenuDefinition const & submenu() const { return submenu_.at(0); }
218 MenuDefinition & submenu() { return submenu_[0]; }
220 void setSubmenu(MenuDefinition const & menu)
223 submenu_.append(menu);
234 QString submenuname_;
239 /// contains 0 or 1 item.
240 QList<MenuDefinition> submenu_;
244 class MenuDefinition {
247 typedef std::vector<MenuItem> ItemList;
249 typedef ItemList::const_iterator const_iterator;
251 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
256 QString const & name() const { return name_; }
258 bool empty() const { return items_.empty(); }
259 /// Clear the menu content.
260 void clear() { items_.clear(); }
262 size_t size() const { return items_.size(); }
264 MenuItem const & operator[](size_t) const;
266 const_iterator begin() const { return items_.begin(); }
268 const_iterator end() const { return items_.end(); }
270 // search for func in this menu iteratively, and put menu
272 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
275 bool hasFunc(FuncRequest const &) const;
276 /// Add the menu item unconditionally
277 void add(MenuItem const & item) { items_.push_back(item); }
278 /// Checks the associated FuncRequest status before adding the
280 void addWithStatusCheck(MenuItem const &);
281 // Check whether the menu shortcuts are unique
282 void checkShortcuts() const;
284 void expandLastfiles();
285 void expandDocuments();
286 void expandBookmarks();
287 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
288 void expandFloatListInsert(Buffer const * buf);
289 void expandFloatInsert(Buffer const * buf);
290 void expandFlexInsert(Buffer const * buf, std::string s);
291 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
292 void expandToc(Buffer const * buf);
293 void expandPasteRecent();
294 void expandToolbars();
295 void expandBranches(Buffer const * buf);
296 void expandCiteStyles(BufferView const *);
297 void expandGraphicsGroups(Buffer const * buf);
305 /// Helper for std::find_if
309 MenuNamesEqual(QString const & name) : name_(name) {}
310 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
317 typedef std::vector<MenuDefinition> MenuList;
319 typedef MenuList::const_iterator const_iterator;
321 typedef MenuList::iterator iterator;
323 /////////////////////////////////////////////////////////////////////
324 // MenuDefinition implementation
325 /////////////////////////////////////////////////////////////////////
327 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
331 case MenuItem::Command: {
332 FuncStatus status = lyx::getStatus(i.func());
333 if (status.unknown() || (!status.enabled() && i.optional()))
336 items_.back().status(status);
340 case MenuItem::Submenu: {
341 if (i.hasSubmenu()) {
342 bool enabled = false;
343 for (const_iterator cit = i.submenu().begin();
344 cit != i.submenu().end(); ++cit) {
345 if ((cit->kind() == MenuItem::Command
346 || cit->kind() == MenuItem::Submenu)
347 && cit->status().enabled()) {
352 if (enabled || !i.optional()) {
354 items_.back().status().enabled(enabled);
362 case MenuItem::Separator:
363 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
373 void MenuDefinition::read(Lexer & lex)
402 LexerKeyword menutags[] = {
403 { "bookmarks", md_bookmarks },
404 { "branches", md_branches },
405 { "charstyles", md_charstyles },
406 { "citestyles", md_citestyles },
407 { "custom", md_custom },
408 { "documents", md_documents },
409 { "elements", md_elements },
410 { "end", md_endmenu },
411 { "exportformats", md_exportformats },
412 { "floatinsert", md_floatinsert },
413 { "floatlistinsert", md_floatlistinsert },
414 { "graphicsgroups", md_graphicsgroups },
415 { "importformats", md_importformats },
417 { "lastfiles", md_lastfiles },
418 { "optitem", md_optitem },
419 { "optsubmenu", md_optsubmenu },
420 { "pasterecent", md_pasterecent },
421 { "separator", md_separator },
422 { "submenu", md_submenu },
424 { "toolbars", md_toolbars },
425 { "updateformats", md_updateformats },
426 { "viewformats", md_viewformats }
429 lex.pushTable(menutags);
430 lex.setContext("MenuDefinition::read: ");
433 bool optional = false;
435 while (lex.isOK() && !quit) {
439 // fallback to md_item
442 docstring const name = translateIfPossible(lex.getDocString());
444 string const command = lex.getString();
445 FuncRequest func = lyxaction.lookupFunc(command);
446 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
452 add(MenuItem(MenuItem::Separator));
456 add(MenuItem(MenuItem::Lastfiles));
460 add(MenuItem(MenuItem::CharStyles));
464 add(MenuItem(MenuItem::Custom));
468 add(MenuItem(MenuItem::Elements));
472 add(MenuItem(MenuItem::Documents));
476 add(MenuItem(MenuItem::Bookmarks));
480 add(MenuItem(MenuItem::Toc));
484 add(MenuItem(MenuItem::ViewFormats));
487 case md_updateformats:
488 add(MenuItem(MenuItem::UpdateFormats));
491 case md_exportformats:
492 add(MenuItem(MenuItem::ExportFormats));
495 case md_importformats:
496 add(MenuItem(MenuItem::ImportFormats));
499 case md_floatlistinsert:
500 add(MenuItem(MenuItem::FloatListInsert));
504 add(MenuItem(MenuItem::FloatInsert));
508 add(MenuItem(MenuItem::PasteRecent));
512 add(MenuItem(MenuItem::Toolbars));
516 add(MenuItem(MenuItem::Branches));
520 add(MenuItem(MenuItem::CiteStyles));
523 case md_graphicsgroups:
524 add(MenuItem(MenuItem::GraphicsGroups));
529 // fallback to md_submenu
532 docstring const mlabel = translateIfPossible(lex.getDocString());
534 docstring const mname = lex.getDocString();
535 add(MenuItem(MenuItem::Submenu,
536 toqstr(mlabel), toqstr(mname), optional));
546 lex.printError("Unknown menu tag");
554 MenuItem const & MenuDefinition::operator[](size_type i) const
560 bool MenuDefinition::hasFunc(FuncRequest const & func) const
562 for (const_iterator it = begin(), et = end(); it != et; ++it)
563 if (it->func() == func)
569 void MenuDefinition::checkShortcuts() const
571 // This is a quadratic algorithm, but we do not care because
572 // menus are short enough
573 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
574 QString shortcut = it1->shortcut();
575 if (shortcut.isEmpty())
577 if (!it1->label().contains(shortcut))
578 LYXERR0("Menu warning: menu entry \""
580 << "\" does not contain shortcut `"
581 << shortcut << "'.");
582 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
583 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
584 LYXERR0("Menu warning: menu entries "
585 << '"' << it1->fulllabel()
586 << "\" and \"" << it2->fulllabel()
587 << "\" share the same shortcut.");
594 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
596 const_iterator m = begin();
597 const_iterator m_end = end();
598 for (; m != m_end; ++m) {
599 if (m->kind() == MenuItem::Command && m->func() == func) {
600 names.push_back(qstring_to_ucs4(m->label()));
603 if (m->kind() == MenuItem::Submenu) {
604 names.push_back(qstring_to_ucs4(m->label()));
605 if (!m->hasSubmenu()) {
606 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
607 << m->label() << " name=" << m->submenuname());
611 if (m->submenu().searchMenu(func, names))
620 bool compareFormat(Format const * p1, Format const * p2)
626 QString limitStringLength(docstring const & str)
628 size_t const max_item_length = 45;
630 if (str.size() > max_item_length)
631 return toqstr(str.substr(0, max_item_length - 3) + "...");
637 void MenuDefinition::expandGraphicsGroups(Buffer const * buf)
640 InsetGraphics::getGraphicsGroups(*buf, grp);
641 set<string>::const_iterator it = grp.begin();
642 set<string>::const_iterator end = grp.end();
643 if (grp.empty()) return;
645 add(MenuItem(MenuItem::Separator));
646 add(MenuItem(MenuItem::Command, qt_("Clear group"), FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
647 for (; it != end; it++) {
648 add(MenuItem(MenuItem::Command, toqstr(*it), FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
652 void MenuDefinition::expandLastfiles()
654 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
655 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
659 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
660 string const file = lfit->absFilename();
661 QString const label = QString("%1. %2|%3").arg(ii)
662 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
663 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
668 void MenuDefinition::expandDocuments()
670 Buffer * first = theBufferList().first();
675 // We cannot use a for loop as the buffer list cycles.
677 QString label = toqstr(b->fileName().displayName(20));
681 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
682 add(MenuItem(MenuItem::Command, label,
683 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
685 b = theBufferList().next(b);
687 } while (b != first);
689 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
690 FuncRequest(LFUN_NOACTION)));
695 void MenuDefinition::expandBookmarks()
697 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
699 for (size_t i = 1; i <= bm.size(); ++i) {
701 string const file = bm.bookmark(i).filename.absFilename();
702 QString const label = QString("%1. %2|%3").arg(i)
703 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
704 add(MenuItem(MenuItem::Command, label,
705 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
711 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
713 if (!buf && kind != MenuItem::ImportFormats) {
714 add(MenuItem(MenuItem::Command,
715 qt_("No Document Open!"),
716 FuncRequest(LFUN_NOACTION)));
720 typedef vector<Format const *> Formats;
725 case MenuItem::ImportFormats:
726 formats = theConverters().importableFormats();
727 action = LFUN_BUFFER_IMPORT;
729 case MenuItem::ViewFormats:
730 formats = buf->exportableFormats(true);
731 action = LFUN_BUFFER_VIEW;
733 case MenuItem::UpdateFormats:
734 formats = buf->exportableFormats(true);
735 action = LFUN_BUFFER_UPDATE;
738 formats = buf->exportableFormats(false);
739 action = LFUN_BUFFER_EXPORT;
741 sort(formats.begin(), formats.end(), &compareFormat);
743 Formats::const_iterator fit = formats.begin();
744 Formats::const_iterator end = formats.end();
745 for (; fit != end ; ++fit) {
748 QString label = toqstr((*fit)->prettyname());
749 QString const shortcut = toqstr((*fit)->shortcut());
752 case MenuItem::ImportFormats:
753 // FIXME: This is a hack, we should rather solve
754 // FIXME: bug 2488 instead.
755 if ((*fit)->name() == "text")
756 label = qt_("Plain Text");
757 else if ((*fit)->name() == "textparagraph")
758 label = qt_("Plain Text, Join Lines");
761 case MenuItem::ViewFormats:
762 case MenuItem::ExportFormats:
763 case MenuItem::UpdateFormats:
764 if (!(*fit)->documentFormat())
768 LASSERT(false, /**/);
771 // FIXME: if we had proper support for translating the
772 // format names defined in configure.py, there would
773 // not be a need to check whether the shortcut is
774 // correct. If we add it uncondiitonally, it would
775 // create useless warnings on bad shortcuts
776 if (!shortcut.isEmpty() && label.contains(shortcut))
777 label += '|' + shortcut;
780 addWithStatusCheck(MenuItem(MenuItem::Command, label,
781 FuncRequest(action, (*fit)->name())));
783 add(MenuItem(MenuItem::Command, label,
784 FuncRequest(action, (*fit)->name())));
789 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
792 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
793 FuncRequest(LFUN_NOACTION)));
797 FloatList const & floats = buf->params().documentClass().floats();
798 FloatList::const_iterator cit = floats.begin();
799 FloatList::const_iterator end = floats.end();
800 for (; cit != end; ++cit) {
801 addWithStatusCheck(MenuItem(MenuItem::Command,
802 qt_(cit->second.listName()),
803 FuncRequest(LFUN_FLOAT_LIST,
804 cit->second.type())));
809 void MenuDefinition::expandFloatInsert(Buffer const * buf)
812 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
813 FuncRequest(LFUN_NOACTION)));
817 FloatList const & floats = buf->params().documentClass().floats();
818 FloatList::const_iterator cit = floats.begin();
819 FloatList::const_iterator end = floats.end();
820 for (; cit != end; ++cit) {
822 QString const label = qt_(cit->second.name());
823 addWithStatusCheck(MenuItem(MenuItem::Command, label,
824 FuncRequest(LFUN_FLOAT_INSERT,
825 cit->second.type())));
830 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
833 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
834 FuncRequest(LFUN_NOACTION)));
837 TextClass::InsetLayouts const & insetLayouts =
838 buf->params().documentClass().insetLayouts();
839 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
840 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
841 for (; cit != end; ++cit) {
842 docstring const label = cit->first;
843 if (cit->second.lyxtype() == s)
844 addWithStatusCheck(MenuItem(MenuItem::Command,
845 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
851 size_t const max_number_of_items = 25;
853 void MenuDefinition::expandToc2(Toc const & toc_list,
854 size_t from, size_t to, int depth)
856 int shortcut_count = 0;
858 // check whether depth is smaller than the smallest depth in toc.
859 int min_depth = 1000;
860 for (size_t i = from; i < to; ++i)
861 min_depth = min(min_depth, toc_list[i].depth());
862 if (min_depth > depth)
865 if (to - from <= max_number_of_items) {
866 for (size_t i = from; i < to; ++i) {
867 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
868 label += limitStringLength(toc_list[i].str());
869 if (toc_list[i].depth() == depth
870 && shortcut_count < 9) {
871 if (label.contains(QString::number(shortcut_count + 1)))
872 label += '|' + QString::number(++shortcut_count);
874 add(MenuItem(MenuItem::Command, label,
875 FuncRequest(toc_list[i].action())));
880 size_t new_pos = pos + 1;
881 while (new_pos < to && toc_list[new_pos].depth() > depth)
884 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
885 label += limitStringLength(toc_list[pos].str());
886 if (toc_list[pos].depth() == depth &&
887 shortcut_count < 9) {
888 if (label.contains(QString::number(shortcut_count + 1)))
889 label += '|' + QString::number(++shortcut_count);
891 if (new_pos == pos + 1) {
892 add(MenuItem(MenuItem::Command,
893 label, FuncRequest(toc_list[pos].action())));
896 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
897 MenuItem item(MenuItem::Submenu, label);
898 item.setSubmenu(sub);
907 void MenuDefinition::expandToc(Buffer const * buf)
909 // To make things very cleanly, we would have to pass buf to
910 // all MenuItem constructors and to expandToc2. However, we
911 // know that all the entries in a TOC will be have status_ ==
912 // OK, so we avoid this unnecessary overhead (JMarc)
915 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
916 FuncRequest(LFUN_NOACTION)));
920 Buffer* cbuf = const_cast<Buffer*>(buf);
921 cbuf->tocBackend().update();
922 cbuf->structureChanged();
924 // Add an entry for the master doc if this is a child doc
925 Buffer const * const master = buf->masterBuffer();
927 ParIterator const pit = par_iterator_begin(master->inset());
928 string const arg = convert<string>(pit->id());
929 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
930 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
933 MenuDefinition other_lists;
935 FloatList const & floatlist = buf->params().documentClass().floats();
936 TocList const & toc_list = buf->tocBackend().tocs();
937 TocList::const_iterator cit = toc_list.begin();
938 TocList::const_iterator end = toc_list.end();
939 for (; cit != end; ++cit) {
941 if (cit->first == "tableofcontents")
944 string const & floatName = floatlist.getType(cit->first).listName();
946 bool in_other_list = true;
947 if (!floatName.empty()) {
948 label = qt_(floatName);
949 in_other_list = false;
951 else if (cit->first == "child") {
952 label = qt_("Child Documents");
953 in_other_list = false;
954 } else if (cit->first == "graphics")
955 label = qt_("List of Graphics");
956 else if (cit->first == "equation")
957 label = qt_("List of Equations");
958 else if (cit->first == "index")
959 label = qt_("List of Indexes");
960 else if (cit->first == "listing") {
961 // FIXME: the listing navigate menu causes a crash for unknown
962 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
963 // This is a temporary fix:
964 //label = qt_("List of Listings");
967 else if (cit->first == "marginalnote")
968 label = qt_("List of Marginal notes");
969 else if (cit->first == "note")
970 label = qt_("List of Notes");
971 else if (cit->first == "footnote")
972 label = qt_("List of Footnotes");
973 else if (cit->first == "label")
974 label = qt_("Labels and References");
975 else if (cit->first == "citation")
976 label = qt_("List of Citations");
978 // This should not happen unless the entry is missing above.
979 label = qt_("Other floats: ") + toqstr(cit->first);
981 MenuDefinition submenu;
983 if (cit->second.size() >= 30) {
984 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
985 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
987 TocIterator ccit = cit->second.begin();
988 TocIterator eend = cit->second.end();
989 for (; ccit != eend; ++ccit) {
990 QString const label = limitStringLength(ccit->str());
991 submenu.add(MenuItem(MenuItem::Command, label,
992 FuncRequest(ccit->action())));
996 MenuItem item(MenuItem::Submenu, label);
997 item.setSubmenu(submenu);
999 other_lists.add(item);
1001 item.setSubmenu(submenu);
1005 if (!other_lists.empty()) {
1006 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1007 item.setSubmenu(other_lists);
1012 // Handle normal TOC
1013 cit = toc_list.find("tableofcontents");
1015 addWithStatusCheck(MenuItem(MenuItem::Command,
1016 qt_("No Table of contents"),
1019 expandToc2(cit->second, 0, cit->second.size(), 0);
1024 void MenuDefinition::expandPasteRecent()
1026 vector<docstring> const sel = cap::availableSelections();
1028 vector<docstring>::const_iterator cit = sel.begin();
1029 vector<docstring>::const_iterator end = sel.end();
1031 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1032 add(MenuItem(MenuItem::Command, toqstr(*cit),
1033 FuncRequest(LFUN_PASTE, convert<string>(index))));
1038 void MenuDefinition::expandToolbars()
1041 // extracts the toolbars from the backend
1042 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1043 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1045 for (; cit != end; ++cit) {
1046 QString label = qt_(cit->gui_name);
1047 // frontends are not supposed to turn on/off toolbars,
1048 // if they cannot update ToolbarBackend::flags. That
1049 // is to say, ToolbarsBackend::flags should reflect
1050 // the true state of toolbars.
1052 // menu is displayed as
1056 // in the case of auto.
1057 if (cit->flags & ToolbarInfo::AUTO)
1058 label += qt_(" (auto)");
1059 add(MenuItem(MenuItem::Command, label,
1060 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1065 void MenuDefinition::expandBranches(Buffer const * buf)
1068 add(MenuItem(MenuItem::Command,
1069 qt_("No Document Open!"),
1070 FuncRequest(LFUN_NOACTION)));
1074 BufferParams const & params = buf->masterBuffer()->params();
1075 if (params.branchlist().empty()) {
1076 add(MenuItem(MenuItem::Command,
1077 qt_("No Branch in Document!"),
1078 FuncRequest(LFUN_NOACTION)));
1082 BranchList::const_iterator cit = params.branchlist().begin();
1083 BranchList::const_iterator end = params.branchlist().end();
1085 for (int ii = 1; cit != end; ++cit, ++ii) {
1086 docstring label = cit->getBranch();
1088 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1089 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1090 FuncRequest(LFUN_BRANCH_INSERT,
1091 cit->getBranch())));
1096 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1099 add(MenuItem(MenuItem::Command,
1100 qt_("No Document Open!"),
1101 FuncRequest(LFUN_NOACTION)));
1105 Inset const * inset = bv->cursor().nextInset();
1106 if (!inset || inset->lyxCode() != CITE_CODE) {
1107 add(MenuItem(MenuItem::Command,
1108 qt_("No Citation in Scope!"),
1109 FuncRequest(LFUN_NOACTION)));
1112 InsetCommand const * citinset =
1113 static_cast<InsetCommand const *>(inset);
1115 Buffer const * buf = &bv->buffer();
1116 docstring key = citinset->getParam("key");
1117 // we can only handle one key currently
1118 if (contains(key, ','))
1119 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1121 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1122 vector<docstring> citeStrings =
1123 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1125 vector<docstring>::const_iterator cit = citeStrings.begin();
1126 vector<docstring>::const_iterator end = citeStrings.end();
1128 for (int ii = 1; cit != end; ++cit, ++ii) {
1129 docstring label = *cit;
1131 CiteStyle cst = citeStyleList[ii - 1];
1133 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1134 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1135 "changetype " + from_utf8(citationStyleToString(cs)))));
1142 /////////////////////////////////////////////////////////////////////
1143 // Menu::Impl definition and implementation
1144 /////////////////////////////////////////////////////////////////////
1148 /// populates the menu or one of its submenu
1149 /// This is used as a recursive function
1150 void populate(QMenu & qMenu, MenuDefinition const & menu);
1152 /// Only needed for top level menus.
1153 MenuDefinition * top_level_menu;
1156 /// the name of this menu
1162 /// Get a MenuDefinition item label from the menu backend
1163 static QString label(MenuItem const & mi)
1165 QString label = mi.label();
1166 label.replace("&", "&&");
1168 QString shortcut = mi.shortcut();
1169 if (!shortcut.isEmpty()) {
1170 int pos = label.indexOf(shortcut);
1172 //label.insert(pos, 1, char_type('&'));
1173 label.replace(pos, 0, "&");
1176 QString const binding = mi.binding();
1177 if (!binding.isEmpty())
1178 label += '\t' + binding;
1183 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1185 LYXERR(Debug::GUI, "populating menu " << menu.name());
1186 if (menu.size() == 0) {
1187 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1190 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1191 MenuDefinition::const_iterator m = menu.begin();
1192 MenuDefinition::const_iterator end = menu.end();
1193 for (; m != end; ++m) {
1194 if (m->kind() == MenuItem::Separator)
1195 qMenu.addSeparator();
1196 else if (m->kind() == MenuItem::Submenu) {
1197 QMenu * subMenu = qMenu.addMenu(label(*m));
1198 populate(*subMenu, m->submenu());
1200 // we have a MenuItem::Command
1201 qMenu.addAction(new Action(view, QIcon(), label(*m),
1202 m->func(), QString(), &qMenu));
1207 /////////////////////////////////////////////////////////////////////
1208 // Menu implementation
1209 /////////////////////////////////////////////////////////////////////
1211 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1212 : QMenu(gv), d(new Menu::Impl)
1214 d->top_level_menu = top_level? new MenuDefinition : 0;
1218 if (d->top_level_menu)
1219 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1225 delete d->top_level_menu;
1230 void Menu::updateView()
1232 guiApp->menus().updateMenu(this);
1236 /////////////////////////////////////////////////////////////////////
1237 // Menus::Impl definition and implementation
1238 /////////////////////////////////////////////////////////////////////
1240 struct Menus::Impl {
1242 bool hasMenu(QString const &) const;
1244 MenuDefinition & getMenu(QString const &);
1246 MenuDefinition const & getMenu(QString const &) const;
1248 /// Expands some special entries of the menu
1249 /** The entries with the following kind are expanded to a
1250 sequence of Command MenuItems: Lastfiles, Documents,
1251 ViewFormats, ExportFormats, UpdateFormats, Branches
1253 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1254 BufferView const *) const;
1256 /// Initialize specific MACOS X menubar
1257 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1259 /// Mac special menu.
1260 /** This defines a menu whose entries list the FuncRequests
1261 that will be removed by expand() in other menus. This is
1262 used by the Qt/Mac code
1264 MenuDefinition specialmenu_;
1269 MenuDefinition menubar_;
1271 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1273 /// name to menu for \c menu() method.
1278 Here is what the Qt documentation says about how a menubar is chosen:
1280 1) If the window has a QMenuBar then it is used. 2) If the window
1281 is a modal then its menubar is used. If no menubar is specified
1282 then a default menubar is used (as documented below) 3) If the
1283 window has no parent then the default menubar is used (as
1286 The above 3 steps are applied all the way up the parent window
1287 chain until one of the above are satisifed. If all else fails a
1288 default menubar will be created, the default menubar on Qt/Mac is
1289 an empty menubar, however you can create a different default
1290 menubar by creating a parentless QMenuBar, the first one created
1291 will thus be designated the default menubar, and will be used
1292 whenever a default menubar is needed.
1294 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1295 that this menubar will be used also when one of LyX' dialogs has
1298 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1300 /* Since Qt 4.2, the qt/mac menu code has special code for
1301 specifying the role of a menu entry. However, it does not
1302 work very well with our scheme of creating menus on demand,
1303 and therefore we need to put these entries in a special
1304 invisible menu. (JMarc)
1307 /* The entries of our special mac menu. If we add support for
1308 * special entries in Menus, we could imagine something
1310 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1311 * and therefore avoid hardcoding. I am not sure it is worth
1312 * the hassle, though. (JMarc)
1314 struct MacMenuEntry {
1318 QAction::MenuRole role;
1321 MacMenuEntry entries[] = {
1322 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1323 QAction::AboutRole},
1324 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1325 QAction::PreferencesRole},
1326 {LFUN_RECONFIGURE, "", "Reconfigure",
1327 QAction::ApplicationSpecificRole},
1328 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1330 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1332 // the special menu for Menus. Fill it up only once.
1333 if (specialmenu_.size() == 0) {
1334 for (size_t i = 0 ; i < num_entries ; ++i) {
1335 FuncRequest const func(entries[i].action,
1336 from_utf8(entries[i].arg));
1337 specialmenu_.add(MenuItem(MenuItem::Command,
1338 entries[i].label, func));
1342 // add the entries to a QMenu that will eventually be empty
1343 // and therefore invisible.
1344 QMenu * qMenu = qmb->addMenu("special");
1345 MenuDefinition::const_iterator cit = specialmenu_.begin();
1346 MenuDefinition::const_iterator end = specialmenu_.end();
1347 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1348 Action * action = new Action(view, QIcon(), cit->label(),
1349 cit->func(), QString(), qMenu);
1350 action->setMenuRole(entries[i].role);
1351 qMenu->addAction(action);
1356 void Menus::Impl::expand(MenuDefinition const & frommenu,
1357 MenuDefinition & tomenu, BufferView const * bv) const
1359 if (!tomenu.empty())
1362 for (MenuDefinition::const_iterator cit = frommenu.begin();
1363 cit != frommenu.end() ; ++cit) {
1364 Buffer const * buf = bv ? &bv->buffer() : 0;
1365 switch (cit->kind()) {
1366 case MenuItem::Lastfiles:
1367 tomenu.expandLastfiles();
1370 case MenuItem::Documents:
1371 tomenu.expandDocuments();
1374 case MenuItem::Bookmarks:
1375 tomenu.expandBookmarks();
1378 case MenuItem::ImportFormats:
1379 case MenuItem::ViewFormats:
1380 case MenuItem::UpdateFormats:
1381 case MenuItem::ExportFormats:
1382 tomenu.expandFormats(cit->kind(), buf);
1385 case MenuItem::CharStyles:
1386 tomenu.expandFlexInsert(buf, "charstyle");
1389 case MenuItem::Custom:
1390 tomenu.expandFlexInsert(buf, "custom");
1393 case MenuItem::Elements:
1394 tomenu.expandFlexInsert(buf, "element");
1397 case MenuItem::FloatListInsert:
1398 tomenu.expandFloatListInsert(buf);
1401 case MenuItem::FloatInsert:
1402 tomenu.expandFloatInsert(buf);
1405 case MenuItem::PasteRecent:
1406 tomenu.expandPasteRecent();
1409 case MenuItem::Toolbars:
1410 tomenu.expandToolbars();
1413 case MenuItem::Branches:
1414 tomenu.expandBranches(buf);
1417 case MenuItem::CiteStyles:
1418 tomenu.expandCiteStyles(bv);
1422 tomenu.expandToc(buf);
1425 case MenuItem::GraphicsGroups:
1426 tomenu.expandGraphicsGroups(buf);
1429 case MenuItem::Submenu: {
1430 MenuItem item(*cit);
1431 item.setSubmenu(MenuDefinition(cit->submenuname()));
1432 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1433 tomenu.addWithStatusCheck(item);
1437 case MenuItem::Separator:
1438 tomenu.addWithStatusCheck(*cit);
1441 case MenuItem::Command:
1442 if (!specialmenu_.hasFunc(cit->func()))
1443 tomenu.addWithStatusCheck(*cit);
1447 // we do not want the menu to end with a separator
1448 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1449 tomenu.items_.pop_back();
1451 // Check whether the shortcuts are unique
1452 tomenu.checkShortcuts();
1456 bool Menus::Impl::hasMenu(QString const & name) const
1458 return find_if(menulist_.begin(), menulist_.end(),
1459 MenuNamesEqual(name)) != menulist_.end();
1463 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1465 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1466 MenuNamesEqual(name));
1467 if (cit == menulist_.end())
1468 LYXERR0("No submenu named " << name);
1469 LASSERT(cit != menulist_.end(), /**/);
1474 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1476 iterator it = find_if(menulist_.begin(), menulist_.end(),
1477 MenuNamesEqual(name));
1478 if (it == menulist_.end())
1479 LYXERR0("No submenu named " << name);
1480 LASSERT(it != menulist_.end(), /**/);
1485 /////////////////////////////////////////////////////////////////////
1489 /////////////////////////////////////////////////////////////////////
1491 Menus::Menus() : d(new Impl) {}
1498 void Menus::read(Lexer & lex)
1506 LexerKeyword menutags[] = {
1507 { "end", md_endmenuset },
1508 { "menu", md_menu },
1509 { "menubar", md_menubar }
1512 // consistency check
1513 if (compare_ascii_no_case(lex.getString(), "menuset"))
1514 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1516 lex.pushTable(menutags);
1517 lex.setContext("Menus::read");
1521 while (lex.isOK() && !quit) {
1522 switch (lex.lex()) {
1524 d->menubar_.read(lex);
1528 QString const name = toqstr(lex.getDocString());
1529 if (d->hasMenu(name))
1530 d->getMenu(name).read(lex);
1532 MenuDefinition menu(name);
1534 d->menulist_.push_back(menu);
1542 lex.printError("Unknown menu tag");
1550 bool Menus::searchMenu(FuncRequest const & func,
1551 vector<docstring> & names) const
1553 MenuDefinition menu;
1554 d->expand(d->menubar_, menu, 0);
1555 return menu.searchMenu(func, names);
1559 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1563 // setup special mac specific menu item
1564 d->macxMenuBarInit(view, qmb);
1567 // Clear all menubar contents before filling it.
1571 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1573 if (d->menubar_.size() == 0) {
1574 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1575 << d->menubar_.name());
1578 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1580 MenuDefinition menu;
1581 BufferView * bv = 0;
1584 d->expand(d->menubar_, menu, bv);
1586 MenuDefinition::const_iterator m = menu.begin();
1587 MenuDefinition::const_iterator end = menu.end();
1589 for (; m != end; ++m) {
1591 if (m->kind() != MenuItem::Submenu) {
1592 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1596 LYXERR(Debug::GUI, "menu bar item " << m->label()
1597 << " is a submenu named " << m->submenuname());
1599 QString name = m->submenuname();
1600 if (!d->hasMenu(name)) {
1601 LYXERR(Debug::GUI, "\tERROR: " << name
1602 << " submenu has no menu!");
1606 Menu * menu = new Menu(view, m->submenuname(), true);
1607 menu->setTitle(label(*m));
1610 d->name_map_[view][name] = menu;
1615 void Menus::updateMenu(Menu * qmenu)
1617 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1620 if (qmenu->d->name.isEmpty())
1623 // Here, We make sure that theLyXFunc points to the correct LyXView.
1624 theLyXFunc().setLyXView(qmenu->d->view);
1626 if (!d->hasMenu(qmenu->d->name)) {
1627 qmenu->addAction(qt_("No action defined!"));
1628 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1633 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1634 BufferView * bv = 0;
1636 bv = qmenu->d->view->view();
1637 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1638 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1642 Menu * Menus::menu(QString const & name, GuiView & view)
1644 LYXERR(Debug::GUI, "Context menu requested: " << name);
1645 Menu * menu = d->name_map_[&view].value(name, 0);
1646 if (!menu && !name.startsWith("context-")) {
1647 LYXERR0("requested context menu not found: " << name);
1651 menu = new Menu(&view, name, true);
1652 d->name_map_[&view][name] = menu;
1656 } // namespace frontend
1659 #include "Menus_moc.cpp"