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"
49 #include "ToolbarBackend.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, std::string s);
292 void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
293 void expandToc(Buffer const * buf);
294 void expandPasteRecent();
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().enabled(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)
642 Cursor const & cur = bv->cursor();
643 Buffer const & buf = bv->buffer();
645 InsetGraphics::getGraphicsGroups(buf, grp);
646 set<string>::const_iterator it = grp.begin();
647 set<string>::const_iterator end = grp.end();
651 InsetGraphics * ins = InsetGraphics::getCurrentGraphicsInset(cur);
654 add(MenuItem(MenuItem::Separator));
655 if (!ins->getParams().groupId.empty())
656 add(MenuItem(MenuItem::Command, qt_("Clear group"), FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
657 for (; it != end; it++) {
658 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it),
659 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
663 void MenuDefinition::expandLastfiles()
665 LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
666 LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
670 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
671 string const file = lfit->absFilename();
672 QString const label = QString("%1. %2|%3").arg(ii)
673 .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
674 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
679 void MenuDefinition::expandDocuments()
681 Buffer * first = theBufferList().first();
686 // We cannot use a for loop as the buffer list cycles.
688 QString label = toqstr(b->fileName().displayName(20));
692 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
693 add(MenuItem(MenuItem::Command, label,
694 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
696 b = theBufferList().next(b);
698 } while (b != first);
700 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
701 FuncRequest(LFUN_NOACTION)));
706 void MenuDefinition::expandBookmarks()
708 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
710 for (size_t i = 1; i <= bm.size(); ++i) {
712 string const file = bm.bookmark(i).filename.absFilename();
713 QString const label = QString("%1. %2|%3").arg(i)
714 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
715 add(MenuItem(MenuItem::Command, label,
716 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
722 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
724 if (!buf && kind != MenuItem::ImportFormats) {
725 add(MenuItem(MenuItem::Command,
726 qt_("No Document Open!"),
727 FuncRequest(LFUN_NOACTION)));
731 typedef vector<Format const *> Formats;
736 case MenuItem::ImportFormats:
737 formats = theConverters().importableFormats();
738 action = LFUN_BUFFER_IMPORT;
740 case MenuItem::ViewFormats:
741 formats = buf->exportableFormats(true);
742 action = LFUN_BUFFER_VIEW;
744 case MenuItem::UpdateFormats:
745 formats = buf->exportableFormats(true);
746 action = LFUN_BUFFER_UPDATE;
749 formats = buf->exportableFormats(false);
750 action = LFUN_BUFFER_EXPORT;
752 sort(formats.begin(), formats.end(), &compareFormat);
754 Formats::const_iterator fit = formats.begin();
755 Formats::const_iterator end = formats.end();
756 for (; fit != end ; ++fit) {
760 docstring lab = from_utf8((*fit)->prettyname());
761 docstring scut = from_utf8((*fit)->shortcut());
762 docstring const tmplab = lab;
765 lab += char_type('|') + scut;
766 docstring lab_i18n = translateIfPossible(lab);
767 bool const untranslated = (lab == lab_i18n);
768 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
769 QString label = toqstr(lab);
771 // this might happen if the shortcut
772 // has been redefined
773 label = toqstr(translateIfPossible(tmplab));
776 case MenuItem::ImportFormats:
779 case MenuItem::ViewFormats:
780 case MenuItem::ExportFormats:
781 case MenuItem::UpdateFormats:
782 if (!(*fit)->documentFormat())
786 LASSERT(false, /**/);
789 if (!shortcut.isEmpty())
790 label += '|' + shortcut;
793 addWithStatusCheck(MenuItem(MenuItem::Command, label,
794 FuncRequest(action, (*fit)->name())));
796 add(MenuItem(MenuItem::Command, label,
797 FuncRequest(action, (*fit)->name())));
802 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
805 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
806 FuncRequest(LFUN_NOACTION)));
810 FloatList const & floats = buf->params().documentClass().floats();
811 FloatList::const_iterator cit = floats.begin();
812 FloatList::const_iterator end = floats.end();
813 for (; cit != end; ++cit) {
814 addWithStatusCheck(MenuItem(MenuItem::Command,
815 qt_(cit->second.listName()),
816 FuncRequest(LFUN_FLOAT_LIST,
817 cit->second.type())));
822 void MenuDefinition::expandFloatInsert(Buffer const * buf)
825 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
826 FuncRequest(LFUN_NOACTION)));
830 FloatList const & floats = buf->params().documentClass().floats();
831 FloatList::const_iterator cit = floats.begin();
832 FloatList::const_iterator end = floats.end();
833 for (; cit != end; ++cit) {
835 QString const label = qt_(cit->second.name());
836 addWithStatusCheck(MenuItem(MenuItem::Command, label,
837 FuncRequest(LFUN_FLOAT_INSERT,
838 cit->second.type())));
843 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
846 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
847 FuncRequest(LFUN_NOACTION)));
850 TextClass::InsetLayouts const & insetLayouts =
851 buf->params().documentClass().insetLayouts();
852 TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
853 TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
854 for (; cit != end; ++cit) {
855 docstring const label = cit->first;
856 if (cit->second.lyxtype() == s)
857 addWithStatusCheck(MenuItem(MenuItem::Command,
858 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
864 size_t const max_number_of_items = 25;
866 void MenuDefinition::expandToc2(Toc const & toc_list,
867 size_t from, size_t to, int depth)
869 int shortcut_count = 0;
871 // check whether depth is smaller than the smallest depth in toc.
872 int min_depth = 1000;
873 for (size_t i = from; i < to; ++i)
874 min_depth = min(min_depth, toc_list[i].depth());
875 if (min_depth > depth)
878 if (to - from <= max_number_of_items) {
879 for (size_t i = from; i < to; ++i) {
880 QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
881 label += limitStringLength(toc_list[i].str());
882 if (toc_list[i].depth() == depth
883 && shortcut_count < 9) {
884 if (label.contains(QString::number(shortcut_count + 1)))
885 label += '|' + QString::number(++shortcut_count);
887 add(MenuItem(MenuItem::Command, label,
888 FuncRequest(toc_list[i].action())));
893 size_t new_pos = pos + 1;
894 while (new_pos < to && toc_list[new_pos].depth() > depth)
897 QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
898 label += limitStringLength(toc_list[pos].str());
899 if (toc_list[pos].depth() == depth &&
900 shortcut_count < 9) {
901 if (label.contains(QString::number(shortcut_count + 1)))
902 label += '|' + QString::number(++shortcut_count);
904 if (new_pos == pos + 1) {
905 add(MenuItem(MenuItem::Command,
906 label, FuncRequest(toc_list[pos].action())));
909 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
910 MenuItem item(MenuItem::Submenu, label);
911 item.setSubmenu(sub);
920 void MenuDefinition::expandToc(Buffer const * buf)
922 // To make things very cleanly, we would have to pass buf to
923 // all MenuItem constructors and to expandToc2. However, we
924 // know that all the entries in a TOC will be have status_ ==
925 // OK, so we avoid this unnecessary overhead (JMarc)
928 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
929 FuncRequest(LFUN_NOACTION)));
933 Buffer* cbuf = const_cast<Buffer*>(buf);
934 cbuf->tocBackend().update();
935 cbuf->structureChanged();
937 // Add an entry for the master doc if this is a child doc
938 Buffer const * const master = buf->masterBuffer();
940 ParIterator const pit = par_iterator_begin(master->inset());
941 string const arg = convert<string>(pit->id());
942 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
943 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
946 MenuDefinition other_lists;
948 FloatList const & floatlist = buf->params().documentClass().floats();
949 TocList const & toc_list = buf->tocBackend().tocs();
950 TocList::const_iterator cit = toc_list.begin();
951 TocList::const_iterator end = toc_list.end();
952 for (; cit != end; ++cit) {
954 if (cit->first == "tableofcontents")
957 MenuDefinition submenu;
958 if (cit->second.size() >= 30) {
959 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
960 submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
962 TocIterator ccit = cit->second.begin();
963 TocIterator eend = cit->second.end();
964 for (; ccit != eend; ++ccit) {
965 submenu.add(MenuItem(MenuItem::Command,
966 limitStringLength(ccit->str()),
967 FuncRequest(ccit->action())));
971 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
972 item.setSubmenu(submenu);
973 if (floatlist.typeExist(cit->first) || cit->first == "child") {
974 // Those two types deserve to be in the main menu.
975 item.setSubmenu(submenu);
978 other_lists.add(item);
980 if (!other_lists.empty()) {
981 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
982 item.setSubmenu(other_lists);
987 cit = toc_list.find("tableofcontents");
989 addWithStatusCheck(MenuItem(MenuItem::Command,
990 qt_("No Table of contents"),
993 expandToc2(cit->second, 0, cit->second.size(), 0);
997 void MenuDefinition::expandPasteRecent()
999 docstring_list const sel = cap::availableSelections();
1001 docstring_list::const_iterator cit = sel.begin();
1002 docstring_list::const_iterator end = sel.end();
1004 for (unsigned int index = 0; cit != end; ++cit, ++index) {
1005 add(MenuItem(MenuItem::Command, toqstr(*cit),
1006 FuncRequest(LFUN_PASTE, convert<string>(index))));
1011 void MenuDefinition::expandToolbars()
1014 // extracts the toolbars from the backend
1015 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1016 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1018 for (; cit != end; ++cit) {
1019 QString label = qt_(cit->gui_name);
1020 // frontends are not supposed to turn on/off toolbars,
1021 // if they cannot update ToolbarBackend::flags. That
1022 // is to say, ToolbarsBackend::flags should reflect
1023 // the true state of toolbars.
1025 // menu is displayed as
1029 // in the case of auto.
1030 if (cit->flags & ToolbarInfo::AUTO)
1031 label += qt_(" (auto)");
1032 add(MenuItem(MenuItem::Command, label,
1033 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1038 void MenuDefinition::expandBranches(Buffer const * buf)
1041 add(MenuItem(MenuItem::Command,
1042 qt_("No Document Open!"),
1043 FuncRequest(LFUN_NOACTION)));
1047 BufferParams const & params = buf->masterBuffer()->params();
1048 if (params.branchlist().empty()) {
1049 add(MenuItem(MenuItem::Command,
1050 qt_("No Branch in Document!"),
1051 FuncRequest(LFUN_NOACTION)));
1055 BranchList::const_iterator cit = params.branchlist().begin();
1056 BranchList::const_iterator end = params.branchlist().end();
1058 for (int ii = 1; cit != end; ++cit, ++ii) {
1059 docstring label = cit->getBranch();
1061 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1062 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1063 FuncRequest(LFUN_BRANCH_INSERT,
1064 cit->getBranch())));
1069 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1072 add(MenuItem(MenuItem::Command,
1073 qt_("No Document Open!"),
1074 FuncRequest(LFUN_NOACTION)));
1078 Inset const * inset = bv->cursor().nextInset();
1079 if (!inset || inset->lyxCode() != CITE_CODE) {
1080 add(MenuItem(MenuItem::Command,
1081 qt_("No Citation in Scope!"),
1082 FuncRequest(LFUN_NOACTION)));
1085 InsetCommand const * citinset =
1086 static_cast<InsetCommand const *>(inset);
1088 Buffer const * buf = &bv->buffer();
1089 docstring key = citinset->getParam("key");
1090 // we can only handle one key currently
1091 if (contains(key, ','))
1092 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1094 vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1095 docstring_list citeStrings =
1096 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1098 docstring_list::const_iterator cit = citeStrings.begin();
1099 docstring_list::const_iterator end = citeStrings.end();
1101 for (int ii = 1; cit != end; ++cit, ++ii) {
1102 docstring label = *cit;
1104 CiteStyle cst = citeStyleList[ii - 1];
1106 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1107 FuncRequest(LFUN_NEXT_INSET_MODIFY,
1108 "changetype " + from_utf8(citationStyleToString(cs)))));
1115 /////////////////////////////////////////////////////////////////////
1116 // Menu::Impl definition and implementation
1117 /////////////////////////////////////////////////////////////////////
1121 /// populates the menu or one of its submenu
1122 /// This is used as a recursive function
1123 void populate(QMenu & qMenu, MenuDefinition const & menu);
1125 /// Only needed for top level menus.
1126 MenuDefinition * top_level_menu;
1129 /// the name of this menu
1135 /// Get a MenuDefinition item label from the menu backend
1136 static QString label(MenuItem const & mi)
1138 QString label = mi.label();
1139 label.replace("&", "&&");
1141 QString shortcut = mi.shortcut();
1142 if (!shortcut.isEmpty()) {
1143 int pos = label.indexOf(shortcut);
1145 //label.insert(pos, 1, char_type('&'));
1146 label.replace(pos, 0, "&");
1149 QString const binding = mi.binding();
1150 if (!binding.isEmpty())
1151 label += '\t' + binding;
1156 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1158 LYXERR(Debug::GUI, "populating menu " << menu.name());
1159 if (menu.size() == 0) {
1160 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1163 LYXERR(Debug::GUI, " ***** menu entries " << menu.size());
1164 MenuDefinition::const_iterator m = menu.begin();
1165 MenuDefinition::const_iterator end = menu.end();
1166 for (; m != end; ++m) {
1167 if (m->kind() == MenuItem::Separator)
1168 qMenu.addSeparator();
1169 else if (m->kind() == MenuItem::Submenu) {
1170 QMenu * subMenu = qMenu.addMenu(label(*m));
1171 populate(*subMenu, m->submenu());
1173 // we have a MenuItem::Command
1174 qMenu.addAction(new Action(view, QIcon(), label(*m),
1175 m->func(), QString(), &qMenu));
1180 /////////////////////////////////////////////////////////////////////
1181 // Menu implementation
1182 /////////////////////////////////////////////////////////////////////
1184 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1185 : QMenu(gv), d(new Menu::Impl)
1187 d->top_level_menu = top_level? new MenuDefinition : 0;
1191 if (d->top_level_menu)
1192 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1198 delete d->top_level_menu;
1203 void Menu::updateView()
1205 guiApp->menus().updateMenu(this);
1209 /////////////////////////////////////////////////////////////////////
1210 // Menus::Impl definition and implementation
1211 /////////////////////////////////////////////////////////////////////
1213 struct Menus::Impl {
1215 bool hasMenu(QString const &) const;
1217 MenuDefinition & getMenu(QString const &);
1219 MenuDefinition const & getMenu(QString const &) const;
1221 /// Expands some special entries of the menu
1222 /** The entries with the following kind are expanded to a
1223 sequence of Command MenuItems: Lastfiles, Documents,
1224 ViewFormats, ExportFormats, UpdateFormats, Branches
1226 void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1227 BufferView const *) const;
1229 /// Initialize specific MACOS X menubar
1230 void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1232 /// Mac special menu.
1233 /** This defines a menu whose entries list the FuncRequests
1234 that will be removed by expand() in other menus. This is
1235 used by the Qt/Mac code
1237 MenuDefinition specialmenu_;
1242 MenuDefinition menubar_;
1244 typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1246 /// name to menu for \c menu() method.
1251 Here is what the Qt documentation says about how a menubar is chosen:
1253 1) If the window has a QMenuBar then it is used. 2) If the window
1254 is a modal then its menubar is used. If no menubar is specified
1255 then a default menubar is used (as documented below) 3) If the
1256 window has no parent then the default menubar is used (as
1259 The above 3 steps are applied all the way up the parent window
1260 chain until one of the above are satisifed. If all else fails a
1261 default menubar will be created, the default menubar on Qt/Mac is
1262 an empty menubar, however you can create a different default
1263 menubar by creating a parentless QMenuBar, the first one created
1264 will thus be designated the default menubar, and will be used
1265 whenever a default menubar is needed.
1267 Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1268 that this menubar will be used also when one of LyX' dialogs has
1271 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1273 /* Since Qt 4.2, the qt/mac menu code has special code for
1274 specifying the role of a menu entry. However, it does not
1275 work very well with our scheme of creating menus on demand,
1276 and therefore we need to put these entries in a special
1277 invisible menu. (JMarc)
1280 /* The entries of our special mac menu. If we add support for
1281 * special entries in Menus, we could imagine something
1283 * SpecialItem About " "About LyX" "dialog-show aboutlyx"
1284 * and therefore avoid hardcoding. I am not sure it is worth
1285 * the hassle, though. (JMarc)
1287 struct MacMenuEntry {
1291 QAction::MenuRole role;
1294 MacMenuEntry entries[] = {
1295 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1296 QAction::AboutRole},
1297 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1298 QAction::PreferencesRole},
1299 {LFUN_RECONFIGURE, "", "Reconfigure",
1300 QAction::ApplicationSpecificRole},
1301 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1303 const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1305 // the special menu for Menus. Fill it up only once.
1306 if (specialmenu_.size() == 0) {
1307 for (size_t i = 0 ; i < num_entries ; ++i) {
1308 FuncRequest const func(entries[i].action,
1309 from_utf8(entries[i].arg));
1310 specialmenu_.add(MenuItem(MenuItem::Command,
1311 entries[i].label, func));
1315 // add the entries to a QMenu that will eventually be empty
1316 // and therefore invisible.
1317 QMenu * qMenu = qmb->addMenu("special");
1318 MenuDefinition::const_iterator cit = specialmenu_.begin();
1319 MenuDefinition::const_iterator end = specialmenu_.end();
1320 for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1321 Action * action = new Action(view, QIcon(), cit->label(),
1322 cit->func(), QString(), qMenu);
1323 action->setMenuRole(entries[i].role);
1324 qMenu->addAction(action);
1329 void Menus::Impl::expand(MenuDefinition const & frommenu,
1330 MenuDefinition & tomenu, BufferView const * bv) const
1332 if (!tomenu.empty())
1335 for (MenuDefinition::const_iterator cit = frommenu.begin();
1336 cit != frommenu.end() ; ++cit) {
1337 Buffer const * buf = bv ? &bv->buffer() : 0;
1338 switch (cit->kind()) {
1339 case MenuItem::Lastfiles:
1340 tomenu.expandLastfiles();
1343 case MenuItem::Documents:
1344 tomenu.expandDocuments();
1347 case MenuItem::Bookmarks:
1348 tomenu.expandBookmarks();
1351 case MenuItem::ImportFormats:
1352 case MenuItem::ViewFormats:
1353 case MenuItem::UpdateFormats:
1354 case MenuItem::ExportFormats:
1355 tomenu.expandFormats(cit->kind(), buf);
1358 case MenuItem::CharStyles:
1359 tomenu.expandFlexInsert(buf, "charstyle");
1362 case MenuItem::Custom:
1363 tomenu.expandFlexInsert(buf, "custom");
1366 case MenuItem::Elements:
1367 tomenu.expandFlexInsert(buf, "element");
1370 case MenuItem::FloatListInsert:
1371 tomenu.expandFloatListInsert(buf);
1374 case MenuItem::FloatInsert:
1375 tomenu.expandFloatInsert(buf);
1378 case MenuItem::PasteRecent:
1379 tomenu.expandPasteRecent();
1382 case MenuItem::Toolbars:
1383 tomenu.expandToolbars();
1386 case MenuItem::Branches:
1387 tomenu.expandBranches(buf);
1390 case MenuItem::CiteStyles:
1391 tomenu.expandCiteStyles(bv);
1395 tomenu.expandToc(buf);
1398 case MenuItem::GraphicsGroups:
1399 tomenu.expandGraphicsGroups(bv);
1402 case MenuItem::Submenu: {
1403 MenuItem item(*cit);
1404 item.setSubmenu(MenuDefinition(cit->submenuname()));
1405 expand(getMenu(cit->submenuname()), item.submenu(), bv);
1406 tomenu.addWithStatusCheck(item);
1410 case MenuItem::Separator:
1411 tomenu.addWithStatusCheck(*cit);
1414 case MenuItem::Command:
1415 if (!specialmenu_.hasFunc(cit->func()))
1416 tomenu.addWithStatusCheck(*cit);
1420 // we do not want the menu to end with a separator
1421 if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1422 tomenu.items_.pop_back();
1424 // Check whether the shortcuts are unique
1425 tomenu.checkShortcuts();
1429 bool Menus::Impl::hasMenu(QString const & name) const
1431 return find_if(menulist_.begin(), menulist_.end(),
1432 MenuNamesEqual(name)) != menulist_.end();
1436 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1438 const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1439 MenuNamesEqual(name));
1440 if (cit == menulist_.end())
1441 LYXERR0("No submenu named " << name);
1442 LASSERT(cit != menulist_.end(), /**/);
1447 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1449 iterator it = find_if(menulist_.begin(), menulist_.end(),
1450 MenuNamesEqual(name));
1451 if (it == menulist_.end())
1452 LYXERR0("No submenu named " << name);
1453 LASSERT(it != menulist_.end(), /**/);
1458 /////////////////////////////////////////////////////////////////////
1462 /////////////////////////////////////////////////////////////////////
1464 Menus::Menus() : d(new Impl) {}
1471 void Menus::read(Lexer & lex)
1479 LexerKeyword menutags[] = {
1480 { "end", md_endmenuset },
1481 { "menu", md_menu },
1482 { "menubar", md_menubar }
1485 // consistency check
1486 if (compare_ascii_no_case(lex.getString(), "menuset"))
1487 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1489 lex.pushTable(menutags);
1490 lex.setContext("Menus::read");
1494 while (lex.isOK() && !quit) {
1495 switch (lex.lex()) {
1497 d->menubar_.read(lex);
1501 QString const name = toqstr(lex.getDocString());
1502 if (d->hasMenu(name))
1503 d->getMenu(name).read(lex);
1505 MenuDefinition menu(name);
1507 d->menulist_.push_back(menu);
1515 lex.printError("Unknown menu tag");
1523 bool Menus::searchMenu(FuncRequest const & func,
1524 docstring_list & names) const
1526 MenuDefinition menu;
1527 d->expand(d->menubar_, menu, 0);
1528 return menu.searchMenu(func, names);
1532 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1536 // setup special mac specific menu item
1537 d->macxMenuBarInit(view, qmb);
1540 // Clear all menubar contents before filling it.
1544 LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1546 if (d->menubar_.size() == 0) {
1547 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1548 << d->menubar_.name());
1551 LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1553 MenuDefinition menu;
1554 BufferView * bv = 0;
1557 d->expand(d->menubar_, menu, bv);
1559 MenuDefinition::const_iterator m = menu.begin();
1560 MenuDefinition::const_iterator end = menu.end();
1562 for (; m != end; ++m) {
1564 if (m->kind() != MenuItem::Submenu) {
1565 LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1569 LYXERR(Debug::GUI, "menu bar item " << m->label()
1570 << " is a submenu named " << m->submenuname());
1572 QString name = m->submenuname();
1573 if (!d->hasMenu(name)) {
1574 LYXERR(Debug::GUI, "\tERROR: " << name
1575 << " submenu has no menu!");
1579 Menu * menu = new Menu(view, m->submenuname(), true);
1580 menu->setTitle(label(*m));
1583 d->name_map_[view][name] = menu;
1588 void Menus::updateMenu(Menu * qmenu)
1590 LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1593 if (qmenu->d->name.isEmpty())
1596 // Here, We make sure that theLyXFunc points to the correct LyXView.
1597 theLyXFunc().setLyXView(qmenu->d->view);
1599 if (!d->hasMenu(qmenu->d->name)) {
1600 qmenu->addAction(qt_("No action defined!"));
1601 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1606 MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1607 BufferView * bv = 0;
1609 bv = qmenu->d->view->view();
1610 d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1611 qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1615 Menu * Menus::menu(QString const & name, GuiView & view)
1617 LYXERR(Debug::GUI, "Context menu requested: " << name);
1618 Menu * menu = d->name_map_[&view].value(name, 0);
1619 if (!menu && !name.startsWith("context-")) {
1620 LYXERR0("requested context menu not found: " << name);
1624 menu = new Menu(&view, name, true);
1625 d->name_map_[&view][name] = menu;
1629 } // namespace frontend
1632 #include "Menus_moc.cpp"