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);
146 LYXERR(Debug::KBMAP, "No binding for "
147 << lyxaction.getActionName(func_.action)
148 << '(' << to_utf8(func_.argument()) << ')');
153 Menu & Menu::add(MenuItem const & i)
160 Menu & Menu::addWithStatusCheck(MenuItem const & i)
164 case MenuItem::Command: {
165 FuncStatus status = lyx::getStatus(i.func());
166 if (status.unknown() || (!status.enabled() && i.optional()))
169 items_.back().status(status);
173 case MenuItem::Submenu: {
175 bool enabled = false;
176 for (const_iterator cit = i.submenu()->begin();
177 cit != i.submenu()->end(); ++cit) {
178 if ((cit->kind() == MenuItem::Command
179 || cit->kind() == MenuItem::Submenu)
180 && cit->status().enabled()) {
185 if (enabled || !i.optional()) {
187 items_.back().status().enabled(enabled);
195 case MenuItem::Separator:
197 && items_.back().kind() != MenuItem::Separator)
209 Menu & Menu::read(Lexer & lex)
237 struct keyword_item menutags[md_last - 1] = {
238 { "bookmarks", md_bookmarks },
239 { "branches", md_branches },
240 { "charstyles", md_charstyles },
241 { "custom", md_custom },
242 { "documents", md_documents },
243 { "elements", md_elements },
244 { "end", md_endmenu },
245 { "exportformats", md_exportformats },
246 { "floatinsert", md_floatinsert },
247 { "floatlistinsert", md_floatlistinsert },
248 { "importformats", md_importformats },
250 { "lastfiles", md_lastfiles },
251 { "optitem", md_optitem },
252 { "optsubmenu", md_optsubmenu },
253 { "pasterecent", md_pasterecent },
254 { "separator", md_separator },
255 { "submenu", md_submenu },
257 { "toolbars", md_toolbars },
258 { "updateformats", md_updateformats },
259 { "viewformats", md_viewformats }
262 lex.pushTable(menutags, md_last - 1);
263 if (lyxerr.debugging(Debug::PARSER))
264 lex.printTable(lyxerr);
267 bool optional = false;
269 while (lex.isOK() && !quit) {
273 // fallback to md_item
276 docstring const name = translateIfPossible(lex.getDocString());
278 string const command = lex.getString();
279 FuncRequest func = lyxaction.lookupFunc(command);
280 add(MenuItem(MenuItem::Command, name, func, optional));
286 add(MenuItem(MenuItem::Separator));
290 add(MenuItem(MenuItem::Lastfiles));
294 add(MenuItem(MenuItem::CharStyles));
298 add(MenuItem(MenuItem::Custom));
302 add(MenuItem(MenuItem::Elements));
306 add(MenuItem(MenuItem::Documents));
310 add(MenuItem(MenuItem::Bookmarks));
314 add(MenuItem(MenuItem::Toc));
318 add(MenuItem(MenuItem::ViewFormats));
321 case md_updateformats:
322 add(MenuItem(MenuItem::UpdateFormats));
325 case md_exportformats:
326 add(MenuItem(MenuItem::ExportFormats));
329 case md_importformats:
330 add(MenuItem(MenuItem::ImportFormats));
333 case md_floatlistinsert:
334 add(MenuItem(MenuItem::FloatListInsert));
338 add(MenuItem(MenuItem::FloatInsert));
342 add(MenuItem(MenuItem::PasteRecent));
346 add(MenuItem(MenuItem::Toolbars));
350 add(MenuItem(MenuItem::Branches));
355 // fallback to md_submenu
358 docstring const mlabel = translateIfPossible(lex.getDocString());
360 docstring const mname = lex.getDocString();
361 add(MenuItem(MenuItem::Submenu, mlabel, mname,
372 lex.printError("Menu::read: "
373 "Unknown menu tag: `$$Token'");
382 MenuItem const & Menu::operator[](size_type i) const
388 bool Menu::hasFunc(FuncRequest const & func) const
390 return find_if(begin(), end(),
391 bind(std::equal_to<FuncRequest>(),
392 bind(&MenuItem::func, _1),
396 void Menu::checkShortcuts() const
398 // This is a quadratic algorithm, but we do not care because
399 // menus are short enough
400 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
401 docstring shortcut = it1->shortcut();
402 if (shortcut.empty())
404 if (!contains(it1->label(), shortcut))
405 lyxerr << "Menu warning: menu entry \""
406 << to_utf8(it1->label())
407 << "\" does not contain shortcut `"
408 << to_utf8(shortcut) << "'." << endl;
409 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
410 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
411 lyxerr << "Menu warning: menu entries "
412 << '"' << to_utf8(it1->fulllabel())
413 << "\" and \"" << to_utf8(it2->fulllabel())
414 << "\" share the same shortcut."
422 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
424 const_iterator m = begin();
425 const_iterator m_end = end();
426 for (; m != m_end; ++m) {
427 if (m->kind() == MenuItem::Command && m->func() == func) {
428 names.push(m->label());
430 } else if (m->kind() == MenuItem::Submenu) {
431 names.push(m->label());
432 Menu submenu = menubackend.getMenu(m->submenuname());
433 if (submenu.searchFunc(func, names))
443 void MenuBackend::specialMenu(Menu const & menu)
451 class compare_format {
453 bool operator()(Format const * p1, Format const * p2) {
458 docstring const limit_string_length(docstring const & str)
460 docstring::size_type const max_item_length = 45;
462 if (str.size() > max_item_length)
463 return str.substr(0, max_item_length - 3) + "...";
469 void expandLastfiles(Menu & tomenu)
471 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
472 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
476 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
477 string const file = lfit->absFilename();
478 docstring const label = convert<docstring>(ii) + ". "
479 + makeDisplayPath(file, 30)
480 + char_type('|') + convert<docstring>(ii);
481 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
486 void expandDocuments(Menu & tomenu)
488 Buffer * first = theBufferList().first();
493 // We cannot use a for loop as the buffer list cycles.
495 docstring label = b->fileName().displayName(20);
499 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
500 tomenu.add(MenuItem(MenuItem::Command, label,
501 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
503 b = theBufferList().next(b);
505 } while (b != first);
507 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
508 FuncRequest(LFUN_NOACTION)));
513 void expandBookmarks(Menu & tomenu)
515 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
517 for (size_t i = 1; i <= bm.size(); ++i) {
519 docstring const label = convert<docstring>(i) + ". "
520 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
521 + char_type('|') + convert<docstring>(i);
522 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
523 convert<docstring>(i))));
529 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
531 if (!buf && kind != MenuItem::ImportFormats) {
532 tomenu.add(MenuItem(MenuItem::Command,
533 _("No Document Open!"),
534 FuncRequest(LFUN_NOACTION)));
538 typedef vector<Format const *> Formats;
543 case MenuItem::ImportFormats:
544 formats = theConverters().importableFormats();
545 action = LFUN_BUFFER_IMPORT;
547 case MenuItem::ViewFormats:
548 formats = buf->exportableFormats(true);
549 action = LFUN_BUFFER_VIEW;
551 case MenuItem::UpdateFormats:
552 formats = buf->exportableFormats(true);
553 action = LFUN_BUFFER_UPDATE;
556 formats = buf->exportableFormats(false);
557 action = LFUN_BUFFER_EXPORT;
559 sort(formats.begin(), formats.end(), compare_format());
561 Formats::const_iterator fit = formats.begin();
562 Formats::const_iterator end = formats.end();
563 for (; fit != end ; ++fit) {
566 docstring label = from_utf8((*fit)->prettyname());
569 case MenuItem::ImportFormats:
570 // FIXME: This is a hack, we should rather solve
571 // FIXME: bug 2488 instead.
572 if ((*fit)->name() == "text")
573 label = _("Plain Text");
574 else if ((*fit)->name() == "textparagraph")
575 label = _("Plain Text, Join Lines");
578 case MenuItem::ViewFormats:
579 case MenuItem::ExportFormats:
580 case MenuItem::UpdateFormats:
581 if (!(*fit)->documentFormat())
588 if (!(*fit)->shortcut().empty())
589 label += char_type('|') + from_utf8((*fit)->shortcut());
592 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
593 FuncRequest(action, (*fit)->name())));
595 tomenu.add(MenuItem(MenuItem::Command, label,
596 FuncRequest(action, (*fit)->name())));
601 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
604 tomenu.add(MenuItem(MenuItem::Command,
605 _("No Document Open!"),
606 FuncRequest(LFUN_NOACTION)));
610 FloatList const & floats =
611 buf->params().getTextClass().floats();
612 FloatList::const_iterator cit = floats.begin();
613 FloatList::const_iterator end = floats.end();
614 for (; cit != end; ++cit) {
615 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
616 _(cit->second.listName()),
617 FuncRequest(LFUN_FLOAT_LIST,
618 cit->second.type())));
623 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
626 tomenu.add(MenuItem(MenuItem::Command,
627 _("No Document Open!"),
628 FuncRequest(LFUN_NOACTION)));
632 FloatList const & floats =
633 buf->params().getTextClass().floats();
634 FloatList::const_iterator cit = floats.begin();
635 FloatList::const_iterator end = floats.end();
636 for (; cit != end; ++cit) {
638 docstring const label = _(cit->second.name());
639 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
640 FuncRequest(LFUN_FLOAT_INSERT,
641 cit->second.type())));
646 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
649 tomenu.add(MenuItem(MenuItem::Command,
650 _("No Document Open!"),
651 FuncRequest(LFUN_NOACTION)));
654 InsetLayouts const & insetlayouts =
655 buf->params().getTextClass().insetlayouts();
656 InsetLayouts::const_iterator cit = insetlayouts.begin();
657 InsetLayouts::const_iterator end = insetlayouts.end();
658 for (; cit != end; ++cit) {
659 docstring const label = cit->first;
660 if (cit->second.lyxtype == s)
661 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
662 label, FuncRequest(LFUN_FLEX_INSERT,
668 Menu::size_type const max_number_of_items = 25;
670 void expandToc2(Menu & tomenu,
671 Toc const & toc_list,
673 Toc::size_type to, int depth)
675 int shortcut_count = 0;
677 // check whether depth is smaller than the smallest depth in toc.
678 int min_depth = 1000;
679 for (Toc::size_type i = from; i < to; ++i)
680 min_depth = std::min(min_depth, toc_list[i].depth());
681 if (min_depth > depth)
685 if (to - from <= max_number_of_items) {
686 for (Toc::size_type i = from; i < to; ++i) {
687 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
688 label += limit_string_length(toc_list[i].str());
689 if (toc_list[i].depth() == depth
690 && shortcut_count < 9) {
691 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
692 label += char_type('|') + convert<docstring>(++shortcut_count);
694 tomenu.add(MenuItem(MenuItem::Command, label,
695 FuncRequest(toc_list[i].action())));
698 Toc::size_type pos = from;
700 Toc::size_type new_pos = pos + 1;
701 while (new_pos < to &&
702 toc_list[new_pos].depth() > depth)
705 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
706 label += limit_string_length(toc_list[pos].str());
707 if (toc_list[pos].depth() == depth &&
708 shortcut_count < 9) {
709 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
710 label += char_type('|') + convert<docstring>(++shortcut_count);
712 if (new_pos == pos + 1) {
713 tomenu.add(MenuItem(MenuItem::Command,
714 label, FuncRequest(toc_list[pos].action())));
716 MenuItem item(MenuItem::Submenu, label);
717 item.submenu(new Menu);
718 expandToc2(*item.submenu(),
719 toc_list, pos, new_pos, depth + 1);
728 void expandToc(Menu & tomenu, Buffer const * buf)
730 // To make things very cleanly, we would have to pass buf to
731 // all MenuItem constructors and to expandToc2. However, we
732 // know that all the entries in a TOC will be have status_ ==
733 // OK, so we avoid this unnecessary overhead (JMarc)
736 tomenu.add(MenuItem(MenuItem::Command,
737 _("No Document Open!"),
738 FuncRequest(LFUN_NOACTION)));
742 Buffer* cbuf = const_cast<Buffer*>(buf);
743 cbuf->tocBackend().update();
744 cbuf->structureChanged();
746 // Add an entry for the master doc if this is a child doc
747 Buffer const * const master = buf->masterBuffer();
749 ParIterator const pit = par_iterator_begin(master->inset());
750 string const arg = convert<string>(pit->id());
751 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
752 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
755 FloatList const & floatlist = buf->params().getTextClass().floats();
756 TocList const & toc_list = buf->tocBackend().tocs();
757 TocList::const_iterator cit = toc_list.begin();
758 TocList::const_iterator end = toc_list.end();
759 for (; cit != end; ++cit) {
761 if (cit->first == "tableofcontents")
764 // All the rest is for floats
765 auto_ptr<Menu> menu(new Menu);
766 TocIterator ccit = cit->second.begin();
767 TocIterator eend = cit->second.end();
768 for (; ccit != eend; ++ccit) {
769 docstring const label = limit_string_length(ccit->str());
770 menu->add(MenuItem(MenuItem::Command,
772 FuncRequest(ccit->action())));
774 string const & floatName = floatlist.getType(cit->first).listName();
776 if (!floatName.empty())
777 label = _(floatName);
778 // BUG3633: listings is not a proper float so its name
779 // is not shown in floatlist.
780 else if (cit->first == "listing")
781 label = _("List of listings");
782 // this should not happen now, but if something else like
783 // listings is added later, this can avoid an empty menu name.
785 label = _("Other floats");
786 MenuItem item(MenuItem::Submenu, label);
787 item.submenu(menu.release());
792 cit = toc_list.find("tableofcontents");
794 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
795 _("No Table of contents"),
798 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
803 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
808 vector<docstring> const sel =
809 cap::availableSelections(*buf);
811 vector<docstring>::const_iterator cit = sel.begin();
812 vector<docstring>::const_iterator end = sel.end();
814 for (unsigned int index = 0; cit != end; ++cit, ++index) {
815 tomenu.add(MenuItem(MenuItem::Command, *cit,
816 FuncRequest(LFUN_PASTE, convert<string>(index))));
821 void expandToolbars(Menu & tomenu)
824 // extracts the toolbars from the backend
825 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
826 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
828 for (; cit != end; ++cit) {
829 docstring label = _(cit->gui_name);
830 // frontends are not supposed to turn on/off toolbars,
831 // if they cannot update ToolbarBackend::flags. That
832 // is to say, ToolbarsBackend::flags should reflect
833 // the true state of toolbars.
835 // menu is displayed as
839 // in the case of auto.
840 if (cit->flags & ToolbarInfo::AUTO)
841 label += _(" (auto)");
842 tomenu.add(MenuItem(MenuItem::Command, label,
843 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
848 void expandBranches(Menu & tomenu, Buffer const * buf)
851 tomenu.add(MenuItem(MenuItem::Command,
852 _("No Document Open!"),
853 FuncRequest(LFUN_NOACTION)));
857 BufferParams const & params = buf->masterBuffer()->params();
858 if (params.branchlist().empty()) {
859 tomenu.add(MenuItem(MenuItem::Command,
860 _("No Branch in Document!"),
861 FuncRequest(LFUN_NOACTION)));
865 BranchList::const_iterator cit = params.branchlist().begin();
866 BranchList::const_iterator end = params.branchlist().end();
868 for (int ii = 1; cit != end; ++cit, ++ii) {
869 docstring label = cit->getBranch();
871 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
872 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
873 FuncRequest(LFUN_BRANCH_INSERT,
882 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
883 Buffer const * buf) const
888 for (Menu::const_iterator cit = frommenu.begin();
889 cit != frommenu.end() ; ++cit) {
890 switch (cit->kind()) {
891 case MenuItem::Lastfiles:
892 expandLastfiles(tomenu);
895 case MenuItem::Documents:
896 expandDocuments(tomenu);
899 case MenuItem::Bookmarks:
900 expandBookmarks(tomenu);
903 case MenuItem::ImportFormats:
904 case MenuItem::ViewFormats:
905 case MenuItem::UpdateFormats:
906 case MenuItem::ExportFormats:
907 expandFormats(cit->kind(), tomenu, buf);
910 case MenuItem::CharStyles:
911 expandFlexInsert(tomenu, buf, "charstyle");
914 case MenuItem::Custom:
915 expandFlexInsert(tomenu, buf, "custom");
918 case MenuItem::Elements:
919 expandFlexInsert(tomenu, buf, "element");
922 case MenuItem::FloatListInsert:
923 expandFloatListInsert(tomenu, buf);
926 case MenuItem::FloatInsert:
927 expandFloatInsert(tomenu, buf);
930 case MenuItem::PasteRecent:
931 expandPasteRecent(tomenu, buf);
934 case MenuItem::Toolbars:
935 expandToolbars(tomenu);
938 case MenuItem::Branches:
939 expandBranches(tomenu, buf);
943 expandToc(tomenu, buf);
946 case MenuItem::Submenu: {
948 item.submenu(new Menu(cit->submenuname()));
949 expand(getMenu(cit->submenuname()),
950 *item.submenu(), buf);
951 tomenu.addWithStatusCheck(item);
955 case MenuItem::Separator:
956 tomenu.addWithStatusCheck(*cit);
959 case MenuItem::Command:
960 if (!specialmenu_.hasFunc(cit->func()))
961 tomenu.addWithStatusCheck(*cit);
965 // we do not want the menu to end with a separator
967 && tomenu.items_.back().kind() == MenuItem::Separator)
968 tomenu.items_.pop_back();
970 // Check whether the shortcuts are unique
971 tomenu.checkShortcuts();
975 void MenuBackend::read(Lexer & lex)
984 struct keyword_item menutags[md_last - 1] = {
985 { "end", md_endmenuset },
987 { "menubar", md_menubar }
991 if (compare_ascii_no_case(lex.getString(), "menuset")) {
992 lyxerr << "Menubackend::read: ERROR wrong token:`"
993 << lex.getString() << '\'' << endl;
996 lex.pushTable(menutags, md_last - 1);
997 if (lyxerr.debugging(Debug::PARSER))
998 lex.printTable(lyxerr);
1002 while (lex.isOK() && !quit) {
1003 switch (lex.lex()) {
1009 docstring const name = lex.getDocString();
1010 if (hasMenu(name)) {
1011 getMenu(name).read(lex);
1023 lex.printError("menubackend::read: "
1024 "Unknown menu tag: `$$Token'");
1032 void MenuBackend::add(Menu const & menu)
1034 menulist_.push_back(menu);
1038 bool MenuBackend::hasMenu(docstring const & name) const
1040 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1044 Menu const & MenuBackend::getMenu(docstring const & name) const
1046 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1048 lyxerr << "No submenu named " << to_utf8(name) << endl;
1049 BOOST_ASSERT(cit != end());
1054 Menu & MenuBackend::getMenu(docstring const & name)
1056 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1058 lyxerr << "No submenu named " << to_utf8(name) << endl;
1059 BOOST_ASSERT(it != end());
1064 Menu const & MenuBackend::getMenubar() const