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 is the list of last opened file,
99 typically for the File menu. */
101 /** This is the list of opened Documents,
102 typically for the Documents menu. */
104 /** This is the bookmarks */
108 /** This is a list of viewable formats
109 typically for the File->View menu. */
111 /** This is a list of updatable formats
112 typically for the File->Update menu. */
114 /** This is a list of exportable formats
115 typically for the File->Export menu. */
117 /** This is a list of importable formats
118 typically for the File->Export menu. */
120 /** This is the list of elements available
121 * for insertion into document. */
123 /** This is the list of user-configurable
124 insets to insert into document */
126 /** This is the list of XML elements to
127 insert into the document */
129 /** This is the list of floats that we can
130 insert a list for. */
132 /** This is the list of floats that we can
135 /** This is the list of selections that can
140 /** Available branches in document */
142 /** Available citation styles for a given citation */
144 /** Available graphics groups */
148 explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
151 QString const & label,
152 QString const & submenu = QString(),
153 bool optional = false)
154 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
156 LASSERT(kind == Submenu, /**/);
160 QString const & label,
161 FuncRequest const & func,
162 bool optional = false)
163 : kind_(kind), label_(label), func_(func), optional_(optional)
165 func_.origin = FuncRequest::MENU;
168 // boost::shared_ptr<MenuDefinition> needs this apprently...
171 /// The label of a given menuitem
172 QString label() const { return label_.split('|')[0]; }
174 /// The keyboard shortcut (usually underlined in the entry)
175 QString shortcut() const
177 return label_.contains('|') ? label_.split('|')[1] : QString();
179 /// The complete label, with label and shortcut separated by a '|'
180 QString fulllabel() const { return label_;}
181 /// The kind of entry
182 Kind kind() const { return kind_; }
183 /// the action (if relevant)
184 FuncRequest const & func() const { return func_; }
185 /// returns true if the entry should be ommited when disabled
186 bool optional() const { return optional_; }
187 /// returns the status of the lfun associated with this entry
188 FuncStatus const & status() const { return status_; }
189 /// returns the status of the lfun associated with this entry
190 FuncStatus & status() { return status_; }
191 /// returns the status of the lfun associated with this entry
192 void status(FuncStatus const & status) { status_ = status; }
194 ///returns the binding associated to this action.
195 QString binding() const
197 if (kind_ != Command)
199 // Get the keys bound to this action, but keep only the
201 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
203 return toqstr(bindings.begin()->print(KeySequence::ForGui));
205 LYXERR(Debug::KBMAP, "No binding for "
206 << lyxaction.getActionName(func_.action)
207 << '(' << func_.argument() << ')');
211 /// the description of the submenu (if relevant)
212 QString const & submenuname() const { return submenuname_; }
213 /// set the description of the submenu
214 void submenuname(QString const & name) { submenuname_ = name; }
216 bool hasSubmenu() const { return !submenu_.isEmpty(); }
218 MenuDefinition const & submenu() const { return submenu_.at(0); }
219 MenuDefinition & submenu() { return submenu_[0]; }
221 void setSubmenu(MenuDefinition const & menu)
224 submenu_.append(menu);
235 QString submenuname_;
240 /// contains 0 or 1 item.
241 QList<MenuDefinition> submenu_;
245 class MenuDefinition {
248 typedef std::vector<MenuItem> ItemList;
250 typedef ItemList::const_iterator const_iterator;
252 explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
257 QString const & name() const { return name_; }
259 bool empty() const { return items_.empty(); }
260 /// Clear the menu content.
261 void clear() { items_.clear(); }
263 size_t size() const { return items_.size(); }
265 MenuItem const & operator[](size_t) const;
267 const_iterator begin() const { return items_.begin(); }
269 const_iterator end() const { return items_.end(); }
271 // search for func in this menu iteratively, and put menu
273 bool searchMenu(FuncRequest const & func, docstring_list & names)
276 bool hasFunc(FuncRequest const &) const;
277 /// Add the menu item unconditionally
278 void add(MenuItem const & item) { items_.push_back(item); }
279 /// Checks the associated FuncRequest status before adding the
281 void addWithStatusCheck(MenuItem const &);
282 // Check whether the menu shortcuts are unique
283 void checkShortcuts() const;
285 void expandLastfiles();
286 void expandDocuments();
287 void expandBookmarks();
288 void expandFormats(MenuItem::Kind kind, Buffer const * buf);
289 void expandFloatListInsert(Buffer const * buf);
290 void expandFloatInsert(Buffer const * buf);
291 void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
292 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
293 void expandToc(Buffer const * buf);
294 void expandPasteRecent(Buffer const * buf);
295 void expandToolbars();
296 void expandBranches(Buffer const * buf);
297 void expandCiteStyles(BufferView const *);
298 void expandGraphicsGroups(BufferView const *);
306 /// Helper for std::find_if
310 MenuNamesEqual(QString const & name) : name_(name) {}
311 bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
318 typedef std::vector<MenuDefinition> MenuList;
320 typedef MenuList::const_iterator const_iterator;
322 typedef MenuList::iterator iterator;
324 /////////////////////////////////////////////////////////////////////
325 // MenuDefinition implementation
326 /////////////////////////////////////////////////////////////////////
328 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
332 case MenuItem::Command: {
333 FuncStatus status = lyx::getStatus(i.func());
334 if (status.unknown() || (!status.enabled() && i.optional()))
337 items_.back().status(status);
341 case MenuItem::Submenu: {
342 if (i.hasSubmenu()) {
343 bool enabled = false;
344 for (const_iterator cit = i.submenu().begin();
345 cit != i.submenu().end(); ++cit) {
346 if ((cit->kind() == MenuItem::Command
347 || cit->kind() == MenuItem::Submenu)
348 && cit->status().enabled()) {
353 if (enabled || !i.optional()) {
355 items_.back().status().setEnabled(enabled);
363 case MenuItem::Separator:
364 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
374 void MenuDefinition::read(Lexer & lex)
403 LexerKeyword menutags[] = {
404 { "bookmarks", md_bookmarks },
405 { "branches", md_branches },
406 { "charstyles", md_charstyles },
407 { "citestyles", md_citestyles },
408 { "custom", md_custom },
409 { "documents", md_documents },
410 { "elements", md_elements },
411 { "end", md_endmenu },
412 { "exportformats", md_exportformats },
413 { "floatinsert", md_floatinsert },
414 { "floatlistinsert", md_floatlistinsert },
415 { "graphicsgroups", md_graphicsgroups },
416 { "importformats", md_importformats },
418 { "lastfiles", md_lastfiles },
419 { "optitem", md_optitem },
420 { "optsubmenu", md_optsubmenu },
421 { "pasterecent", md_pasterecent },
422 { "separator", md_separator },
423 { "submenu", md_submenu },
425 { "toolbars", md_toolbars },
426 { "updateformats", md_updateformats },
427 { "viewformats", md_viewformats }
430 lex.pushTable(menutags);
431 lex.setContext("MenuDefinition::read: ");
434 bool optional = false;
436 while (lex.isOK() && !quit) {
440 // fallback to md_item
443 docstring const name = translateIfPossible(lex.getDocString());
445 string const command = lex.getString();
446 FuncRequest func = lyxaction.lookupFunc(command);
447 add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
453 add(MenuItem(MenuItem::Separator));
457 add(MenuItem(MenuItem::Lastfiles));
461 add(MenuItem(MenuItem::CharStyles));
465 add(MenuItem(MenuItem::Custom));
469 add(MenuItem(MenuItem::Elements));
473 add(MenuItem(MenuItem::Documents));
477 add(MenuItem(MenuItem::Bookmarks));
481 add(MenuItem(MenuItem::Toc));
485 add(MenuItem(MenuItem::ViewFormats));
488 case md_updateformats:
489 add(MenuItem(MenuItem::UpdateFormats));
492 case md_exportformats:
493 add(MenuItem(MenuItem::ExportFormats));
496 case md_importformats:
497 add(MenuItem(MenuItem::ImportFormats));
500 case md_floatlistinsert:
501 add(MenuItem(MenuItem::FloatListInsert));
505 add(MenuItem(MenuItem::FloatInsert));
509 add(MenuItem(MenuItem::PasteRecent));
513 add(MenuItem(MenuItem::Toolbars));
517 add(MenuItem(MenuItem::Branches));
521 add(MenuItem(MenuItem::CiteStyles));
524 case md_graphicsgroups:
525 add(MenuItem(MenuItem::GraphicsGroups));
530 // fallback to md_submenu
533 docstring const mlabel = translateIfPossible(lex.getDocString());
535 docstring const mname = lex.getDocString();
536 add(MenuItem(MenuItem::Submenu,
537 toqstr(mlabel), toqstr(mname), optional));
547 lex.printError("Unknown menu tag");
555 MenuItem const & MenuDefinition::operator[](size_type i) const
561 bool MenuDefinition::hasFunc(FuncRequest const & func) const
563 for (const_iterator it = begin(), et = end(); it != et; ++it)
564 if (it->func() == func)
570 void MenuDefinition::checkShortcuts() const
572 // This is a quadratic algorithm, but we do not care because
573 // menus are short enough
574 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
575 QString shortcut = it1->shortcut();
576 if (shortcut.isEmpty())
578 if (!it1->label().contains(shortcut))
579 LYXERR0("Menu warning: menu entry \""
581 << "\" does not contain shortcut `"
582 << shortcut << "'.");
583 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
584 if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
585 LYXERR0("Menu warning: menu entries "
586 << '"' << it1->fulllabel()
587 << "\" and \"" << it2->fulllabel()
588 << "\" share the same shortcut.");
595 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
597 const_iterator m = begin();
598 const_iterator m_end = end();
599 for (; m != m_end; ++m) {
600 if (m->kind() == MenuItem::Command && m->func() == func) {
601 names.push_back(qstring_to_ucs4(m->label()));
604 if (m->kind() == MenuItem::Submenu) {
605 names.push_back(qstring_to_ucs4(m->label()));
606 if (!m->hasSubmenu()) {
607 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
608 << m->label() << " name=" << m->submenuname());
612 if (m->submenu().searchMenu(func, names))
621 bool compareFormat(Format const * p1, Format const * p2)
627 QString limitStringLength(docstring const & str)
629 size_t const max_item_length = 45;
631 if (str.size() > max_item_length)
632 return toqstr(str.substr(0, max_item_length - 3) + "...");
638 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
643 graphics::getGraphicsGroups(bv->buffer(), grp);
647 set<string>::const_iterator it = grp.begin();
648 set<string>::const_iterator end = grp.end();
649 add(MenuItem(MenuItem::Command, qt_("No Group"),
650 FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
651 for (; it != end; it++) {
652 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
653 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
657 void MenuDefinition::expandLastfiles()
659 LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
660 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
664 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
665 string const file = lfit->absFilename();
666 QString const label = QString("%1. %2|%3").arg(ii)
667 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
668 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
673 void MenuDefinition::expandDocuments()
675 Buffer * first = theBufferList().first();
680 // We cannot use a for loop as the buffer list cycles.
682 QString label = toqstr(b->fileName().displayName(20));
686 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
687 add(MenuItem(MenuItem::Command, label,
688 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
690 b = theBufferList().next(b);
692 } while (b != first);
694 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
695 FuncRequest(LFUN_NOACTION)));
700 void MenuDefinition::expandBookmarks()
702 lyx::BookmarksSection const & bm = theSession().bookmarks();
704 for (size_t i = 1; i <= bm.size(); ++i) {
706 string const file = bm.bookmark(i).filename.absFilename();
707 QString const label = QString("%1. %2|%3").arg(i)
708 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
709 add(MenuItem(MenuItem::Command, label,
710 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
716 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
718 if (!buf && kind != MenuItem::ImportFormats) {
719 add(MenuItem(MenuItem::Command,
720 qt_("No Document Open!"),
721 FuncRequest(LFUN_NOACTION)));
725 typedef vector<Format const *> Formats;
730 case MenuItem::ImportFormats:
731 formats = theConverters().importableFormats();
732 action = LFUN_BUFFER_IMPORT;
734 case MenuItem::ViewFormats:
735 formats = buf->exportableFormats(true);
736 action = LFUN_BUFFER_VIEW;
738 case MenuItem::UpdateFormats:
739 formats = buf->exportableFormats(true);
740 action = LFUN_BUFFER_UPDATE;
743 formats = buf->exportableFormats(false);
744 action = LFUN_BUFFER_EXPORT;
746 sort(formats.begin(), formats.end(), &compareFormat);
748 Formats::const_iterator fit = formats.begin();
749 Formats::const_iterator end = formats.end();
750 for (; fit != end ; ++fit) {
754 docstring lab = from_utf8((*fit)->prettyname());
755 docstring scut = from_utf8((*fit)->shortcut());
756 docstring const tmplab = lab;
759 lab += char_type('|') + scut;
760 docstring lab_i18n = translateIfPossible(lab);
761 bool const untranslated = (lab == lab_i18n);
762 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
763 QString label = toqstr(lab);
765 // this might happen if the shortcut
766 // has been redefined
767 label = toqstr(translateIfPossible(tmplab));
770 case MenuItem::ImportFormats:
773 case MenuItem::ViewFormats:
774 case MenuItem::ExportFormats:
775 case MenuItem::UpdateFormats:
776 if (!(*fit)->documentFormat())
780 LASSERT(false, /**/);
783 if (!shortcut.isEmpty())
784 label += '|' + shortcut;
787 addWithStatusCheck(MenuItem(MenuItem::Command, label,
788 FuncRequest(action, (*fit)->name())));
790 add(MenuItem(MenuItem::Command, label,
791 FuncRequest(action, (*fit)->name())));
796 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
799 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
800 FuncRequest(LFUN_NOACTION)));
804 FloatList const & floats = buf->params().documentClass().floats();
805 FloatList::const_iterator cit = floats.begin();
806 FloatList::const_iterator end = floats.end();
807 for (; cit != end; ++cit) {
808 addWithStatusCheck(MenuItem(MenuItem::Command,
809 qt_(cit->second.listName()),
810 FuncRequest(LFUN_FLOAT_LIST_INSERT,
811 cit->second.type())));
816 void MenuDefinition::expandFloatInsert(Buffer const * buf)
819 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
820 FuncRequest(LFUN_NOACTION)));
824 FloatList const & floats = buf->params().documentClass().floats();
825 FloatList::const_iterator cit = floats.begin();
826 FloatList::const_iterator end = floats.end();
827 for (; cit != end; ++cit) {
829 QString const label = qt_(cit->second.name());
830 addWithStatusCheck(MenuItem(MenuItem::Command, label,
831 FuncRequest(LFUN_FLOAT_INSERT,
832 cit->second.type())));
837 void MenuDefinition::expandFlexInsert(
838 Buffer const * buf, InsetLayout::InsetLyXType type)
841 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
842 FuncRequest(LFUN_NOACTION)));
845 TextClass::InsetLayouts const & insetLayouts =
846 buf->params().documentClass().insetLayouts();
847 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
848 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
849 for (; cit != end; ++cit) {
850 if (cit->second.lyxtype() == type) {
851 docstring const label = cit->first;
852 addWithStatusCheck(MenuItem(MenuItem::Command,
853 toqstr(translateIfPossible(label)),
854 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
857 // FIXME This is a little clunky.
858 if (items_.empty() && type == InsetLayout::CUSTOM)
859 add(MenuItem(MenuItem::Command,
860 qt_("No custom insets defined!"),
861 FuncRequest(LFUN_NOACTION)));
865 size_t const max_number_of_items = 25;
867 void MenuDefinition::expandToc2(Toc const & toc_list,
868 size_t from, size_t to, int depth)
870 int shortcut_count = 0;
872 // check whether depth is smaller than the smallest depth in toc.
873 int min_depth = 1000;
874 for (size_t i = from; i < to; ++i)
875 min_depth = min(min_depth, toc_list[i].depth());
876 if (min_depth > depth)
879 if (to - from <= max_number_of_items) {
880 for (size_t i = from; i < to; ++i) {
881 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
882 label += limitStringLength(toc_list[i].str());
883 if (toc_list[i].depth() == depth
884 && shortcut_count < 9) {
885 if (label.contains(QString::number(shortcut_count + 1)))
886 label += '|' + QString::number(++shortcut_count);
888 add(MenuItem(MenuItem::Command, label,
889 FuncRequest(toc_list[i].action())));
894 size_t new_pos = pos + 1;
895 while (new_pos < to && toc_list[new_pos].depth() > depth)
898 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
899 label += limitStringLength(toc_list[pos].str());
900 if (toc_list[pos].depth() == depth &&
901 shortcut_count < 9) {
902 if (label.contains(QString::number(shortcut_count + 1)))
903 label += '|' + QString::number(++shortcut_count);
905 if (new_pos == pos + 1) {
906 add(MenuItem(MenuItem::Command,
907 label, FuncRequest(toc_list[pos].action())));
910 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
911 MenuItem item(MenuItem::Submenu, label);
912 item.setSubmenu(sub);
921 void MenuDefinition::expandToc(Buffer const * buf)
923 // To make things very cleanly, we would have to pass buf to
924 // all MenuItem constructors and to expandToc2. However, we
925 // know that all the entries in a TOC will be have status_ ==
926 // OK, so we avoid this unnecessary overhead (JMarc)
929 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
930 FuncRequest(LFUN_NOACTION)));
934 // Add an entry for the master doc if this is a child doc
935 Buffer const * const master = buf->masterBuffer();
937 ParIterator const pit = par_iterator_begin(master->inset());
938 string const arg = convert<string>(pit->id());
939 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
940 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
943 MenuDefinition other_lists;
945 FloatList const & floatlist = buf->params().documentClass().floats();
946 TocList const & toc_list = buf->tocBackend().tocs();
947 TocList::const_iterator cit = toc_list.begin();
948 TocList::const_iterator end = toc_list.end();
949 for (; cit != end; ++cit) {
951 if (cit->first == "tableofcontents")
954 MenuDefinition submenu;
955 if (cit->second.size() >= 30) {
956 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
957 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
959 TocIterator ccit = cit->second.begin();
960 TocIterator eend = cit->second.end();
961 for (; ccit != eend; ++ccit) {
962 submenu.add(MenuItem(MenuItem::Command,
963 limitStringLength(ccit->str()),
964 FuncRequest(ccit->action())));
968 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
969 item.setSubmenu(submenu);
970 if (floatlist.typeExist(cit->first) || cit->first == "child") {
971 // Those two types deserve to be in the main menu.
972 item.setSubmenu(submenu);
975 other_lists.add(item);
977 if (!other_lists.empty()) {
978 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
979 item.setSubmenu(other_lists);
984 cit = toc_list.find("tableofcontents");
986 addWithStatusCheck(MenuItem(MenuItem::Command,
987 qt_("No Table of contents"),
990 expandToc2(cit->second, 0, cit->second.size(), 0);
994 void MenuDefinition::expandPasteRecent(Buffer const * buf)
996 docstring_list const sel = cap::availableSelections(buf);
998 docstring_list::const_iterator cit = sel.begin();
999 docstring_list::const_iterator end = sel.end();
1001 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1002 add(MenuItem(MenuItem::Command, toqstr(*cit),
1003 FuncRequest(LFUN_PASTE, convert<string>(index))));
1008 void MenuDefinition::expandToolbars()
1010 MenuDefinition other_lists;
1011 // extracts the toolbars from the backend
1012 Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1013 Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1014 for (; cit != end; ++cit) {
1015 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1016 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1017 if (guiApp->toolbars().isMainToolbar(cit->name))
1020 other_lists.add(item);
1023 if (!other_lists.empty()) {
1024 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1025 item.setSubmenu(other_lists);
1031 void MenuDefinition::expandBranches(Buffer const * buf)
1034 add(MenuItem(MenuItem::Command,
1035 qt_("No Document Open!"),
1036 FuncRequest(LFUN_NOACTION)));
1040 BufferParams const & params = buf->masterBuffer()->params();
1041 if (params.branchlist().empty()) {
1042 add(MenuItem(MenuItem::Command,
1043 qt_("No Branch in Document!"),
1044 FuncRequest(LFUN_NOACTION)));
1048 BranchList::const_iterator cit = params.branchlist().begin();
1049 BranchList::const_iterator end = params.branchlist().end();
1051 for (int ii = 1; cit != end; ++cit, ++ii) {
1052 docstring label = cit->branch();
1054 label = convert<docstring>(ii) + ". " + label
1055 + char_type('|') + convert<docstring>(ii);
1057 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1058 FuncRequest(LFUN_BRANCH_INSERT,
1064 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1067 add(MenuItem(MenuItem::Command,
1068 qt_("No Document Open!"),
1069 FuncRequest(LFUN_NOACTION)));
1073 Inset const * inset = bv->cursor().nextInset();
1074 if (!inset || inset->lyxCode() != CITE_CODE) {
1075 add(MenuItem(MenuItem::Command,
1076 qt_("No Citation in Scope!"),
1077 FuncRequest(LFUN_NOACTION)));
1080 InsetCommand const * citinset =
1081 static_cast<InsetCommand const *>(inset);
1083 Buffer const * buf = &bv->buffer();
1084 docstring key = citinset->getParam("key");
1085 // we can only handle one key currently
1086 if (contains(key, ','))
1087 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1089 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1090 docstring_list citeStrings =
1091 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1093 docstring_list::const_iterator cit = citeStrings.begin();
1094 docstring_list::const_iterator end = citeStrings.end();
1096 for (int ii = 1; cit != end; ++cit, ++ii) {
1097 docstring label = *cit;
1099 CiteStyle cst = citeStyleList[ii - 1];
1101 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1102 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1103 "changetype " + from_utf8(citationStyleToString(cs)))));
1110 /////////////////////////////////////////////////////////////////////
1111 // Menu::Impl definition and implementation
1112 /////////////////////////////////////////////////////////////////////
1116 /// populates the menu or one of its submenu
1117 /// This is used as a recursive function
1118 void populate(QMenu & qMenu, MenuDefinition const & menu);
1120 /// Only needed for top level menus.
1121 MenuDefinition * top_level_menu;
1124 /// the name of this menu
1130 /// Get a MenuDefinition item label from the menu backend
1131 static QString label(MenuItem const & mi)
1133 QString label = mi.label();
1134 label.replace("&", "&&");
1136 QString shortcut = mi.shortcut();
1137 if (!shortcut.isEmpty()) {
1138 int pos = label.indexOf(shortcut);
1140 //label.insert(pos, 1, char_type('&'));
1141 label.replace(pos, 0, "&");
1144 QString const binding = mi.binding();
1145 if (!binding.isEmpty())
1146 label += '\t' + binding;
1151 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1153 LYXERR(Debug::GUI, "populating menu " << menu.name());
1154 if (menu.size() == 0) {
1155 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1158 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1159 MenuDefinition::const_iterator m = menu.begin();
1160 MenuDefinition::const_iterator end = menu.end();
1161 for (; m != end; ++m) {
1162 if (m->kind() == MenuItem::Separator)
1163 qMenu.addSeparator();
1164 else if (m->kind() == MenuItem::Submenu) {
1165 QMenu * subMenu = qMenu.addMenu(label(*m));
1166 populate(*subMenu, m->submenu());
1167 subMenu->setEnabled(m->status().enabled());
1169 // we have a MenuItem::Command
1170 qMenu.addAction(new Action(view, QIcon(), label(*m),
1171 m->func(), QString(), &qMenu));
1176 /////////////////////////////////////////////////////////////////////
1177 // Menu implementation
1178 /////////////////////////////////////////////////////////////////////
1180 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1181 : QMenu(gv), d(new Menu::Impl)
1183 d->top_level_menu = top_level? new MenuDefinition : 0;
1187 if (d->top_level_menu)
1188 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1194 delete d->top_level_menu;
1199 void Menu::updateView()
1201 guiApp->menus().updateMenu(this);
1205 /////////////////////////////////////////////////////////////////////
1206 // Menus::Impl definition and implementation
1207 /////////////////////////////////////////////////////////////////////
1209 struct Menus::Impl {
1211 bool hasMenu(QString const &) const;
1213 MenuDefinition & getMenu(QString const &);
1215 MenuDefinition const & getMenu(QString const &) const;
1217 /// Expands some special entries of the menu
1218 /** The entries with the following kind are expanded to a
1219 sequence of Command MenuItems: Lastfiles, Documents,
1220 ViewFormats, ExportFormats, UpdateFormats, Branches
1222 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1223 BufferView const *) const;
1225 /// Initialize specific MACOS X menubar
1226 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1228 /// Mac special menu.
1229 /** This defines a menu whose entries list the FuncRequests
1230 that will be removed by expand() in other menus. This is
1231 used by the Qt/Mac code.
1233 NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1234 such that the items will keep accessing the FuncRequests in
1235 the MenuDefinition. While Menus::Impl might be recreated,
1236 we keep mac_special_menu_ in memory by making it static.
1238 static MenuDefinition mac_special_menu_;
1243 MenuDefinition menubar_;
1245 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1247 /// name to menu for \c menu() method.
1252 MenuDefinition Menus::Impl::mac_special_menu_;
1256 Here is what the Qt documentation says about how a menubar is chosen:
1258 1) If the window has a QMenuBar then it is used. 2) If the window
1259 is a modal then its menubar is used. If no menubar is specified
1260 then a default menubar is used (as documented below) 3) If the
1261 window has no parent then the default menubar is used (as
1264 The above 3 steps are applied all the way up the parent window
1265 chain until one of the above are satisifed. If all else fails a
1266 default menubar will be created, the default menubar on Qt/Mac is
1267 an empty menubar, however you can create a different default
1268 menubar by creating a parentless QMenuBar, the first one created
1269 will thus be designated the default menubar, and will be used
1270 whenever a default menubar is needed.
1272 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1273 that this menubar will be used also when one of LyX' dialogs has
1276 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1278 /* Since Qt 4.2, the qt/mac menu code has special code for
1279 specifying the role of a menu entry. However, it does not
1280 work very well with our scheme of creating menus on demand,
1281 and therefore we need to put these entries in a special
1282 invisible menu. (JMarc)
1285 /* The entries of our special mac menu. If we add support for
1286 * special entries in Menus, we could imagine something
1288 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1289 * and therefore avoid hardcoding. I am not sure it is worth
1290 * the hassle, though. (JMarc)
1292 struct MacMenuEntry {
1296 QAction::MenuRole role;
1299 MacMenuEntry entries[] = {
1300 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1301 QAction::AboutRole},
1302 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1303 QAction::PreferencesRole},
1304 {LFUN_RECONFIGURE, "", "Reconfigure",
1305 QAction::ApplicationSpecificRole},
1306 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1308 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1310 // the special menu for Menus. Fill it up only once.
1311 if (mac_special_menu_.size() == 0) {
1312 for (size_t i = 0 ; i < num_entries ; ++i) {
1313 FuncRequest const func(entries[i].action,
1314 from_utf8(entries[i].arg));
1315 mac_special_menu_.add(MenuItem(MenuItem::Command,
1316 entries[i].label, func));
1320 // add the entries to a QMenu that will eventually be empty
1321 // and therefore invisible.
1322 QMenu * qMenu = qmb->addMenu("special");
1323 MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1324 MenuDefinition::const_iterator end = mac_special_menu_.end();
1325 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1326 Action * action = new Action(view, QIcon(), cit->label(),
1327 cit->func(), QString(), qMenu);
1328 action->setMenuRole(entries[i].role);
1329 qMenu->addAction(action);
1334 void Menus::Impl::expand(MenuDefinition const & frommenu,
1335 MenuDefinition & tomenu, BufferView const * bv) const
1337 if (!tomenu.empty())
1340 for (MenuDefinition::const_iterator cit = frommenu.begin();
1341 cit != frommenu.end() ; ++cit) {
1342 Buffer const * buf = bv ? &bv->buffer() : 0;
1343 switch (cit->kind()) {
1344 case MenuItem::Lastfiles:
1345 tomenu.expandLastfiles();
1348 case MenuItem::Documents:
1349 tomenu.expandDocuments();
1352 case MenuItem::Bookmarks:
1353 tomenu.expandBookmarks();
1356 case MenuItem::ImportFormats:
1357 case MenuItem::ViewFormats:
1358 case MenuItem::UpdateFormats:
1359 case MenuItem::ExportFormats:
1360 tomenu.expandFormats(cit->kind(), buf);
1363 case MenuItem::CharStyles:
1364 tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1367 case MenuItem::Custom:
1368 tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1371 case MenuItem::Elements:
1372 tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1375 case MenuItem::FloatListInsert:
1376 tomenu.expandFloatListInsert(buf);
1379 case MenuItem::FloatInsert:
1380 tomenu.expandFloatInsert(buf);
1383 case MenuItem::PasteRecent:
1384 tomenu.expandPasteRecent(buf);
1387 case MenuItem::Toolbars:
1388 tomenu.expandToolbars();
1391 case MenuItem::Branches:
1392 tomenu.expandBranches(buf);
1395 case MenuItem::CiteStyles:
1396 tomenu.expandCiteStyles(bv);
1400 tomenu.expandToc(buf);
1403 case MenuItem::GraphicsGroups:
1404 tomenu.expandGraphicsGroups(bv);
1407 case MenuItem::Submenu: {
1408 MenuItem item(*cit);
1409 item.setSubmenu(MenuDefinition(cit->submenuname()));
1410 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1411 tomenu.addWithStatusCheck(item);
1415 case MenuItem::Separator:
1416 tomenu.addWithStatusCheck(*cit);
1419 case MenuItem::Command:
1420 if (!mac_special_menu_.hasFunc(cit->func()))
1421 tomenu.addWithStatusCheck(*cit);
1425 // we do not want the menu to end with a separator
1426 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1427 tomenu.items_.pop_back();
1429 // Check whether the shortcuts are unique
1430 tomenu.checkShortcuts();
1434 bool Menus::Impl::hasMenu(QString const & name) const
1436 return find_if(menulist_.begin(), menulist_.end(),
1437 MenuNamesEqual(name)) != menulist_.end();
1441 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1443 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1444 MenuNamesEqual(name));
1445 if (cit == menulist_.end())
1446 LYXERR0("No submenu named " << name);
1447 LASSERT(cit != menulist_.end(), /**/);
1452 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1454 iterator it = find_if(menulist_.begin(), menulist_.end(),
1455 MenuNamesEqual(name));
1456 if (it == menulist_.end())
1457 LYXERR0("No submenu named " << name);
1458 LASSERT(it != menulist_.end(), /**/);
1463 /////////////////////////////////////////////////////////////////////
1467 /////////////////////////////////////////////////////////////////////
1469 Menus::Menus() : d(new Impl) {}
1485 void Menus::read(Lexer & lex)
1493 LexerKeyword menutags[] = {
1494 { "end", md_endmenuset },
1495 { "menu", md_menu },
1496 { "menubar", md_menubar }
1499 // consistency check
1500 if (compare_ascii_no_case(lex.getString(), "menuset"))
1501 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1503 lex.pushTable(menutags);
1504 lex.setContext("Menus::read");
1508 while (lex.isOK() && !quit) {
1509 switch (lex.lex()) {
1511 d->menubar_.read(lex);
1515 QString const name = toqstr(lex.getDocString());
1516 if (d->hasMenu(name))
1517 d->getMenu(name).read(lex);
1519 MenuDefinition menu(name);
1521 d->menulist_.push_back(menu);
1529 lex.printError("Unknown menu tag");
1537 bool Menus::searchMenu(FuncRequest const & func,
1538 docstring_list & names) const
1540 MenuDefinition menu;
1541 d->expand(d->menubar_, menu, 0);
1542 return menu.searchMenu(func, names);
1546 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1550 // setup special mac specific menu items, but only do this
1551 // the first time a QMenuBar is created. Otherwise Qt will
1552 // create duplicate items in the application menu. It seems
1553 // that Qt does not remove them when the QMenubar is cleared.
1554 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1555 d->macxMenuBarInit(view, qmb);
1558 // Clear all menubar contents before filling it.
1562 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1564 if (d->menubar_.size() == 0) {
1565 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1566 << d->menubar_.name());
1569 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1571 MenuDefinition menu;
1572 BufferView * bv = 0;
1575 d->expand(d->menubar_, menu, bv);
1577 MenuDefinition::const_iterator m = menu.begin();
1578 MenuDefinition::const_iterator end = menu.end();
1580 for (; m != end; ++m) {
1582 if (m->kind() != MenuItem::Submenu) {
1583 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1587 LYXERR(Debug::GUI, "menu bar item " << m->label()
1588 << " is a submenu named " << m->submenuname());
1590 QString name = m->submenuname();
1591 if (!d->hasMenu(name)) {
1592 LYXERR(Debug::GUI, "\tERROR: " << name
1593 << " submenu has no menu!");
1597 Menu * menu = new Menu(view, m->submenuname(), true);
1598 menu->setTitle(label(*m));
1601 d->name_map_[view][name] = menu;
1606 void Menus::updateMenu(Menu * qmenu)
1608 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1611 if (qmenu->d->name.isEmpty())
1614 // Here, We make sure that theLyXFunc points to the correct LyXView.
1615 theLyXFunc().setLyXView(qmenu->d->view);
1617 if (!d->hasMenu(qmenu->d->name)) {
1618 qmenu->addAction(qt_("No action defined!"));
1619 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1624 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1625 BufferView * bv = 0;
1627 bv = qmenu->d->view->view();
1628 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1629 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1633 Menu * Menus::menu(QString const & name, GuiView & view)
1635 LYXERR(Debug::GUI, "Context menu requested: " << name);
1636 Menu * menu = d->name_map_[&view].value(name, 0);
1637 if (!menu && !name.startsWith("context-")) {
1638 LYXERR0("requested context menu not found: " << name);
1642 menu = new Menu(&view, name, true);
1643 d->name_map_[&view][name] = menu;
1647 } // namespace frontend
1650 #include "moc_Menus.cpp"