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 "BranchList.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "Converter.h"
31 #include "CutAndPaste.h"
33 #include "FloatList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
39 #include "LyXAction.h"
40 #include "LyX.h" // for lastfiles
42 #include "Paragraph.h"
44 #include "TextClass.h"
45 #include "TocBackend.h"
46 #include "ToolbarBackend.h"
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/filetools.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h"
65 using namespace lyx::support;
73 // MacOSX specific stuff is at the end.
80 /// The type of elements that can be in a menu
88 /** This is the list of last opened file,
89 typically for the File menu. */
91 /** This is the list of opened Documents,
92 typically for the Documents menu. */
94 /** This is the bookmarks */
98 /** This is a list of viewable formats
99 typically for the File->View menu. */
101 /** This is a list of updatable formats
102 typically for the File->Update menu. */
104 /** This is a list of exportable formats
105 typically for the File->Export menu. */
107 /** This is a list of importable formats
108 typically for the File->Export menu. */
110 /** This is the list of elements available
111 * for insertion into document. */
113 /** This is the list of user-configurable
114 insets to insert into document */
116 /** This is the list of XML elements to
117 insert into the document */
119 /** This is the list of floats that we can
120 insert a list for. */
122 /** This is the list of floats that we can
125 /** This is the list of selections that can
130 /** Available branches in document */
134 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
137 QString const & label,
138 QString const & submenu = QString(),
139 bool optional = false)
140 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
142 BOOST_ASSERT(kind == Submenu);
146 QString const & label,
147 FuncRequest const & func,
148 bool optional = false)
149 : kind_(kind), label_(label), func_(func), optional_(optional)
151 func_.origin = FuncRequest::MENU;
154 // boost::shared_ptr<MenuDefinition> needs this apprently...
157 /// The label of a given menuitem
158 QString label() const { return label_.split('|')[0]; }
160 /// The keyboard shortcut (usually underlined in the entry)
161 QString shortcut() const
163 return label_.contains('|') ? label_.split('|')[1] : QString();
165 /// The complete label, with label and shortcut separated by a '|'
166 QString fulllabel() const { return label_;}
167 /// The kind of entry
168 Kind kind() const { return kind_; }
169 /// the action (if relevant)
170 FuncRequest const & func() const { return func_; }
171 /// returns true if the entry should be ommited when disabled
172 bool optional() const { return optional_; }
173 /// returns the status of the lfun associated with this entry
174 FuncStatus const & status() const { return status_; }
175 /// returns the status of the lfun associated with this entry
176 FuncStatus & status() { return status_; }
177 /// returns the status of the lfun associated with this entry
178 void status(FuncStatus const & status) { status_ = status; }
180 ///returns the binding associated to this action.
181 QString binding() const
183 if (kind_ != Command)
185 // Get the keys bound to this action, but keep only the
187 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
189 return toqstr(bindings.begin()->print(KeySequence::ForGui));
191 LYXERR(Debug::KBMAP, "No binding for "
192 << lyxaction.getActionName(func_.action)
193 << '(' << func_.argument() << ')');
197 /// the description of the submenu (if relevant)
198 QString const & submenuname() const { return submenuname_; }
199 /// set the description of the submenu
200 void submenuname(QString const & name) { submenuname_ = name; }
202 bool hasSubmenu() const { return submenu_.isEmpty(); }
204 MenuDefinition const & submenu() const { return submenu_.at(0); }
205 MenuDefinition & submenu() { return submenu_[0]; }
207 void setSubmenu(MenuDefinition const & menu)
210 submenu_.append(menu);
221 QString submenuname_;
226 /// contains 0 or 1 item.
227 QList<MenuDefinition> submenu_;
231 class MenuDefinition {
234 typedef std::vector<MenuItem> ItemList;
236 typedef ItemList::const_iterator const_iterator;
238 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
243 QString const & name() const { return name_; }
245 bool empty() const { return items_.empty(); }
246 /// Clear the menu content.
247 void clear() { items_.clear(); }
249 size_t size() const { return items_.size(); }
251 MenuItem const & operator[](size_t) const;
253 const_iterator begin() const { return items_.begin(); }
255 const_iterator end() const { return items_.end(); }
257 // search for func in this menu iteratively, and put menu
259 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
262 bool hasFunc(FuncRequest const &) const;
263 /// Add the menu item unconditionally
264 void add(MenuItem const & item) { items_.push_back(item); }
265 /// Checks the associated FuncRequest status before adding the
267 void addWithStatusCheck(MenuItem const &);
268 // Check whether the menu shortcuts are unique
269 void checkShortcuts() const;
271 void expandLastfiles();
272 void expandDocuments();
273 void expandBookmarks();
274 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
275 void expandFloatListInsert(Buffer const * buf);
276 void expandFloatInsert(Buffer const * buf);
277 void expandFlexInsert(Buffer const * buf, std::string s);
278 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
279 void expandToc(Buffer const * buf);
280 void expandPasteRecent();
281 void expandToolbars();
282 void expandBranches(Buffer const * buf);
290 /// Helper for std::find_if
294 MenuNamesEqual(QString const & name) : name_(name) {}
295 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
302 typedef std::vector<MenuDefinition> MenuList;
304 typedef MenuList::const_iterator const_iterator;
306 typedef MenuList::iterator iterator;
308 /////////////////////////////////////////////////////////////////////
309 // MenuDefinition implementation
310 /////////////////////////////////////////////////////////////////////
312 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
316 case MenuItem::Command: {
317 FuncStatus status = lyx::getStatus(i.func());
318 if (status.unknown() || (!status.enabled() && i.optional()))
321 items_.back().status(status);
325 case MenuItem::Submenu: {
326 if (i.hasSubmenu()) {
327 bool enabled = false;
328 for (const_iterator cit = i.submenu().begin();
329 cit != i.submenu().end(); ++cit) {
330 if ((cit->kind() == MenuItem::Command
331 || cit->kind() == MenuItem::Submenu)
332 && cit->status().enabled()) {
337 if (enabled || !i.optional()) {
339 items_.back().status().enabled(enabled);
347 case MenuItem::Separator:
348 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
358 void MenuDefinition::read(Lexer & lex)
385 struct LexerKeyword menutags[] = {
386 { "bookmarks", md_bookmarks },
387 { "branches", md_branches },
388 { "charstyles", md_charstyles },
389 { "custom", md_custom },
390 { "documents", md_documents },
391 { "elements", md_elements },
392 { "end", md_endmenu },
393 { "exportformats", md_exportformats },
394 { "floatinsert", md_floatinsert },
395 { "floatlistinsert", md_floatlistinsert },
396 { "importformats", md_importformats },
398 { "lastfiles", md_lastfiles },
399 { "optitem", md_optitem },
400 { "optsubmenu", md_optsubmenu },
401 { "pasterecent", md_pasterecent },
402 { "separator", md_separator },
403 { "submenu", md_submenu },
405 { "toolbars", md_toolbars },
406 { "updateformats", md_updateformats },
407 { "viewformats", md_viewformats }
410 lex.pushTable(menutags);
411 if (lyxerr.debugging(Debug::PARSER))
412 lex.printTable(lyxerr);
415 bool optional = false;
417 while (lex.isOK() && !quit) {
421 // fallback to md_item
424 docstring const name = translateIfPossible(lex.getDocString());
426 string const command = lex.getString();
427 FuncRequest func = lyxaction.lookupFunc(command);
428 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
434 add(MenuItem(MenuItem::Separator));
438 add(MenuItem(MenuItem::Lastfiles));
442 add(MenuItem(MenuItem::CharStyles));
446 add(MenuItem(MenuItem::Custom));
450 add(MenuItem(MenuItem::Elements));
454 add(MenuItem(MenuItem::Documents));
458 add(MenuItem(MenuItem::Bookmarks));
462 add(MenuItem(MenuItem::Toc));
466 add(MenuItem(MenuItem::ViewFormats));
469 case md_updateformats:
470 add(MenuItem(MenuItem::UpdateFormats));
473 case md_exportformats:
474 add(MenuItem(MenuItem::ExportFormats));
477 case md_importformats:
478 add(MenuItem(MenuItem::ImportFormats));
481 case md_floatlistinsert:
482 add(MenuItem(MenuItem::FloatListInsert));
486 add(MenuItem(MenuItem::FloatInsert));
490 add(MenuItem(MenuItem::PasteRecent));
494 add(MenuItem(MenuItem::Toolbars));
498 add(MenuItem(MenuItem::Branches));
503 // fallback to md_submenu
506 docstring const mlabel = translateIfPossible(lex.getDocString());
508 docstring const mname = lex.getDocString();
509 add(MenuItem(MenuItem::Submenu,
510 toqstr(mlabel), toqstr(mname), optional));
520 lex.printError("MenuDefinition::read: "
521 "Unknown menu tag: `$$Token'");
529 MenuItem const & MenuDefinition::operator[](size_type i) const
535 bool MenuDefinition::hasFunc(FuncRequest const & func) const
537 for (const_iterator it = begin(), et = end(); it != et; ++it)
538 if (it->func() == func)
544 void MenuDefinition::checkShortcuts() const
546 // This is a quadratic algorithm, but we do not care because
547 // menus are short enough
548 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
549 QString shortcut = it1->shortcut();
550 if (shortcut.isEmpty())
552 if (!it1->label().contains(shortcut))
553 lyxerr << "Menu warning: menu entry \""
554 << fromqstr(it1->label())
555 << "\" does not contain shortcut `"
556 << fromqstr(shortcut) << "'." << endl;
557 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
558 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
559 lyxerr << "Menu warning: menu entries "
560 << '"' << fromqstr(it1->fulllabel())
561 << "\" and \"" << fromqstr(it2->fulllabel())
562 << "\" share the same shortcut."
570 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
572 const_iterator m = begin();
573 const_iterator m_end = end();
574 for (; m != m_end; ++m) {
575 if (m->kind() == MenuItem::Command && m->func() == func) {
576 names.push_back(qstring_to_ucs4(m->label()));
579 if (m->kind() == MenuItem::Submenu) {
580 names.push_back(qstring_to_ucs4(m->label()));
581 if (!m->hasSubmenu()) {
582 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
583 << fromqstr(m->label())
584 << " name=" << fromqstr(m->submenuname()));
588 if (m->submenu().searchMenu(func, names))
597 bool compareFormat(Format const * p1, Format const * p2)
603 QString limitStringLength(docstring const & str)
605 size_t const max_item_length = 45;
607 if (str.size() > max_item_length)
608 return toqstr(str.substr(0, max_item_length - 3) + "...");
614 void MenuDefinition::expandLastfiles()
616 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
617 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
621 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
622 string const file = lfit->absFilename();
623 QString const label = QString("%1. %2|%3").arg(ii)
624 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
625 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
630 void MenuDefinition::expandDocuments()
632 Buffer * first = theBufferList().first();
637 // We cannot use a for loop as the buffer list cycles.
639 QString label = toqstr(b->fileName().displayName(20));
643 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
644 add(MenuItem(MenuItem::Command, label,
645 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
647 b = theBufferList().next(b);
649 } while (b != first);
651 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
652 FuncRequest(LFUN_NOACTION)));
657 void MenuDefinition::expandBookmarks()
659 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
661 for (size_t i = 1; i <= bm.size(); ++i) {
663 string const file = bm.bookmark(i).filename.absFilename();
664 QString const label = QString("%1. %2|%3").arg(i)
665 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
666 add(MenuItem(MenuItem::Command, label,
667 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
673 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
675 if (!buf && kind != MenuItem::ImportFormats) {
676 add(MenuItem(MenuItem::Command,
677 qt_("No Document Open!"),
678 FuncRequest(LFUN_NOACTION)));
682 typedef vector<Format const *> Formats;
687 case MenuItem::ImportFormats:
688 formats = theConverters().importableFormats();
689 action = LFUN_BUFFER_IMPORT;
691 case MenuItem::ViewFormats:
692 formats = buf->exportableFormats(true);
693 action = LFUN_BUFFER_VIEW;
695 case MenuItem::UpdateFormats:
696 formats = buf->exportableFormats(true);
697 action = LFUN_BUFFER_UPDATE;
700 formats = buf->exportableFormats(false);
701 action = LFUN_BUFFER_EXPORT;
703 sort(formats.begin(), formats.end(), &compareFormat);
705 Formats::const_iterator fit = formats.begin();
706 Formats::const_iterator end = formats.end();
707 for (; fit != end ; ++fit) {
710 QString label = toqstr((*fit)->prettyname());
711 QString const shortcut = toqstr((*fit)->shortcut());
714 case MenuItem::ImportFormats:
715 // FIXME: This is a hack, we should rather solve
716 // FIXME: bug 2488 instead.
717 if ((*fit)->name() == "text")
718 label = qt_("Plain Text");
719 else if ((*fit)->name() == "textparagraph")
720 label = qt_("Plain Text, Join Lines");
723 case MenuItem::ViewFormats:
724 case MenuItem::ExportFormats:
725 case MenuItem::UpdateFormats:
726 if (!(*fit)->documentFormat())
733 // FIXME: if we had proper support for translating the
734 // format names defined in configure.py, there would
735 // not be a need to check whether the shortcut is
736 // correct. If we add it uncondiitonally, it would
737 // create useless warnings on bad shortcuts
738 if (!shortcut.isEmpty() && label.contains(shortcut))
739 label += '|' + shortcut;
742 addWithStatusCheck(MenuItem(MenuItem::Command, label,
743 FuncRequest(action, (*fit)->name())));
745 add(MenuItem(MenuItem::Command, label,
746 FuncRequest(action, (*fit)->name())));
751 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
754 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
755 FuncRequest(LFUN_NOACTION)));
759 FloatList const & floats = buf->params().documentClass().floats();
760 FloatList::const_iterator cit = floats.begin();
761 FloatList::const_iterator end = floats.end();
762 for (; cit != end; ++cit) {
763 addWithStatusCheck(MenuItem(MenuItem::Command,
764 qt_(cit->second.listName()),
765 FuncRequest(LFUN_FLOAT_LIST,
766 cit->second.type())));
771 void MenuDefinition::expandFloatInsert(Buffer const * buf)
774 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
775 FuncRequest(LFUN_NOACTION)));
779 FloatList const & floats = buf->params().documentClass().floats();
780 FloatList::const_iterator cit = floats.begin();
781 FloatList::const_iterator end = floats.end();
782 for (; cit != end; ++cit) {
784 QString const label = qt_(cit->second.name());
785 addWithStatusCheck(MenuItem(MenuItem::Command, label,
786 FuncRequest(LFUN_FLOAT_INSERT,
787 cit->second.type())));
792 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
795 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
796 FuncRequest(LFUN_NOACTION)));
799 TextClass::InsetLayouts const & insetLayouts =
800 buf->params().documentClass().insetLayouts();
801 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
802 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
803 for (; cit != end; ++cit) {
804 docstring const label = cit->first;
805 if (cit->second.lyxtype() == s)
806 addWithStatusCheck(MenuItem(MenuItem::Command,
807 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
813 size_t const max_number_of_items = 25;
815 void MenuDefinition::expandToc2(Toc const & toc_list,
816 size_t from, size_t to, int depth)
818 int shortcut_count = 0;
820 // check whether depth is smaller than the smallest depth in toc.
821 int min_depth = 1000;
822 for (size_t i = from; i < to; ++i)
823 min_depth = min(min_depth, toc_list[i].depth());
824 if (min_depth > depth)
827 if (to - from <= max_number_of_items) {
828 for (size_t i = from; i < to; ++i) {
829 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
830 label += limitStringLength(toc_list[i].str());
831 if (toc_list[i].depth() == depth
832 && shortcut_count < 9) {
833 if (label.contains(QString::number(shortcut_count + 1)))
834 label += '|' + QString::number(++shortcut_count);
836 add(MenuItem(MenuItem::Command, label,
837 FuncRequest(toc_list[i].action())));
842 size_t new_pos = pos + 1;
843 while (new_pos < to && toc_list[new_pos].depth() > depth)
846 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
847 label += limitStringLength(toc_list[pos].str());
848 if (toc_list[pos].depth() == depth &&
849 shortcut_count < 9) {
850 if (label.contains(QString::number(shortcut_count + 1)))
851 label += '|' + QString::number(++shortcut_count);
853 if (new_pos == pos + 1) {
854 add(MenuItem(MenuItem::Command,
855 label, FuncRequest(toc_list[pos].action())));
858 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
859 MenuItem item(MenuItem::Submenu, label);
860 item.setSubmenu(sub);
869 void MenuDefinition::expandToc(Buffer const * buf)
871 // To make things very cleanly, we would have to pass buf to
872 // all MenuItem constructors and to expandToc2. However, we
873 // know that all the entries in a TOC will be have status_ ==
874 // OK, so we avoid this unnecessary overhead (JMarc)
877 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
878 FuncRequest(LFUN_NOACTION)));
882 Buffer* cbuf = const_cast<Buffer*>(buf);
883 cbuf->tocBackend().update();
884 cbuf->structureChanged();
886 // Add an entry for the master doc if this is a child doc
887 Buffer const * const master = buf->masterBuffer();
889 ParIterator const pit = par_iterator_begin(master->inset());
890 string const arg = convert<string>(pit->id());
891 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
892 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
895 MenuDefinition other_lists;
897 FloatList const & floatlist = buf->params().documentClass().floats();
898 TocList const & toc_list = buf->tocBackend().tocs();
899 TocList::const_iterator cit = toc_list.begin();
900 TocList::const_iterator end = toc_list.end();
901 for (; cit != end; ++cit) {
903 if (cit->first == "tableofcontents")
906 string const & floatName = floatlist.getType(cit->first).listName();
908 bool in_other_list = true;
909 if (!floatName.empty()) {
910 label = qt_(floatName);
911 in_other_list = false;
913 else if (cit->first == "child") {
914 label = qt_("Child Documents");
915 in_other_list = false;
916 } else if (cit->first == "embedded")
917 label = qt_("Embedded Files");
918 else if (cit->first == "graphics")
919 label = qt_("List of Graphics");
920 else if (cit->first == "equation")
921 label = qt_("List of Equations");
922 else if (cit->first == "index")
923 label = qt_("List of Indexes");
924 else if (cit->first == "listing") {
925 // FIXME: the listing navigate menu causes a crash for unknown
926 // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
927 // This is a temporary fix:
928 //label = qt_("List of Listings");
931 else if (cit->first == "marginalnote")
932 label = qt_("List of Marginal notes");
933 else if (cit->first == "note")
934 label = qt_("List of Notes");
935 else if (cit->first == "footnote")
936 label = qt_("List of Foot notes");
937 else if (cit->first == "label")
938 label = qt_("Labels and References");
939 else if (cit->first == "citation")
940 label = qt_("List of Citations");
942 // This should not happen unless the entry is missing above.
943 label = qt_("Other floats: ") + toqstr(cit->first);
945 MenuDefinition submenu;
947 if (cit->second.size() >= 30) {
948 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
949 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
951 TocIterator ccit = cit->second.begin();
952 TocIterator eend = cit->second.end();
953 for (; ccit != eend; ++ccit) {
954 QString const label = limitStringLength(ccit->str());
955 submenu.add(MenuItem(MenuItem::Command, label,
956 FuncRequest(ccit->action())));
960 MenuItem item(MenuItem::Submenu, label);
961 item.setSubmenu(submenu);
963 other_lists.add(item);
965 item.setSubmenu(submenu);
969 if (!other_lists.empty()) {
970 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
971 item.setSubmenu(other_lists);
977 cit = toc_list.find("tableofcontents");
979 addWithStatusCheck(MenuItem(MenuItem::Command,
980 qt_("No Table of contents"),
983 expandToc2(cit->second, 0, cit->second.size(), 0);
988 void MenuDefinition::expandPasteRecent()
990 vector<docstring> const sel = cap::availableSelections();
992 vector<docstring>::const_iterator cit = sel.begin();
993 vector<docstring>::const_iterator end = sel.end();
995 for (unsigned int index = 0; cit != end; ++cit, ++index) {
996 add(MenuItem(MenuItem::Command, toqstr(*cit),
997 FuncRequest(LFUN_PASTE, convert<string>(index))));
1002 void MenuDefinition::expandToolbars()
1005 // extracts the toolbars from the backend
1006 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1007 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1009 for (; cit != end; ++cit) {
1010 QString label = qt_(cit->gui_name);
1011 // frontends are not supposed to turn on/off toolbars,
1012 // if they cannot update ToolbarBackend::flags. That
1013 // is to say, ToolbarsBackend::flags should reflect
1014 // the true state of toolbars.
1016 // menu is displayed as
1020 // in the case of auto.
1021 if (cit->flags & ToolbarInfo::AUTO)
1022 label += qt_(" (auto)");
1023 add(MenuItem(MenuItem::Command, label,
1024 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1029 void MenuDefinition::expandBranches(Buffer const * buf)
1032 add(MenuItem(MenuItem::Command,
1033 qt_("No Document Open!"),
1034 FuncRequest(LFUN_NOACTION)));
1038 BufferParams const & params = buf->masterBuffer()->params();
1039 if (params.branchlist().empty()) {
1040 add(MenuItem(MenuItem::Command,
1041 qt_("No Branch in Document!"),
1042 FuncRequest(LFUN_NOACTION)));
1046 BranchList::const_iterator cit = params.branchlist().begin();
1047 BranchList::const_iterator end = params.branchlist().end();
1049 for (int ii = 1; cit != end; ++cit, ++ii) {
1050 docstring label = cit->getBranch();
1052 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1053 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1054 FuncRequest(LFUN_BRANCH_INSERT,
1055 cit->getBranch())));
1062 /////////////////////////////////////////////////////////////////////
1063 // Menu::Impl definition and implementation
1064 /////////////////////////////////////////////////////////////////////
1068 /// populates the menu or one of its submenu
1069 /// This is used as a recursive function
1070 void populate(QMenu & qMenu, MenuDefinition const & menu);
1072 /// Only needed for top level menus.
1073 MenuDefinition * top_level_menu;
1076 /// the name of this menu
1082 /// Get a MenuDefinition item label from the menu backend
1083 static QString label(MenuItem const & mi)
1085 QString label = mi.label();
1086 label.replace("&", "&&");
1088 QString shortcut = mi.shortcut();
1089 if (!shortcut.isEmpty()) {
1090 int pos = label.indexOf(shortcut);
1092 //label.insert(pos, 1, char_type('&'));
1093 label.replace(pos, 0, "&");
1096 QString const binding = mi.binding();
1097 if (!binding.isEmpty())
1098 label += '\t' + binding;
1103 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1105 LYXERR(Debug::GUI, "populating menu " << fromqstr(menu.name()));
1106 if (menu.size() == 0) {
1107 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu.name()));
1110 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1111 MenuDefinition::const_iterator m = menu.begin();
1112 MenuDefinition::const_iterator end = menu.end();
1113 for (; m != end; ++m) {
1114 if (m->kind() == MenuItem::Separator)
1115 qMenu.addSeparator();
1116 else if (m->kind() == MenuItem::Submenu) {
1117 QMenu * subMenu = qMenu.addMenu(label(*m));
1118 populate(*subMenu, m->submenu());
1120 // we have a MenuItem::Command
1121 qMenu.addAction(new Action(view, QIcon(), label(*m),
1122 m->func(), QString(), &qMenu));
1127 /////////////////////////////////////////////////////////////////////
1128 // Menu implementation
1129 /////////////////////////////////////////////////////////////////////
1131 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1134 d->top_level_menu = top_level? new MenuDefinition : 0;
1138 if (d->top_level_menu)
1139 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1145 delete d->top_level_menu;
1150 void Menu::updateView()
1152 guiApp->menus().updateMenu(this);
1156 /////////////////////////////////////////////////////////////////////
1157 // Menus::Impl definition and implementation
1158 /////////////////////////////////////////////////////////////////////
1160 struct Menus::Impl {
1162 bool hasMenu(QString const &) const;
1164 MenuDefinition & getMenu(QString const &);
1166 MenuDefinition const & getMenu(QString const &) const;
1168 /// Expands some special entries of the menu
1169 /** The entries with the following kind are expanded to a
1170 sequence of Command MenuItems: Lastfiles, Documents,
1171 ViewFormats, ExportFormats, UpdateFormats, Branches
1173 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1174 Buffer const *) const;
1176 /// Initialize specific MACOS X menubar
1177 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1179 /// Mac special menu.
1180 /** This defines a menu whose entries list the FuncRequests
1181 that will be removed by expand() in other menus. This is
1182 used by the Qt/Mac code
1184 MenuDefinition specialmenu_;
1189 MenuDefinition menubar_;
1191 typedef QMap<GuiView *, QHash<QString, Menu *> > NameMap;
1193 /// name to menu for \c menu() method.
1198 Here is what the Qt documentation says about how a menubar is chosen:
1200 1) If the window has a QMenuBar then it is used. 2) If the window
1201 is a modal then its menubar is used. If no menubar is specified
1202 then a default menubar is used (as documented below) 3) If the
1203 window has no parent then the default menubar is used (as
1206 The above 3 steps are applied all the way up the parent window
1207 chain until one of the above are satisifed. If all else fails a
1208 default menubar will be created, the default menubar on Qt/Mac is
1209 an empty menubar, however you can create a different default
1210 menubar by creating a parentless QMenuBar, the first one created
1211 will thus be designated the default menubar, and will be used
1212 whenever a default menubar is needed.
1214 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1215 that this menubar will be used also when one of LyX' dialogs has
1218 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1220 /* Since Qt 4.2, the qt/mac menu code has special code for
1221 specifying the role of a menu entry. However, it does not
1222 work very well with our scheme of creating menus on demand,
1223 and therefore we need to put these entries in a special
1224 invisible menu. (JMarc)
1227 /* The entries of our special mac menu. If we add support for
1228 * special entries in Menus, we could imagine something
1230 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1231 * and therefore avoid hardcoding. I am not sure it is worth
1232 * the hassle, though. (JMarc)
1234 struct MacMenuEntry {
1238 QAction::MenuRole role;
1241 MacMenuEntry entries[] = {
1242 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1243 QAction::AboutRole},
1244 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1245 QAction::PreferencesRole},
1246 {LFUN_RECONFIGURE, "", "Reconfigure",
1247 QAction::ApplicationSpecificRole},
1248 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1250 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1252 // the special menu for Menus. Fill it up only once.
1253 if (specialmenu_.size() == 0) {
1254 for (size_t i = 0 ; i < num_entries ; ++i) {
1255 FuncRequest const func(entries[i].action,
1256 from_utf8(entries[i].arg));
1257 specialmenu_.add(MenuItem(MenuItem::Command,
1258 entries[i].label, func));
1262 // add the entries to a QMenu that will eventually be empty
1263 // and therefore invisible.
1264 QMenu * qMenu = qmb->addMenu("special");
1265 MenuDefinition::const_iterator cit = specialmenu_.begin();
1266 MenuDefinition::const_iterator end = specialmenu_.end();
1267 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1268 Action * action = new Action(view, QIcon(), cit->label(),
1269 cit->func(), QString(), qMenu);
1270 action->setMenuRole(entries[i].role);
1271 qMenu->addAction(action);
1276 void Menus::Impl::expand(MenuDefinition const & frommenu,
1277 MenuDefinition & tomenu, Buffer const * buf) const
1279 if (!tomenu.empty())
1282 for (MenuDefinition::const_iterator cit = frommenu.begin();
1283 cit != frommenu.end() ; ++cit) {
1284 switch (cit->kind()) {
1285 case MenuItem::Lastfiles:
1286 tomenu.expandLastfiles();
1289 case MenuItem::Documents:
1290 tomenu.expandDocuments();
1293 case MenuItem::Bookmarks:
1294 tomenu.expandBookmarks();
1297 case MenuItem::ImportFormats:
1298 case MenuItem::ViewFormats:
1299 case MenuItem::UpdateFormats:
1300 case MenuItem::ExportFormats:
1301 tomenu.expandFormats(cit->kind(), buf);
1304 case MenuItem::CharStyles:
1305 tomenu.expandFlexInsert(buf, "charstyle");
1308 case MenuItem::Custom:
1309 tomenu.expandFlexInsert(buf, "custom");
1312 case MenuItem::Elements:
1313 tomenu.expandFlexInsert(buf, "element");
1316 case MenuItem::FloatListInsert:
1317 tomenu.expandFloatListInsert(buf);
1320 case MenuItem::FloatInsert:
1321 tomenu.expandFloatInsert(buf);
1324 case MenuItem::PasteRecent:
1325 tomenu.expandPasteRecent();
1328 case MenuItem::Toolbars:
1329 tomenu.expandToolbars();
1332 case MenuItem::Branches:
1333 tomenu.expandBranches(buf);
1337 tomenu.expandToc(buf);
1340 case MenuItem::Submenu: {
1341 MenuItem item(*cit);
1342 item.setSubmenu(MenuDefinition(cit->submenuname()));
1343 expand(getMenu(cit->submenuname()), item.submenu(), buf);
1344 tomenu.addWithStatusCheck(item);
1348 case MenuItem::Separator:
1349 tomenu.addWithStatusCheck(*cit);
1352 case MenuItem::Command:
1353 if (!specialmenu_.hasFunc(cit->func()))
1354 tomenu.addWithStatusCheck(*cit);
1358 // we do not want the menu to end with a separator
1359 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1360 tomenu.items_.pop_back();
1362 // Check whether the shortcuts are unique
1363 tomenu.checkShortcuts();
1367 bool Menus::Impl::hasMenu(QString const & name) const
1369 return find_if(menulist_.begin(), menulist_.end(),
1370 MenuNamesEqual(name)) != menulist_.end();
1374 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1376 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1377 MenuNamesEqual(name));
1378 if (cit == menulist_.end())
1379 lyxerr << "No submenu named " << fromqstr(name) << endl;
1380 BOOST_ASSERT(cit != menulist_.end());
1385 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1387 iterator it = find_if(menulist_.begin(), menulist_.end(),
1388 MenuNamesEqual(name));
1389 if (it == menulist_.end())
1390 lyxerr << "No submenu named " << fromqstr(name) << endl;
1391 BOOST_ASSERT(it != menulist_.end());
1396 /////////////////////////////////////////////////////////////////////
1400 /////////////////////////////////////////////////////////////////////
1402 Menus::Menus() : d(new Impl) {}
1405 void Menus::read(Lexer & lex)
1413 struct LexerKeyword menutags[] = {
1414 { "end", md_endmenuset },
1415 { "menu", md_menu },
1416 { "menubar", md_menubar }
1420 if (compare_ascii_no_case(lex.getString(), "menuset")) {
1421 lyxerr << "Menubackend::read: ERROR wrong token:`"
1422 << lex.getString() << '\'' << endl;
1425 lex.pushTable(menutags);
1426 if (lyxerr.debugging(Debug::PARSER))
1427 lex.printTable(lyxerr);
1431 while (lex.isOK() && !quit) {
1432 switch (lex.lex()) {
1434 d->menubar_.read(lex);
1438 QString const name = toqstr(lex.getDocString());
1439 if (d->hasMenu(name))
1440 d->getMenu(name).read(lex);
1442 MenuDefinition menu(name);
1444 d->menulist_.push_back(menu);
1452 lex.printError("menubackend::read: "
1453 "Unknown menu tag: `$$Token'");
1461 bool Menus::searchMenu(FuncRequest const & func,
1462 vector<docstring> & names) const
1464 MenuDefinition menu;
1465 d->expand(d->menubar_, menu, 0);
1466 return menu.searchMenu(func, names);
1470 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1474 // setup special mac specific menu item
1475 d->macxMenuBarInit(view, qmb);
1478 // Clear all menubar contents before filling it.
1482 LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
1484 if (d->menubar_.size() == 0) {
1485 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1486 << fromqstr(d->menubar_.name()));
1490 LYXERR(Debug::GUI, "menu bar entries "
1491 << d->menubar_.size());
1494 MenuDefinition menu;
1497 buf = view->buffer();
1498 d->expand(d->menubar_, menu, buf);
1500 MenuDefinition::const_iterator m = menu.begin();
1501 MenuDefinition::const_iterator end = menu.end();
1503 for (; m != end; ++m) {
1505 if (m->kind() != MenuItem::Submenu) {
1506 LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
1510 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
1511 << " is a submenu named " << fromqstr(m->submenuname()));
1513 QString name = m->submenuname();
1514 if (!d->hasMenu(name)) {
1515 LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
1516 << " submenu has no menu!");
1520 Menu * menu = new Menu(view, m->submenuname(), true);
1521 menu->setTitle(label(*m));
1524 d->name_map_[view][name] = menu;
1529 void Menus::updateMenu(Menu * qmenu)
1531 LYXERR(Debug::GUI, "Triggered menu: " << fromqstr(qmenu->d->name));
1534 if (qmenu->d->name.isEmpty())
1537 // Here, We make sure that theLyXFunc points to the correct LyXView.
1538 theLyXFunc().setLyXView(qmenu->d->view);
1540 if (!d->hasMenu(qmenu->d->name)) {
1541 qmenu->addAction(qt_("No action defined!"));
1542 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1543 << fromqstr(qmenu->d->name));
1547 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1550 buf = qmenu->d->view->buffer();
1551 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, buf);
1552 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1556 Menu * Menus::menu(QString const & name, GuiView & view)
1558 LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
1559 Menu * menu = d->name_map_[&view].value(name, 0);
1560 if (!menu && !name.startsWith("context-")) {
1561 LYXERR0("requested context menu not found: " << fromqstr(name));
1565 menu = new Menu(&view, name, true);
1566 d->name_map_[&view][name] = menu;
1570 } // namespace frontend
1573 #include "Menus_moc.cpp"