3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Asger Alstrup
8 * \author Lars Gullik Bjønnes
9 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * \author Martin Vermeer
14 * Full author contact details are available in file CREDITS.
22 #include "GuiApplication.h"
24 #include "qt_helpers.h"
26 #include "BiblioInfo.h"
27 #include "BranchList.h"
29 #include "BufferList.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "Converter.h"
33 #include "CutAndPaste.h"
35 #include "FloatList.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
41 #include "LyXAction.h"
42 #include "LyX.h" // for lastfiles
44 #include "Paragraph.h"
45 #include "ParIterator.h"
47 #include "TextClass.h"
48 #include "TocBackend.h"
51 #include "insets/Inset.h"
52 #include "insets/InsetCitation.h"
53 #include "insets/InsetGraphics.h"
55 #include "support/lassert.h"
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/docstring_list.h"
59 #include "support/filetools.h"
60 #include "support/gettext.h"
61 #include "support/lstrings.h"
69 #include <boost/shared_ptr.hpp>
75 using namespace lyx::support;
83 // MacOSX specific stuff is at the end.
90 /// The type of elements that can be in a menu
98 /** This type of item explains why something is unavailable. If this
99 menuitem is in a submenu, the submenu is enabled to make sure the
100 user sees the information. */
102 /** This type of item merely shows that there might be a list or
103 something alike at this position, but the list is still empty.
104 If this item is in a submenu, the submenu will not always be
107 /** This is the list of last opened file,
108 typically for the File menu. */
110 /** This is the list of opened Documents,
111 typically for the Documents menu. */
113 /** This is the bookmarks */
117 /** This is a list of viewable formats
118 typically for the File->View menu. */
120 /** This is a list of updatable formats
121 typically for the File->Update menu. */
123 /** This is a list of exportable formats
124 typically for the File->Export menu. */
126 /** This is a list of importable formats
127 typically for the File->Export menu. */
129 /** This is the list of elements available
130 * for insertion into document. */
132 /** This is the list of user-configurable
133 insets to insert into document */
135 /** This is the list of XML elements to
136 insert into the document */
138 /** This is the list of floats that we can
139 insert a list for. */
141 /** This is the list of floats that we can
144 /** This is the list of selections that can
149 /** Available branches in document */
151 /** Available citation styles for a given citation */
153 /** Available graphics groups */
157 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
160 QString const & label,
161 QString const & submenu = QString(),
162 bool optional = false)
163 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
165 LASSERT(kind == Submenu || kind == Help || kind == Info, /**/);
169 QString const & label,
170 FuncRequest const & func,
171 bool optional = false)
172 : kind_(kind), label_(label), func_(func), optional_(optional)
174 func_.origin = FuncRequest::MENU;
177 // boost::shared_ptr<MenuDefinition> needs this apprently...
180 /// The label of a given menuitem
181 QString label() const { return label_.split('|')[0]; }
183 /// The keyboard shortcut (usually underlined in the entry)
184 QString shortcut() const
186 return label_.contains('|') ? label_.split('|')[1] : QString();
188 /// The complete label, with label and shortcut separated by a '|'
189 QString fulllabel() const { return label_;}
190 /// The kind of entry
191 Kind kind() const { return kind_; }
192 /// the action (if relevant)
193 FuncRequest const & func() const { return func_; }
194 /// returns true if the entry should be ommited when disabled
195 bool optional() const { return optional_; }
196 /// returns the status of the lfun associated with this entry
197 FuncStatus const & status() const { return status_; }
198 /// returns the status of the lfun associated with this entry
199 FuncStatus & status() { return status_; }
200 /// returns the status of the lfun associated with this entry
201 void status(FuncStatus const & status) { status_ = status; }
203 ///returns the binding associated to this action.
204 QString binding() const
206 if (kind_ != Command)
208 // Get the keys bound to this action, but keep only the
210 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
212 return toqstr(bindings.begin()->print(KeySequence::ForGui));
214 LYXERR(Debug::KBMAP, "No binding for "
215 << lyxaction.getActionName(func_.action)
216 << '(' << func_.argument() << ')');
220 /// the description of the submenu (if relevant)
221 QString const & submenuname() const { return submenuname_; }
222 /// set the description of the submenu
223 void submenuname(QString const & name) { submenuname_ = name; }
225 bool hasSubmenu() const { return !submenu_.isEmpty(); }
227 MenuDefinition const & submenu() const { return submenu_.at(0); }
228 MenuDefinition & submenu() { return submenu_[0]; }
230 void setSubmenu(MenuDefinition const & menu)
233 submenu_.append(menu);
244 QString submenuname_;
249 /// contains 0 or 1 item.
250 QList<MenuDefinition> submenu_;
254 class MenuDefinition {
257 typedef std::vector<MenuItem> ItemList;
259 typedef ItemList::const_iterator const_iterator;
261 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
266 QString const & name() const { return name_; }
268 bool empty() const { return items_.empty(); }
269 /// Clear the menu content.
270 void clear() { items_.clear(); }
272 size_t size() const { return items_.size(); }
274 MenuItem const & operator[](size_t) const;
276 const_iterator begin() const { return items_.begin(); }
278 const_iterator end() const { return items_.end(); }
280 // search for func in this menu iteratively, and put menu
282 bool searchMenu(FuncRequest const & func, docstring_list & names)
285 bool hasFunc(FuncRequest const &) const;
286 /// Add the menu item unconditionally
287 void add(MenuItem const & item) { items_.push_back(item); }
288 /// Checks the associated FuncRequest status before adding the
290 void addWithStatusCheck(MenuItem const &);
291 // Check whether the menu shortcuts are unique
292 void checkShortcuts() const;
294 void expandLastfiles();
295 void expandDocuments();
296 void expandBookmarks();
297 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
298 void expandFloatListInsert(Buffer const * buf);
299 void expandFloatInsert(Buffer const * buf);
300 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
301 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
302 void expandToc(Buffer const * buf);
303 void expandPasteRecent(Buffer const * buf);
304 void expandToolbars();
305 void expandBranches(Buffer const * buf);
306 void expandCiteStyles(BufferView const *);
307 void expandGraphicsGroups(BufferView const *);
315 /// Helper for std::find_if
319 MenuNamesEqual(QString const & name) : name_(name) {}
320 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
327 typedef std::vector<MenuDefinition> MenuList;
329 typedef MenuList::const_iterator const_iterator;
331 typedef MenuList::iterator iterator;
333 /////////////////////////////////////////////////////////////////////
334 // MenuDefinition implementation
335 /////////////////////////////////////////////////////////////////////
337 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
341 case MenuItem::Command: {
342 FuncStatus status = lyx::getStatus(i.func());
343 if (status.unknown() || (!status.enabled() && i.optional()))
346 items_.back().status(status);
350 case MenuItem::Submenu: {
351 bool enabled = false;
352 if (i.hasSubmenu()) {
353 for (const_iterator cit = i.submenu().begin();
354 cit != i.submenu().end(); ++cit) {
355 // Only these kind of items affect the status of the submenu
356 if ((cit->kind() == MenuItem::Command
357 || cit->kind() == MenuItem::Submenu
358 || cit->kind() == MenuItem::Help)
359 && cit->status().enabled()) {
365 if (enabled || !i.optional()) {
367 items_.back().status().setEnabled(enabled);
372 case MenuItem::Separator:
373 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
383 void MenuDefinition::read(Lexer & lex)
412 LexerKeyword menutags[] = {
413 { "bookmarks", md_bookmarks },
414 { "branches", md_branches },
415 { "charstyles", md_charstyles },
416 { "citestyles", md_citestyles },
417 { "custom", md_custom },
418 { "documents", md_documents },
419 { "elements", md_elements },
420 { "end", md_endmenu },
421 { "exportformats", md_exportformats },
422 { "floatinsert", md_floatinsert },
423 { "floatlistinsert", md_floatlistinsert },
424 { "graphicsgroups", md_graphicsgroups },
425 { "importformats", md_importformats },
427 { "lastfiles", md_lastfiles },
428 { "optitem", md_optitem },
429 { "optsubmenu", md_optsubmenu },
430 { "pasterecent", md_pasterecent },
431 { "separator", md_separator },
432 { "submenu", md_submenu },
434 { "toolbars", md_toolbars },
435 { "updateformats", md_updateformats },
436 { "viewformats", md_viewformats }
439 lex.pushTable(menutags);
440 lex.setContext("MenuDefinition::read: ");
443 bool optional = false;
445 while (lex.isOK() && !quit) {
449 // fallback to md_item
452 docstring const name = translateIfPossible(lex.getDocString());
454 string const command = lex.getString();
455 FuncRequest func = lyxaction.lookupFunc(command);
456 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
462 add(MenuItem(MenuItem::Separator));
466 add(MenuItem(MenuItem::Lastfiles));
470 add(MenuItem(MenuItem::CharStyles));
474 add(MenuItem(MenuItem::Custom));
478 add(MenuItem(MenuItem::Elements));
482 add(MenuItem(MenuItem::Documents));
486 add(MenuItem(MenuItem::Bookmarks));
490 add(MenuItem(MenuItem::Toc));
494 add(MenuItem(MenuItem::ViewFormats));
497 case md_updateformats:
498 add(MenuItem(MenuItem::UpdateFormats));
501 case md_exportformats:
502 add(MenuItem(MenuItem::ExportFormats));
505 case md_importformats:
506 add(MenuItem(MenuItem::ImportFormats));
509 case md_floatlistinsert:
510 add(MenuItem(MenuItem::FloatListInsert));
514 add(MenuItem(MenuItem::FloatInsert));
518 add(MenuItem(MenuItem::PasteRecent));
522 add(MenuItem(MenuItem::Toolbars));
526 add(MenuItem(MenuItem::Branches));
530 add(MenuItem(MenuItem::CiteStyles));
533 case md_graphicsgroups:
534 add(MenuItem(MenuItem::GraphicsGroups));
539 // fallback to md_submenu
542 docstring const mlabel = translateIfPossible(lex.getDocString());
544 docstring const mname = lex.getDocString();
545 add(MenuItem(MenuItem::Submenu,
546 toqstr(mlabel), toqstr(mname), optional));
556 lex.printError("Unknown menu tag");
564 MenuItem const & MenuDefinition::operator[](size_type i) const
570 bool MenuDefinition::hasFunc(FuncRequest const & func) const
572 for (const_iterator it = begin(), et = end(); it != et; ++it)
573 if (it->func() == func)
579 void MenuDefinition::checkShortcuts() const
581 // This is a quadratic algorithm, but we do not care because
582 // menus are short enough
583 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
584 QString shortcut = it1->shortcut();
585 if (shortcut.isEmpty())
587 if (!it1->label().contains(shortcut))
588 LYXERR0("Menu warning: menu entry \""
590 << "\" does not contain shortcut `"
591 << shortcut << "'.");
592 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
593 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
594 LYXERR0("Menu warning: menu entries "
595 << '"' << it1->fulllabel()
596 << "\" and \"" << it2->fulllabel()
597 << "\" share the same shortcut.");
604 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
606 const_iterator m = begin();
607 const_iterator m_end = end();
608 for (; m != m_end; ++m) {
609 if (m->kind() == MenuItem::Command && m->func() == func) {
610 names.push_back(qstring_to_ucs4(m->label()));
613 if (m->kind() == MenuItem::Submenu) {
614 names.push_back(qstring_to_ucs4(m->label()));
615 if (!m->hasSubmenu()) {
616 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
617 << m->label() << " name=" << m->submenuname());
621 if (m->submenu().searchMenu(func, names))
630 bool compareFormat(Format const * p1, Format const * p2)
636 QString limitStringLength(docstring const & str)
638 size_t const max_item_length = 45;
640 if (str.size() > max_item_length)
641 return toqstr(str.substr(0, max_item_length - 3) + "...");
647 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
652 graphics::getGraphicsGroups(bv->buffer(), grp);
656 set<string>::const_iterator it = grp.begin();
657 set<string>::const_iterator end = grp.end();
658 add(MenuItem(MenuItem::Command, qt_("No Group"),
659 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
660 for (; it != end; it++) {
661 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
662 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
666 void MenuDefinition::expandLastfiles()
668 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
669 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
673 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
674 string const file = lfit->absFilename();
675 QString const label = QString("%1. %2|%3").arg(ii)
676 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
677 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
682 void MenuDefinition::expandDocuments()
684 Buffer * first = theBufferList().first();
689 // We cannot use a for loop as the buffer list cycles.
691 QString label = toqstr(b->fileName().displayName(20));
695 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
696 add(MenuItem(MenuItem::Command, label,
697 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
699 b = theBufferList().next(b);
701 } while (b != first);
703 add(MenuItem(MenuItem::Info, qt_("<No documents open>")));
707 void MenuDefinition::expandBookmarks()
709 lyx::BookmarksSection const & bm = theSession().bookmarks();
712 for (size_t i = 1; i <= bm.size(); ++i) {
714 string const file = bm.bookmark(i).filename.absFilename();
715 QString const label = QString("%1. %2|%3").arg(i)
716 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
717 add(MenuItem(MenuItem::Command, label,
718 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
723 add(MenuItem(MenuItem::Info, qt_("<No bookmarks saved yet>")));
727 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
729 if (!buf && kind != MenuItem::ImportFormats)
732 typedef vector<Format const *> Formats;
737 case MenuItem::ImportFormats:
738 formats = theConverters().importableFormats();
739 action = LFUN_BUFFER_IMPORT;
741 case MenuItem::ViewFormats:
742 formats = buf->exportableFormats(true);
743 action = LFUN_BUFFER_VIEW;
745 case MenuItem::UpdateFormats:
746 formats = buf->exportableFormats(true);
747 action = LFUN_BUFFER_UPDATE;
750 formats = buf->exportableFormats(false);
751 action = LFUN_BUFFER_EXPORT;
753 sort(formats.begin(), formats.end(), &compareFormat);
755 Formats::const_iterator fit = formats.begin();
756 Formats::const_iterator end = formats.end();
757 for (; fit != end ; ++fit) {
761 docstring lab = from_utf8((*fit)->prettyname());
762 docstring scut = from_utf8((*fit)->shortcut());
763 docstring const tmplab = lab;
766 lab += char_type('|') + scut;
767 docstring lab_i18n = translateIfPossible(lab);
768 bool const untranslated = (lab == lab_i18n);
769 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
770 QString label = toqstr(lab);
772 // this might happen if the shortcut
773 // has been redefined
774 label = toqstr(translateIfPossible(tmplab));
777 case MenuItem::ImportFormats:
780 case MenuItem::ViewFormats:
781 case MenuItem::ExportFormats:
782 case MenuItem::UpdateFormats:
783 if (!(*fit)->documentFormat())
787 LASSERT(false, /**/);
790 if (!shortcut.isEmpty())
791 label += '|' + shortcut;
794 addWithStatusCheck(MenuItem(MenuItem::Command, label,
795 FuncRequest(action, (*fit)->name())));
797 add(MenuItem(MenuItem::Command, label,
798 FuncRequest(action, (*fit)->name())));
803 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
808 FloatList const & floats = buf->params().documentClass().floats();
809 FloatList::const_iterator cit = floats.begin();
810 FloatList::const_iterator end = floats.end();
811 for (; cit != end; ++cit) {
812 addWithStatusCheck(MenuItem(MenuItem::Command,
813 qt_(cit->second.listName()),
814 FuncRequest(LFUN_FLOAT_LIST_INSERT,
815 cit->second.type())));
820 void MenuDefinition::expandFloatInsert(Buffer const * buf)
825 FloatList const & floats = buf->params().documentClass().floats();
826 FloatList::const_iterator cit = floats.begin();
827 FloatList::const_iterator end = floats.end();
828 for (; cit != end; ++cit) {
830 QString const label = qt_(cit->second.name());
831 addWithStatusCheck(MenuItem(MenuItem::Command, label,
832 FuncRequest(LFUN_FLOAT_INSERT,
833 cit->second.type())));
838 void MenuDefinition::expandFlexInsert(
839 Buffer const * buf, InsetLayout::InsetLyXType type)
844 TextClass::InsetLayouts const & insetLayouts =
845 buf->params().documentClass().insetLayouts();
846 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
847 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
848 for (; cit != end; ++cit) {
849 if (cit->second.lyxtype() == type) {
850 docstring const label = cit->first;
851 addWithStatusCheck(MenuItem(MenuItem::Command,
852 toqstr(translateIfPossible(label)),
853 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
856 // FIXME This is a little clunky.
857 if (items_.empty() && type == InsetLayout::CUSTOM)
858 add(MenuItem(MenuItem::Help, qt_("No custom insets defined!")));
862 size_t const max_number_of_items = 25;
864 void MenuDefinition::expandToc2(Toc const & toc_list,
865 size_t from, size_t to, int depth)
867 int shortcut_count = 0;
869 // check whether depth is smaller than the smallest depth in toc.
870 int min_depth = 1000;
871 for (size_t i = from; i < to; ++i)
872 min_depth = min(min_depth, toc_list[i].depth());
873 if (min_depth > depth)
876 if (to - from <= max_number_of_items) {
877 for (size_t i = from; i < to; ++i) {
878 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
879 label += limitStringLength(toc_list[i].str());
880 if (toc_list[i].depth() == depth
881 && shortcut_count < 9) {
882 if (label.contains(QString::number(shortcut_count + 1)))
883 label += '|' + QString::number(++shortcut_count);
885 add(MenuItem(MenuItem::Command, label,
886 FuncRequest(toc_list[i].action())));
891 size_t new_pos = pos + 1;
892 while (new_pos < to && toc_list[new_pos].depth() > depth)
895 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
896 label += limitStringLength(toc_list[pos].str());
897 if (toc_list[pos].depth() == depth &&
898 shortcut_count < 9) {
899 if (label.contains(QString::number(shortcut_count + 1)))
900 label += '|' + QString::number(++shortcut_count);
902 if (new_pos == pos + 1) {
903 add(MenuItem(MenuItem::Command,
904 label, FuncRequest(toc_list[pos].action())));
907 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
908 MenuItem item(MenuItem::Submenu, label);
909 item.setSubmenu(sub);
918 void MenuDefinition::expandToc(Buffer const * buf)
920 // To make things very cleanly, we would have to pass buf to
921 // all MenuItem constructors and to expandToc2. However, we
922 // know that all the entries in a TOC will be have status_ ==
923 // OK, so we avoid this unnecessary overhead (JMarc)
926 add(MenuItem(MenuItem::Info, qt_("<No document open>")));
930 // Add an entry for the master doc if this is a child doc
931 Buffer const * const master = buf->masterBuffer();
933 ParIterator const pit = par_iterator_begin(master->inset());
934 string const arg = convert<string>(pit->id());
935 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
936 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
939 MenuDefinition other_lists;
941 FloatList const & floatlist = buf->params().documentClass().floats();
942 TocList const & toc_list = buf->tocBackend().tocs();
943 TocList::const_iterator cit = toc_list.begin();
944 TocList::const_iterator end = toc_list.end();
945 for (; cit != end; ++cit) {
947 if (cit->first == "tableofcontents")
950 MenuDefinition submenu;
951 if (cit->second.size() >= 30) {
952 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
953 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
955 TocIterator ccit = cit->second.begin();
956 TocIterator eend = cit->second.end();
957 for (; ccit != eend; ++ccit) {
958 submenu.add(MenuItem(MenuItem::Command,
959 limitStringLength(ccit->str()),
960 FuncRequest(ccit->action())));
964 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
965 item.setSubmenu(submenu);
966 if (floatlist.typeExist(cit->first) || cit->first == "child") {
967 // Those two types deserve to be in the main menu.
968 item.setSubmenu(submenu);
971 other_lists.add(item);
973 if (!other_lists.empty()) {
974 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
975 item.setSubmenu(other_lists);
980 cit = toc_list.find("tableofcontents");
982 LYXERR(Debug::GUI, "No table of contents.");
984 if (cit->second.size() > 0 )
985 expandToc2(cit->second, 0, cit->second.size(), 0);
987 add(MenuItem(MenuItem::Info, qt_("<Empty table of contents>")));
992 void MenuDefinition::expandPasteRecent(Buffer const * buf)
994 docstring_list const sel = cap::availableSelections(buf);
996 docstring_list::const_iterator cit = sel.begin();
997 docstring_list::const_iterator end = sel.end();
999 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1000 add(MenuItem(MenuItem::Command, toqstr(*cit),
1001 FuncRequest(LFUN_PASTE, convert<string>(index))));
1006 void MenuDefinition::expandToolbars()
1008 MenuDefinition other_lists;
1009 // extracts the toolbars from the backend
1010 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1011 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1012 for (; cit != end; ++cit) {
1013 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1014 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1015 if (guiApp->toolbars().isMainToolbar(cit->name))
1018 other_lists.add(item);
1021 if (!other_lists.empty()) {
1022 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1023 item.setSubmenu(other_lists);
1029 void MenuDefinition::expandBranches(Buffer const * buf)
1034 BufferParams const & params = buf->masterBuffer()->params();
1035 if (params.branchlist().empty()) {
1036 add(MenuItem(MenuItem::Help, qt_("No branches set for document!")));
1040 BranchList::const_iterator cit = params.branchlist().begin();
1041 BranchList::const_iterator end = params.branchlist().end();
1043 for (int ii = 1; cit != end; ++cit, ++ii) {
1044 docstring label = cit->branch();
1046 label = convert<docstring>(ii) + ". " + label
1047 + char_type('|') + convert<docstring>(ii);
1049 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1050 FuncRequest(LFUN_BRANCH_INSERT,
1056 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1061 Inset const * inset = bv->cursor().nextInset();
1062 if (!inset || inset->lyxCode() != CITE_CODE) {
1063 add(MenuItem(MenuItem::Command,
1064 qt_("No Citation in Scope!"),
1065 FuncRequest(LFUN_NOACTION)));
1068 InsetCommand const * citinset =
1069 static_cast<InsetCommand const *>(inset);
1071 Buffer const * buf = &bv->buffer();
1072 docstring key = citinset->getParam("key");
1073 // we can only handle one key currently
1074 if (contains(key, ','))
1075 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1077 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1078 docstring_list citeStrings =
1079 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1081 docstring_list::const_iterator cit = citeStrings.begin();
1082 docstring_list::const_iterator end = citeStrings.end();
1084 for (int ii = 1; cit != end; ++cit, ++ii) {
1085 docstring label = *cit;
1087 CiteStyle cst = citeStyleList[ii - 1];
1089 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1090 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1091 "changetype " + from_utf8(citationStyleToString(cs)))));
1098 /////////////////////////////////////////////////////////////////////
1099 // Menu::Impl definition and implementation
1100 /////////////////////////////////////////////////////////////////////
1104 /// populates the menu or one of its submenu
1105 /// This is used as a recursive function
1106 void populate(QMenu & qMenu, MenuDefinition const & menu);
1108 /// Only needed for top level menus.
1109 MenuDefinition * top_level_menu;
1112 /// the name of this menu
1118 /// Get a MenuDefinition item label from the menu backend
1119 static QString label(MenuItem const & mi)
1121 QString label = mi.label();
1122 label.replace("&", "&&");
1124 QString shortcut = mi.shortcut();
1125 if (!shortcut.isEmpty()) {
1126 int pos = label.indexOf(shortcut);
1128 //label.insert(pos, 1, char_type('&'));
1129 label.replace(pos, 0, "&");
1132 QString const binding = mi.binding();
1133 if (!binding.isEmpty())
1134 label += '\t' + binding;
1139 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1141 LYXERR(Debug::GUI, "populating menu " << menu.name());
1142 if (menu.size() == 0) {
1143 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1146 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1147 MenuDefinition::const_iterator m = menu.begin();
1148 MenuDefinition::const_iterator end = menu.end();
1149 for (; m != end; ++m) {
1150 if (m->kind() == MenuItem::Separator)
1151 qMenu.addSeparator();
1152 else if (m->kind() == MenuItem::Submenu) {
1153 QMenu * subMenu = qMenu.addMenu(label(*m));
1154 populate(*subMenu, m->submenu());
1155 subMenu->setEnabled(m->status().enabled());
1157 // we have a MenuItem::Command
1158 qMenu.addAction(new Action(view, QIcon(), label(*m),
1159 m->func(), QString(), &qMenu));
1164 /////////////////////////////////////////////////////////////////////
1165 // Menu implementation
1166 /////////////////////////////////////////////////////////////////////
1168 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1169 : QMenu(gv), d(new Menu::Impl)
1171 d->top_level_menu = top_level? new MenuDefinition : 0;
1175 if (d->top_level_menu)
1176 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1182 delete d->top_level_menu;
1187 void Menu::updateView()
1189 guiApp->menus().updateMenu(this);
1193 /////////////////////////////////////////////////////////////////////
1194 // Menus::Impl definition and implementation
1195 /////////////////////////////////////////////////////////////////////
1197 struct Menus::Impl {
1199 bool hasMenu(QString const &) const;
1201 MenuDefinition & getMenu(QString const &);
1203 MenuDefinition const & getMenu(QString const &) const;
1205 /// Expands some special entries of the menu
1206 /** The entries with the following kind are expanded to a
1207 sequence of Command MenuItems: Lastfiles, Documents,
1208 ViewFormats, ExportFormats, UpdateFormats, Branches
1210 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1211 BufferView const *) const;
1213 /// Initialize specific MACOS X menubar
1214 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1216 /// Mac special menu.
1217 /** This defines a menu whose entries list the FuncRequests
1218 that will be removed by expand() in other menus. This is
1219 used by the Qt/Mac code.
1221 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1222 such that the items will keep accessing the FuncRequests in
1223 the MenuDefinition. While Menus::Impl might be recreated,
1224 we keep mac_special_menu_ in memory by making it static.
1226 static MenuDefinition mac_special_menu_;
1231 MenuDefinition menubar_;
1233 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1235 /// name to menu for \c menu() method.
1240 MenuDefinition Menus::Impl::mac_special_menu_;
1244 Here is what the Qt documentation says about how a menubar is chosen:
1246 1) If the window has a QMenuBar then it is used. 2) If the window
1247 is a modal then its menubar is used. If no menubar is specified
1248 then a default menubar is used (as documented below) 3) If the
1249 window has no parent then the default menubar is used (as
1252 The above 3 steps are applied all the way up the parent window
1253 chain until one of the above are satisifed. If all else fails a
1254 default menubar will be created, the default menubar on Qt/Mac is
1255 an empty menubar, however you can create a different default
1256 menubar by creating a parentless QMenuBar, the first one created
1257 will thus be designated the default menubar, and will be used
1258 whenever a default menubar is needed.
1260 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1261 that this menubar will be used also when one of LyX' dialogs has
1264 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1266 /* Since Qt 4.2, the qt/mac menu code has special code for
1267 specifying the role of a menu entry. However, it does not
1268 work very well with our scheme of creating menus on demand,
1269 and therefore we need to put these entries in a special
1270 invisible menu. (JMarc)
1273 /* The entries of our special mac menu. If we add support for
1274 * special entries in Menus, we could imagine something
1276 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1277 * and therefore avoid hardcoding. I am not sure it is worth
1278 * the hassle, though. (JMarc)
1280 struct MacMenuEntry {
1284 QAction::MenuRole role;
1287 MacMenuEntry entries[] = {
1288 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1289 QAction::AboutRole},
1290 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1291 QAction::PreferencesRole},
1292 {LFUN_RECONFIGURE, "", "Reconfigure",
1293 QAction::ApplicationSpecificRole},
1294 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1296 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1298 // the special menu for Menus. Fill it up only once.
1299 if (mac_special_menu_.size() == 0) {
1300 for (size_t i = 0 ; i < num_entries ; ++i) {
1301 FuncRequest const func(entries[i].action,
1302 from_utf8(entries[i].arg));
1303 mac_special_menu_.add(MenuItem(MenuItem::Command,
1304 entries[i].label, func));
1308 // add the entries to a QMenu that will eventually be empty
1309 // and therefore invisible.
1310 QMenu * qMenu = qmb->addMenu("special");
1311 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1312 MenuDefinition::const_iterator end = mac_special_menu_.end();
1313 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1314 Action * action = new Action(view, QIcon(), cit->label(),
1315 cit->func(), QString(), qMenu);
1316 action->setMenuRole(entries[i].role);
1317 qMenu->addAction(action);
1322 void Menus::Impl::expand(MenuDefinition const & frommenu,
1323 MenuDefinition & tomenu, BufferView const * bv) const
1325 if (!tomenu.empty())
1328 for (MenuDefinition::const_iterator cit = frommenu.begin();
1329 cit != frommenu.end() ; ++cit) {
1330 Buffer const * buf = bv ? &bv->buffer() : 0;
1331 switch (cit->kind()) {
1332 case MenuItem::Lastfiles:
1333 tomenu.expandLastfiles();
1336 case MenuItem::Documents:
1337 tomenu.expandDocuments();
1340 case MenuItem::Bookmarks:
1341 tomenu.expandBookmarks();
1344 case MenuItem::ImportFormats:
1345 case MenuItem::ViewFormats:
1346 case MenuItem::UpdateFormats:
1347 case MenuItem::ExportFormats:
1348 tomenu.expandFormats(cit->kind(), buf);
1351 case MenuItem::CharStyles:
1352 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1355 case MenuItem::Custom:
1356 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1359 case MenuItem::Elements:
1360 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1363 case MenuItem::FloatListInsert:
1364 tomenu.expandFloatListInsert(buf);
1367 case MenuItem::FloatInsert:
1368 tomenu.expandFloatInsert(buf);
1371 case MenuItem::PasteRecent:
1372 tomenu.expandPasteRecent(buf);
1375 case MenuItem::Toolbars:
1376 tomenu.expandToolbars();
1379 case MenuItem::Branches:
1380 tomenu.expandBranches(buf);
1383 case MenuItem::CiteStyles:
1384 tomenu.expandCiteStyles(bv);
1388 tomenu.expandToc(buf);
1391 case MenuItem::GraphicsGroups:
1392 tomenu.expandGraphicsGroups(bv);
1395 case MenuItem::Submenu: {
1396 MenuItem item(*cit);
1397 item.setSubmenu(MenuDefinition(cit->submenuname()));
1398 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1399 tomenu.addWithStatusCheck(item);
1403 case MenuItem::Info:
1404 case MenuItem::Help:
1405 case MenuItem::Separator:
1406 tomenu.addWithStatusCheck(*cit);
1409 case MenuItem::Command:
1410 if (!mac_special_menu_.hasFunc(cit->func()))
1411 tomenu.addWithStatusCheck(*cit);
1415 // we do not want the menu to end with a separator
1416 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1417 tomenu.items_.pop_back();
1419 // Check whether the shortcuts are unique
1420 tomenu.checkShortcuts();
1424 bool Menus::Impl::hasMenu(QString const & name) const
1426 return find_if(menulist_.begin(), menulist_.end(),
1427 MenuNamesEqual(name)) != menulist_.end();
1431 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1433 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1434 MenuNamesEqual(name));
1435 if (cit == menulist_.end())
1436 LYXERR0("No submenu named " << name);
1437 LASSERT(cit != menulist_.end(), /**/);
1442 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1444 iterator it = find_if(menulist_.begin(), menulist_.end(),
1445 MenuNamesEqual(name));
1446 if (it == menulist_.end())
1447 LYXERR0("No submenu named " << name);
1448 LASSERT(it != menulist_.end(), /**/);
1453 /////////////////////////////////////////////////////////////////////
1457 /////////////////////////////////////////////////////////////////////
1459 Menus::Menus() : d(new Impl) {}
1475 void Menus::read(Lexer & lex)
1483 LexerKeyword menutags[] = {
1484 { "end", md_endmenuset },
1485 { "menu", md_menu },
1486 { "menubar", md_menubar }
1489 // consistency check
1490 if (compare_ascii_no_case(lex.getString(), "menuset"))
1491 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1493 lex.pushTable(menutags);
1494 lex.setContext("Menus::read");
1498 while (lex.isOK() && !quit) {
1499 switch (lex.lex()) {
1501 d->menubar_.read(lex);
1505 QString const name = toqstr(lex.getDocString());
1506 if (d->hasMenu(name))
1507 d->getMenu(name).read(lex);
1509 MenuDefinition menu(name);
1511 d->menulist_.push_back(menu);
1519 lex.printError("Unknown menu tag");
1527 bool Menus::searchMenu(FuncRequest const & func,
1528 docstring_list & names) const
1530 MenuDefinition menu;
1531 d->expand(d->menubar_, menu, 0);
1532 return menu.searchMenu(func, names);
1536 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1540 // setup special mac specific menu items, but only do this
1541 // the first time a QMenuBar is created. Otherwise Qt will
1542 // create duplicate items in the application menu. It seems
1543 // that Qt does not remove them when the QMenubar is cleared.
1544 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1545 d->macxMenuBarInit(view, qmb);
1548 // Clear all menubar contents before filling it.
1552 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1554 if (d->menubar_.size() == 0) {
1555 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1556 << d->menubar_.name());
1559 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1561 MenuDefinition menu;
1562 BufferView * bv = 0;
1565 d->expand(d->menubar_, menu, bv);
1567 MenuDefinition::const_iterator m = menu.begin();
1568 MenuDefinition::const_iterator end = menu.end();
1570 for (; m != end; ++m) {
1572 if (m->kind() != MenuItem::Submenu) {
1573 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1577 LYXERR(Debug::GUI, "menu bar item " << m->label()
1578 << " is a submenu named " << m->submenuname());
1580 QString name = m->submenuname();
1581 if (!d->hasMenu(name)) {
1582 LYXERR(Debug::GUI, "\tERROR: " << name
1583 << " submenu has no menu!");
1587 Menu * menu = new Menu(view, m->submenuname(), true);
1588 menu->setTitle(label(*m));
1591 d->name_map_[view][name] = menu;
1596 void Menus::updateMenu(Menu * qmenu)
1598 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1601 if (qmenu->d->name.isEmpty())
1604 // Here, We make sure that theLyXFunc points to the correct LyXView.
1605 theLyXFunc().setLyXView(qmenu->d->view);
1607 if (!d->hasMenu(qmenu->d->name)) {
1608 qmenu->addAction(qt_("No action defined!"));
1609 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1614 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1615 BufferView * bv = 0;
1617 bv = qmenu->d->view->view();
1618 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1619 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1623 Menu * Menus::menu(QString const & name, GuiView & view)
1625 LYXERR(Debug::GUI, "Context menu requested: " << name);
1626 Menu * menu = d->name_map_[&view].value(name, 0);
1627 if (!menu && !name.startsWith("context-")) {
1628 LYXERR0("requested context menu not found: " << name);
1632 menu = new Menu(&view, name, true);
1633 d->name_map_[&view][name] = menu;
1637 } // namespace frontend
1640 #include "moc_Menus.cpp"