2 * \file MenuBackend.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
11 * \author Martin Vermeer
13 * Full author contact details are available in file CREDITS.
18 #include "MenuBackend.h"
20 #include "BranchList.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "Converter.h"
25 #include "CutAndPaste.h"
28 #include "FloatList.h"
33 #include "LyXAction.h"
34 #include "LyX.h" // for lastfiles
37 #include "Paragraph.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
40 #include "ToolbarBackend.h"
42 #include "support/filetools.h"
43 #include "support/lstrings.h"
44 #include "support/convert.h"
46 #include <boost/bind.hpp>
53 using support::compare_ascii_no_case;
54 using support::contains;
55 using support::makeDisplayPath;
72 class MenuNamesEqual : public std::unary_function<Menu, bool> {
74 MenuNamesEqual(docstring const & name)
76 bool operator()(Menu const & menu) const {
77 return menu.name() == name_;
86 // This is the global menu definition
87 MenuBackend menubackend;
90 MenuItem::MenuItem(Kind kind)
91 : kind_(kind), optional_(false)
95 MenuItem::MenuItem(Kind kind, docstring const & label,
96 docstring const & submenu, bool optional)
97 : kind_(kind), label_(label),
98 submenuname_(submenu), optional_(optional)
100 BOOST_ASSERT(kind == Submenu);
104 MenuItem::MenuItem(Kind kind, docstring const & label,
105 FuncRequest const & func, bool optional)
106 : kind_(kind), label_(label), func_(func), optional_(optional)
108 func_.origin = FuncRequest::MENU;
112 MenuItem::~MenuItem()
116 void MenuItem::submenu(Menu * menu)
118 submenu_.reset(menu);
122 docstring const MenuItem::label() const
124 return token(label_, char_type('|'), 0);
128 docstring const MenuItem::shortcut() const
130 return token(label_, char_type('|'), 1);
134 docstring const MenuItem::binding(bool forgui) const
136 if (kind_ != Command)
139 // Get the keys bound to this action, but keep only the
141 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
144 return bindings.begin()->print(KeySequence::ForGui);
148 << lyxaction.getActionName(func_.action)
149 << '(' << to_utf8(func_.argument()) << ')' << endl;
154 Menu & Menu::add(MenuItem const & i)
161 Menu & Menu::addWithStatusCheck(MenuItem const & i)
165 case MenuItem::Command: {
166 FuncStatus status = lyx::getStatus(i.func());
167 if (status.unknown() || (!status.enabled() && i.optional()))
170 items_.back().status(status);
174 case MenuItem::Submenu: {
176 bool enabled = false;
177 for (const_iterator cit = i.submenu()->begin();
178 cit != i.submenu()->end(); ++cit) {
179 if ((cit->kind() == MenuItem::Command
180 || cit->kind() == MenuItem::Submenu)
181 && cit->status().enabled()) {
186 if (enabled || !i.optional()) {
188 items_.back().status().enabled(enabled);
196 case MenuItem::Separator:
198 && items_.back().kind() != MenuItem::Separator)
210 Menu & Menu::read(Lexer & lex)
238 struct keyword_item menutags[md_last - 1] = {
239 { "bookmarks", md_bookmarks },
240 { "branches", md_branches },
241 { "charstyles", md_charstyles },
242 { "custom", md_custom },
243 { "documents", md_documents },
244 { "elements", md_elements },
245 { "end", md_endmenu },
246 { "exportformats", md_exportformats },
247 { "floatinsert", md_floatinsert },
248 { "floatlistinsert", md_floatlistinsert },
249 { "importformats", md_importformats },
251 { "lastfiles", md_lastfiles },
252 { "optitem", md_optitem },
253 { "optsubmenu", md_optsubmenu },
254 { "pasterecent", md_pasterecent },
255 { "separator", md_separator },
256 { "submenu", md_submenu },
258 { "toolbars", md_toolbars },
259 { "updateformats", md_updateformats },
260 { "viewformats", md_viewformats }
263 lex.pushTable(menutags, md_last - 1);
264 if (lyxerr.debugging(Debug::PARSER))
265 lex.printTable(lyxerr);
268 bool optional = false;
270 while (lex.isOK() && !quit) {
274 // fallback to md_item
277 docstring const name = translateIfPossible(lex.getDocString());
279 string const command = lex.getString();
280 FuncRequest func = lyxaction.lookupFunc(command);
281 add(MenuItem(MenuItem::Command, name, func, optional));
287 add(MenuItem(MenuItem::Separator));
291 add(MenuItem(MenuItem::Lastfiles));
295 add(MenuItem(MenuItem::CharStyles));
299 add(MenuItem(MenuItem::Custom));
303 add(MenuItem(MenuItem::Elements));
307 add(MenuItem(MenuItem::Documents));
311 add(MenuItem(MenuItem::Bookmarks));
315 add(MenuItem(MenuItem::Toc));
319 add(MenuItem(MenuItem::ViewFormats));
322 case md_updateformats:
323 add(MenuItem(MenuItem::UpdateFormats));
326 case md_exportformats:
327 add(MenuItem(MenuItem::ExportFormats));
330 case md_importformats:
331 add(MenuItem(MenuItem::ImportFormats));
334 case md_floatlistinsert:
335 add(MenuItem(MenuItem::FloatListInsert));
339 add(MenuItem(MenuItem::FloatInsert));
343 add(MenuItem(MenuItem::PasteRecent));
347 add(MenuItem(MenuItem::Toolbars));
351 add(MenuItem(MenuItem::Branches));
356 // fallback to md_submenu
359 docstring const mlabel = translateIfPossible(lex.getDocString());
361 docstring const mname = lex.getDocString();
362 add(MenuItem(MenuItem::Submenu, mlabel, mname,
373 lex.printError("Menu::read: "
374 "Unknown menu tag: `$$Token'");
383 MenuItem const & Menu::operator[](size_type i) const
389 bool Menu::hasFunc(FuncRequest const & func) const
391 return find_if(begin(), end(),
392 bind(std::equal_to<FuncRequest>(),
393 bind(&MenuItem::func, _1),
397 void Menu::checkShortcuts() const
399 // This is a quadratic algorithm, but we do not care because
400 // menus are short enough
401 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
402 docstring shortcut = it1->shortcut();
403 if (shortcut.empty())
405 if (!contains(it1->label(), shortcut))
406 lyxerr << "Menu warning: menu entry \""
407 << to_utf8(it1->label())
408 << "\" does not contain shortcut `"
409 << to_utf8(shortcut) << "'." << endl;
410 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
411 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
412 lyxerr << "Menu warning: menu entries "
413 << '"' << to_utf8(it1->fulllabel())
414 << "\" and \"" << to_utf8(it2->fulllabel())
415 << "\" share the same shortcut."
423 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
425 const_iterator m = begin();
426 const_iterator m_end = end();
427 for (; m != m_end; ++m) {
428 if (m->kind() == MenuItem::Command && m->func() == func) {
429 names.push(m->label());
431 } else if (m->kind() == MenuItem::Submenu) {
432 names.push(m->label());
433 Menu submenu = menubackend.getMenu(m->submenuname());
434 if (submenu.searchFunc(func, names))
444 void MenuBackend::specialMenu(Menu const & menu)
452 class compare_format {
454 bool operator()(Format const * p1, Format const * p2) {
459 docstring const limit_string_length(docstring const & str)
461 docstring::size_type const max_item_length = 45;
463 if (str.size() > max_item_length)
464 return str.substr(0, max_item_length - 3) + "...";
470 void expandLastfiles(Menu & tomenu)
472 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
473 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
477 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
478 string const file = lfit->absFilename();
479 docstring const label = convert<docstring>(ii) + ". "
480 + makeDisplayPath(file, 30)
481 + char_type('|') + convert<docstring>(ii);
482 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
487 void expandDocuments(Menu & tomenu)
489 Buffer * first = theBufferList().first();
494 // We cannot use a for loop as the buffer list cycles.
496 docstring label = b->fileName().displayName(20);
500 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
501 tomenu.add(MenuItem(MenuItem::Command, label,
502 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
504 b = theBufferList().next(b);
506 } while (b != first);
508 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
509 FuncRequest(LFUN_NOACTION)));
514 void expandBookmarks(Menu & tomenu)
516 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
518 for (size_t i = 1; i <= bm.size(); ++i) {
520 docstring const label = convert<docstring>(i) + ". "
521 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
522 + char_type('|') + convert<docstring>(i);
523 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
524 convert<docstring>(i))));
530 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
532 if (!buf && kind != MenuItem::ImportFormats) {
533 tomenu.add(MenuItem(MenuItem::Command,
534 _("No Document Open!"),
535 FuncRequest(LFUN_NOACTION)));
539 typedef vector<Format const *> Formats;
544 case MenuItem::ImportFormats:
545 formats = theConverters().importableFormats();
546 action = LFUN_BUFFER_IMPORT;
548 case MenuItem::ViewFormats:
549 formats = buf->exportableFormats(true);
550 action = LFUN_BUFFER_VIEW;
552 case MenuItem::UpdateFormats:
553 formats = buf->exportableFormats(true);
554 action = LFUN_BUFFER_UPDATE;
557 formats = buf->exportableFormats(false);
558 action = LFUN_BUFFER_EXPORT;
560 sort(formats.begin(), formats.end(), compare_format());
562 Formats::const_iterator fit = formats.begin();
563 Formats::const_iterator end = formats.end();
564 for (; fit != end ; ++fit) {
567 docstring label = from_utf8((*fit)->prettyname());
570 case MenuItem::ImportFormats:
571 // FIXME: This is a hack, we should rather solve
572 // FIXME: bug 2488 instead.
573 if ((*fit)->name() == "text")
574 label = _("Plain Text");
575 else if ((*fit)->name() == "textparagraph")
576 label = _("Plain Text, Join Lines");
579 case MenuItem::ViewFormats:
580 case MenuItem::ExportFormats:
581 case MenuItem::UpdateFormats:
582 if (!(*fit)->documentFormat())
589 if (!(*fit)->shortcut().empty())
590 label += char_type('|') + from_utf8((*fit)->shortcut());
593 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
594 FuncRequest(action, (*fit)->name())));
596 tomenu.add(MenuItem(MenuItem::Command, label,
597 FuncRequest(action, (*fit)->name())));
602 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
605 tomenu.add(MenuItem(MenuItem::Command,
606 _("No Document Open!"),
607 FuncRequest(LFUN_NOACTION)));
611 FloatList const & floats =
612 buf->params().getTextClass().floats();
613 FloatList::const_iterator cit = floats.begin();
614 FloatList::const_iterator end = floats.end();
615 for (; cit != end; ++cit) {
616 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
617 _(cit->second.listName()),
618 FuncRequest(LFUN_FLOAT_LIST,
619 cit->second.type())));
624 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
627 tomenu.add(MenuItem(MenuItem::Command,
628 _("No Document Open!"),
629 FuncRequest(LFUN_NOACTION)));
633 FloatList const & floats =
634 buf->params().getTextClass().floats();
635 FloatList::const_iterator cit = floats.begin();
636 FloatList::const_iterator end = floats.end();
637 for (; cit != end; ++cit) {
639 docstring const label = _(cit->second.name());
640 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
641 FuncRequest(LFUN_FLOAT_INSERT,
642 cit->second.type())));
647 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
650 tomenu.add(MenuItem(MenuItem::Command,
651 _("No Document Open!"),
652 FuncRequest(LFUN_NOACTION)));
655 InsetLayouts const & insetlayouts =
656 buf->params().getTextClass().insetlayouts();
657 InsetLayouts::const_iterator cit = insetlayouts.begin();
658 InsetLayouts::const_iterator end = insetlayouts.end();
659 for (; cit != end; ++cit) {
660 docstring const label = cit->first;
661 if (cit->second.lyxtype == s)
662 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
663 label, FuncRequest(LFUN_FLEX_INSERT,
669 Menu::size_type const max_number_of_items = 25;
671 void expandToc2(Menu & tomenu,
672 Toc const & toc_list,
674 Toc::size_type to, int depth)
676 int shortcut_count = 0;
678 // check whether depth is smaller than the smallest depth in toc.
679 int min_depth = 1000;
680 for (Toc::size_type i = from; i < to; ++i)
681 min_depth = std::min(min_depth, toc_list[i].depth());
682 if (min_depth > depth)
686 if (to - from <= max_number_of_items) {
687 for (Toc::size_type i = from; i < to; ++i) {
688 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
689 label += limit_string_length(toc_list[i].str());
690 if (toc_list[i].depth() == depth
691 && shortcut_count < 9) {
692 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
693 label += char_type('|') + convert<docstring>(++shortcut_count);
695 tomenu.add(MenuItem(MenuItem::Command, label,
696 FuncRequest(toc_list[i].action())));
699 Toc::size_type pos = from;
701 Toc::size_type new_pos = pos + 1;
702 while (new_pos < to &&
703 toc_list[new_pos].depth() > depth)
706 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
707 label += limit_string_length(toc_list[pos].str());
708 if (toc_list[pos].depth() == depth &&
709 shortcut_count < 9) {
710 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
711 label += char_type('|') + convert<docstring>(++shortcut_count);
713 if (new_pos == pos + 1) {
714 tomenu.add(MenuItem(MenuItem::Command,
715 label, FuncRequest(toc_list[pos].action())));
717 MenuItem item(MenuItem::Submenu, label);
718 item.submenu(new Menu);
719 expandToc2(*item.submenu(),
720 toc_list, pos, new_pos, depth + 1);
729 void expandToc(Menu & tomenu, Buffer const * buf)
731 // To make things very cleanly, we would have to pass buf to
732 // all MenuItem constructors and to expandToc2. However, we
733 // know that all the entries in a TOC will be have status_ ==
734 // OK, so we avoid this unnecessary overhead (JMarc)
737 tomenu.add(MenuItem(MenuItem::Command,
738 _("No Document Open!"),
739 FuncRequest(LFUN_NOACTION)));
743 Buffer* cbuf = const_cast<Buffer*>(buf);
744 cbuf->tocBackend().update();
745 cbuf->structureChanged();
747 // Add an entry for the master doc if this is a child doc
748 Buffer const * const master = buf->masterBuffer();
750 ParIterator const pit = par_iterator_begin(master->inset());
751 string const arg = convert<string>(pit->id());
752 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
753 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
756 FloatList const & floatlist = buf->params().getTextClass().floats();
757 TocList const & toc_list = buf->tocBackend().tocs();
758 TocList::const_iterator cit = toc_list.begin();
759 TocList::const_iterator end = toc_list.end();
760 for (; cit != end; ++cit) {
762 if (cit->first == "tableofcontents")
765 // All the rest is for floats
766 auto_ptr<Menu> menu(new Menu);
767 TocIterator ccit = cit->second.begin();
768 TocIterator eend = cit->second.end();
769 for (; ccit != eend; ++ccit) {
770 docstring const label = limit_string_length(ccit->str());
771 menu->add(MenuItem(MenuItem::Command,
773 FuncRequest(ccit->action())));
775 string const & floatName = floatlist.getType(cit->first).listName();
777 if (!floatName.empty())
778 label = _(floatName);
779 // BUG3633: listings is not a proper float so its name
780 // is not shown in floatlist.
781 else if (cit->first == "listing")
782 label = _("List of listings");
783 // this should not happen now, but if something else like
784 // listings is added later, this can avoid an empty menu name.
786 label = _("Other floats");
787 MenuItem item(MenuItem::Submenu, label);
788 item.submenu(menu.release());
793 cit = toc_list.find("tableofcontents");
795 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
796 _("No Table of contents"),
799 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
804 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
809 vector<docstring> const sel =
810 cap::availableSelections(*buf);
812 vector<docstring>::const_iterator cit = sel.begin();
813 vector<docstring>::const_iterator end = sel.end();
815 for (unsigned int index = 0; cit != end; ++cit, ++index) {
816 tomenu.add(MenuItem(MenuItem::Command, *cit,
817 FuncRequest(LFUN_PASTE, convert<string>(index))));
822 void expandToolbars(Menu & tomenu)
825 // extracts the toolbars from the backend
826 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
827 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
829 for (; cit != end; ++cit) {
830 docstring label = _(cit->gui_name);
831 // frontends are not supposed to turn on/off toolbars,
832 // if they cannot update ToolbarBackend::flags. That
833 // is to say, ToolbarsBackend::flags should reflect
834 // the true state of toolbars.
836 // menu is displayed as
840 // in the case of auto.
841 if (cit->flags & ToolbarInfo::AUTO)
842 label += _(" (auto)");
843 tomenu.add(MenuItem(MenuItem::Command, label,
844 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
849 void expandBranches(Menu & tomenu, Buffer const * buf)
852 tomenu.add(MenuItem(MenuItem::Command,
853 _("No Document Open!"),
854 FuncRequest(LFUN_NOACTION)));
858 BufferParams const & params = buf->masterBuffer()->params();
859 if (params.branchlist().empty()) {
860 tomenu.add(MenuItem(MenuItem::Command,
861 _("No Branch in Document!"),
862 FuncRequest(LFUN_NOACTION)));
866 BranchList::const_iterator cit = params.branchlist().begin();
867 BranchList::const_iterator end = params.branchlist().end();
869 for (int ii = 1; cit != end; ++cit, ++ii) {
870 docstring label = cit->getBranch();
872 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
873 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
874 FuncRequest(LFUN_BRANCH_INSERT,
883 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
884 Buffer const * buf) const
889 for (Menu::const_iterator cit = frommenu.begin();
890 cit != frommenu.end() ; ++cit) {
891 switch (cit->kind()) {
892 case MenuItem::Lastfiles:
893 expandLastfiles(tomenu);
896 case MenuItem::Documents:
897 expandDocuments(tomenu);
900 case MenuItem::Bookmarks:
901 expandBookmarks(tomenu);
904 case MenuItem::ImportFormats:
905 case MenuItem::ViewFormats:
906 case MenuItem::UpdateFormats:
907 case MenuItem::ExportFormats:
908 expandFormats(cit->kind(), tomenu, buf);
911 case MenuItem::CharStyles:
912 expandFlexInsert(tomenu, buf, "charstyle");
915 case MenuItem::Custom:
916 expandFlexInsert(tomenu, buf, "custom");
919 case MenuItem::Elements:
920 expandFlexInsert(tomenu, buf, "element");
923 case MenuItem::FloatListInsert:
924 expandFloatListInsert(tomenu, buf);
927 case MenuItem::FloatInsert:
928 expandFloatInsert(tomenu, buf);
931 case MenuItem::PasteRecent:
932 expandPasteRecent(tomenu, buf);
935 case MenuItem::Toolbars:
936 expandToolbars(tomenu);
939 case MenuItem::Branches:
940 expandBranches(tomenu, buf);
944 expandToc(tomenu, buf);
947 case MenuItem::Submenu: {
949 item.submenu(new Menu(cit->submenuname()));
950 expand(getMenu(cit->submenuname()),
951 *item.submenu(), buf);
952 tomenu.addWithStatusCheck(item);
956 case MenuItem::Separator:
957 tomenu.addWithStatusCheck(*cit);
960 case MenuItem::Command:
961 if (!specialmenu_.hasFunc(cit->func()))
962 tomenu.addWithStatusCheck(*cit);
966 // we do not want the menu to end with a separator
968 && tomenu.items_.back().kind() == MenuItem::Separator)
969 tomenu.items_.pop_back();
971 // Check whether the shortcuts are unique
972 tomenu.checkShortcuts();
976 void MenuBackend::read(Lexer & lex)
985 struct keyword_item menutags[md_last - 1] = {
986 { "end", md_endmenuset },
988 { "menubar", md_menubar }
992 if (compare_ascii_no_case(lex.getString(), "menuset")) {
993 lyxerr << "Menubackend::read: ERROR wrong token:`"
994 << lex.getString() << '\'' << endl;
997 lex.pushTable(menutags, md_last - 1);
998 if (lyxerr.debugging(Debug::PARSER))
999 lex.printTable(lyxerr);
1003 while (lex.isOK() && !quit) {
1004 switch (lex.lex()) {
1010 docstring const name = lex.getDocString();
1011 if (hasMenu(name)) {
1012 getMenu(name).read(lex);
1024 lex.printError("menubackend::read: "
1025 "Unknown menu tag: `$$Token'");
1033 void MenuBackend::add(Menu const & menu)
1035 menulist_.push_back(menu);
1039 bool MenuBackend::hasMenu(docstring const & name) const
1041 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1045 Menu const & MenuBackend::getMenu(docstring const & name) const
1047 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1049 lyxerr << "No submenu named " << to_utf8(name) << endl;
1050 BOOST_ASSERT(cit != end());
1055 Menu & MenuBackend::getMenu(docstring const & name)
1057 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1059 lyxerr << "No submenu named " << to_utf8(name) << endl;
1060 BOOST_ASSERT(it != end());
1065 Menu const & MenuBackend::getMenubar() const