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"
59 #include <boost/shared_ptr.hpp>
66 using namespace lyx::support;
74 // MacOSX specific stuff is at the end.
81 /// The type of elements that can be in a menu
89 /** This is the list of last opened file,
90 typically for the File menu. */
92 /** This is the list of opened Documents,
93 typically for the Documents menu. */
95 /** This is the bookmarks */
99 /** This is a list of viewable formats
100 typically for the File->View menu. */
102 /** This is a list of updatable formats
103 typically for the File->Update menu. */
105 /** This is a list of exportable formats
106 typically for the File->Export menu. */
108 /** This is a list of importable formats
109 typically for the File->Export menu. */
111 /** This is the list of elements available
112 * for insertion into document. */
114 /** This is the list of user-configurable
115 insets to insert into document */
117 /** This is the list of XML elements to
118 insert into the document */
120 /** This is the list of floats that we can
121 insert a list for. */
123 /** This is the list of floats that we can
126 /** This is the list of selections that can
131 /** Available branches in document */
135 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
138 QString const & label,
139 QString const & submenu = QString(),
140 bool optional = false)
141 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
143 BOOST_ASSERT(kind == Submenu);
147 QString const & label,
148 FuncRequest const & func,
149 bool optional = false)
150 : kind_(kind), label_(label), func_(func), optional_(optional)
152 func_.origin = FuncRequest::MENU;
155 // boost::shared_ptr<MenuDefinition> needs this apprently...
158 /// The label of a given menuitem
159 QString label() const { return label_.split('|')[0]; }
161 /// The keyboard shortcut (usually underlined in the entry)
162 QString shortcut() const
164 return label_.contains('|') ? label_.split('|')[1] : QString();
166 /// The complete label, with label and shortcut separated by a '|'
167 QString fulllabel() const { return label_;}
168 /// The kind of entry
169 Kind kind() const { return kind_; }
170 /// the action (if relevant)
171 FuncRequest const & func() const { return func_; }
172 /// returns true if the entry should be ommited when disabled
173 bool optional() const { return optional_; }
174 /// returns the status of the lfun associated with this entry
175 FuncStatus const & status() const { return status_; }
176 /// returns the status of the lfun associated with this entry
177 FuncStatus & status() { return status_; }
178 /// returns the status of the lfun associated with this entry
179 void status(FuncStatus const & status) { status_ = status; }
181 ///returns the binding associated to this action.
182 QString binding() const
184 if (kind_ != Command)
186 // Get the keys bound to this action, but keep only the
188 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
190 return toqstr(bindings.begin()->print(KeySequence::ForGui));
192 LYXERR(Debug::KBMAP, "No binding for "
193 << lyxaction.getActionName(func_.action)
194 << '(' << func_.argument() << ')');
198 /// the description of the submenu (if relevant)
199 QString const & submenuname() const { return submenuname_; }
200 /// set the description of the submenu
201 void submenuname(QString const & name) { submenuname_ = name; }
203 MenuDefinition * submenu() const { return submenu_.get(); }
205 void setSubmenu(MenuDefinition * menu) { submenu_.reset(menu); }
215 QString submenuname_;
221 boost::shared_ptr<MenuDefinition> submenu_;
225 class MenuDefinition {
228 typedef std::vector<MenuItem> ItemList;
230 typedef ItemList::const_iterator const_iterator;
232 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
237 QString const & name() const { return name_; }
239 bool empty() const { return items_.empty(); }
240 /// Clear the menu content.
241 void clear() { items_.clear(); }
243 size_t size() const { return items_.size(); }
245 MenuItem const & operator[](size_t) const;
247 const_iterator begin() const { return items_.begin(); }
249 const_iterator end() const { return items_.end(); }
251 // search for func in this menu iteratively, and put menu
253 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
256 bool hasFunc(FuncRequest const &) const;
257 /// Add the menu item unconditionally
258 void add(MenuItem const & item) { items_.push_back(item); }
259 /// Checks the associated FuncRequest status before adding the
261 void addWithStatusCheck(MenuItem const &);
262 // Check whether the menu shortcuts are unique
263 void checkShortcuts() const;
265 void expandLastfiles();
266 void expandDocuments();
267 void expandBookmarks();
268 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
269 void expandFloatListInsert(Buffer const * buf);
270 void expandFloatInsert(Buffer const * buf);
271 void expandFlexInsert(Buffer const * buf, std::string s);
272 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
273 void expandToc(Buffer const * buf);
274 void expandPasteRecent();
275 void expandToolbars();
276 void expandBranches(Buffer const * buf);
284 /// Helper for std::find_if
288 MenuNamesEqual(QString const & name) : name_(name) {}
289 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
296 typedef std::vector<MenuDefinition> MenuList;
298 typedef MenuList::const_iterator const_iterator;
300 typedef MenuList::iterator iterator;
302 /////////////////////////////////////////////////////////////////////
303 // MenuDefinition implementation
304 /////////////////////////////////////////////////////////////////////
306 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
310 case MenuItem::Command: {
311 FuncStatus status = lyx::getStatus(i.func());
312 if (status.unknown() || (!status.enabled() && i.optional()))
315 items_.back().status(status);
319 case MenuItem::Submenu: {
321 bool enabled = false;
322 for (const_iterator cit = i.submenu()->begin();
323 cit != i.submenu()->end(); ++cit) {
324 if ((cit->kind() == MenuItem::Command
325 || cit->kind() == MenuItem::Submenu)
326 && cit->status().enabled()) {
331 if (enabled || !i.optional()) {
333 items_.back().status().enabled(enabled);
341 case MenuItem::Separator:
342 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
352 void MenuDefinition::read(Lexer & lex)
380 struct keyword_item menutags[md_last - 1] = {
381 { "bookmarks", md_bookmarks },
382 { "branches", md_branches },
383 { "charstyles", md_charstyles },
384 { "custom", md_custom },
385 { "documents", md_documents },
386 { "elements", md_elements },
387 { "end", md_endmenu },
388 { "exportformats", md_exportformats },
389 { "floatinsert", md_floatinsert },
390 { "floatlistinsert", md_floatlistinsert },
391 { "importformats", md_importformats },
393 { "lastfiles", md_lastfiles },
394 { "optitem", md_optitem },
395 { "optsubmenu", md_optsubmenu },
396 { "pasterecent", md_pasterecent },
397 { "separator", md_separator },
398 { "submenu", md_submenu },
400 { "toolbars", md_toolbars },
401 { "updateformats", md_updateformats },
402 { "viewformats", md_viewformats }
405 lex.pushTable(menutags, md_last - 1);
406 if (lyxerr.debugging(Debug::PARSER))
407 lex.printTable(lyxerr);
410 bool optional = false;
412 while (lex.isOK() && !quit) {
416 // fallback to md_item
419 docstring const name = translateIfPossible(lex.getDocString());
421 string const command = lex.getString();
422 FuncRequest func = lyxaction.lookupFunc(command);
423 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
429 add(MenuItem(MenuItem::Separator));
433 add(MenuItem(MenuItem::Lastfiles));
437 add(MenuItem(MenuItem::CharStyles));
441 add(MenuItem(MenuItem::Custom));
445 add(MenuItem(MenuItem::Elements));
449 add(MenuItem(MenuItem::Documents));
453 add(MenuItem(MenuItem::Bookmarks));
457 add(MenuItem(MenuItem::Toc));
461 add(MenuItem(MenuItem::ViewFormats));
464 case md_updateformats:
465 add(MenuItem(MenuItem::UpdateFormats));
468 case md_exportformats:
469 add(MenuItem(MenuItem::ExportFormats));
472 case md_importformats:
473 add(MenuItem(MenuItem::ImportFormats));
476 case md_floatlistinsert:
477 add(MenuItem(MenuItem::FloatListInsert));
481 add(MenuItem(MenuItem::FloatInsert));
485 add(MenuItem(MenuItem::PasteRecent));
489 add(MenuItem(MenuItem::Toolbars));
493 add(MenuItem(MenuItem::Branches));
498 // fallback to md_submenu
501 docstring const mlabel = translateIfPossible(lex.getDocString());
503 docstring const mname = lex.getDocString();
504 add(MenuItem(MenuItem::Submenu,
505 toqstr(mlabel), toqstr(mname), optional));
515 lex.printError("MenuDefinition::read: "
516 "Unknown menu tag: `$$Token'");
524 MenuItem const & MenuDefinition::operator[](size_type i) const
530 bool MenuDefinition::hasFunc(FuncRequest const & func) const
532 for (const_iterator it = begin(), et = end(); it != et; ++it)
533 if (it->func() == func)
539 void MenuDefinition::checkShortcuts() const
541 // This is a quadratic algorithm, but we do not care because
542 // menus are short enough
543 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
544 QString shortcut = it1->shortcut();
545 if (shortcut.isEmpty())
547 if (!it1->label().contains(shortcut))
548 lyxerr << "Menu warning: menu entry \""
549 << fromqstr(it1->label())
550 << "\" does not contain shortcut `"
551 << fromqstr(shortcut) << "'." << endl;
552 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
553 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
554 lyxerr << "Menu warning: menu entries "
555 << '"' << fromqstr(it1->fulllabel())
556 << "\" and \"" << fromqstr(it2->fulllabel())
557 << "\" share the same shortcut."
565 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
567 const_iterator m = begin();
568 const_iterator m_end = end();
569 for (; m != m_end; ++m) {
570 if (m->kind() == MenuItem::Command && m->func() == func) {
571 names.push_back(qstring_to_ucs4(m->label()));
574 if (m->kind() == MenuItem::Submenu) {
575 names.push_back(qstring_to_ucs4(m->label()));
576 MenuDefinition const & submenu = *m->submenu();
577 if (submenu.searchMenu(func, names))
586 bool compareFormat(Format const * p1, Format const * p2)
592 QString limitStringLength(docstring const & str)
594 size_t const max_item_length = 45;
596 if (str.size() > max_item_length)
597 return toqstr(str.substr(0, max_item_length - 3) + "...");
603 void MenuDefinition::expandLastfiles()
605 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
606 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
610 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
611 string const file = lfit->absFilename();
612 QString const label = QString("%1. %2|%3").arg(ii)
613 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
614 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
619 void MenuDefinition::expandDocuments()
621 Buffer * first = theBufferList().first();
626 // We cannot use a for loop as the buffer list cycles.
628 QString label = toqstr(b->fileName().displayName(20));
632 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
633 add(MenuItem(MenuItem::Command, label,
634 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
636 b = theBufferList().next(b);
638 } while (b != first);
640 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
641 FuncRequest(LFUN_NOACTION)));
646 void MenuDefinition::expandBookmarks()
648 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
650 for (size_t i = 1; i <= bm.size(); ++i) {
652 string const file = bm.bookmark(i).filename.absFilename();
653 QString const label = QString("%1. %2|%3").arg(i)
654 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
655 add(MenuItem(MenuItem::Command, label,
656 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
662 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
664 if (!buf && kind != MenuItem::ImportFormats) {
665 add(MenuItem(MenuItem::Command,
666 qt_("No Document Open!"),
667 FuncRequest(LFUN_NOACTION)));
671 typedef vector<Format const *> Formats;
676 case MenuItem::ImportFormats:
677 formats = theConverters().importableFormats();
678 action = LFUN_BUFFER_IMPORT;
680 case MenuItem::ViewFormats:
681 formats = buf->exportableFormats(true);
682 action = LFUN_BUFFER_VIEW;
684 case MenuItem::UpdateFormats:
685 formats = buf->exportableFormats(true);
686 action = LFUN_BUFFER_UPDATE;
689 formats = buf->exportableFormats(false);
690 action = LFUN_BUFFER_EXPORT;
692 sort(formats.begin(), formats.end(), &compareFormat);
694 Formats::const_iterator fit = formats.begin();
695 Formats::const_iterator end = formats.end();
696 for (; fit != end ; ++fit) {
699 QString label = toqstr((*fit)->prettyname());
700 QString const shortcut = toqstr((*fit)->shortcut());
703 case MenuItem::ImportFormats:
704 // FIXME: This is a hack, we should rather solve
705 // FIXME: bug 2488 instead.
706 if ((*fit)->name() == "text")
707 label = qt_("Plain Text");
708 else if ((*fit)->name() == "textparagraph")
709 label = qt_("Plain Text, Join Lines");
712 case MenuItem::ViewFormats:
713 case MenuItem::ExportFormats:
714 case MenuItem::UpdateFormats:
715 if (!(*fit)->documentFormat())
722 // FIXME: if we had proper support for translating the
723 // format names defined in configure.py, there would
724 // not be a need to check whether the shortcut is
725 // correct. If we add it uncondiitonally, it would
726 // create useless warnings on bad shortcuts
727 if (!shortcut.isEmpty() && label.contains(shortcut))
728 label += '|' + shortcut;
731 addWithStatusCheck(MenuItem(MenuItem::Command, label,
732 FuncRequest(action, (*fit)->name())));
734 add(MenuItem(MenuItem::Command, label,
735 FuncRequest(action, (*fit)->name())));
740 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
743 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
744 FuncRequest(LFUN_NOACTION)));
748 FloatList const & floats = buf->params().documentClass().floats();
749 FloatList::const_iterator cit = floats.begin();
750 FloatList::const_iterator end = floats.end();
751 for (; cit != end; ++cit) {
752 addWithStatusCheck(MenuItem(MenuItem::Command,
753 qt_(cit->second.listName()),
754 FuncRequest(LFUN_FLOAT_LIST,
755 cit->second.type())));
760 void MenuDefinition::expandFloatInsert(Buffer const * buf)
763 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
764 FuncRequest(LFUN_NOACTION)));
768 FloatList const & floats = buf->params().documentClass().floats();
769 FloatList::const_iterator cit = floats.begin();
770 FloatList::const_iterator end = floats.end();
771 for (; cit != end; ++cit) {
773 QString const label = qt_(cit->second.name());
774 addWithStatusCheck(MenuItem(MenuItem::Command, label,
775 FuncRequest(LFUN_FLOAT_INSERT,
776 cit->second.type())));
781 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
784 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
785 FuncRequest(LFUN_NOACTION)));
788 TextClass::InsetLayouts const & insetLayouts =
789 buf->params().documentClass().insetLayouts();
790 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
791 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
792 for (; cit != end; ++cit) {
793 docstring const label = cit->first;
794 if (cit->second.lyxtype() == s)
795 addWithStatusCheck(MenuItem(MenuItem::Command,
796 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
802 size_t const max_number_of_items = 25;
804 void MenuDefinition::expandToc2(Toc const & toc_list,
805 size_t from, size_t to, int depth)
807 int shortcut_count = 0;
809 // check whether depth is smaller than the smallest depth in toc.
810 int min_depth = 1000;
811 for (size_t i = from; i < to; ++i)
812 min_depth = min(min_depth, toc_list[i].depth());
813 if (min_depth > depth)
816 if (to - from <= max_number_of_items) {
817 for (size_t i = from; i < to; ++i) {
818 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
819 label += limitStringLength(toc_list[i].str());
820 if (toc_list[i].depth() == depth
821 && shortcut_count < 9) {
822 if (label.contains(QString::number(shortcut_count + 1)))
823 label += '|' + QString::number(++shortcut_count);
825 add(MenuItem(MenuItem::Command, label,
826 FuncRequest(toc_list[i].action())));
831 size_t new_pos = pos + 1;
832 while (new_pos < to &&
833 toc_list[new_pos].depth() > depth)
836 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
837 label += limitStringLength(toc_list[pos].str());
838 if (toc_list[pos].depth() == depth &&
839 shortcut_count < 9) {
840 if (label.contains(QString::number(shortcut_count + 1)))
841 label += '|' + QString::number(++shortcut_count);
843 if (new_pos == pos + 1) {
844 add(MenuItem(MenuItem::Command,
845 label, FuncRequest(toc_list[pos].action())));
847 MenuItem item(MenuItem::Submenu, label);
848 item.setSubmenu(new MenuDefinition);
849 item.submenu()->expandToc2(toc_list, pos, new_pos, depth + 1);
858 void MenuDefinition::expandToc(Buffer const * buf)
860 // To make things very cleanly, we would have to pass buf to
861 // all MenuItem constructors and to expandToc2. However, we
862 // know that all the entries in a TOC will be have status_ ==
863 // OK, so we avoid this unnecessary overhead (JMarc)
866 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
867 FuncRequest(LFUN_NOACTION)));
871 Buffer* cbuf = const_cast<Buffer*>(buf);
872 cbuf->tocBackend().update();
873 cbuf->structureChanged();
875 // Add an entry for the master doc if this is a child doc
876 Buffer const * const master = buf->masterBuffer();
878 ParIterator const pit = par_iterator_begin(master->inset());
879 string const arg = convert<string>(pit->id());
880 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
881 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
884 FloatList const & floatlist = buf->params().documentClass().floats();
885 TocList const & toc_list = buf->tocBackend().tocs();
886 TocList::const_iterator cit = toc_list.begin();
887 TocList::const_iterator end = toc_list.end();
888 for (; cit != end; ++cit) {
890 if (cit->first == "tableofcontents")
893 // All the rest is for floats
894 MenuDefinition * submenu = new MenuDefinition;
895 TocIterator ccit = cit->second.begin();
896 TocIterator eend = cit->second.end();
897 for (; ccit != eend; ++ccit) {
898 QString const label = limitStringLength(ccit->str());
899 submenu->add(MenuItem(MenuItem::Command, label,
900 FuncRequest(ccit->action())));
902 string const & floatName = floatlist.getType(cit->first).listName();
904 if (!floatName.empty())
905 label = qt_(floatName);
906 // BUG3633: listings is not a proper float so its name
907 // is not shown in floatlist.
908 else if (cit->first == "equation")
909 label = qt_("List of Equations");
910 else if (cit->first == "index")
911 label = qt_("List of Indexes");
912 else if (cit->first == "listing")
913 label = qt_("List of Listings");
914 else if (cit->first == "marginalnote")
915 label = qt_("List of Marginal notes");
916 else if (cit->first == "note")
917 label = qt_("List of Notes");
918 else if (cit->first == "footnote")
919 label = qt_("List of Foot notes");
920 else if (cit->first == "label")
921 label = qt_("Labels and References");
922 else if (cit->first == "citation")
923 label = qt_("List of Citations");
924 // this should not happen now, but if something else like
925 // listings is added later, this can avoid an empty menu name.
927 label = qt_("Other floats");
928 MenuItem item(MenuItem::Submenu, label);
929 item.setSubmenu(submenu);
934 cit = toc_list.find("tableofcontents");
936 addWithStatusCheck(MenuItem(MenuItem::Command,
937 qt_("No Table of contents"),
940 expandToc2(cit->second, 0, cit->second.size(), 0);
945 void MenuDefinition::expandPasteRecent()
947 vector<docstring> const sel = cap::availableSelections();
949 vector<docstring>::const_iterator cit = sel.begin();
950 vector<docstring>::const_iterator end = sel.end();
952 for (unsigned int index = 0; cit != end; ++cit, ++index) {
953 add(MenuItem(MenuItem::Command, toqstr(*cit),
954 FuncRequest(LFUN_PASTE, convert<string>(index))));
959 void MenuDefinition::expandToolbars()
962 // extracts the toolbars from the backend
963 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
964 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
966 for (; cit != end; ++cit) {
967 QString label = qt_(cit->gui_name);
968 // frontends are not supposed to turn on/off toolbars,
969 // if they cannot update ToolbarBackend::flags. That
970 // is to say, ToolbarsBackend::flags should reflect
971 // the true state of toolbars.
973 // menu is displayed as
977 // in the case of auto.
978 if (cit->flags & ToolbarInfo::AUTO)
979 label += qt_(" (auto)");
980 add(MenuItem(MenuItem::Command, label,
981 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
986 void MenuDefinition::expandBranches(Buffer const * buf)
989 add(MenuItem(MenuItem::Command,
990 qt_("No Document Open!"),
991 FuncRequest(LFUN_NOACTION)));
995 BufferParams const & params = buf->masterBuffer()->params();
996 if (params.branchlist().empty()) {
997 add(MenuItem(MenuItem::Command,
998 qt_("No Branch in Document!"),
999 FuncRequest(LFUN_NOACTION)));
1003 BranchList::const_iterator cit = params.branchlist().begin();
1004 BranchList::const_iterator end = params.branchlist().end();
1006 for (int ii = 1; cit != end; ++cit, ++ii) {
1007 docstring label = cit->getBranch();
1009 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1010 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1011 FuncRequest(LFUN_BRANCH_INSERT,
1012 cit->getBranch())));
1019 /////////////////////////////////////////////////////////////////////
1020 // Menu::Impl definition and implementation
1021 /////////////////////////////////////////////////////////////////////
1025 /// populates the menu or one of its submenu
1026 /// This is used as a recursive function
1027 void populate(QMenu * qMenu, MenuDefinition * menu);
1029 /// Only needed for top level menus.
1030 MenuDefinition * top_level_menu;
1033 /// the name of this menu
1039 /// Get a MenuDefinition item label from the menu backend
1040 static QString label(MenuItem const & mi)
1042 QString label = mi.label();
1043 label.replace("&", "&&");
1045 QString shortcut = mi.shortcut();
1046 if (!shortcut.isEmpty()) {
1047 int pos = label.indexOf(shortcut);
1049 //label.insert(pos, 1, char_type('&'));
1050 label.replace(pos, 0, "&");
1053 QString const binding = mi.binding();
1054 if (!binding.isEmpty())
1055 label += '\t' + binding;
1060 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition * menu)
1062 LYXERR(Debug::GUI, "populating menu " << fromqstr(menu->name()));
1063 if (menu->size() == 0) {
1064 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu->name()));
1067 LYXERR(Debug::GUI, " ***** menu entries " << menu->size());
1068 MenuDefinition::const_iterator m = menu->begin();
1069 MenuDefinition::const_iterator end = menu->end();
1070 for (; m != end; ++m) {
1071 if (m->kind() == MenuItem::Separator)
1072 qMenu->addSeparator();
1073 else if (m->kind() == MenuItem::Submenu) {
1074 QMenu * subMenu = qMenu->addMenu(label(*m));
1075 populate(subMenu, m->submenu());
1077 // we have a MenuItem::Command
1078 qMenu->addAction(new Action(*view, QIcon(), label(*m), m->func(),
1084 /////////////////////////////////////////////////////////////////////
1085 // Menu implementation
1086 /////////////////////////////////////////////////////////////////////
1088 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1091 d->top_level_menu = top_level? new MenuDefinition : 0;
1095 if (d->top_level_menu)
1096 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1102 delete d->top_level_menu;
1107 void Menu::updateView()
1109 guiApp->menus().updateMenu(d->name);
1112 /////////////////////////////////////////////////////////////////////
1113 // Menus::Impl definition and implementation
1114 /////////////////////////////////////////////////////////////////////
1116 struct Menus::Impl {
1118 bool hasMenu(QString const &) const;
1120 MenuDefinition & getMenu(QString const &);
1122 MenuDefinition const & getMenu(QString const &) const;
1124 /// Expands some special entries of the menu
1125 /** The entries with the following kind are expanded to a
1126 sequence of Command MenuItems: Lastfiles, Documents,
1127 ViewFormats, ExportFormats, UpdateFormats, Branches
1129 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1130 Buffer const *) const;
1132 /// Initialize specific MACOS X menubar
1133 void macxMenuBarInit(GuiView * view);
1135 /// Mac special menu.
1136 /** This defines a menu whose entries list the FuncRequests
1137 that will be removed by expand() in other menus. This is
1138 used by the Qt/Mac code
1140 MenuDefinition specialmenu_;
1145 MenuDefinition menubar_;
1147 typedef QHash<QString, Menu *> NameMap;
1149 /// name to menu for \c menu() method.
1154 Here is what the Qt documentation says about how a menubar is chosen:
1156 1) If the window has a QMenuBar then it is used. 2) If the window
1157 is a modal then its menubar is used. If no menubar is specified
1158 then a default menubar is used (as documented below) 3) If the
1159 window has no parent then the default menubar is used (as
1162 The above 3 steps are applied all the way up the parent window
1163 chain until one of the above are satisifed. If all else fails a
1164 default menubar will be created, the default menubar on Qt/Mac is
1165 an empty menubar, however you can create a different default
1166 menubar by creating a parentless QMenuBar, the first one created
1167 will thus be designated the default menubar, and will be used
1168 whenever a default menubar is needed.
1170 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1171 that this menubar will be used also when one of LyX' dialogs has
1174 void Menus::Impl::macxMenuBarInit(GuiView * view)
1176 // The Mac menubar initialisation must be done only once!
1177 static bool done = false;
1182 /* Since Qt 4.2, the qt/mac menu code has special code for
1183 specifying the role of a menu entry. However, it does not
1184 work very well with our scheme of creating menus on demand,
1185 and therefore we need to put these entries in a special
1186 invisible menu. (JMarc)
1189 /* The entries of our special mac menu. If we add support for
1190 * special entries in Menus, we could imagine something
1192 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1193 * and therefore avoid hardcoding. I am not sure it is worth
1194 * the hassle, though. (JMarc)
1196 struct MacMenuEntry {
1200 QAction::MenuRole role;
1203 MacMenuEntry entries[] = {
1204 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1205 QAction::AboutRole},
1206 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1207 QAction::PreferencesRole},
1208 {LFUN_RECONFIGURE, "", "Reconfigure",
1209 QAction::ApplicationSpecificRole},
1210 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1212 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1214 // the special menu for Menus.
1215 for (size_t i = 0 ; i < num_entries ; ++i) {
1216 FuncRequest const func(entries[i].action,
1217 from_utf8(entries[i].arg));
1218 specialmenu_.add(MenuItem(MenuItem::Command, entries[i].label, func));
1221 // add the entries to a QMenu that will eventually be empty
1222 // and therefore invisible.
1223 QMenu * qMenu = view->menuBar()->addMenu("special");
1224 MenuDefinition::const_iterator cit = specialmenu_.begin();
1225 MenuDefinition::const_iterator end = specialmenu_.end();
1226 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1227 Action * action = new Action(*view, QIcon(), cit->label(),
1228 cit->func(), QString());
1229 action->setMenuRole(entries[i].role);
1230 qMenu->addAction(action);
1235 void Menus::Impl::expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1236 Buffer const * buf) const
1238 if (!tomenu.empty())
1241 for (MenuDefinition::const_iterator cit = frommenu.begin();
1242 cit != frommenu.end() ; ++cit) {
1243 switch (cit->kind()) {
1244 case MenuItem::Lastfiles:
1245 tomenu.expandLastfiles();
1248 case MenuItem::Documents:
1249 tomenu.expandDocuments();
1252 case MenuItem::Bookmarks:
1253 tomenu.expandBookmarks();
1256 case MenuItem::ImportFormats:
1257 case MenuItem::ViewFormats:
1258 case MenuItem::UpdateFormats:
1259 case MenuItem::ExportFormats:
1260 tomenu.expandFormats(cit->kind(), buf);
1263 case MenuItem::CharStyles:
1264 tomenu.expandFlexInsert(buf, "charstyle");
1267 case MenuItem::Custom:
1268 tomenu.expandFlexInsert(buf, "custom");
1271 case MenuItem::Elements:
1272 tomenu.expandFlexInsert(buf, "element");
1275 case MenuItem::FloatListInsert:
1276 tomenu.expandFloatListInsert(buf);
1279 case MenuItem::FloatInsert:
1280 tomenu.expandFloatInsert(buf);
1283 case MenuItem::PasteRecent:
1284 tomenu.expandPasteRecent();
1287 case MenuItem::Toolbars:
1288 tomenu.expandToolbars();
1291 case MenuItem::Branches:
1292 tomenu.expandBranches(buf);
1296 tomenu.expandToc(buf);
1299 case MenuItem::Submenu: {
1300 MenuItem item(*cit);
1301 item.setSubmenu(new MenuDefinition(cit->submenuname()));
1302 expand(getMenu(cit->submenuname()), *item.submenu(), buf);
1303 tomenu.addWithStatusCheck(item);
1307 case MenuItem::Separator:
1308 tomenu.addWithStatusCheck(*cit);
1311 case MenuItem::Command:
1312 if (!specialmenu_.hasFunc(cit->func()))
1313 tomenu.addWithStatusCheck(*cit);
1317 // we do not want the menu to end with a separator
1318 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1319 tomenu.items_.pop_back();
1321 // Check whether the shortcuts are unique
1322 tomenu.checkShortcuts();
1326 bool Menus::Impl::hasMenu(QString const & name) const
1328 return find_if(menulist_.begin(), menulist_.end(),
1329 MenuNamesEqual(name)) != menulist_.end();
1333 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1335 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1336 MenuNamesEqual(name));
1337 if (cit == menulist_.end())
1338 lyxerr << "No submenu named " << fromqstr(name) << endl;
1339 BOOST_ASSERT(cit != menulist_.end());
1344 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1346 iterator it = find_if(menulist_.begin(), menulist_.end(),
1347 MenuNamesEqual(name));
1348 if (it == menulist_.end())
1349 lyxerr << "No submenu named " << fromqstr(name) << endl;
1350 BOOST_ASSERT(it != menulist_.end());
1354 /////////////////////////////////////////////////////////////////////
1355 // Menus implementation
1356 /////////////////////////////////////////////////////////////////////
1358 Menus::Menus(): d(new Impl) {}
1361 void Menus::read(Lexer & lex)
1370 struct keyword_item menutags[md_last - 1] = {
1371 { "end", md_endmenuset },
1372 { "menu", md_menu },
1373 { "menubar", md_menubar }
1377 if (compare_ascii_no_case(lex.getString(), "menuset")) {
1378 lyxerr << "Menubackend::read: ERROR wrong token:`"
1379 << lex.getString() << '\'' << endl;
1382 lex.pushTable(menutags, md_last - 1);
1383 if (lyxerr.debugging(Debug::PARSER))
1384 lex.printTable(lyxerr);
1388 while (lex.isOK() && !quit) {
1389 switch (lex.lex()) {
1391 d->menubar_.read(lex);
1395 QString const name = toqstr(lex.getDocString());
1396 if (d->hasMenu(name))
1397 d->getMenu(name).read(lex);
1399 MenuDefinition menu(name);
1401 d->menulist_.push_back(menu);
1409 lex.printError("menubackend::read: "
1410 "Unknown menu tag: `$$Token'");
1418 bool Menus::searchMenu(FuncRequest const & func,
1419 vector<docstring> & names) const
1421 return d->menubar_.searchMenu(func, names);
1425 void Menus::fillMenuBar(GuiView * view)
1427 // Clear all menubar contents before filling it.
1428 view->menuBar()->clear();
1431 // setup special mac specific menu item
1432 d->macxMenuBarInit(view);
1435 LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
1437 if (d->menubar_.size() == 0) {
1438 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1439 << fromqstr(d->menubar_.name()));
1443 LYXERR(Debug::GUI, "menu bar entries "
1444 << d->menubar_.size());
1447 MenuDefinition menu;
1448 d->expand(d->menubar_, menu, view->buffer());
1450 MenuDefinition::const_iterator m = menu.begin();
1451 MenuDefinition::const_iterator end = menu.end();
1453 for (; m != end; ++m) {
1455 if (m->kind() != MenuItem::Submenu) {
1456 LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
1460 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
1461 << " is a submenu named " << fromqstr(m->submenuname()));
1463 QString name = m->submenuname();
1464 if (!d->hasMenu(name)) {
1465 LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
1466 << " submenu has no menu!");
1470 Menu * menu = new Menu(view, m->submenuname(), true);
1471 menu->setTitle(label(*m));
1472 view->menuBar()->addMenu(menu);
1474 d->name_map_[name] = menu;
1479 void Menus::updateMenu(QString const & name)
1481 Menu * qmenu = d->name_map_[name];
1482 LYXERR(Debug::GUI, "Triggered menu: " << fromqstr(name));
1485 if (qmenu->d->name.isEmpty())
1488 // Here, We make sure that theLyXFunc points to the correct LyXView.
1489 theLyXFunc().setLyXView(qmenu->d->view);
1491 if (!d->hasMenu(name)) {
1492 qmenu->addAction(qt_("No action defined!"));
1493 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1494 << fromqstr(qmenu->d->name));
1498 MenuDefinition const & fromLyxMenu = d->getMenu(name);
1499 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, qmenu->d->view->buffer());
1500 qmenu->d->populate(qmenu, qmenu->d->top_level_menu);
1504 Menu * Menus::menu(QString const & name, GuiView & view)
1506 LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
1507 Menu * menu = d->name_map_.value(name, 0);
1508 if (!menu && !name.startsWith("context-")) {
1509 LYXERR0("resquested context menu not found: " << fromqstr(name));
1513 menu = new Menu(&view, name, true);
1514 d->name_map_[name] = menu;
1518 } // namespace frontend
1521 #include "Menus_moc.cpp"