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"
46 #include "TextClass.h"
47 #include "TocBackend.h"
48 #include "ToolbarBackend.h"
50 #include "insets/Inset.h"
51 #include "insets/InsetCitation.h"
53 #include "support/lassert.h"
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/filetools.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
66 #include <boost/shared_ptr.hpp>
73 using namespace lyx::support;
81 // MacOSX specific stuff is at the end.
88 /// The type of elements that can be in a menu
96 /** This is the list of last opened file,
97 typically for the File menu. */
99 /** This is the list of opened Documents,
100 typically for the Documents menu. */
102 /** This is the bookmarks */
106 /** This is a list of viewable formats
107 typically for the File->View menu. */
109 /** This is a list of updatable formats
110 typically for the File->Update menu. */
112 /** This is a list of exportable formats
113 typically for the File->Export menu. */
115 /** This is a list of importable formats
116 typically for the File->Export menu. */
118 /** This is the list of elements available
119 * for insertion into document. */
121 /** This is the list of user-configurable
122 insets to insert into document */
124 /** This is the list of XML elements to
125 insert into the document */
127 /** This is the list of floats that we can
128 insert a list for. */
130 /** This is the list of floats that we can
133 /** This is the list of selections that can
138 /** Available branches in document */
140 /** Available citation styles for a given citation */
144 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
147 QString const & label,
148 QString const & submenu = QString(),
149 bool optional = false)
150 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
152 LASSERT(kind == Submenu, /**/);
156 QString const & label,
157 FuncRequest const & func,
158 bool optional = false)
159 : kind_(kind), label_(label), func_(func), optional_(optional)
161 func_.origin = FuncRequest::MENU;
164 // boost::shared_ptr<MenuDefinition> needs this apprently...
167 /// The label of a given menuitem
168 QString label() const { return label_.split('|')[0]; }
170 /// The keyboard shortcut (usually underlined in the entry)
171 QString shortcut() const
173 return label_.contains('|') ? label_.split('|')[1] : QString();
175 /// The complete label, with label and shortcut separated by a '|'
176 QString fulllabel() const { return label_;}
177 /// The kind of entry
178 Kind kind() const { return kind_; }
179 /// the action (if relevant)
180 FuncRequest const & func() const { return func_; }
181 /// returns true if the entry should be ommited when disabled
182 bool optional() const { return optional_; }
183 /// returns the status of the lfun associated with this entry
184 FuncStatus const & status() const { return status_; }
185 /// returns the status of the lfun associated with this entry
186 FuncStatus & status() { return status_; }
187 /// returns the status of the lfun associated with this entry
188 void status(FuncStatus const & status) { status_ = status; }
190 ///returns the binding associated to this action.
191 QString binding() const
193 if (kind_ != Command)
195 // Get the keys bound to this action, but keep only the
197 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
199 return toqstr(bindings.begin()->print(KeySequence::ForGui));
201 LYXERR(Debug::KBMAP, "No binding for "
202 << lyxaction.getActionName(func_.action)
203 << '(' << func_.argument() << ')');
207 /// the description of the submenu (if relevant)
208 QString const & submenuname() const { return submenuname_; }
209 /// set the description of the submenu
210 void submenuname(QString const & name) { submenuname_ = name; }
212 bool hasSubmenu() const { return !submenu_.isEmpty(); }
214 MenuDefinition const & submenu() const { return submenu_.at(0); }
215 MenuDefinition & submenu() { return submenu_[0]; }
217 void setSubmenu(MenuDefinition const & menu)
220 submenu_.append(menu);
231 QString submenuname_;
236 /// contains 0 or 1 item.
237 QList<MenuDefinition> submenu_;
241 class MenuDefinition {
244 typedef std::vector<MenuItem> ItemList;
246 typedef ItemList::const_iterator const_iterator;
248 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
253 QString const & name() const { return name_; }
255 bool empty() const { return items_.empty(); }
256 /// Clear the menu content.
257 void clear() { items_.clear(); }
259 size_t size() const { return items_.size(); }
261 MenuItem const & operator[](size_t) const;
263 const_iterator begin() const { return items_.begin(); }
265 const_iterator end() const { return items_.end(); }
267 // search for func in this menu iteratively, and put menu
269 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
272 bool hasFunc(FuncRequest const &) const;
273 /// Add the menu item unconditionally
274 void add(MenuItem const & item) { items_.push_back(item); }
275 /// Checks the associated FuncRequest status before adding the
277 void addWithStatusCheck(MenuItem const &);
278 // Check whether the menu shortcuts are unique
279 void checkShortcuts() const;
281 void expandLastfiles();
282 void expandDocuments();
283 void expandBookmarks();
284 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
285 void expandFloatListInsert(Buffer const * buf);
286 void expandFloatInsert(Buffer const * buf);
287 void expandFlexInsert(Buffer const * buf, std::string s);
288 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
289 void expandToc(Buffer const * buf);
290 void expandPasteRecent();
291 void expandToolbars();
292 void expandBranches(Buffer const * buf);
293 void expandCiteStyles(BufferView const *);
301 /// Helper for std::find_if
305 MenuNamesEqual(QString const & name) : name_(name) {}
306 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
313 typedef std::vector<MenuDefinition> MenuList;
315 typedef MenuList::const_iterator const_iterator;
317 typedef MenuList::iterator iterator;
319 /////////////////////////////////////////////////////////////////////
320 // MenuDefinition implementation
321 /////////////////////////////////////////////////////////////////////
323 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
327 case MenuItem::Command: {
328 FuncStatus status = lyx::getStatus(i.func());
329 if (status.unknown() || (!status.enabled() && i.optional()))
332 items_.back().status(status);
336 case MenuItem::Submenu: {
337 if (i.hasSubmenu()) {
338 bool enabled = false;
339 for (const_iterator cit = i.submenu().begin();
340 cit != i.submenu().end(); ++cit) {
341 if ((cit->kind() == MenuItem::Command
342 || cit->kind() == MenuItem::Submenu)
343 && cit->status().enabled()) {
348 if (enabled || !i.optional()) {
350 items_.back().status().enabled(enabled);
358 case MenuItem::Separator:
359 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
369 void MenuDefinition::read(Lexer & lex)
397 LexerKeyword menutags[] = {
398 { "bookmarks", md_bookmarks },
399 { "branches", md_branches },
400 { "charstyles", md_charstyles },
401 { "citestyles", md_citestyles },
402 { "custom", md_custom },
403 { "documents", md_documents },
404 { "elements", md_elements },
405 { "end", md_endmenu },
406 { "exportformats", md_exportformats },
407 { "floatinsert", md_floatinsert },
408 { "floatlistinsert", md_floatlistinsert },
409 { "importformats", md_importformats },
411 { "lastfiles", md_lastfiles },
412 { "optitem", md_optitem },
413 { "optsubmenu", md_optsubmenu },
414 { "pasterecent", md_pasterecent },
415 { "separator", md_separator },
416 { "submenu", md_submenu },
418 { "toolbars", md_toolbars },
419 { "updateformats", md_updateformats },
420 { "viewformats", md_viewformats }
423 lex.pushTable(menutags);
424 lex.setContext("MenuDefinition::read: ");
427 bool optional = false;
429 while (lex.isOK() && !quit) {
433 // fallback to md_item
436 docstring const name = translateIfPossible(lex.getDocString());
438 string const command = lex.getString();
439 FuncRequest func = lyxaction.lookupFunc(command);
440 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
446 add(MenuItem(MenuItem::Separator));
450 add(MenuItem(MenuItem::Lastfiles));
454 add(MenuItem(MenuItem::CharStyles));
458 add(MenuItem(MenuItem::Custom));
462 add(MenuItem(MenuItem::Elements));
466 add(MenuItem(MenuItem::Documents));
470 add(MenuItem(MenuItem::Bookmarks));
474 add(MenuItem(MenuItem::Toc));
478 add(MenuItem(MenuItem::ViewFormats));
481 case md_updateformats:
482 add(MenuItem(MenuItem::UpdateFormats));
485 case md_exportformats:
486 add(MenuItem(MenuItem::ExportFormats));
489 case md_importformats:
490 add(MenuItem(MenuItem::ImportFormats));
493 case md_floatlistinsert:
494 add(MenuItem(MenuItem::FloatListInsert));
498 add(MenuItem(MenuItem::FloatInsert));
502 add(MenuItem(MenuItem::PasteRecent));
506 add(MenuItem(MenuItem::Toolbars));
510 add(MenuItem(MenuItem::Branches));
514 add(MenuItem(MenuItem::CiteStyles));
519 // fallback to md_submenu
522 docstring const mlabel = translateIfPossible(lex.getDocString());
524 docstring const mname = lex.getDocString();
525 add(MenuItem(MenuItem::Submenu,
526 toqstr(mlabel), toqstr(mname), optional));
536 lex.printError("Unknown menu tag");
544 MenuItem const & MenuDefinition::operator[](size_type i) const
550 bool MenuDefinition::hasFunc(FuncRequest const & func) const
552 for (const_iterator it = begin(), et = end(); it != et; ++it)
553 if (it->func() == func)
559 void MenuDefinition::checkShortcuts() const
561 // This is a quadratic algorithm, but we do not care because
562 // menus are short enough
563 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
564 QString shortcut = it1->shortcut();
565 if (shortcut.isEmpty())
567 if (!it1->label().contains(shortcut))
568 lyxerr << "Menu warning: menu entry \""
569 << fromqstr(it1->label())
570 << "\" does not contain shortcut `"
571 << fromqstr(shortcut) << "'." << endl;
572 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
573 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
574 lyxerr << "Menu warning: menu entries "
575 << '"' << fromqstr(it1->fulllabel())
576 << "\" and \"" << fromqstr(it2->fulllabel())
577 << "\" share the same shortcut."
585 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
587 const_iterator m = begin();
588 const_iterator m_end = end();
589 for (; m != m_end; ++m) {
590 if (m->kind() == MenuItem::Command && m->func() == func) {
591 names.push_back(qstring_to_ucs4(m->label()));
594 if (m->kind() == MenuItem::Submenu) {
595 names.push_back(qstring_to_ucs4(m->label()));
596 if (!m->hasSubmenu()) {
597 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
598 << fromqstr(m->label())
599 << " name=" << fromqstr(m->submenuname()));
603 if (m->submenu().searchMenu(func, names))
612 bool compareFormat(Format const * p1, Format const * p2)
618 QString limitStringLength(docstring const & str)
620 size_t const max_item_length = 45;
622 if (str.size() > max_item_length)
623 return toqstr(str.substr(0, max_item_length - 3) + "...");
629 void MenuDefinition::expandLastfiles()
631 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
632 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
636 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
637 string const file = lfit->absFilename();
638 QString const label = QString("%1. %2|%3").arg(ii)
639 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
640 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
645 void MenuDefinition::expandDocuments()
647 Buffer * first = theBufferList().first();
652 // We cannot use a for loop as the buffer list cycles.
654 QString label = toqstr(b->fileName().displayName(20));
658 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
659 add(MenuItem(MenuItem::Command, label,
660 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
662 b = theBufferList().next(b);
664 } while (b != first);
666 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
667 FuncRequest(LFUN_NOACTION)));
672 void MenuDefinition::expandBookmarks()
674 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
676 for (size_t i = 1; i <= bm.size(); ++i) {
678 string const file = bm.bookmark(i).filename.absFilename();
679 QString const label = QString("%1. %2|%3").arg(i)
680 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
681 add(MenuItem(MenuItem::Command, label,
682 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
688 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
690 if (!buf && kind != MenuItem::ImportFormats) {
691 add(MenuItem(MenuItem::Command,
692 qt_("No Document Open!"),
693 FuncRequest(LFUN_NOACTION)));
697 typedef vector<Format const *> Formats;
702 case MenuItem::ImportFormats:
703 formats = theConverters().importableFormats();
704 action = LFUN_BUFFER_IMPORT;
706 case MenuItem::ViewFormats:
707 formats = buf->exportableFormats(true);
708 action = LFUN_BUFFER_VIEW;
710 case MenuItem::UpdateFormats:
711 formats = buf->exportableFormats(true);
712 action = LFUN_BUFFER_UPDATE;
715 formats = buf->exportableFormats(false);
716 action = LFUN_BUFFER_EXPORT;
718 sort(formats.begin(), formats.end(), &compareFormat);
720 Formats::const_iterator fit = formats.begin();
721 Formats::const_iterator end = formats.end();
722 for (; fit != end ; ++fit) {
725 QString label = toqstr((*fit)->prettyname());
726 QString const shortcut = toqstr((*fit)->shortcut());
729 case MenuItem::ImportFormats:
730 // FIXME: This is a hack, we should rather solve
731 // FIXME: bug 2488 instead.
732 if ((*fit)->name() == "text")
733 label = qt_("Plain Text");
734 else if ((*fit)->name() == "textparagraph")
735 label = qt_("Plain Text, Join Lines");
738 case MenuItem::ViewFormats:
739 case MenuItem::ExportFormats:
740 case MenuItem::UpdateFormats:
741 if (!(*fit)->documentFormat())
745 LASSERT(false, /**/);
748 // FIXME: if we had proper support for translating the
749 // format names defined in configure.py, there would
750 // not be a need to check whether the shortcut is
751 // correct. If we add it uncondiitonally, it would
752 // create useless warnings on bad shortcuts
753 if (!shortcut.isEmpty() && label.contains(shortcut))
754 label += '|' + shortcut;
757 addWithStatusCheck(MenuItem(MenuItem::Command, label,
758 FuncRequest(action, (*fit)->name())));
760 add(MenuItem(MenuItem::Command, label,
761 FuncRequest(action, (*fit)->name())));
766 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
769 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
770 FuncRequest(LFUN_NOACTION)));
774 FloatList const & floats = buf->params().documentClass().floats();
775 FloatList::const_iterator cit = floats.begin();
776 FloatList::const_iterator end = floats.end();
777 for (; cit != end; ++cit) {
778 addWithStatusCheck(MenuItem(MenuItem::Command,
779 qt_(cit->second.listName()),
780 FuncRequest(LFUN_FLOAT_LIST,
781 cit->second.type())));
786 void MenuDefinition::expandFloatInsert(Buffer const * buf)
789 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
790 FuncRequest(LFUN_NOACTION)));
794 FloatList const & floats = buf->params().documentClass().floats();
795 FloatList::const_iterator cit = floats.begin();
796 FloatList::const_iterator end = floats.end();
797 for (; cit != end; ++cit) {
799 QString const label = qt_(cit->second.name());
800 addWithStatusCheck(MenuItem(MenuItem::Command, label,
801 FuncRequest(LFUN_FLOAT_INSERT,
802 cit->second.type())));
807 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
810 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
811 FuncRequest(LFUN_NOACTION)));
814 TextClass::InsetLayouts const & insetLayouts =
815 buf->params().documentClass().insetLayouts();
816 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
817 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
818 for (; cit != end; ++cit) {
819 docstring const label = cit->first;
820 if (cit->second.lyxtype() == s)
821 addWithStatusCheck(MenuItem(MenuItem::Command,
822 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
828 size_t const max_number_of_items = 25;
830 void MenuDefinition::expandToc2(Toc const & toc_list,
831 size_t from, size_t to, int depth)
833 int shortcut_count = 0;
835 // check whether depth is smaller than the smallest depth in toc.
836 int min_depth = 1000;
837 for (size_t i = from; i < to; ++i)
838 min_depth = min(min_depth, toc_list[i].depth());
839 if (min_depth > depth)
842 if (to - from <= max_number_of_items) {
843 for (size_t i = from; i < to; ++i) {
844 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
845 label += limitStringLength(toc_list[i].str());
846 if (toc_list[i].depth() == depth
847 && shortcut_count < 9) {
848 if (label.contains(QString::number(shortcut_count + 1)))
849 label += '|' + QString::number(++shortcut_count);
851 add(MenuItem(MenuItem::Command, label,
852 FuncRequest(toc_list[i].action())));
857 size_t new_pos = pos + 1;
858 while (new_pos < to && toc_list[new_pos].depth() > depth)
861 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
862 label += limitStringLength(toc_list[pos].str());
863 if (toc_list[pos].depth() == depth &&
864 shortcut_count < 9) {
865 if (label.contains(QString::number(shortcut_count + 1)))
866 label += '|' + QString::number(++shortcut_count);
868 if (new_pos == pos + 1) {
869 add(MenuItem(MenuItem::Command,
870 label, FuncRequest(toc_list[pos].action())));
873 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
874 MenuItem item(MenuItem::Submenu, label);
875 item.setSubmenu(sub);
884 void MenuDefinition::expandToc(Buffer const * buf)
886 // To make things very cleanly, we would have to pass buf to
887 // all MenuItem constructors and to expandToc2. However, we
888 // know that all the entries in a TOC will be have status_ ==
889 // OK, so we avoid this unnecessary overhead (JMarc)
892 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
893 FuncRequest(LFUN_NOACTION)));
897 Buffer* cbuf = const_cast<Buffer*>(buf);
898 cbuf->tocBackend().update();
899 cbuf->structureChanged();
901 // Add an entry for the master doc if this is a child doc
902 Buffer const * const master = buf->masterBuffer();
904 ParIterator const pit = par_iterator_begin(master->inset());
905 string const arg = convert<string>(pit->id());
906 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
907 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
910 MenuDefinition other_lists;
912 FloatList const & floatlist = buf->params().documentClass().floats();
913 TocList const & toc_list = buf->tocBackend().tocs();
914 TocList::const_iterator cit = toc_list.begin();
915 TocList::const_iterator end = toc_list.end();
916 for (; cit != end; ++cit) {
918 if (cit->first == "tableofcontents")
921 string const & floatName = floatlist.getType(cit->first).listName();
923 bool in_other_list = true;
924 if (!floatName.empty()) {
925 label = qt_(floatName);
926 in_other_list = false;
928 else if (cit->first == "child") {
929 label = qt_("Child Documents");
930 in_other_list = false;
931 } else if (cit->first == "graphics")
932 label = qt_("List of Graphics");
933 else if (cit->first == "equation")
934 label = qt_("List of Equations");
935 else if (cit->first == "index")
936 label = qt_("List of Indexes");
937 else if (cit->first == "listing") {
938 // FIXME: the listing navigate menu causes a crash for unknown
939 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
940 // This is a temporary fix:
941 //label = qt_("List of Listings");
944 else if (cit->first == "marginalnote")
945 label = qt_("List of Marginal notes");
946 else if (cit->first == "note")
947 label = qt_("List of Notes");
948 else if (cit->first == "footnote")
949 label = qt_("List of Footnotes");
950 else if (cit->first == "label")
951 label = qt_("Labels and References");
952 else if (cit->first == "citation")
953 label = qt_("List of Citations");
955 // This should not happen unless the entry is missing above.
956 label = qt_("Other floats: ") + toqstr(cit->first);
958 MenuDefinition submenu;
960 if (cit->second.size() >= 30) {
961 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
962 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
964 TocIterator ccit = cit->second.begin();
965 TocIterator eend = cit->second.end();
966 for (; ccit != eend; ++ccit) {
967 QString const label = limitStringLength(ccit->str());
968 submenu.add(MenuItem(MenuItem::Command, label,
969 FuncRequest(ccit->action())));
973 MenuItem item(MenuItem::Submenu, label);
974 item.setSubmenu(submenu);
976 other_lists.add(item);
978 item.setSubmenu(submenu);
982 if (!other_lists.empty()) {
983 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
984 item.setSubmenu(other_lists);
990 cit = toc_list.find("tableofcontents");
992 addWithStatusCheck(MenuItem(MenuItem::Command,
993 qt_("No Table of contents"),
996 expandToc2(cit->second, 0, cit->second.size(), 0);
1001 void MenuDefinition::expandPasteRecent()
1003 vector<docstring> const sel = cap::availableSelections();
1005 vector<docstring>::const_iterator cit = sel.begin();
1006 vector<docstring>::const_iterator end = sel.end();
1008 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1009 add(MenuItem(MenuItem::Command, toqstr(*cit),
1010 FuncRequest(LFUN_PASTE, convert<string>(index))));
1015 void MenuDefinition::expandToolbars()
1018 // extracts the toolbars from the backend
1019 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1020 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1022 for (; cit != end; ++cit) {
1023 QString label = qt_(cit->gui_name);
1024 // frontends are not supposed to turn on/off toolbars,
1025 // if they cannot update ToolbarBackend::flags. That
1026 // is to say, ToolbarsBackend::flags should reflect
1027 // the true state of toolbars.
1029 // menu is displayed as
1033 // in the case of auto.
1034 if (cit->flags & ToolbarInfo::AUTO)
1035 label += qt_(" (auto)");
1036 add(MenuItem(MenuItem::Command, label,
1037 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1042 void MenuDefinition::expandBranches(Buffer const * buf)
1045 add(MenuItem(MenuItem::Command,
1046 qt_("No Document Open!"),
1047 FuncRequest(LFUN_NOACTION)));
1051 BufferParams const & params = buf->masterBuffer()->params();
1052 if (params.branchlist().empty()) {
1053 add(MenuItem(MenuItem::Command,
1054 qt_("No Branch in Document!"),
1055 FuncRequest(LFUN_NOACTION)));
1059 BranchList::const_iterator cit = params.branchlist().begin();
1060 BranchList::const_iterator end = params.branchlist().end();
1062 for (int ii = 1; cit != end; ++cit, ++ii) {
1063 docstring label = cit->getBranch();
1065 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1066 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1067 FuncRequest(LFUN_BRANCH_INSERT,
1068 cit->getBranch())));
1073 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1076 add(MenuItem(MenuItem::Command,
1077 qt_("No Document Open!"),
1078 FuncRequest(LFUN_NOACTION)));
1082 Inset const * inset = bv->cursor().nextInset();
1083 if (!inset || inset->lyxCode() != CITE_CODE) {
1084 add(MenuItem(MenuItem::Command,
1085 qt_("No Citation in Scope!"),
1086 FuncRequest(LFUN_NOACTION)));
1089 InsetCommand const * citinset =
1090 static_cast<InsetCommand const *>(inset);
1092 Buffer const * buf = &bv->buffer();
1093 docstring key = citinset->getParam("key");
1094 // we can only handle one key currently
1095 if (contains(key, ','))
1096 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1098 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1099 vector<docstring> citeStrings =
1100 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1102 vector<docstring>::const_iterator cit = citeStrings.begin();
1103 vector<docstring>::const_iterator end = citeStrings.end();
1105 for (int ii = 1; cit != end; ++cit, ++ii) {
1106 docstring label = *cit;
1108 CiteStyle cst = citeStyleList[ii - 1];
1110 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1111 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1112 "changetype " + from_utf8(citationStyleToString(cs)))));
1119 /////////////////////////////////////////////////////////////////////
1120 // Menu::Impl definition and implementation
1121 /////////////////////////////////////////////////////////////////////
1125 /// populates the menu or one of its submenu
1126 /// This is used as a recursive function
1127 void populate(QMenu & qMenu, MenuDefinition const & menu);
1129 /// Only needed for top level menus.
1130 MenuDefinition * top_level_menu;
1133 /// the name of this menu
1139 /// Get a MenuDefinition item label from the menu backend
1140 static QString label(MenuItem const & mi)
1142 QString label = mi.label();
1143 label.replace("&", "&&");
1145 QString shortcut = mi.shortcut();
1146 if (!shortcut.isEmpty()) {
1147 int pos = label.indexOf(shortcut);
1149 //label.insert(pos, 1, char_type('&'));
1150 label.replace(pos, 0, "&");
1153 QString const binding = mi.binding();
1154 if (!binding.isEmpty())
1155 label += '\t' + binding;
1160 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1162 LYXERR(Debug::GUI, "populating menu " << fromqstr(menu.name()));
1163 if (menu.size() == 0) {
1164 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu.name()));
1167 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1168 MenuDefinition::const_iterator m = menu.begin();
1169 MenuDefinition::const_iterator end = menu.end();
1170 for (; m != end; ++m) {
1171 if (m->kind() == MenuItem::Separator)
1172 qMenu.addSeparator();
1173 else if (m->kind() == MenuItem::Submenu) {
1174 QMenu * subMenu = qMenu.addMenu(label(*m));
1175 populate(*subMenu, m->submenu());
1177 // we have a MenuItem::Command
1178 qMenu.addAction(new Action(view, QIcon(), label(*m),
1179 m->func(), QString(), &qMenu));
1184 /////////////////////////////////////////////////////////////////////
1185 // Menu implementation
1186 /////////////////////////////////////////////////////////////////////
1188 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1189 : QMenu(gv), d(new Menu::Impl)
1191 d->top_level_menu = top_level? new MenuDefinition : 0;
1195 if (d->top_level_menu)
1196 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1202 delete d->top_level_menu;
1207 void Menu::updateView()
1209 guiApp->menus().updateMenu(this);
1213 /////////////////////////////////////////////////////////////////////
1214 // Menus::Impl definition and implementation
1215 /////////////////////////////////////////////////////////////////////
1217 struct Menus::Impl {
1219 bool hasMenu(QString const &) const;
1221 MenuDefinition & getMenu(QString const &);
1223 MenuDefinition const & getMenu(QString const &) const;
1225 /// Expands some special entries of the menu
1226 /** The entries with the following kind are expanded to a
1227 sequence of Command MenuItems: Lastfiles, Documents,
1228 ViewFormats, ExportFormats, UpdateFormats, Branches
1230 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1231 BufferView const *) const;
1233 /// Initialize specific MACOS X menubar
1234 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1236 /// Mac special menu.
1237 /** This defines a menu whose entries list the FuncRequests
1238 that will be removed by expand() in other menus. This is
1239 used by the Qt/Mac code
1241 MenuDefinition specialmenu_;
1246 MenuDefinition menubar_;
1248 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1250 /// name to menu for \c menu() method.
1255 Here is what the Qt documentation says about how a menubar is chosen:
1257 1) If the window has a QMenuBar then it is used. 2) If the window
1258 is a modal then its menubar is used. If no menubar is specified
1259 then a default menubar is used (as documented below) 3) If the
1260 window has no parent then the default menubar is used (as
1263 The above 3 steps are applied all the way up the parent window
1264 chain until one of the above are satisifed. If all else fails a
1265 default menubar will be created, the default menubar on Qt/Mac is
1266 an empty menubar, however you can create a different default
1267 menubar by creating a parentless QMenuBar, the first one created
1268 will thus be designated the default menubar, and will be used
1269 whenever a default menubar is needed.
1271 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1272 that this menubar will be used also when one of LyX' dialogs has
1275 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1277 /* Since Qt 4.2, the qt/mac menu code has special code for
1278 specifying the role of a menu entry. However, it does not
1279 work very well with our scheme of creating menus on demand,
1280 and therefore we need to put these entries in a special
1281 invisible menu. (JMarc)
1284 /* The entries of our special mac menu. If we add support for
1285 * special entries in Menus, we could imagine something
1287 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1288 * and therefore avoid hardcoding. I am not sure it is worth
1289 * the hassle, though. (JMarc)
1291 struct MacMenuEntry {
1295 QAction::MenuRole role;
1298 MacMenuEntry entries[] = {
1299 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1300 QAction::AboutRole},
1301 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1302 QAction::PreferencesRole},
1303 {LFUN_RECONFIGURE, "", "Reconfigure",
1304 QAction::ApplicationSpecificRole},
1305 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1307 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1309 // the special menu for Menus. Fill it up only once.
1310 if (specialmenu_.size() == 0) {
1311 for (size_t i = 0 ; i < num_entries ; ++i) {
1312 FuncRequest const func(entries[i].action,
1313 from_utf8(entries[i].arg));
1314 specialmenu_.add(MenuItem(MenuItem::Command,
1315 entries[i].label, func));
1319 // add the entries to a QMenu that will eventually be empty
1320 // and therefore invisible.
1321 QMenu * qMenu = qmb->addMenu("special");
1322 MenuDefinition::const_iterator cit = specialmenu_.begin();
1323 MenuDefinition::const_iterator end = specialmenu_.end();
1324 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1325 Action * action = new Action(view, QIcon(), cit->label(),
1326 cit->func(), QString(), qMenu);
1327 action->setMenuRole(entries[i].role);
1328 qMenu->addAction(action);
1333 void Menus::Impl::expand(MenuDefinition const & frommenu,
1334 MenuDefinition & tomenu, BufferView const * bv) const
1336 if (!tomenu.empty())
1339 for (MenuDefinition::const_iterator cit = frommenu.begin();
1340 cit != frommenu.end() ; ++cit) {
1341 Buffer const * buf = bv ? &bv->buffer() : 0;
1342 switch (cit->kind()) {
1343 case MenuItem::Lastfiles:
1344 tomenu.expandLastfiles();
1347 case MenuItem::Documents:
1348 tomenu.expandDocuments();
1351 case MenuItem::Bookmarks:
1352 tomenu.expandBookmarks();
1355 case MenuItem::ImportFormats:
1356 case MenuItem::ViewFormats:
1357 case MenuItem::UpdateFormats:
1358 case MenuItem::ExportFormats:
1359 tomenu.expandFormats(cit->kind(), buf);
1362 case MenuItem::CharStyles:
1363 tomenu.expandFlexInsert(buf, "charstyle");
1366 case MenuItem::Custom:
1367 tomenu.expandFlexInsert(buf, "custom");
1370 case MenuItem::Elements:
1371 tomenu.expandFlexInsert(buf, "element");
1374 case MenuItem::FloatListInsert:
1375 tomenu.expandFloatListInsert(buf);
1378 case MenuItem::FloatInsert:
1379 tomenu.expandFloatInsert(buf);
1382 case MenuItem::PasteRecent:
1383 tomenu.expandPasteRecent();
1386 case MenuItem::Toolbars:
1387 tomenu.expandToolbars();
1390 case MenuItem::Branches:
1391 tomenu.expandBranches(buf);
1394 case MenuItem::CiteStyles:
1395 tomenu.expandCiteStyles(bv);
1399 tomenu.expandToc(buf);
1402 case MenuItem::Submenu: {
1403 MenuItem item(*cit);
1404 item.setSubmenu(MenuDefinition(cit->submenuname()));
1405 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1406 tomenu.addWithStatusCheck(item);
1410 case MenuItem::Separator:
1411 tomenu.addWithStatusCheck(*cit);
1414 case MenuItem::Command:
1415 if (!specialmenu_.hasFunc(cit->func()))
1416 tomenu.addWithStatusCheck(*cit);
1420 // we do not want the menu to end with a separator
1421 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1422 tomenu.items_.pop_back();
1424 // Check whether the shortcuts are unique
1425 tomenu.checkShortcuts();
1429 bool Menus::Impl::hasMenu(QString const & name) const
1431 return find_if(menulist_.begin(), menulist_.end(),
1432 MenuNamesEqual(name)) != menulist_.end();
1436 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1438 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1439 MenuNamesEqual(name));
1440 if (cit == menulist_.end())
1441 lyxerr << "No submenu named " << fromqstr(name) << endl;
1442 LASSERT(cit != menulist_.end(), /**/);
1447 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1449 iterator it = find_if(menulist_.begin(), menulist_.end(),
1450 MenuNamesEqual(name));
1451 if (it == menulist_.end())
1452 lyxerr << "No submenu named " << fromqstr(name) << endl;
1453 LASSERT(it != menulist_.end(), /**/);
1458 /////////////////////////////////////////////////////////////////////
1462 /////////////////////////////////////////////////////////////////////
1464 Menus::Menus() : d(new Impl) {}
1471 void Menus::read(Lexer & lex)
1479 LexerKeyword menutags[] = {
1480 { "end", md_endmenuset },
1481 { "menu", md_menu },
1482 { "menubar", md_menubar }
1485 // consistency check
1486 if (compare_ascii_no_case(lex.getString(), "menuset"))
1487 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1489 lex.pushTable(menutags);
1490 lex.setContext("Menus::read");
1494 while (lex.isOK() && !quit) {
1495 switch (lex.lex()) {
1497 d->menubar_.read(lex);
1501 QString const name = toqstr(lex.getDocString());
1502 if (d->hasMenu(name))
1503 d->getMenu(name).read(lex);
1505 MenuDefinition menu(name);
1507 d->menulist_.push_back(menu);
1515 lex.printError("Unknown menu tag");
1523 bool Menus::searchMenu(FuncRequest const & func,
1524 vector<docstring> & names) const
1526 MenuDefinition menu;
1527 d->expand(d->menubar_, menu, 0);
1528 return menu.searchMenu(func, names);
1532 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1536 // setup special mac specific menu item
1537 d->macxMenuBarInit(view, qmb);
1540 // Clear all menubar contents before filling it.
1544 LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
1546 if (d->menubar_.size() == 0) {
1547 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1548 << fromqstr(d->menubar_.name()));
1551 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1553 MenuDefinition menu;
1554 BufferView * bv = 0;
1557 d->expand(d->menubar_, menu, bv);
1559 MenuDefinition::const_iterator m = menu.begin();
1560 MenuDefinition::const_iterator end = menu.end();
1562 for (; m != end; ++m) {
1564 if (m->kind() != MenuItem::Submenu) {
1565 LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
1569 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
1570 << " is a submenu named " << fromqstr(m->submenuname()));
1572 QString name = m->submenuname();
1573 if (!d->hasMenu(name)) {
1574 LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
1575 << " submenu has no menu!");
1579 Menu * menu = new Menu(view, m->submenuname(), true);
1580 menu->setTitle(label(*m));
1583 d->name_map_[view][name] = menu;
1588 void Menus::updateMenu(Menu * qmenu)
1590 LYXERR(Debug::GUI, "Triggered menu: " << fromqstr(qmenu->d->name));
1593 if (qmenu->d->name.isEmpty())
1596 // Here, We make sure that theLyXFunc points to the correct LyXView.
1597 theLyXFunc().setLyXView(qmenu->d->view);
1599 if (!d->hasMenu(qmenu->d->name)) {
1600 qmenu->addAction(qt_("No action defined!"));
1601 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1602 << fromqstr(qmenu->d->name));
1606 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1607 BufferView * bv = 0;
1609 bv = qmenu->d->view->view();
1610 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1611 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1615 Menu * Menus::menu(QString const & name, GuiView & view)
1617 LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
1618 Menu * menu = d->name_map_[&view].value(name, 0);
1619 if (!menu && !name.startsWith("context-")) {
1620 LYXERR0("requested context menu not found: " << fromqstr(name));
1624 menu = new Menu(&view, name, true);
1625 d->name_map_[&view][name] = menu;
1629 } // namespace frontend
1632 #include "Menus_moc.cpp"