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 "TocBackend.h"
39 #include "ToolbarBackend.h"
41 #include "support/filetools.h"
42 #include "support/lstrings.h"
43 #include "support/convert.h"
45 #include <boost/bind.hpp>
52 using support::compare_ascii_no_case;
53 using support::contains;
54 using support::makeDisplayPath;
71 class MenuNamesEqual : public std::unary_function<Menu, bool> {
73 MenuNamesEqual(docstring const & name)
75 bool operator()(Menu const & menu) const {
76 return menu.name() == name_;
85 // This is the global menu definition
86 MenuBackend menubackend;
89 MenuItem::MenuItem(Kind kind)
90 : kind_(kind), optional_(false)
94 MenuItem::MenuItem(Kind kind, docstring const & label,
95 docstring const & submenu, bool optional)
96 : kind_(kind), label_(label),
97 submenuname_(submenu), optional_(optional)
99 BOOST_ASSERT(kind == Submenu);
103 MenuItem::MenuItem(Kind kind, docstring const & label,
104 FuncRequest const & func, bool optional)
105 : kind_(kind), label_(label), func_(func), optional_(optional)
107 func_.origin = FuncRequest::MENU;
111 MenuItem::~MenuItem()
115 void MenuItem::submenu(Menu * menu)
117 submenu_.reset(menu);
121 docstring const MenuItem::label() const
123 return token(label_, char_type('|'), 0);
127 docstring const MenuItem::shortcut() const
129 return token(label_, char_type('|'), 1);
133 docstring const MenuItem::binding(bool forgui) const
135 if (kind_ != Command)
138 // Get the keys bound to this action, but keep only the
140 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
142 if (bindings.size()) {
143 return bindings.begin()->print(KeySequence::ForGui);
147 << lyxaction.getActionName(func_.action)
148 << '(' << to_utf8(func_.argument()) << ')' << endl;
155 Menu & Menu::add(MenuItem const & i)
162 Menu & Menu::addWithStatusCheck(MenuItem const & i)
166 case MenuItem::Command: {
167 FuncStatus status = lyx::getStatus(i.func());
168 if (status.unknown() || (!status.enabled() && i.optional()))
171 items_.back().status(status);
175 case MenuItem::Submenu: {
177 bool enabled = false;
178 for (const_iterator cit = i.submenu()->begin();
179 cit != i.submenu()->end(); ++cit) {
180 if ((cit->kind() == MenuItem::Command
181 || cit->kind() == MenuItem::Submenu)
182 && cit->status().enabled()) {
187 if (enabled || !i.optional()) {
189 items_.back().status().enabled(enabled);
197 case MenuItem::Separator:
199 && items_.back().kind() != MenuItem::Separator)
211 Menu & Menu::read(Lexer & lex)
239 struct keyword_item menutags[md_last - 1] = {
240 { "bookmarks", md_bookmarks },
241 { "branches", md_branches },
242 { "charstyles", md_charstyles },
243 { "custom", md_custom },
244 { "documents", md_documents },
245 { "elements", md_elements },
246 { "end", md_endmenu },
247 { "exportformats", md_exportformats },
248 { "floatinsert", md_floatinsert },
249 { "floatlistinsert", md_floatlistinsert },
250 { "importformats", md_importformats },
252 { "lastfiles", md_lastfiles },
253 { "optitem", md_optitem },
254 { "optsubmenu", md_optsubmenu },
255 { "pasterecent", md_pasterecent },
256 { "separator", md_separator },
257 { "submenu", md_submenu },
259 { "toolbars", md_toolbars },
260 { "updateformats", md_updateformats },
261 { "viewformats", md_viewformats }
264 lex.pushTable(menutags, md_last - 1);
265 if (lyxerr.debugging(Debug::PARSER))
266 lex.printTable(lyxerr);
269 bool optional = false;
271 while (lex.isOK() && !quit) {
275 // fallback to md_item
278 docstring const name = translateIfPossible(lex.getDocString());
280 string const command = lex.getString();
281 FuncRequest func = lyxaction.lookupFunc(command);
282 add(MenuItem(MenuItem::Command, name, func, optional));
288 add(MenuItem(MenuItem::Separator));
292 add(MenuItem(MenuItem::Lastfiles));
296 add(MenuItem(MenuItem::CharStyles));
300 add(MenuItem(MenuItem::Custom));
304 add(MenuItem(MenuItem::Elements));
308 add(MenuItem(MenuItem::Documents));
312 add(MenuItem(MenuItem::Bookmarks));
316 add(MenuItem(MenuItem::Toc));
320 add(MenuItem(MenuItem::ViewFormats));
323 case md_updateformats:
324 add(MenuItem(MenuItem::UpdateFormats));
327 case md_exportformats:
328 add(MenuItem(MenuItem::ExportFormats));
331 case md_importformats:
332 add(MenuItem(MenuItem::ImportFormats));
335 case md_floatlistinsert:
336 add(MenuItem(MenuItem::FloatListInsert));
340 add(MenuItem(MenuItem::FloatInsert));
344 add(MenuItem(MenuItem::PasteRecent));
348 add(MenuItem(MenuItem::Toolbars));
352 add(MenuItem(MenuItem::Branches));
357 // fallback to md_submenu
360 docstring const mlabel = translateIfPossible(lex.getDocString());
362 docstring const mname = lex.getDocString();
363 add(MenuItem(MenuItem::Submenu, mlabel, mname,
374 lex.printError("Menu::read: "
375 "Unknown menu tag: `$$Token'");
384 MenuItem const & Menu::operator[](size_type i) const
390 bool Menu::hasFunc(FuncRequest const & func) const
392 return find_if(begin(), end(),
393 bind(std::equal_to<FuncRequest>(),
394 bind(&MenuItem::func, _1),
398 void Menu::checkShortcuts() const
400 // This is a quadratic algorithm, but we do not care because
401 // menus are short enough
402 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
403 docstring shortcut = it1->shortcut();
404 if (shortcut.empty())
406 if (!contains(it1->label(), shortcut))
407 lyxerr << "Menu warning: menu entry \""
408 << to_utf8(it1->label())
409 << "\" does not contain shortcut `"
410 << to_utf8(shortcut) << "'." << endl;
411 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
412 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
413 lyxerr << "Menu warning: menu entries "
414 << '"' << to_utf8(it1->fulllabel())
415 << "\" and \"" << to_utf8(it2->fulllabel())
416 << "\" share the same shortcut."
424 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
426 const_iterator m = begin();
427 const_iterator m_end = end();
428 for (; m != m_end; ++m) {
429 if (m->kind() == MenuItem::Command && m->func() == func) {
430 names.push(m->label());
432 } else if (m->kind() == MenuItem::Submenu) {
433 names.push(m->label());
434 Menu submenu = menubackend.getMenu(m->submenuname());
435 if (submenu.searchFunc(func, names))
445 void MenuBackend::specialMenu(Menu const & menu)
453 class compare_format {
455 bool operator()(Format const * p1, Format const * p2) {
460 docstring const limit_string_length(docstring const & str)
462 docstring::size_type const max_item_length = 45;
464 if (str.size() > max_item_length)
465 return str.substr(0, max_item_length - 3) + "...";
471 void expandLastfiles(Menu & tomenu)
473 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
474 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
478 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
479 string const file = lfit->absFilename();
480 docstring const label = convert<docstring>(ii) + ". "
481 + makeDisplayPath(file, 30)
482 + char_type('|') + convert<docstring>(ii);
483 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
488 void expandDocuments(Menu & tomenu)
490 Buffer * first = theBufferList().first();
495 // We cannot use a for loop as the buffer list cycles.
497 docstring label = makeDisplayPath(b->absFileName(), 20);
498 if (!b->isClean()) label = label + "*";
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)));
515 void expandBookmarks(Menu & tomenu)
517 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
519 for (size_t i = 1; i <= bm.size(); ++i) {
521 docstring const label = convert<docstring>(i) + ". "
522 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
523 + char_type('|') + convert<docstring>(i);
524 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
525 convert<docstring>(i))));
531 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
533 if (!buf && kind != MenuItem::ImportFormats) {
534 tomenu.add(MenuItem(MenuItem::Command,
535 _("No Document Open!"),
536 FuncRequest(LFUN_NOACTION)));
540 typedef vector<Format const *> Formats;
545 case MenuItem::ImportFormats:
546 formats = theConverters().importableFormats();
547 action = LFUN_BUFFER_IMPORT;
549 case MenuItem::ViewFormats:
550 formats = buf->exportableFormats(true);
551 action = LFUN_BUFFER_VIEW;
553 case MenuItem::UpdateFormats:
554 formats = buf->exportableFormats(true);
555 action = LFUN_BUFFER_UPDATE;
558 formats = buf->exportableFormats(false);
559 action = LFUN_BUFFER_EXPORT;
561 sort(formats.begin(), formats.end(), compare_format());
563 Formats::const_iterator fit = formats.begin();
564 Formats::const_iterator end = formats.end();
565 for (; fit != end ; ++fit) {
568 docstring label = from_utf8((*fit)->prettyname());
571 case MenuItem::ImportFormats:
572 // FIXME: This is a hack, we should rather solve
573 // FIXME: bug 2488 instead.
574 if ((*fit)->name() == "text")
575 label = _("Plain Text");
576 else if ((*fit)->name() == "textparagraph")
577 label = _("Plain Text, Join Lines");
580 case MenuItem::ViewFormats:
581 case MenuItem::ExportFormats:
582 case MenuItem::UpdateFormats:
583 if (!(*fit)->documentFormat())
590 if (!(*fit)->shortcut().empty())
591 label += char_type('|') + from_utf8((*fit)->shortcut());
594 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
595 FuncRequest(action, (*fit)->name())));
597 tomenu.add(MenuItem(MenuItem::Command, label,
598 FuncRequest(action, (*fit)->name())));
603 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
606 tomenu.add(MenuItem(MenuItem::Command,
607 _("No Document Open!"),
608 FuncRequest(LFUN_NOACTION)));
612 FloatList const & floats =
613 buf->params().getTextClass().floats();
614 FloatList::const_iterator cit = floats.begin();
615 FloatList::const_iterator end = floats.end();
616 for (; cit != end; ++cit) {
617 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
618 _(cit->second.listName()),
619 FuncRequest(LFUN_FLOAT_LIST,
620 cit->second.type())));
625 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
628 tomenu.add(MenuItem(MenuItem::Command,
629 _("No Document Open!"),
630 FuncRequest(LFUN_NOACTION)));
634 FloatList const & floats =
635 buf->params().getTextClass().floats();
636 FloatList::const_iterator cit = floats.begin();
637 FloatList::const_iterator end = floats.end();
638 for (; cit != end; ++cit) {
640 docstring const label = _(cit->second.name());
641 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
642 FuncRequest(LFUN_FLOAT_INSERT,
643 cit->second.type())));
648 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
651 tomenu.add(MenuItem(MenuItem::Command,
652 _("No Document Open!"),
653 FuncRequest(LFUN_NOACTION)));
656 InsetLayouts const & insetlayouts =
657 buf->params().getTextClass().insetlayouts();
658 InsetLayouts::const_iterator cit = insetlayouts.begin();
659 InsetLayouts::const_iterator end = insetlayouts.end();
660 for (; cit != end; ++cit) {
661 docstring const label = cit->first;
662 if (cit->second.lyxtype == s)
663 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
664 label, FuncRequest(LFUN_FLEX_INSERT,
670 Menu::size_type const max_number_of_items = 25;
672 void expandToc2(Menu & tomenu,
673 Toc const & toc_list,
675 Toc::size_type to, int depth)
677 int shortcut_count = 0;
679 // check whether depth is smaller than the smallest depth in toc.
680 int min_depth = 1000;
681 for (Toc::size_type i = from; i < to; ++i)
682 min_depth = std::min(min_depth, toc_list[i].depth());
683 if (min_depth > depth)
687 if (to - from <= max_number_of_items) {
688 for (Toc::size_type i = from; i < to; ++i) {
689 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
690 label += limit_string_length(toc_list[i].str());
691 if (toc_list[i].depth() == depth
692 && shortcut_count < 9) {
693 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
694 label += char_type('|') + convert<docstring>(++shortcut_count);
696 tomenu.add(MenuItem(MenuItem::Command, label,
697 FuncRequest(toc_list[i].action())));
700 Toc::size_type pos = from;
702 Toc::size_type new_pos = pos + 1;
703 while (new_pos < to &&
704 toc_list[new_pos].depth() > depth)
707 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
708 label += limit_string_length(toc_list[pos].str());
709 if (toc_list[pos].depth() == depth &&
710 shortcut_count < 9) {
711 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
712 label += char_type('|') + convert<docstring>(++shortcut_count);
714 if (new_pos == pos + 1) {
715 tomenu.add(MenuItem(MenuItem::Command,
716 label, FuncRequest(toc_list[pos].action())));
718 MenuItem item(MenuItem::Submenu, label);
719 item.submenu(new Menu);
720 expandToc2(*item.submenu(),
721 toc_list, pos, new_pos, depth + 1);
730 void expandToc(Menu & tomenu, Buffer const * buf)
732 // To make things very cleanly, we would have to pass buf to
733 // all MenuItem constructors and to expandToc2. However, we
734 // know that all the entries in a TOC will be have status_ ==
735 // OK, so we avoid this unnecessary overhead (JMarc)
738 tomenu.add(MenuItem(MenuItem::Command,
739 _("No Document Open!"),
740 FuncRequest(LFUN_NOACTION)));
744 Buffer* cbuf = const_cast<Buffer*>(buf);
745 cbuf->tocBackend().update();
746 cbuf->structureChanged();
748 // Add an entry for the master doc if this is a child doc
749 Buffer const * const master = buf->masterBuffer();
751 ParIterator const pit = par_iterator_begin(master->inset());
752 string const arg = convert<string>(pit->id());
753 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
754 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
757 FloatList const & floatlist = buf->params().getTextClass().floats();
758 TocList const & toc_list = buf->tocBackend().tocs();
759 TocList::const_iterator cit = toc_list.begin();
760 TocList::const_iterator end = toc_list.end();
761 for (; cit != end; ++cit) {
763 if (cit->first == "tableofcontents")
766 // All the rest is for floats
767 auto_ptr<Menu> menu(new Menu);
768 TocIterator ccit = cit->second.begin();
769 TocIterator eend = cit->second.end();
770 for (; ccit != eend; ++ccit) {
771 docstring const label = limit_string_length(ccit->str());
772 menu->add(MenuItem(MenuItem::Command,
774 FuncRequest(ccit->action())));
776 string const & floatName = floatlist.getType(cit->first).listName();
778 if (!floatName.empty())
779 label = _(floatName);
780 // BUG3633: listings is not a proper float so its name
781 // is not shown in floatlist.
782 else if (cit->first == "listing")
783 label = _("List of listings");
784 // this should not happen now, but if something else like
785 // listings is added later, this can avoid an empty menu name.
787 label = _("Other floats");
788 MenuItem item(MenuItem::Submenu, label);
789 item.submenu(menu.release());
794 cit = toc_list.find("tableofcontents");
796 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
797 _("No Table of contents"),
800 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
805 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
810 vector<docstring> const sel =
811 cap::availableSelections(*buf);
813 vector<docstring>::const_iterator cit = sel.begin();
814 vector<docstring>::const_iterator end = sel.end();
816 for (unsigned int index = 0; cit != end; ++cit, ++index) {
817 tomenu.add(MenuItem(MenuItem::Command, *cit,
818 FuncRequest(LFUN_PASTE, convert<string>(index))));
823 void expandToolbars(Menu & tomenu)
826 // extracts the toolbars from the backend
827 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
828 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
830 for (; cit != end; ++cit) {
831 docstring label = _(cit->gui_name);
832 // frontends are not supposed to turn on/off toolbars,
833 // if they cannot update ToolbarBackend::flags. That
834 // is to say, ToolbarsBackend::flags should reflect
835 // the true state of toolbars.
837 // menu is displayed as
841 // in the case of auto.
842 if (cit->flags & ToolbarInfo::AUTO)
843 label += _(" (auto)");
844 tomenu.add(MenuItem(MenuItem::Command, label,
845 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
850 void expandBranches(Menu & tomenu, Buffer const * buf)
853 tomenu.add(MenuItem(MenuItem::Command,
854 _("No Document Open!"),
855 FuncRequest(LFUN_NOACTION)));
859 BufferParams const & params = buf->masterBuffer()->params();
860 if (params.branchlist().empty()) {
861 tomenu.add(MenuItem(MenuItem::Command,
862 _("No Branch in Document!"),
863 FuncRequest(LFUN_NOACTION)));
867 BranchList::const_iterator cit = params.branchlist().begin();
868 BranchList::const_iterator end = params.branchlist().end();
870 for (int ii = 1; cit != end; ++cit, ++ii) {
871 docstring label = cit->getBranch();
873 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
874 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
875 FuncRequest(LFUN_BRANCH_INSERT,
884 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
885 Buffer const * buf) const
890 for (Menu::const_iterator cit = frommenu.begin();
891 cit != frommenu.end() ; ++cit) {
892 switch (cit->kind()) {
893 case MenuItem::Lastfiles:
894 expandLastfiles(tomenu);
897 case MenuItem::Documents:
898 expandDocuments(tomenu);
901 case MenuItem::Bookmarks:
902 expandBookmarks(tomenu);
905 case MenuItem::ImportFormats:
906 case MenuItem::ViewFormats:
907 case MenuItem::UpdateFormats:
908 case MenuItem::ExportFormats:
909 expandFormats(cit->kind(), tomenu, buf);
912 case MenuItem::CharStyles:
913 expandFlexInsert(tomenu, buf, "charstyle");
916 case MenuItem::Custom:
917 expandFlexInsert(tomenu, buf, "custom");
920 case MenuItem::Elements:
921 expandFlexInsert(tomenu, buf, "element");
924 case MenuItem::FloatListInsert:
925 expandFloatListInsert(tomenu, buf);
928 case MenuItem::FloatInsert:
929 expandFloatInsert(tomenu, buf);
932 case MenuItem::PasteRecent:
933 expandPasteRecent(tomenu, buf);
936 case MenuItem::Toolbars:
937 expandToolbars(tomenu);
940 case MenuItem::Branches:
941 expandBranches(tomenu, buf);
945 expandToc(tomenu, buf);
948 case MenuItem::Submenu: {
950 item.submenu(new Menu(cit->submenuname()));
951 expand(getMenu(cit->submenuname()),
952 *item.submenu(), buf);
953 tomenu.addWithStatusCheck(item);
957 case MenuItem::Separator:
958 tomenu.addWithStatusCheck(*cit);
961 case MenuItem::Command:
962 if (!specialmenu_.hasFunc(cit->func()))
963 tomenu.addWithStatusCheck(*cit);
967 // we do not want the menu to end with a separator
969 && tomenu.items_.back().kind() == MenuItem::Separator)
970 tomenu.items_.pop_back();
972 // Check whether the shortcuts are unique
973 tomenu.checkShortcuts();
977 void MenuBackend::read(Lexer & lex)
986 struct keyword_item menutags[md_last - 1] = {
987 { "end", md_endmenuset },
989 { "menubar", md_menubar }
993 if (compare_ascii_no_case(lex.getString(), "menuset")) {
994 lyxerr << "Menubackend::read: ERROR wrong token:`"
995 << lex.getString() << '\'' << endl;
998 lex.pushTable(menutags, md_last - 1);
999 if (lyxerr.debugging(Debug::PARSER))
1000 lex.printTable(lyxerr);
1004 while (lex.isOK() && !quit) {
1005 switch (lex.lex()) {
1011 docstring const name = lex.getDocString();
1012 if (hasMenu(name)) {
1013 getMenu(name).read(lex);
1025 lex.printError("menubackend::read: "
1026 "Unknown menu tag: `$$Token'");
1034 void MenuBackend::add(Menu const & menu)
1036 menulist_.push_back(menu);
1040 bool MenuBackend::hasMenu(docstring const & name) const
1042 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1046 Menu const & MenuBackend::getMenu(docstring const & name) const
1048 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1050 lyxerr << "No submenu named " << to_utf8(name) << endl;
1051 BOOST_ASSERT(cit != end());
1056 Menu & MenuBackend::getMenu(docstring const & name)
1058 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1060 lyxerr << "No submenu named " << to_utf8(name) << endl;
1061 BOOST_ASSERT(it != end());
1066 Menu const & MenuBackend::getMenubar() const