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 "frontends/Application.h"
44 #include "support/filetools.h"
45 #include "support/lstrings.h"
46 #include "support/convert.h"
48 #include <boost/bind.hpp>
55 using namespace lyx::support;
61 class MenuNamesEqual : public unary_function<Menu, bool> {
63 MenuNamesEqual(docstring const & name)
65 bool operator()(Menu const & menu) const {
66 return menu.name() == name_;
75 MenuItem::MenuItem(Kind kind)
76 : kind_(kind), optional_(false)
80 MenuItem::MenuItem(Kind kind, docstring const & label,
81 docstring const & submenu, bool optional)
82 : kind_(kind), label_(label),
83 submenuname_(submenu), optional_(optional)
85 BOOST_ASSERT(kind == Submenu);
89 MenuItem::MenuItem(Kind kind, docstring const & label,
90 FuncRequest const & func, bool optional)
91 : kind_(kind), label_(label), func_(func), optional_(optional)
93 func_.origin = FuncRequest::MENU;
101 void MenuItem::submenu(Menu * menu)
103 submenu_.reset(menu);
107 docstring const MenuItem::label() const
109 return token(label_, char_type('|'), 0);
113 docstring const MenuItem::shortcut() const
115 return token(label_, char_type('|'), 1);
119 docstring const MenuItem::binding(bool forgui) const
121 if (kind_ != Command)
124 // Get the keys bound to this action, but keep only the
126 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
129 return bindings.begin()->print(KeySequence::ForGui);
131 LYXERR(Debug::KBMAP, "No binding for "
132 << lyxaction.getActionName(func_.action)
133 << '(' << to_utf8(func_.argument()) << ')');
138 Menu & Menu::add(MenuItem const & i)
145 Menu & Menu::addWithStatusCheck(MenuItem const & i)
149 case MenuItem::Command: {
150 FuncStatus status = lyx::getStatus(i.func());
151 if (status.unknown() || (!status.enabled() && i.optional()))
154 items_.back().status(status);
158 case MenuItem::Submenu: {
160 bool enabled = false;
161 for (const_iterator cit = i.submenu()->begin();
162 cit != i.submenu()->end(); ++cit) {
163 if ((cit->kind() == MenuItem::Command
164 || cit->kind() == MenuItem::Submenu)
165 && cit->status().enabled()) {
170 if (enabled || !i.optional()) {
172 items_.back().status().enabled(enabled);
180 case MenuItem::Separator:
182 && items_.back().kind() != MenuItem::Separator)
194 Menu & Menu::read(Lexer & lex)
222 struct keyword_item menutags[md_last - 1] = {
223 { "bookmarks", md_bookmarks },
224 { "branches", md_branches },
225 { "charstyles", md_charstyles },
226 { "custom", md_custom },
227 { "documents", md_documents },
228 { "elements", md_elements },
229 { "end", md_endmenu },
230 { "exportformats", md_exportformats },
231 { "floatinsert", md_floatinsert },
232 { "floatlistinsert", md_floatlistinsert },
233 { "importformats", md_importformats },
235 { "lastfiles", md_lastfiles },
236 { "optitem", md_optitem },
237 { "optsubmenu", md_optsubmenu },
238 { "pasterecent", md_pasterecent },
239 { "separator", md_separator },
240 { "submenu", md_submenu },
242 { "toolbars", md_toolbars },
243 { "updateformats", md_updateformats },
244 { "viewformats", md_viewformats }
247 lex.pushTable(menutags, md_last - 1);
248 if (lyxerr.debugging(Debug::PARSER))
249 lex.printTable(lyxerr);
252 bool optional = false;
254 while (lex.isOK() && !quit) {
258 // fallback to md_item
261 docstring const name = translateIfPossible(lex.getDocString());
263 string const command = lex.getString();
264 FuncRequest func = lyxaction.lookupFunc(command);
265 add(MenuItem(MenuItem::Command, name, func, optional));
271 add(MenuItem(MenuItem::Separator));
275 add(MenuItem(MenuItem::Lastfiles));
279 add(MenuItem(MenuItem::CharStyles));
283 add(MenuItem(MenuItem::Custom));
287 add(MenuItem(MenuItem::Elements));
291 add(MenuItem(MenuItem::Documents));
295 add(MenuItem(MenuItem::Bookmarks));
299 add(MenuItem(MenuItem::Toc));
303 add(MenuItem(MenuItem::ViewFormats));
306 case md_updateformats:
307 add(MenuItem(MenuItem::UpdateFormats));
310 case md_exportformats:
311 add(MenuItem(MenuItem::ExportFormats));
314 case md_importformats:
315 add(MenuItem(MenuItem::ImportFormats));
318 case md_floatlistinsert:
319 add(MenuItem(MenuItem::FloatListInsert));
323 add(MenuItem(MenuItem::FloatInsert));
327 add(MenuItem(MenuItem::PasteRecent));
331 add(MenuItem(MenuItem::Toolbars));
335 add(MenuItem(MenuItem::Branches));
340 // fallback to md_submenu
343 docstring const mlabel = translateIfPossible(lex.getDocString());
345 docstring const mname = lex.getDocString();
346 add(MenuItem(MenuItem::Submenu, mlabel, mname,
357 lex.printError("Menu::read: "
358 "Unknown menu tag: `$$Token'");
367 MenuItem const & Menu::operator[](size_type i) const
373 bool Menu::hasFunc(FuncRequest const & func) const
375 return find_if(begin(), end(),
376 bind(equal_to<FuncRequest>(),
377 bind(&MenuItem::func, _1),
381 void Menu::checkShortcuts() const
383 // This is a quadratic algorithm, but we do not care because
384 // menus are short enough
385 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
386 docstring shortcut = it1->shortcut();
387 if (shortcut.empty())
389 if (!contains(it1->label(), shortcut))
390 lyxerr << "Menu warning: menu entry \""
391 << to_utf8(it1->label())
392 << "\" does not contain shortcut `"
393 << to_utf8(shortcut) << "'." << endl;
394 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
395 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
396 lyxerr << "Menu warning: menu entries "
397 << '"' << to_utf8(it1->fulllabel())
398 << "\" and \"" << to_utf8(it2->fulllabel())
399 << "\" share the same shortcut."
407 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names) const
409 const_iterator m = begin();
410 const_iterator m_end = end();
411 for (; m != m_end; ++m) {
412 if (m->kind() == MenuItem::Command && m->func() == func) {
413 names.push(m->label());
415 } else if (m->kind() == MenuItem::Submenu) {
416 names.push(m->label());
417 Menu submenu = theApp()->menuBackend().getMenu(m->submenuname());
418 if (submenu.searchFunc(func, names))
428 void MenuBackend::specialMenu(Menu const & menu)
436 class compare_format {
438 bool operator()(Format const * p1, Format const * p2) {
443 docstring const limit_string_length(docstring const & str)
445 docstring::size_type const max_item_length = 45;
447 if (str.size() > max_item_length)
448 return str.substr(0, max_item_length - 3) + "...";
454 void expandLastfiles(Menu & tomenu)
456 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
457 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
461 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
462 string const file = lfit->absFilename();
463 docstring const label = convert<docstring>(ii) + ". "
464 + makeDisplayPath(file, 30)
465 + char_type('|') + convert<docstring>(ii);
466 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
471 void expandDocuments(Menu & tomenu)
473 Buffer * first = theBufferList().first();
478 // We cannot use a for loop as the buffer list cycles.
480 docstring label = b->fileName().displayName(20);
484 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
485 tomenu.add(MenuItem(MenuItem::Command, label,
486 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
488 b = theBufferList().next(b);
490 } while (b != first);
492 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
493 FuncRequest(LFUN_NOACTION)));
498 void expandBookmarks(Menu & tomenu)
500 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
502 for (size_t i = 1; i <= bm.size(); ++i) {
504 docstring const label = convert<docstring>(i) + ". "
505 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
506 + char_type('|') + convert<docstring>(i);
507 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
508 convert<docstring>(i))));
514 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
516 if (!buf && kind != MenuItem::ImportFormats) {
517 tomenu.add(MenuItem(MenuItem::Command,
518 _("No Document Open!"),
519 FuncRequest(LFUN_NOACTION)));
523 typedef vector<Format const *> Formats;
528 case MenuItem::ImportFormats:
529 formats = theConverters().importableFormats();
530 action = LFUN_BUFFER_IMPORT;
532 case MenuItem::ViewFormats:
533 formats = buf->exportableFormats(true);
534 action = LFUN_BUFFER_VIEW;
536 case MenuItem::UpdateFormats:
537 formats = buf->exportableFormats(true);
538 action = LFUN_BUFFER_UPDATE;
541 formats = buf->exportableFormats(false);
542 action = LFUN_BUFFER_EXPORT;
544 sort(formats.begin(), formats.end(), compare_format());
546 Formats::const_iterator fit = formats.begin();
547 Formats::const_iterator end = formats.end();
548 for (; fit != end ; ++fit) {
551 docstring label = from_utf8((*fit)->prettyname());
554 case MenuItem::ImportFormats:
555 // FIXME: This is a hack, we should rather solve
556 // FIXME: bug 2488 instead.
557 if ((*fit)->name() == "text")
558 label = _("Plain Text");
559 else if ((*fit)->name() == "textparagraph")
560 label = _("Plain Text, Join Lines");
563 case MenuItem::ViewFormats:
564 case MenuItem::ExportFormats:
565 case MenuItem::UpdateFormats:
566 if (!(*fit)->documentFormat())
573 if (!(*fit)->shortcut().empty())
574 label += char_type('|') + from_utf8((*fit)->shortcut());
577 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
578 FuncRequest(action, (*fit)->name())));
580 tomenu.add(MenuItem(MenuItem::Command, label,
581 FuncRequest(action, (*fit)->name())));
586 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
589 tomenu.add(MenuItem(MenuItem::Command,
590 _("No Document Open!"),
591 FuncRequest(LFUN_NOACTION)));
595 FloatList const & floats =
596 buf->params().getTextClass().floats();
597 FloatList::const_iterator cit = floats.begin();
598 FloatList::const_iterator end = floats.end();
599 for (; cit != end; ++cit) {
600 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
601 _(cit->second.listName()),
602 FuncRequest(LFUN_FLOAT_LIST,
603 cit->second.type())));
608 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
611 tomenu.add(MenuItem(MenuItem::Command,
612 _("No Document Open!"),
613 FuncRequest(LFUN_NOACTION)));
617 FloatList const & floats =
618 buf->params().getTextClass().floats();
619 FloatList::const_iterator cit = floats.begin();
620 FloatList::const_iterator end = floats.end();
621 for (; cit != end; ++cit) {
623 docstring const label = _(cit->second.name());
624 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
625 FuncRequest(LFUN_FLOAT_INSERT,
626 cit->second.type())));
631 void expandFlexInsert(Menu & tomenu, Buffer const * buf, string s)
634 tomenu.add(MenuItem(MenuItem::Command,
635 _("No Document Open!"),
636 FuncRequest(LFUN_NOACTION)));
639 InsetLayouts const & insetlayouts =
640 buf->params().getTextClass().insetlayouts();
641 InsetLayouts::const_iterator cit = insetlayouts.begin();
642 InsetLayouts::const_iterator end = insetlayouts.end();
643 for (; cit != end; ++cit) {
644 docstring const label = cit->first;
645 if (cit->second.lyxtype == s)
646 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
647 label, FuncRequest(LFUN_FLEX_INSERT,
653 Menu::size_type const max_number_of_items = 25;
655 void expandToc2(Menu & tomenu,
656 Toc const & toc_list,
658 Toc::size_type to, int depth)
660 int shortcut_count = 0;
662 // check whether depth is smaller than the smallest depth in toc.
663 int min_depth = 1000;
664 for (Toc::size_type i = from; i < to; ++i)
665 min_depth = min(min_depth, toc_list[i].depth());
666 if (min_depth > depth)
670 if (to - from <= max_number_of_items) {
671 for (Toc::size_type i = from; i < to; ++i) {
672 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
673 label += limit_string_length(toc_list[i].str());
674 if (toc_list[i].depth() == depth
675 && shortcut_count < 9) {
676 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
677 label += char_type('|') + convert<docstring>(++shortcut_count);
679 tomenu.add(MenuItem(MenuItem::Command, label,
680 FuncRequest(toc_list[i].action())));
683 Toc::size_type pos = from;
685 Toc::size_type new_pos = pos + 1;
686 while (new_pos < to &&
687 toc_list[new_pos].depth() > depth)
690 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
691 label += limit_string_length(toc_list[pos].str());
692 if (toc_list[pos].depth() == depth &&
693 shortcut_count < 9) {
694 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
695 label += char_type('|') + convert<docstring>(++shortcut_count);
697 if (new_pos == pos + 1) {
698 tomenu.add(MenuItem(MenuItem::Command,
699 label, FuncRequest(toc_list[pos].action())));
701 MenuItem item(MenuItem::Submenu, label);
702 item.submenu(new Menu);
703 expandToc2(*item.submenu(),
704 toc_list, pos, new_pos, depth + 1);
713 void expandToc(Menu & tomenu, Buffer const * buf)
715 // To make things very cleanly, we would have to pass buf to
716 // all MenuItem constructors and to expandToc2. However, we
717 // know that all the entries in a TOC will be have status_ ==
718 // OK, so we avoid this unnecessary overhead (JMarc)
721 tomenu.add(MenuItem(MenuItem::Command,
722 _("No Document Open!"),
723 FuncRequest(LFUN_NOACTION)));
727 Buffer* cbuf = const_cast<Buffer*>(buf);
728 cbuf->tocBackend().update();
729 cbuf->structureChanged();
731 // Add an entry for the master doc if this is a child doc
732 Buffer const * const master = buf->masterBuffer();
734 ParIterator const pit = par_iterator_begin(master->inset());
735 string const arg = convert<string>(pit->id());
736 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
737 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
740 FloatList const & floatlist = buf->params().getTextClass().floats();
741 TocList const & toc_list = buf->tocBackend().tocs();
742 TocList::const_iterator cit = toc_list.begin();
743 TocList::const_iterator end = toc_list.end();
744 for (; cit != end; ++cit) {
746 if (cit->first == "tableofcontents")
749 // All the rest is for floats
750 auto_ptr<Menu> menu(new Menu);
751 TocIterator ccit = cit->second.begin();
752 TocIterator eend = cit->second.end();
753 for (; ccit != eend; ++ccit) {
754 docstring const label = limit_string_length(ccit->str());
755 menu->add(MenuItem(MenuItem::Command,
757 FuncRequest(ccit->action())));
759 string const & floatName = floatlist.getType(cit->first).listName();
761 if (!floatName.empty())
762 label = _(floatName);
763 // BUG3633: listings is not a proper float so its name
764 // is not shown in floatlist.
765 else if (cit->first == "listing")
766 label = _("List of listings");
767 // this should not happen now, but if something else like
768 // listings is added later, this can avoid an empty menu name.
770 label = _("Other floats");
771 MenuItem item(MenuItem::Submenu, label);
772 item.submenu(menu.release());
777 cit = toc_list.find("tableofcontents");
779 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
780 _("No Table of contents"),
783 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
788 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
793 vector<docstring> const sel =
794 cap::availableSelections(*buf);
796 vector<docstring>::const_iterator cit = sel.begin();
797 vector<docstring>::const_iterator end = sel.end();
799 for (unsigned int index = 0; cit != end; ++cit, ++index) {
800 tomenu.add(MenuItem(MenuItem::Command, *cit,
801 FuncRequest(LFUN_PASTE, convert<string>(index))));
806 void expandToolbars(Menu & tomenu)
809 // extracts the toolbars from the backend
810 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
811 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
813 for (; cit != end; ++cit) {
814 docstring label = _(cit->gui_name);
815 // frontends are not supposed to turn on/off toolbars,
816 // if they cannot update ToolbarBackend::flags. That
817 // is to say, ToolbarsBackend::flags should reflect
818 // the true state of toolbars.
820 // menu is displayed as
824 // in the case of auto.
825 if (cit->flags & ToolbarInfo::AUTO)
826 label += _(" (auto)");
827 tomenu.add(MenuItem(MenuItem::Command, label,
828 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
833 void expandBranches(Menu & tomenu, Buffer const * buf)
836 tomenu.add(MenuItem(MenuItem::Command,
837 _("No Document Open!"),
838 FuncRequest(LFUN_NOACTION)));
842 BufferParams const & params = buf->masterBuffer()->params();
843 if (params.branchlist().empty()) {
844 tomenu.add(MenuItem(MenuItem::Command,
845 _("No Branch in Document!"),
846 FuncRequest(LFUN_NOACTION)));
850 BranchList::const_iterator cit = params.branchlist().begin();
851 BranchList::const_iterator end = params.branchlist().end();
853 for (int ii = 1; cit != end; ++cit, ++ii) {
854 docstring label = cit->getBranch();
856 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
857 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
858 FuncRequest(LFUN_BRANCH_INSERT,
867 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
868 Buffer const * buf) const
873 for (Menu::const_iterator cit = frommenu.begin();
874 cit != frommenu.end() ; ++cit) {
875 switch (cit->kind()) {
876 case MenuItem::Lastfiles:
877 expandLastfiles(tomenu);
880 case MenuItem::Documents:
881 expandDocuments(tomenu);
884 case MenuItem::Bookmarks:
885 expandBookmarks(tomenu);
888 case MenuItem::ImportFormats:
889 case MenuItem::ViewFormats:
890 case MenuItem::UpdateFormats:
891 case MenuItem::ExportFormats:
892 expandFormats(cit->kind(), tomenu, buf);
895 case MenuItem::CharStyles:
896 expandFlexInsert(tomenu, buf, "charstyle");
899 case MenuItem::Custom:
900 expandFlexInsert(tomenu, buf, "custom");
903 case MenuItem::Elements:
904 expandFlexInsert(tomenu, buf, "element");
907 case MenuItem::FloatListInsert:
908 expandFloatListInsert(tomenu, buf);
911 case MenuItem::FloatInsert:
912 expandFloatInsert(tomenu, buf);
915 case MenuItem::PasteRecent:
916 expandPasteRecent(tomenu, buf);
919 case MenuItem::Toolbars:
920 expandToolbars(tomenu);
923 case MenuItem::Branches:
924 expandBranches(tomenu, buf);
928 expandToc(tomenu, buf);
931 case MenuItem::Submenu: {
933 item.submenu(new Menu(cit->submenuname()));
934 expand(getMenu(cit->submenuname()),
935 *item.submenu(), buf);
936 tomenu.addWithStatusCheck(item);
940 case MenuItem::Separator:
941 tomenu.addWithStatusCheck(*cit);
944 case MenuItem::Command:
945 if (!specialmenu_.hasFunc(cit->func()))
946 tomenu.addWithStatusCheck(*cit);
950 // we do not want the menu to end with a separator
952 && tomenu.items_.back().kind() == MenuItem::Separator)
953 tomenu.items_.pop_back();
955 // Check whether the shortcuts are unique
956 tomenu.checkShortcuts();
960 void MenuBackend::read(Lexer & lex)
969 struct keyword_item menutags[md_last - 1] = {
970 { "end", md_endmenuset },
972 { "menubar", md_menubar }
976 if (compare_ascii_no_case(lex.getString(), "menuset")) {
977 lyxerr << "Menubackend::read: ERROR wrong token:`"
978 << lex.getString() << '\'' << endl;
981 lex.pushTable(menutags, md_last - 1);
982 if (lyxerr.debugging(Debug::PARSER))
983 lex.printTable(lyxerr);
987 while (lex.isOK() && !quit) {
994 docstring const name = lex.getDocString();
996 getMenu(name).read(lex);
1008 lex.printError("menubackend::read: "
1009 "Unknown menu tag: `$$Token'");
1017 void MenuBackend::add(Menu const & menu)
1019 menulist_.push_back(menu);
1023 bool MenuBackend::hasMenu(docstring const & name) const
1025 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1029 Menu const & MenuBackend::getMenu(docstring const & name) const
1031 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1033 lyxerr << "No submenu named " << to_utf8(name) << endl;
1034 BOOST_ASSERT(cit != end());
1039 Menu & MenuBackend::getMenu(docstring const & name)
1041 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1043 lyxerr << "No submenu named " << to_utf8(name) << endl;
1044 BOOST_ASSERT(it != end());
1049 Menu const & MenuBackend::getMenubar() const