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 /// The label of a given menuitem
156 QString label() const { return label_.split('|')[0]; }
158 /// The keyboard shortcut (usually underlined in the entry)
159 QString shortcut() const
161 return label_.contains('|') ? label_.split('|')[1] : QString();
163 /// The complete label, with label and shortcut separated by a '|'
164 QString fulllabel() const { return label_;}
165 /// The kind of entry
166 Kind kind() const { return kind_; }
167 /// the action (if relevant)
168 FuncRequest const & func() const { return func_; }
169 /// returns true if the entry should be ommited when disabled
170 bool optional() const { return optional_; }
171 /// returns the status of the lfun associated with this entry
172 FuncStatus const & status() const { return status_; }
173 /// returns the status of the lfun associated with this entry
174 FuncStatus & status() { return status_; }
175 /// returns the status of the lfun associated with this entry
176 void status(FuncStatus const & status) { status_ = status; }
178 ///returns the binding associated to this action.
179 QString binding() const
181 if (kind_ != Command)
183 // Get the keys bound to this action, but keep only the
185 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
187 return toqstr(bindings.begin()->print(KeySequence::ForGui));
189 LYXERR(Debug::KBMAP, "No binding for "
190 << lyxaction.getActionName(func_.action)
191 << '(' << func_.argument() << ')');
195 /// the description of the submenu (if relevant)
196 QString const & submenuname() const { return submenuname_; }
197 /// set the description of the submenu
198 void submenuname(QString const & name) { submenuname_ = name; }
200 Menu * submenu() const { return submenu_; }
202 void setSubmenu(Menu * menu) { submenu_ = menu; }
212 QString submenuname_;
225 typedef std::vector<MenuItem> ItemList;
227 typedef ItemList::const_iterator const_iterator;
229 explicit Menu(QString const & name = QString()) : name_(name) {}
234 QString const & name() const { return name_; }
236 bool empty() const { return items_.empty(); }
237 /// Clear the menu content.
238 void clear() { items_.clear(); }
240 size_t size() const { return items_.size(); }
242 MenuItem const & operator[](size_t) const;
244 const_iterator begin() const { return items_.begin(); }
246 const_iterator end() const { return items_.end(); }
248 // search for func in this menu iteratively, and put menu
250 bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
253 bool hasFunc(FuncRequest const &) const;
254 /// Add the menu item unconditionally
255 void add(MenuItem const & item) { items_.push_back(item); }
256 /// Checks the associated FuncRequest status before adding the
258 void addWithStatusCheck(MenuItem const &);
259 // Check whether the menu shortcuts are unique
260 void checkShortcuts() const;
262 void expandLastfiles();
263 void expandDocuments();
264 void expandBookmarks();
265 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
266 void expandFloatListInsert(Buffer const * buf);
267 void expandFloatInsert(Buffer const * buf);
268 void expandFlexInsert(Buffer const * buf, std::string s);
269 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
270 void expandToc(Buffer const * buf);
271 void expandPasteRecent();
272 void expandToolbars();
273 void expandBranches(Buffer const * buf);
281 class GuiPopupMenu : public QMenu
285 GuiPopupMenu(GuiView * gv, MenuItem const & mi, bool top_level)
286 : QMenu(gv), top_level_menu(top_level? new Menu : 0), view(gv),
287 name(mi.submenuname())
292 /// populates the menu or one of its submenu
293 /// This is used as a recursive function
294 void populate(QMenu * qMenu, Menu * menu);
296 /// Get a Menu item label from the menu backend
297 QString label(MenuItem const & mi) const;
299 void showEvent(QShowEvent * ev)
302 guiApp->menus().updateMenu(name);
303 QMenu::showEvent(ev);
306 /// Only needed for top level menus.
307 Menu * top_level_menu;
310 /// the name of this menu
314 /// Helper for std::find_if
318 MenuNamesEqual(QString const & name) : name_(name) {}
319 bool operator()(Menu const & menu) const { return menu.name() == name_; }
326 typedef std::vector<Menu> MenuList;
328 typedef MenuList::const_iterator const_iterator;
330 typedef MenuList::iterator iterator;
332 /////////////////////////////////////////////////////////////////////
333 // GuiPopupMenu implementation
334 /////////////////////////////////////////////////////////////////////
336 void GuiPopupMenu::populate(QMenu * qMenu, Menu * menu)
338 LYXERR(Debug::GUI, "populating menu " << fromqstr(menu->name()));
339 if (menu->size() == 0) {
340 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu->name()));
343 LYXERR(Debug::GUI, " ***** menu entries " << menu->size());
344 Menu::const_iterator m = menu->begin();
345 Menu::const_iterator end = menu->end();
346 for (; m != end; ++m) {
347 if (m->kind() == MenuItem::Separator)
348 qMenu->addSeparator();
349 else if (m->kind() == MenuItem::Submenu) {
350 QMenu * subMenu = qMenu->addMenu(label(*m));
351 populate(subMenu, m->submenu());
353 // we have a MenuItem::Command
354 qMenu->addAction(new Action(*view, QIcon(), label(*m), m->func(),
361 QString GuiPopupMenu::label(MenuItem const & mi) const
363 QString label = mi.label();
364 label.replace("&", "&&");
366 QString shortcut = mi.shortcut();
367 if (!shortcut.isEmpty()) {
368 int pos = label.indexOf(shortcut);
370 //label.insert(pos, 1, char_type('&'));
371 label.replace(pos, 0, "&");
374 QString const binding = mi.binding();
375 if (!binding.isEmpty())
376 label += '\t' + binding;
381 /////////////////////////////////////////////////////////////////////
382 // Menu implementation
383 /////////////////////////////////////////////////////////////////////
385 void Menu::addWithStatusCheck(MenuItem const & i)
389 case MenuItem::Command: {
390 FuncStatus status = lyx::getStatus(i.func());
391 if (status.unknown() || (!status.enabled() && i.optional()))
394 items_.back().status(status);
398 case MenuItem::Submenu: {
400 bool enabled = false;
401 for (const_iterator cit = i.submenu()->begin();
402 cit != i.submenu()->end(); ++cit) {
403 if ((cit->kind() == MenuItem::Command
404 || cit->kind() == MenuItem::Submenu)
405 && cit->status().enabled()) {
410 if (enabled || !i.optional()) {
412 items_.back().status().enabled(enabled);
420 case MenuItem::Separator:
421 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
431 void Menu::read(Lexer & lex)
459 struct keyword_item menutags[md_last - 1] = {
460 { "bookmarks", md_bookmarks },
461 { "branches", md_branches },
462 { "charstyles", md_charstyles },
463 { "custom", md_custom },
464 { "documents", md_documents },
465 { "elements", md_elements },
466 { "end", md_endmenu },
467 { "exportformats", md_exportformats },
468 { "floatinsert", md_floatinsert },
469 { "floatlistinsert", md_floatlistinsert },
470 { "importformats", md_importformats },
472 { "lastfiles", md_lastfiles },
473 { "optitem", md_optitem },
474 { "optsubmenu", md_optsubmenu },
475 { "pasterecent", md_pasterecent },
476 { "separator", md_separator },
477 { "submenu", md_submenu },
479 { "toolbars", md_toolbars },
480 { "updateformats", md_updateformats },
481 { "viewformats", md_viewformats }
484 lex.pushTable(menutags, md_last - 1);
485 if (lyxerr.debugging(Debug::PARSER))
486 lex.printTable(lyxerr);
489 bool optional = false;
491 while (lex.isOK() && !quit) {
495 // fallback to md_item
498 docstring const name = translateIfPossible(lex.getDocString());
500 string const command = lex.getString();
501 FuncRequest func = lyxaction.lookupFunc(command);
502 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
508 add(MenuItem(MenuItem::Separator));
512 add(MenuItem(MenuItem::Lastfiles));
516 add(MenuItem(MenuItem::CharStyles));
520 add(MenuItem(MenuItem::Custom));
524 add(MenuItem(MenuItem::Elements));
528 add(MenuItem(MenuItem::Documents));
532 add(MenuItem(MenuItem::Bookmarks));
536 add(MenuItem(MenuItem::Toc));
540 add(MenuItem(MenuItem::ViewFormats));
543 case md_updateformats:
544 add(MenuItem(MenuItem::UpdateFormats));
547 case md_exportformats:
548 add(MenuItem(MenuItem::ExportFormats));
551 case md_importformats:
552 add(MenuItem(MenuItem::ImportFormats));
555 case md_floatlistinsert:
556 add(MenuItem(MenuItem::FloatListInsert));
560 add(MenuItem(MenuItem::FloatInsert));
564 add(MenuItem(MenuItem::PasteRecent));
568 add(MenuItem(MenuItem::Toolbars));
572 add(MenuItem(MenuItem::Branches));
577 // fallback to md_submenu
580 docstring const mlabel = translateIfPossible(lex.getDocString());
582 docstring const mname = lex.getDocString();
583 add(MenuItem(MenuItem::Submenu,
584 toqstr(mlabel), toqstr(mname), optional));
594 lex.printError("Menu::read: "
595 "Unknown menu tag: `$$Token'");
603 MenuItem const & Menu::operator[](size_type i) const
609 bool Menu::hasFunc(FuncRequest const & func) const
611 for (const_iterator it = begin(), et = end(); it != et; ++it)
612 if (it->func() == func)
618 void Menu::checkShortcuts() const
620 // This is a quadratic algorithm, but we do not care because
621 // menus are short enough
622 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
623 QString shortcut = it1->shortcut();
624 if (shortcut.isEmpty())
626 if (!it1->label().contains(shortcut))
627 lyxerr << "Menu warning: menu entry \""
628 << fromqstr(it1->label())
629 << "\" does not contain shortcut `"
630 << fromqstr(shortcut) << "'." << endl;
631 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
632 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
633 lyxerr << "Menu warning: menu entries "
634 << '"' << fromqstr(it1->fulllabel())
635 << "\" and \"" << fromqstr(it2->fulllabel())
636 << "\" share the same shortcut."
644 bool Menu::searchMenu(FuncRequest const & func, vector<docstring> & names) const
646 const_iterator m = begin();
647 const_iterator m_end = end();
648 for (; m != m_end; ++m) {
649 if (m->kind() == MenuItem::Command && m->func() == func) {
650 names.push_back(qstring_to_ucs4(m->label()));
653 if (m->kind() == MenuItem::Submenu) {
654 names.push_back(qstring_to_ucs4(m->label()));
655 Menu const & submenu = *m->submenu();
656 if (submenu.searchMenu(func, names))
665 bool compareFormat(Format const * p1, Format const * p2)
671 QString limitStringLength(docstring const & str)
673 size_t const max_item_length = 45;
675 if (str.size() > max_item_length)
676 return toqstr(str.substr(0, max_item_length - 3) + "...");
682 void Menu::expandLastfiles()
684 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
685 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
689 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
690 string const file = lfit->absFilename();
691 QString const label = QString("%1. %2|%3").arg(ii)
692 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
693 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
698 void Menu::expandDocuments()
700 Buffer * first = theBufferList().first();
705 // We cannot use a for loop as the buffer list cycles.
707 QString label = toqstr(b->fileName().displayName(20));
711 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
712 add(MenuItem(MenuItem::Command, label,
713 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
715 b = theBufferList().next(b);
717 } while (b != first);
719 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
720 FuncRequest(LFUN_NOACTION)));
725 void Menu::expandBookmarks()
727 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
729 for (size_t i = 1; i <= bm.size(); ++i) {
731 string const file = bm.bookmark(i).filename.absFilename();
732 QString const label = QString("%1. %2|%3").arg(i)
733 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
734 add(MenuItem(MenuItem::Command, label,
735 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
741 void Menu::expandFormats(MenuItem::Kind kind, Buffer const * buf)
743 if (!buf && kind != MenuItem::ImportFormats) {
744 add(MenuItem(MenuItem::Command,
745 qt_("No Document Open!"),
746 FuncRequest(LFUN_NOACTION)));
750 typedef vector<Format const *> Formats;
755 case MenuItem::ImportFormats:
756 formats = theConverters().importableFormats();
757 action = LFUN_BUFFER_IMPORT;
759 case MenuItem::ViewFormats:
760 formats = buf->exportableFormats(true);
761 action = LFUN_BUFFER_VIEW;
763 case MenuItem::UpdateFormats:
764 formats = buf->exportableFormats(true);
765 action = LFUN_BUFFER_UPDATE;
768 formats = buf->exportableFormats(false);
769 action = LFUN_BUFFER_EXPORT;
771 sort(formats.begin(), formats.end(), &compareFormat);
773 Formats::const_iterator fit = formats.begin();
774 Formats::const_iterator end = formats.end();
775 for (; fit != end ; ++fit) {
778 QString label = toqstr((*fit)->prettyname());
779 QString const shortcut = toqstr((*fit)->shortcut());
782 case MenuItem::ImportFormats:
783 // FIXME: This is a hack, we should rather solve
784 // FIXME: bug 2488 instead.
785 if ((*fit)->name() == "text")
786 label = qt_("Plain Text");
787 else if ((*fit)->name() == "textparagraph")
788 label = qt_("Plain Text, Join Lines");
791 case MenuItem::ViewFormats:
792 case MenuItem::ExportFormats:
793 case MenuItem::UpdateFormats:
794 if (!(*fit)->documentFormat())
801 // FIXME: if we had proper support for translating the
802 // format names defined in configure.py, there would
803 // not be a need to check whether the shortcut is
804 // correct. If we add it uncondiitonally, it would
805 // create useless warnings on bad shortcuts
806 if (!shortcut.isEmpty() && label.contains(shortcut))
807 label += '|' + shortcut;
810 addWithStatusCheck(MenuItem(MenuItem::Command, label,
811 FuncRequest(action, (*fit)->name())));
813 add(MenuItem(MenuItem::Command, label,
814 FuncRequest(action, (*fit)->name())));
819 void Menu::expandFloatListInsert(Buffer const * buf)
822 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
823 FuncRequest(LFUN_NOACTION)));
827 FloatList const & floats = buf->params().documentClass().floats();
828 FloatList::const_iterator cit = floats.begin();
829 FloatList::const_iterator end = floats.end();
830 for (; cit != end; ++cit) {
831 addWithStatusCheck(MenuItem(MenuItem::Command,
832 qt_(cit->second.listName()),
833 FuncRequest(LFUN_FLOAT_LIST,
834 cit->second.type())));
839 void Menu::expandFloatInsert(Buffer const * buf)
842 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
843 FuncRequest(LFUN_NOACTION)));
847 FloatList const & floats = buf->params().documentClass().floats();
848 FloatList::const_iterator cit = floats.begin();
849 FloatList::const_iterator end = floats.end();
850 for (; cit != end; ++cit) {
852 QString const label = qt_(cit->second.name());
853 addWithStatusCheck(MenuItem(MenuItem::Command, label,
854 FuncRequest(LFUN_FLOAT_INSERT,
855 cit->second.type())));
860 void Menu::expandFlexInsert(Buffer const * buf, string s)
863 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
864 FuncRequest(LFUN_NOACTION)));
867 TextClass::InsetLayouts const & insetLayouts =
868 buf->params().documentClass().insetLayouts();
869 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
870 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
871 for (; cit != end; ++cit) {
872 docstring const label = cit->first;
873 if (cit->second.lyxtype() == s)
874 addWithStatusCheck(MenuItem(MenuItem::Command,
875 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
881 size_t const max_number_of_items = 25;
883 void Menu::expandToc2(Toc const & toc_list,
884 size_t from, size_t to, int depth)
886 int shortcut_count = 0;
888 // check whether depth is smaller than the smallest depth in toc.
889 int min_depth = 1000;
890 for (size_t i = from; i < to; ++i)
891 min_depth = min(min_depth, toc_list[i].depth());
892 if (min_depth > depth)
895 if (to - from <= max_number_of_items) {
896 for (size_t i = from; i < to; ++i) {
897 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
898 label += limitStringLength(toc_list[i].str());
899 if (toc_list[i].depth() == depth
900 && shortcut_count < 9) {
901 if (label.contains(QString::number(shortcut_count + 1)))
902 label += '|' + QString::number(++shortcut_count);
904 add(MenuItem(MenuItem::Command, label,
905 FuncRequest(toc_list[i].action())));
910 size_t new_pos = pos + 1;
911 while (new_pos < to &&
912 toc_list[new_pos].depth() > depth)
915 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
916 label += limitStringLength(toc_list[pos].str());
917 if (toc_list[pos].depth() == depth &&
918 shortcut_count < 9) {
919 if (label.contains(QString::number(shortcut_count + 1)))
920 label += '|' + QString::number(++shortcut_count);
922 if (new_pos == pos + 1) {
923 add(MenuItem(MenuItem::Command,
924 label, FuncRequest(toc_list[pos].action())));
926 MenuItem item(MenuItem::Submenu, label);
927 item.setSubmenu(new Menu);
928 item.submenu()->expandToc2(toc_list, pos, new_pos, depth + 1);
937 void Menu::expandToc(Buffer const * buf)
939 // To make things very cleanly, we would have to pass buf to
940 // all MenuItem constructors and to expandToc2. However, we
941 // know that all the entries in a TOC will be have status_ ==
942 // OK, so we avoid this unnecessary overhead (JMarc)
945 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
946 FuncRequest(LFUN_NOACTION)));
950 Buffer* cbuf = const_cast<Buffer*>(buf);
951 cbuf->tocBackend().update();
952 cbuf->structureChanged();
954 // Add an entry for the master doc if this is a child doc
955 Buffer const * const master = buf->masterBuffer();
957 ParIterator const pit = par_iterator_begin(master->inset());
958 string const arg = convert<string>(pit->id());
959 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
960 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
963 FloatList const & floatlist = buf->params().documentClass().floats();
964 TocList const & toc_list = buf->tocBackend().tocs();
965 TocList::const_iterator cit = toc_list.begin();
966 TocList::const_iterator end = toc_list.end();
967 for (; cit != end; ++cit) {
969 if (cit->first == "tableofcontents")
972 // All the rest is for floats
973 auto_ptr<Menu> menu(new Menu);
974 TocIterator ccit = cit->second.begin();
975 TocIterator eend = cit->second.end();
976 for (; ccit != eend; ++ccit) {
977 QString const label = limitStringLength(ccit->str());
978 menu->add(MenuItem(MenuItem::Command, label,
979 FuncRequest(ccit->action())));
981 string const & floatName = floatlist.getType(cit->first).listName();
983 if (!floatName.empty())
984 label = qt_(floatName);
985 // BUG3633: listings is not a proper float so its name
986 // is not shown in floatlist.
987 else if (cit->first == "equation")
988 label = qt_("List of Equations");
989 else if (cit->first == "index")
990 label = qt_("List of Indexes");
991 else if (cit->first == "listing")
992 label = qt_("List of Listings");
993 else if (cit->first == "marginalnote")
994 label = qt_("List of Marginal notes");
995 else if (cit->first == "note")
996 label = qt_("List of Notes");
997 else if (cit->first == "footnote")
998 label = qt_("List of Foot notes");
999 else if (cit->first == "label")
1000 label = qt_("Labels and References");
1001 else if (cit->first == "citation")
1002 label = qt_("List of Citations");
1003 // this should not happen now, but if something else like
1004 // listings is added later, this can avoid an empty menu name.
1006 label = qt_("Other floats");
1007 MenuItem item(MenuItem::Submenu, label);
1008 item.setSubmenu(menu.release());
1012 // Handle normal TOC
1013 cit = toc_list.find("tableofcontents");
1015 addWithStatusCheck(MenuItem(MenuItem::Command,
1016 qt_("No Table of contents"),
1019 expandToc2(cit->second, 0, cit->second.size(), 0);
1024 void Menu::expandPasteRecent()
1026 vector<docstring> const sel = cap::availableSelections();
1028 vector<docstring>::const_iterator cit = sel.begin();
1029 vector<docstring>::const_iterator end = sel.end();
1031 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1032 add(MenuItem(MenuItem::Command, toqstr(*cit),
1033 FuncRequest(LFUN_PASTE, convert<string>(index))));
1038 void Menu::expandToolbars()
1041 // extracts the toolbars from the backend
1042 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1043 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1045 for (; cit != end; ++cit) {
1046 QString label = qt_(cit->gui_name);
1047 // frontends are not supposed to turn on/off toolbars,
1048 // if they cannot update ToolbarBackend::flags. That
1049 // is to say, ToolbarsBackend::flags should reflect
1050 // the true state of toolbars.
1052 // menu is displayed as
1056 // in the case of auto.
1057 if (cit->flags & ToolbarInfo::AUTO)
1058 label += qt_(" (auto)");
1059 add(MenuItem(MenuItem::Command, label,
1060 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1065 void Menu::expandBranches(Buffer const * buf)
1068 add(MenuItem(MenuItem::Command,
1069 qt_("No Document Open!"),
1070 FuncRequest(LFUN_NOACTION)));
1074 BufferParams const & params = buf->masterBuffer()->params();
1075 if (params.branchlist().empty()) {
1076 add(MenuItem(MenuItem::Command,
1077 qt_("No Branch in Document!"),
1078 FuncRequest(LFUN_NOACTION)));
1082 BranchList::const_iterator cit = params.branchlist().begin();
1083 BranchList::const_iterator end = params.branchlist().end();
1085 for (int ii = 1; cit != end; ++cit, ++ii) {
1086 docstring label = cit->getBranch();
1088 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1089 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1090 FuncRequest(LFUN_BRANCH_INSERT,
1091 cit->getBranch())));
1098 struct Menus::Impl {
1100 void add(Menu const &);
1102 bool hasMenu(QString const &) const;
1104 Menu & getMenu(QString const &);
1106 Menu const & getMenu(QString const &) const;
1108 /// Expands some special entries of the menu
1109 /** The entries with the following kind are expanded to a
1110 sequence of Command MenuItems: Lastfiles, Documents,
1111 ViewFormats, ExportFormats, UpdateFormats, Branches
1113 void expand(Menu const & frommenu, Menu & tomenu,
1114 Buffer const *) const;
1116 /// Initialize specific MACOS X menubar
1117 void macxMenuBarInit(GuiView * view);
1119 /// Mac special menu.
1120 /** This defines a menu whose entries list the FuncRequests
1121 that will be removed by expand() in other menus. This is
1122 used by the Qt/Mac code
1131 typedef QHash<QString, GuiPopupMenu *> NameMap;
1133 /// name to menu for \c menu() method.
1138 /////////////////////////////////////////////////////////////////////
1139 // Menus::Impl implementation
1140 /////////////////////////////////////////////////////////////////////
1143 Here is what the Qt documentation says about how a menubar is chosen:
1145 1) If the window has a QMenuBar then it is used. 2) If the window
1146 is a modal then its menubar is used. If no menubar is specified
1147 then a default menubar is used (as documented below) 3) If the
1148 window has no parent then the default menubar is used (as
1151 The above 3 steps are applied all the way up the parent window
1152 chain until one of the above are satisifed. If all else fails a
1153 default menubar will be created, the default menubar on Qt/Mac is
1154 an empty menubar, however you can create a different default
1155 menubar by creating a parentless QMenuBar, the first one created
1156 will thus be designated the default menubar, and will be used
1157 whenever a default menubar is needed.
1159 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1160 that this menubar will be used also when one of LyX' dialogs has
1163 void Menus::Impl::macxMenuBarInit(GuiView * view)
1165 // The Mac menubar initialisation must be done only once!
1166 static bool done = false;
1171 /* Since Qt 4.2, the qt/mac menu code has special code for
1172 specifying the role of a menu entry. However, it does not
1173 work very well with our scheme of creating menus on demand,
1174 and therefore we need to put these entries in a special
1175 invisible menu. (JMarc)
1178 /* The entries of our special mac menu. If we add support for
1179 * special entries in Menus, we could imagine something
1181 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1182 * and therefore avoid hardcoding. I am not sure it is worth
1183 * the hassle, though. (JMarc)
1185 struct MacMenuEntry {
1189 QAction::MenuRole role;
1192 MacMenuEntry entries[] = {
1193 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1194 QAction::AboutRole},
1195 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1196 QAction::PreferencesRole},
1197 {LFUN_RECONFIGURE, "", "Reconfigure",
1198 QAction::ApplicationSpecificRole},
1199 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1201 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1203 // the special menu for Menus.
1204 for (size_t i = 0 ; i < num_entries ; ++i) {
1205 FuncRequest const func(entries[i].action,
1206 from_utf8(entries[i].arg));
1207 specialmenu_.add(MenuItem(MenuItem::Command, entries[i].label, func));
1210 // add the entries to a QMenu that will eventually be empty
1211 // and therefore invisible.
1212 QMenu * qMenu = view->menuBar()->addMenu("special");
1213 Menu::const_iterator cit = specialmenu_.begin();
1214 Menu::const_iterator end = specialmenu_.end();
1215 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1216 Action * action = new Action(*view, QIcon(), cit->label(),
1217 cit->func(), QString());
1218 action->setMenuRole(entries[i].role);
1219 qMenu->addAction(action);
1224 void Menus::Impl::expand(Menu const & frommenu, Menu & tomenu,
1225 Buffer const * buf) const
1227 if (!tomenu.empty())
1230 for (Menu::const_iterator cit = frommenu.begin();
1231 cit != frommenu.end() ; ++cit) {
1232 switch (cit->kind()) {
1233 case MenuItem::Lastfiles:
1234 tomenu.expandLastfiles();
1237 case MenuItem::Documents:
1238 tomenu.expandDocuments();
1241 case MenuItem::Bookmarks:
1242 tomenu.expandBookmarks();
1245 case MenuItem::ImportFormats:
1246 case MenuItem::ViewFormats:
1247 case MenuItem::UpdateFormats:
1248 case MenuItem::ExportFormats:
1249 tomenu.expandFormats(cit->kind(), buf);
1252 case MenuItem::CharStyles:
1253 tomenu.expandFlexInsert(buf, "charstyle");
1256 case MenuItem::Custom:
1257 tomenu.expandFlexInsert(buf, "custom");
1260 case MenuItem::Elements:
1261 tomenu.expandFlexInsert(buf, "element");
1264 case MenuItem::FloatListInsert:
1265 tomenu.expandFloatListInsert(buf);
1268 case MenuItem::FloatInsert:
1269 tomenu.expandFloatInsert(buf);
1272 case MenuItem::PasteRecent:
1273 tomenu.expandPasteRecent();
1276 case MenuItem::Toolbars:
1277 tomenu.expandToolbars();
1280 case MenuItem::Branches:
1281 tomenu.expandBranches(buf);
1285 tomenu.expandToc(buf);
1288 case MenuItem::Submenu: {
1289 MenuItem item(*cit);
1290 item.setSubmenu(new Menu(cit->submenuname()));
1291 expand(getMenu(cit->submenuname()),
1292 *item.submenu(), buf);
1293 tomenu.addWithStatusCheck(item);
1297 case MenuItem::Separator:
1298 tomenu.addWithStatusCheck(*cit);
1301 case MenuItem::Command:
1302 if (!specialmenu_.hasFunc(cit->func()))
1303 tomenu.addWithStatusCheck(*cit);
1307 // we do not want the menu to end with a separator
1308 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1309 tomenu.items_.pop_back();
1311 // Check whether the shortcuts are unique
1312 tomenu.checkShortcuts();
1316 void Menus::Impl::add(Menu const & menu)
1318 menulist_.push_back(menu);
1322 bool Menus::Impl::hasMenu(QString const & name) const
1324 return find_if(menulist_.begin(), menulist_.end(),
1325 MenuNamesEqual(name)) != menulist_.end();
1329 Menu const & Menus::Impl::getMenu(QString const & name) const
1331 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1332 MenuNamesEqual(name));
1333 if (cit == menulist_.end())
1334 lyxerr << "No submenu named " << fromqstr(name) << endl;
1335 BOOST_ASSERT(cit != menulist_.end());
1340 Menu & Menus::Impl::getMenu(QString const & name)
1342 iterator it = find_if(menulist_.begin(), menulist_.end(),
1343 MenuNamesEqual(name));
1344 if (it == menulist_.end())
1345 lyxerr << "No submenu named " << fromqstr(name) << endl;
1346 BOOST_ASSERT(it != menulist_.end());
1350 /////////////////////////////////////////////////////////////////////
1351 // Menus implementation
1352 /////////////////////////////////////////////////////////////////////
1354 Menus::Menus(): d(new Impl) {}
1357 void Menus::read(Lexer & lex)
1366 struct keyword_item menutags[md_last - 1] = {
1367 { "end", md_endmenuset },
1368 { "menu", md_menu },
1369 { "menubar", md_menubar }
1373 if (compare_ascii_no_case(lex.getString(), "menuset")) {
1374 lyxerr << "Menubackend::read: ERROR wrong token:`"
1375 << lex.getString() << '\'' << endl;
1378 lex.pushTable(menutags, md_last - 1);
1379 if (lyxerr.debugging(Debug::PARSER))
1380 lex.printTable(lyxerr);
1384 while (lex.isOK() && !quit) {
1385 switch (lex.lex()) {
1387 d->menubar_.read(lex);
1391 QString const name = toqstr(lex.getDocString());
1392 if (d->hasMenu(name))
1393 d->getMenu(name).read(lex);
1405 lex.printError("menubackend::read: "
1406 "Unknown menu tag: `$$Token'");
1414 bool Menus::searchMenu(FuncRequest const & func,
1415 vector<docstring> & names) const
1417 return d->menubar_.searchMenu(func, names);
1421 void Menus::fillMenuBar(GuiView * view)
1423 // Clear all menubar contents before filling it.
1424 view->menuBar()->clear();
1427 // setup special mac specific menu item
1428 macxMenuBarInit(view);
1431 LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
1433 if (d->menubar_.size() == 0) {
1434 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1435 << fromqstr(d->menubar_.name()));
1439 LYXERR(Debug::GUI, "menu bar entries "
1440 << d->menubar_.size());
1444 d->expand(d->menubar_, menu, view->buffer());
1446 Menu::const_iterator m = menu.begin();
1447 Menu::const_iterator end = menu.end();
1449 for (; m != end; ++m) {
1451 if (m->kind() != MenuItem::Submenu) {
1452 LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
1456 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
1457 << " is a submenu named " << fromqstr(m->submenuname()));
1459 QString name = m->submenuname();
1460 if (!d->hasMenu(name)) {
1461 LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
1462 << " submenu has no menu!");
1466 GuiPopupMenu * qmenu = new GuiPopupMenu(view, *m, true);
1467 view->menuBar()->addMenu(qmenu);
1469 d->name_map_[name] = qmenu;
1474 void Menus::updateMenu(QString const & name)
1476 GuiPopupMenu * qmenu = d->name_map_[name];
1477 LYXERR(Debug::GUI, "GuiPopupMenu::updateView()"
1478 << "\tTriggered menu: " << fromqstr(qmenu->name));
1481 if (qmenu->name.isEmpty())
1484 // Here, We make sure that theLyXFunc points to the correct LyXView.
1485 theLyXFunc().setLyXView(qmenu->view);
1487 Menu const & fromLyxMenu = d->getMenu(qmenu->name);
1488 d->expand(fromLyxMenu, *qmenu->top_level_menu, qmenu->view->buffer());
1490 if (!d->hasMenu(qmenu->top_level_menu->name())) {
1491 LYXERR(Debug::GUI, "\tWARNING: menu seems empty"
1492 << fromqstr(qmenu->top_level_menu->name()));
1494 qmenu->populate(qmenu, qmenu->top_level_menu);
1498 QMenu * Menus::menu(QString const & name)
1500 LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
1501 GuiPopupMenu * menu = d->name_map_.value(name, 0);
1503 LYXERR0("resquested context menu not found: " << fromqstr(name));
1507 } // namespace frontend
1510 #include "Menus_moc.cpp"