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"
26 #include "support/debug.h"
28 #include "FloatList.h"
30 #include "support/gettext.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 namespace lyx::support;
59 class MenuNamesEqual : public std::unary_function<Menu, bool> {
61 MenuNamesEqual(docstring const & name)
63 bool operator()(Menu const & menu) const {
64 return menu.name() == name_;
73 // This is the global menu definition
74 MenuBackend menubackend;
77 MenuItem::MenuItem(Kind kind)
78 : kind_(kind), optional_(false)
82 MenuItem::MenuItem(Kind kind, docstring const & label,
83 docstring const & submenu, bool optional)
84 : kind_(kind), label_(label),
85 submenuname_(submenu), optional_(optional)
87 BOOST_ASSERT(kind == Submenu);
91 MenuItem::MenuItem(Kind kind, docstring const & label,
92 FuncRequest const & func, bool optional)
93 : kind_(kind), label_(label), func_(func), optional_(optional)
95 func_.origin = FuncRequest::MENU;
103 void MenuItem::submenu(Menu * menu)
105 submenu_.reset(menu);
109 docstring const MenuItem::label() const
111 return token(label_, char_type('|'), 0);
115 docstring const MenuItem::shortcut() const
117 return token(label_, char_type('|'), 1);
121 docstring const MenuItem::binding(bool forgui) const
123 if (kind_ != Command)
126 // Get the keys bound to this action, but keep only the
128 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
131 return bindings.begin()->print(KeySequence::ForGui);
133 LYXERR(Debug::KBMAP, "No binding for "
134 << lyxaction.getActionName(func_.action)
135 << '(' << to_utf8(func_.argument()) << ')');
140 Menu & Menu::add(MenuItem const & i)
147 Menu & Menu::addWithStatusCheck(MenuItem const & i)
151 case MenuItem::Command: {
152 FuncStatus status = lyx::getStatus(i.func());
153 if (status.unknown() || (!status.enabled() && i.optional()))
156 items_.back().status(status);
160 case MenuItem::Submenu: {
162 bool enabled = false;
163 for (const_iterator cit = i.submenu()->begin();
164 cit != i.submenu()->end(); ++cit) {
165 if ((cit->kind() == MenuItem::Command
166 || cit->kind() == MenuItem::Submenu)
167 && cit->status().enabled()) {
172 if (enabled || !i.optional()) {
174 items_.back().status().enabled(enabled);
182 case MenuItem::Separator:
184 && items_.back().kind() != MenuItem::Separator)
196 Menu & Menu::read(Lexer & lex)
224 struct keyword_item menutags[md_last - 1] = {
225 { "bookmarks", md_bookmarks },
226 { "branches", md_branches },
227 { "charstyles", md_charstyles },
228 { "custom", md_custom },
229 { "documents", md_documents },
230 { "elements", md_elements },
231 { "end", md_endmenu },
232 { "exportformats", md_exportformats },
233 { "floatinsert", md_floatinsert },
234 { "floatlistinsert", md_floatlistinsert },
235 { "importformats", md_importformats },
237 { "lastfiles", md_lastfiles },
238 { "optitem", md_optitem },
239 { "optsubmenu", md_optsubmenu },
240 { "pasterecent", md_pasterecent },
241 { "separator", md_separator },
242 { "submenu", md_submenu },
244 { "toolbars", md_toolbars },
245 { "updateformats", md_updateformats },
246 { "viewformats", md_viewformats }
249 lex.pushTable(menutags, md_last - 1);
250 if (lyxerr.debugging(Debug::PARSER))
251 lex.printTable(lyxerr);
254 bool optional = false;
256 while (lex.isOK() && !quit) {
260 // fallback to md_item
263 docstring const name = translateIfPossible(lex.getDocString());
265 string const command = lex.getString();
266 FuncRequest func = lyxaction.lookupFunc(command);
267 add(MenuItem(MenuItem::Command, name, func, optional));
273 add(MenuItem(MenuItem::Separator));
277 add(MenuItem(MenuItem::Lastfiles));
281 add(MenuItem(MenuItem::CharStyles));
285 add(MenuItem(MenuItem::Custom));
289 add(MenuItem(MenuItem::Elements));
293 add(MenuItem(MenuItem::Documents));
297 add(MenuItem(MenuItem::Bookmarks));
301 add(MenuItem(MenuItem::Toc));
305 add(MenuItem(MenuItem::ViewFormats));
308 case md_updateformats:
309 add(MenuItem(MenuItem::UpdateFormats));
312 case md_exportformats:
313 add(MenuItem(MenuItem::ExportFormats));
316 case md_importformats:
317 add(MenuItem(MenuItem::ImportFormats));
320 case md_floatlistinsert:
321 add(MenuItem(MenuItem::FloatListInsert));
325 add(MenuItem(MenuItem::FloatInsert));
329 add(MenuItem(MenuItem::PasteRecent));
333 add(MenuItem(MenuItem::Toolbars));
337 add(MenuItem(MenuItem::Branches));
342 // fallback to md_submenu
345 docstring const mlabel = translateIfPossible(lex.getDocString());
347 docstring const mname = lex.getDocString();
348 add(MenuItem(MenuItem::Submenu, mlabel, mname,
359 lex.printError("Menu::read: "
360 "Unknown menu tag: `$$Token'");
369 MenuItem const & Menu::operator[](size_type i) const
375 bool Menu::hasFunc(FuncRequest const & func) const
377 return find_if(begin(), end(),
378 bind(std::equal_to<FuncRequest>(),
379 bind(&MenuItem::func, _1),
383 void Menu::checkShortcuts() const
385 // This is a quadratic algorithm, but we do not care because
386 // menus are short enough
387 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
388 docstring shortcut = it1->shortcut();
389 if (shortcut.empty())
391 if (!contains(it1->label(), shortcut))
392 lyxerr << "Menu warning: menu entry \""
393 << to_utf8(it1->label())
394 << "\" does not contain shortcut `"
395 << to_utf8(shortcut) << "'." << endl;
396 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
397 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
398 lyxerr << "Menu warning: menu entries "
399 << '"' << to_utf8(it1->fulllabel())
400 << "\" and \"" << to_utf8(it2->fulllabel())
401 << "\" share the same shortcut."
409 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
411 const_iterator m = begin();
412 const_iterator m_end = end();
413 for (; m != m_end; ++m) {
414 if (m->kind() == MenuItem::Command && m->func() == func) {
415 names.push(m->label());
417 } else if (m->kind() == MenuItem::Submenu) {
418 names.push(m->label());
419 Menu submenu = menubackend.getMenu(m->submenuname());
420 if (submenu.searchFunc(func, names))
430 void MenuBackend::specialMenu(Menu const & menu)
438 class compare_format {
440 bool operator()(Format const * p1, Format const * p2) {
445 docstring const limit_string_length(docstring const & str)
447 docstring::size_type const max_item_length = 45;
449 if (str.size() > max_item_length)
450 return str.substr(0, max_item_length - 3) + "...";
456 void expandLastfiles(Menu & tomenu)
458 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
459 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
463 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
464 string const file = lfit->absFilename();
465 docstring const label = convert<docstring>(ii) + ". "
466 + makeDisplayPath(file, 30)
467 + char_type('|') + convert<docstring>(ii);
468 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
473 void expandDocuments(Menu & tomenu)
475 Buffer * first = theBufferList().first();
480 // We cannot use a for loop as the buffer list cycles.
482 docstring label = b->fileName().displayName(20);
486 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
487 tomenu.add(MenuItem(MenuItem::Command, label,
488 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
490 b = theBufferList().next(b);
492 } while (b != first);
494 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
495 FuncRequest(LFUN_NOACTION)));
500 void expandBookmarks(Menu & tomenu)
502 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
504 for (size_t i = 1; i <= bm.size(); ++i) {
506 docstring const label = convert<docstring>(i) + ". "
507 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
508 + char_type('|') + convert<docstring>(i);
509 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
510 convert<docstring>(i))));
516 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
518 if (!buf && kind != MenuItem::ImportFormats) {
519 tomenu.add(MenuItem(MenuItem::Command,
520 _("No Document Open!"),
521 FuncRequest(LFUN_NOACTION)));
525 typedef vector<Format const *> Formats;
530 case MenuItem::ImportFormats:
531 formats = theConverters().importableFormats();
532 action = LFUN_BUFFER_IMPORT;
534 case MenuItem::ViewFormats:
535 formats = buf->exportableFormats(true);
536 action = LFUN_BUFFER_VIEW;
538 case MenuItem::UpdateFormats:
539 formats = buf->exportableFormats(true);
540 action = LFUN_BUFFER_UPDATE;
543 formats = buf->exportableFormats(false);
544 action = LFUN_BUFFER_EXPORT;
546 sort(formats.begin(), formats.end(), compare_format());
548 Formats::const_iterator fit = formats.begin();
549 Formats::const_iterator end = formats.end();
550 for (; fit != end ; ++fit) {
553 docstring label = from_utf8((*fit)->prettyname());
556 case MenuItem::ImportFormats:
557 // FIXME: This is a hack, we should rather solve
558 // FIXME: bug 2488 instead.
559 if ((*fit)->name() == "text")
560 label = _("Plain Text");
561 else if ((*fit)->name() == "textparagraph")
562 label = _("Plain Text, Join Lines");
565 case MenuItem::ViewFormats:
566 case MenuItem::ExportFormats:
567 case MenuItem::UpdateFormats:
568 if (!(*fit)->documentFormat())
575 if (!(*fit)->shortcut().empty())
576 label += char_type('|') + from_utf8((*fit)->shortcut());
579 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
580 FuncRequest(action, (*fit)->name())));
582 tomenu.add(MenuItem(MenuItem::Command, label,
583 FuncRequest(action, (*fit)->name())));
588 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
591 tomenu.add(MenuItem(MenuItem::Command,
592 _("No Document Open!"),
593 FuncRequest(LFUN_NOACTION)));
597 FloatList const & floats =
598 buf->params().getTextClass().floats();
599 FloatList::const_iterator cit = floats.begin();
600 FloatList::const_iterator end = floats.end();
601 for (; cit != end; ++cit) {
602 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
603 _(cit->second.listName()),
604 FuncRequest(LFUN_FLOAT_LIST,
605 cit->second.type())));
610 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
613 tomenu.add(MenuItem(MenuItem::Command,
614 _("No Document Open!"),
615 FuncRequest(LFUN_NOACTION)));
619 FloatList const & floats =
620 buf->params().getTextClass().floats();
621 FloatList::const_iterator cit = floats.begin();
622 FloatList::const_iterator end = floats.end();
623 for (; cit != end; ++cit) {
625 docstring const label = _(cit->second.name());
626 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
627 FuncRequest(LFUN_FLOAT_INSERT,
628 cit->second.type())));
633 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
636 tomenu.add(MenuItem(MenuItem::Command,
637 _("No Document Open!"),
638 FuncRequest(LFUN_NOACTION)));
641 InsetLayouts const & insetlayouts =
642 buf->params().getTextClass().insetlayouts();
643 InsetLayouts::const_iterator cit = insetlayouts.begin();
644 InsetLayouts::const_iterator end = insetlayouts.end();
645 for (; cit != end; ++cit) {
646 docstring const label = cit->first;
647 if (cit->second.lyxtype == s)
648 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
649 label, FuncRequest(LFUN_FLEX_INSERT,
655 Menu::size_type const max_number_of_items = 25;
657 void expandToc2(Menu & tomenu,
658 Toc const & toc_list,
660 Toc::size_type to, int depth)
662 int shortcut_count = 0;
664 // check whether depth is smaller than the smallest depth in toc.
665 int min_depth = 1000;
666 for (Toc::size_type i = from; i < to; ++i)
667 min_depth = std::min(min_depth, toc_list[i].depth());
668 if (min_depth > depth)
672 if (to - from <= max_number_of_items) {
673 for (Toc::size_type i = from; i < to; ++i) {
674 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
675 label += limit_string_length(toc_list[i].str());
676 if (toc_list[i].depth() == depth
677 && shortcut_count < 9) {
678 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
679 label += char_type('|') + convert<docstring>(++shortcut_count);
681 tomenu.add(MenuItem(MenuItem::Command, label,
682 FuncRequest(toc_list[i].action())));
685 Toc::size_type pos = from;
687 Toc::size_type new_pos = pos + 1;
688 while (new_pos < to &&
689 toc_list[new_pos].depth() > depth)
692 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
693 label += limit_string_length(toc_list[pos].str());
694 if (toc_list[pos].depth() == depth &&
695 shortcut_count < 9) {
696 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
697 label += char_type('|') + convert<docstring>(++shortcut_count);
699 if (new_pos == pos + 1) {
700 tomenu.add(MenuItem(MenuItem::Command,
701 label, FuncRequest(toc_list[pos].action())));
703 MenuItem item(MenuItem::Submenu, label);
704 item.submenu(new Menu);
705 expandToc2(*item.submenu(),
706 toc_list, pos, new_pos, depth + 1);
715 void expandToc(Menu & tomenu, Buffer const * buf)
717 // To make things very cleanly, we would have to pass buf to
718 // all MenuItem constructors and to expandToc2. However, we
719 // know that all the entries in a TOC will be have status_ ==
720 // OK, so we avoid this unnecessary overhead (JMarc)
723 tomenu.add(MenuItem(MenuItem::Command,
724 _("No Document Open!"),
725 FuncRequest(LFUN_NOACTION)));
729 Buffer* cbuf = const_cast<Buffer*>(buf);
730 cbuf->tocBackend().update();
731 cbuf->structureChanged();
733 // Add an entry for the master doc if this is a child doc
734 Buffer const * const master = buf->masterBuffer();
736 ParIterator const pit = par_iterator_begin(master->inset());
737 string const arg = convert<string>(pit->id());
738 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
739 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
742 FloatList const & floatlist = buf->params().getTextClass().floats();
743 TocList const & toc_list = buf->tocBackend().tocs();
744 TocList::const_iterator cit = toc_list.begin();
745 TocList::const_iterator end = toc_list.end();
746 for (; cit != end; ++cit) {
748 if (cit->first == "tableofcontents")
751 // All the rest is for floats
752 auto_ptr<Menu> menu(new Menu);
753 TocIterator ccit = cit->second.begin();
754 TocIterator eend = cit->second.end();
755 for (; ccit != eend; ++ccit) {
756 docstring const label = limit_string_length(ccit->str());
757 menu->add(MenuItem(MenuItem::Command,
759 FuncRequest(ccit->action())));
761 string const & floatName = floatlist.getType(cit->first).listName();
763 if (!floatName.empty())
764 label = _(floatName);
765 // BUG3633: listings is not a proper float so its name
766 // is not shown in floatlist.
767 else if (cit->first == "listing")
768 label = _("List of listings");
769 // this should not happen now, but if something else like
770 // listings is added later, this can avoid an empty menu name.
772 label = _("Other floats");
773 MenuItem item(MenuItem::Submenu, label);
774 item.submenu(menu.release());
779 cit = toc_list.find("tableofcontents");
781 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
782 _("No Table of contents"),
785 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
790 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
795 vector<docstring> const sel =
796 cap::availableSelections(*buf);
798 vector<docstring>::const_iterator cit = sel.begin();
799 vector<docstring>::const_iterator end = sel.end();
801 for (unsigned int index = 0; cit != end; ++cit, ++index) {
802 tomenu.add(MenuItem(MenuItem::Command, *cit,
803 FuncRequest(LFUN_PASTE, convert<string>(index))));
808 void expandToolbars(Menu & tomenu)
811 // extracts the toolbars from the backend
812 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
813 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
815 for (; cit != end; ++cit) {
816 docstring label = _(cit->gui_name);
817 // frontends are not supposed to turn on/off toolbars,
818 // if they cannot update ToolbarBackend::flags. That
819 // is to say, ToolbarsBackend::flags should reflect
820 // the true state of toolbars.
822 // menu is displayed as
826 // in the case of auto.
827 if (cit->flags & ToolbarInfo::AUTO)
828 label += _(" (auto)");
829 tomenu.add(MenuItem(MenuItem::Command, label,
830 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
835 void expandBranches(Menu & tomenu, Buffer const * buf)
838 tomenu.add(MenuItem(MenuItem::Command,
839 _("No Document Open!"),
840 FuncRequest(LFUN_NOACTION)));
844 BufferParams const & params = buf->masterBuffer()->params();
845 if (params.branchlist().empty()) {
846 tomenu.add(MenuItem(MenuItem::Command,
847 _("No Branch in Document!"),
848 FuncRequest(LFUN_NOACTION)));
852 BranchList::const_iterator cit = params.branchlist().begin();
853 BranchList::const_iterator end = params.branchlist().end();
855 for (int ii = 1; cit != end; ++cit, ++ii) {
856 docstring label = cit->getBranch();
858 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
859 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
860 FuncRequest(LFUN_BRANCH_INSERT,
869 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
870 Buffer const * buf) const
875 for (Menu::const_iterator cit = frommenu.begin();
876 cit != frommenu.end() ; ++cit) {
877 switch (cit->kind()) {
878 case MenuItem::Lastfiles:
879 expandLastfiles(tomenu);
882 case MenuItem::Documents:
883 expandDocuments(tomenu);
886 case MenuItem::Bookmarks:
887 expandBookmarks(tomenu);
890 case MenuItem::ImportFormats:
891 case MenuItem::ViewFormats:
892 case MenuItem::UpdateFormats:
893 case MenuItem::ExportFormats:
894 expandFormats(cit->kind(), tomenu, buf);
897 case MenuItem::CharStyles:
898 expandFlexInsert(tomenu, buf, "charstyle");
901 case MenuItem::Custom:
902 expandFlexInsert(tomenu, buf, "custom");
905 case MenuItem::Elements:
906 expandFlexInsert(tomenu, buf, "element");
909 case MenuItem::FloatListInsert:
910 expandFloatListInsert(tomenu, buf);
913 case MenuItem::FloatInsert:
914 expandFloatInsert(tomenu, buf);
917 case MenuItem::PasteRecent:
918 expandPasteRecent(tomenu, buf);
921 case MenuItem::Toolbars:
922 expandToolbars(tomenu);
925 case MenuItem::Branches:
926 expandBranches(tomenu, buf);
930 expandToc(tomenu, buf);
933 case MenuItem::Submenu: {
935 item.submenu(new Menu(cit->submenuname()));
936 expand(getMenu(cit->submenuname()),
937 *item.submenu(), buf);
938 tomenu.addWithStatusCheck(item);
942 case MenuItem::Separator:
943 tomenu.addWithStatusCheck(*cit);
946 case MenuItem::Command:
947 if (!specialmenu_.hasFunc(cit->func()))
948 tomenu.addWithStatusCheck(*cit);
952 // we do not want the menu to end with a separator
954 && tomenu.items_.back().kind() == MenuItem::Separator)
955 tomenu.items_.pop_back();
957 // Check whether the shortcuts are unique
958 tomenu.checkShortcuts();
962 void MenuBackend::read(Lexer & lex)
971 struct keyword_item menutags[md_last - 1] = {
972 { "end", md_endmenuset },
974 { "menubar", md_menubar }
978 if (compare_ascii_no_case(lex.getString(), "menuset")) {
979 lyxerr << "Menubackend::read: ERROR wrong token:`"
980 << lex.getString() << '\'' << endl;
983 lex.pushTable(menutags, md_last - 1);
984 if (lyxerr.debugging(Debug::PARSER))
985 lex.printTable(lyxerr);
989 while (lex.isOK() && !quit) {
996 docstring const name = lex.getDocString();
998 getMenu(name).read(lex);
1010 lex.printError("menubackend::read: "
1011 "Unknown menu tag: `$$Token'");
1019 void MenuBackend::add(Menu const & menu)
1021 menulist_.push_back(menu);
1025 bool MenuBackend::hasMenu(docstring const & name) const
1027 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1031 Menu const & MenuBackend::getMenu(docstring const & name) const
1033 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1035 lyxerr << "No submenu named " << to_utf8(name) << endl;
1036 BOOST_ASSERT(cit != end());
1041 Menu & MenuBackend::getMenu(docstring const & name)
1043 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1045 lyxerr << "No submenu named " << to_utf8(name) << endl;
1046 BOOST_ASSERT(it != end());
1051 Menu const & MenuBackend::getMenubar() const