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 "CutAndPaste.h"
28 #include "FloatList.h"
34 #include "LyXAction.h"
35 #include "LyX.h" // for lastfiles
38 #include "Paragraph.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
78 return menu.name() == name_;
87 // This is the global menu definition
88 MenuBackend menubackend;
91 MenuItem::MenuItem(Kind kind)
92 : kind_(kind), optional_(false)
96 MenuItem::MenuItem(Kind kind, docstring const & label,
97 docstring const & submenu, bool optional)
98 : kind_(kind), label_(label),
99 submenuname_(submenu), optional_(optional)
101 BOOST_ASSERT(kind == Submenu);
105 MenuItem::MenuItem(Kind kind, docstring const & label,
106 FuncRequest const & func, bool optional)
107 : kind_(kind), label_(label), func_(func), optional_(optional)
109 func_.origin = FuncRequest::MENU;
113 MenuItem::~MenuItem()
117 void MenuItem::submenu(Menu * menu)
119 submenu_.reset(menu);
123 docstring const MenuItem::label() const
125 return token(label_, char_type('|'), 0);
129 docstring const MenuItem::shortcut() const
131 return token(label_, char_type('|'), 1);
135 docstring const MenuItem::binding(bool forgui) const
137 if (kind_ != Command)
140 // Get the keys bound to this action, but keep only the
142 KeyMap::Bindings bindings = theTopLevelKeymap().findbindings(func_);
144 if (bindings.size()) {
145 return bindings.begin()->print(forgui);
149 << lyxaction.getActionName(func_.action)
150 << '(' << to_utf8(func_.argument()) << ')' << endl;
157 Menu & Menu::add(MenuItem const & i)
164 Menu & Menu::addWithStatusCheck(MenuItem const & i)
168 case MenuItem::Command: {
169 FuncStatus status = lyx::getStatus(i.func());
170 if (status.unknown() || (!status.enabled() && i.optional()))
173 items_.back().status(status);
177 case MenuItem::Submenu: {
179 bool enabled = false;
180 for (const_iterator cit = i.submenu()->begin();
181 cit != i.submenu()->end(); ++cit) {
182 if ((cit->kind() == MenuItem::Command
183 || cit->kind() == MenuItem::Submenu)
184 && cit->status().enabled()) {
189 if (enabled || !i.optional()) {
191 items_.back().status().enabled(enabled);
199 case MenuItem::Separator:
201 && items_.back().kind() != MenuItem::Separator)
213 Menu & Menu::read(Lexer & lex)
241 struct keyword_item menutags[md_last - 1] = {
242 { "bookmarks", md_bookmarks },
243 { "branches", md_branches },
244 { "charstyles", md_charstyles },
245 { "custom", md_custom },
246 { "documents", md_documents },
247 { "elements", md_elements },
248 { "end", md_endmenu },
249 { "exportformats", md_exportformats },
250 { "floatinsert", md_floatinsert },
251 { "floatlistinsert", md_floatlistinsert },
252 { "importformats", md_importformats },
254 { "lastfiles", md_lastfiles },
255 { "optitem", md_optitem },
256 { "optsubmenu", md_optsubmenu },
257 { "pasterecent", md_pasterecent },
258 { "separator", md_separator },
259 { "submenu", md_submenu },
261 { "toolbars", md_toolbars },
262 { "updateformats", md_updateformats },
263 { "viewformats", md_viewformats }
266 lex.pushTable(menutags, md_last - 1);
267 if (lyxerr.debugging(Debug::PARSER))
268 lex.printTable(lyxerr);
271 bool optional = false;
273 while (lex.isOK() && !quit) {
277 // fallback to md_item
280 docstring const name = translateIfPossible(lex.getDocString());
282 string const command = lex.getString();
283 FuncRequest func = lyxaction.lookupFunc(command);
284 add(MenuItem(MenuItem::Command, name, func, optional));
290 add(MenuItem(MenuItem::Separator));
294 add(MenuItem(MenuItem::Lastfiles));
298 add(MenuItem(MenuItem::CharStyles));
302 add(MenuItem(MenuItem::Custom));
306 add(MenuItem(MenuItem::Elements));
310 add(MenuItem(MenuItem::Documents));
314 add(MenuItem(MenuItem::Bookmarks));
318 add(MenuItem(MenuItem::Toc));
322 add(MenuItem(MenuItem::ViewFormats));
325 case md_updateformats:
326 add(MenuItem(MenuItem::UpdateFormats));
329 case md_exportformats:
330 add(MenuItem(MenuItem::ExportFormats));
333 case md_importformats:
334 add(MenuItem(MenuItem::ImportFormats));
337 case md_floatlistinsert:
338 add(MenuItem(MenuItem::FloatListInsert));
342 add(MenuItem(MenuItem::FloatInsert));
346 add(MenuItem(MenuItem::PasteRecent));
350 add(MenuItem(MenuItem::Toolbars));
354 add(MenuItem(MenuItem::Branches));
359 // fallback to md_submenu
362 docstring const mlabel = translateIfPossible(lex.getDocString());
364 docstring const mname = lex.getDocString();
365 add(MenuItem(MenuItem::Submenu, mlabel, mname,
376 lex.printError("Menu::read: "
377 "Unknown menu tag: `$$Token'");
386 MenuItem const & Menu::operator[](size_type i) const
392 bool Menu::hasFunc(FuncRequest const & func) const
394 return find_if(begin(), end(),
395 bind(std::equal_to<FuncRequest>(),
396 bind(&MenuItem::func, _1),
400 void Menu::checkShortcuts() const
402 // This is a quadratic algorithm, but we do not care because
403 // menus are short enough
404 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
405 docstring shortcut = it1->shortcut();
406 if (shortcut.empty())
408 if (!contains(it1->label(), shortcut))
409 lyxerr << "Menu warning: menu entry \""
410 << to_utf8(it1->label())
411 << "\" does not contain shortcut `"
412 << to_utf8(shortcut) << "'." << endl;
413 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
414 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
415 lyxerr << "Menu warning: menu entries "
416 << '"' << to_utf8(it1->fulllabel())
417 << "\" and \"" << to_utf8(it2->fulllabel())
418 << "\" share the same shortcut."
426 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
428 const_iterator m = begin();
429 const_iterator m_end = end();
430 for (; m != m_end; ++m) {
431 if (m->kind() == MenuItem::Command && m->func() == func) {
432 names.push(m->label());
434 } else if (m->kind() == MenuItem::Submenu) {
435 names.push(m->label());
436 Menu submenu = menubackend.getMenu(m->submenuname());
437 if (submenu.searchFunc(func, names))
447 void MenuBackend::specialMenu(Menu const & menu)
455 class compare_format {
457 bool operator()(Format const * p1, Format const * p2) {
462 docstring const limit_string_length(docstring const & str)
464 docstring::size_type const max_item_length = 45;
466 if (str.size() > max_item_length)
467 return str.substr(0, max_item_length - 3) + "...";
473 void expandLastfiles(Menu & tomenu)
475 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
476 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
480 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
481 string const file = lfit->absFilename();
482 docstring const label = convert<docstring>(ii) + ". "
483 + makeDisplayPath(file, 30)
484 + char_type('|') + convert<docstring>(ii);
485 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
490 void expandDocuments(Menu & tomenu)
492 Buffer * first = theBufferList().first();
497 // We cannot use a for loop as the buffer list cycles.
499 docstring label = makeDisplayPath(b->fileName(), 20);
500 if (!b->isClean()) label = label + "*";
502 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
503 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BUFFER_SWITCH, b->fileName())));
505 b = theBufferList().next(b);
507 } while (b != first);
509 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
510 FuncRequest(LFUN_NOACTION)));
516 void expandBookmarks(Menu & tomenu)
518 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
520 for (size_t i = 1; i <= bm.size(); ++i) {
522 docstring const label = convert<docstring>(i) + ". "
523 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
524 + char_type('|') + convert<docstring>(i);
525 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
526 convert<docstring>(i))));
532 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
534 if (!buf && kind != MenuItem::ImportFormats) {
535 tomenu.add(MenuItem(MenuItem::Command,
536 _("No Document Open!"),
537 FuncRequest(LFUN_NOACTION)));
541 typedef vector<Format const *> Formats;
546 case MenuItem::ImportFormats:
547 formats = Importer::GetImportableFormats();
548 action = LFUN_BUFFER_IMPORT;
550 case MenuItem::ViewFormats:
551 formats = Exporter::getExportableFormats(*buf, true);
552 action = LFUN_BUFFER_VIEW;
554 case MenuItem::UpdateFormats:
555 formats = Exporter::getExportableFormats(*buf, true);
556 action = LFUN_BUFFER_UPDATE;
559 formats = Exporter::getExportableFormats(*buf, false);
560 action = LFUN_BUFFER_EXPORT;
562 sort(formats.begin(), formats.end(), compare_format());
564 Formats::const_iterator fit = formats.begin();
565 Formats::const_iterator end = formats.end();
566 for (; fit != end ; ++fit) {
569 docstring label = from_utf8((*fit)->prettyname());
572 case MenuItem::ImportFormats:
573 // FIXME: This is a hack, we should rather solve
574 // FIXME: bug 2488 instead.
575 if ((*fit)->name() == "text")
576 label = _("Plain Text");
577 else if ((*fit)->name() == "textparagraph")
578 label = _("Plain Text, Join Lines");
581 case MenuItem::ViewFormats:
582 case MenuItem::ExportFormats:
583 case MenuItem::UpdateFormats:
584 if (!(*fit)->documentFormat())
591 if (!(*fit)->shortcut().empty())
592 label += char_type('|') + from_utf8((*fit)->shortcut());
595 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
596 FuncRequest(action, (*fit)->name())));
598 tomenu.add(MenuItem(MenuItem::Command, label,
599 FuncRequest(action, (*fit)->name())));
604 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
607 tomenu.add(MenuItem(MenuItem::Command,
608 _("No Document Open!"),
609 FuncRequest(LFUN_NOACTION)));
613 FloatList const & floats =
614 buf->params().getTextClass().floats();
615 FloatList::const_iterator cit = floats.begin();
616 FloatList::const_iterator end = floats.end();
617 for (; cit != end; ++cit) {
618 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
619 _(cit->second.listName()),
620 FuncRequest(LFUN_FLOAT_LIST,
621 cit->second.type())));
626 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
629 tomenu.add(MenuItem(MenuItem::Command,
630 _("No Document Open!"),
631 FuncRequest(LFUN_NOACTION)));
635 FloatList const & floats =
636 buf->params().getTextClass().floats();
637 FloatList::const_iterator cit = floats.begin();
638 FloatList::const_iterator end = floats.end();
639 for (; cit != end; ++cit) {
641 docstring const label = _(cit->second.name());
642 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
643 FuncRequest(LFUN_FLOAT_INSERT,
644 cit->second.type())));
649 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
652 tomenu.add(MenuItem(MenuItem::Command,
653 _("No Document Open!"),
654 FuncRequest(LFUN_NOACTION)));
657 InsetLayouts const & insetlayouts =
658 buf->params().getTextClass().insetlayouts();
659 InsetLayouts::const_iterator cit = insetlayouts.begin();
660 InsetLayouts::const_iterator end = insetlayouts.end();
661 for (; cit != end; ++cit) {
662 docstring const label = cit->first;
663 if (cit->second.lyxtype == s)
664 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
665 label, FuncRequest(LFUN_FLEX_INSERT,
671 Menu::size_type const max_number_of_items = 25;
673 void expandToc2(Menu & tomenu,
674 Toc const & toc_list,
676 Toc::size_type to, int depth)
678 int shortcut_count = 0;
680 // check whether depth is smaller than the smallest depth in toc.
681 int min_depth = 1000;
682 for (Toc::size_type i = from; i < to; ++i)
683 min_depth = std::min(min_depth, toc_list[i].depth());
684 if (min_depth > depth)
688 if (to - from <= max_number_of_items) {
689 for (Toc::size_type i = from; i < to; ++i) {
690 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
691 label += limit_string_length(toc_list[i].str());
692 if (toc_list[i].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 tomenu.add(MenuItem(MenuItem::Command, label,
698 FuncRequest(toc_list[i].action())));
701 Toc::size_type pos = from;
703 Toc::size_type new_pos = pos + 1;
704 while (new_pos < to &&
705 toc_list[new_pos].depth() > depth)
708 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
709 label += limit_string_length(toc_list[pos].str());
710 if (toc_list[pos].depth() == depth &&
711 shortcut_count < 9) {
712 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
713 label += char_type('|') + convert<docstring>(++shortcut_count);
715 if (new_pos == pos + 1) {
716 tomenu.add(MenuItem(MenuItem::Command,
717 label, FuncRequest(toc_list[pos].action())));
719 MenuItem item(MenuItem::Submenu, label);
720 item.submenu(new Menu);
721 expandToc2(*item.submenu(),
722 toc_list, pos, new_pos, depth + 1);
731 void expandToc(Menu & tomenu, Buffer const * buf)
733 // To make things very cleanly, we would have to pass buf to
734 // all MenuItem constructors and to expandToc2. However, we
735 // know that all the entries in a TOC will be have status_ ==
736 // OK, so we avoid this unnecessary overhead (JMarc)
739 tomenu.add(MenuItem(MenuItem::Command,
740 _("No Document Open!"),
741 FuncRequest(LFUN_NOACTION)));
745 Buffer* cbuf = const_cast<Buffer*>(buf);
746 cbuf->tocBackend().update();
747 cbuf->structureChanged();
749 // Add an entry for the master doc if this is a child doc
750 Buffer const * const master = buf->getMasterBuffer();
752 ParIterator const pit = par_iterator_begin(master->inset());
753 string const arg = convert<string>(pit->id());
754 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
755 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
758 FloatList const & floatlist = buf->params().getTextClass().floats();
759 TocList const & toc_list = buf->tocBackend().tocs();
760 TocList::const_iterator cit = toc_list.begin();
761 TocList::const_iterator end = toc_list.end();
762 for (; cit != end; ++cit) {
764 if (cit->first == "tableofcontents")
767 // All the rest is for floats
768 auto_ptr<Menu> menu(new Menu);
769 TocIterator ccit = cit->second.begin();
770 TocIterator eend = cit->second.end();
771 for (; ccit != eend; ++ccit) {
772 docstring const label = limit_string_length(ccit->str());
773 menu->add(MenuItem(MenuItem::Command,
775 FuncRequest(ccit->action())));
777 string const & floatName = floatlist.getType(cit->first).listName();
779 if (!floatName.empty())
780 label = _(floatName);
781 // BUG3633: listings is not a proper float so its name
782 // is not shown in floatlist.
783 else if (cit->first == "listing")
784 label = _("List of listings");
785 // this should not happen now, but if something else like
786 // listings is added later, this can avoid an empty menu name.
788 label = _("Other floats");
789 MenuItem item(MenuItem::Submenu, label);
790 item.submenu(menu.release());
795 cit = toc_list.find("tableofcontents");
797 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
798 _("No Table of contents"),
801 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
806 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
811 vector<docstring> const sel =
812 cap::availableSelections(*buf);
814 vector<docstring>::const_iterator cit = sel.begin();
815 vector<docstring>::const_iterator end = sel.end();
817 for (unsigned int index = 0; cit != end; ++cit, ++index) {
818 tomenu.add(MenuItem(MenuItem::Command, *cit,
819 FuncRequest(LFUN_PASTE, convert<string>(index))));
824 void expandToolbars(Menu & tomenu)
827 // extracts the toolbars from the backend
828 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
829 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
831 for (; cit != end; ++cit) {
832 docstring label = _(cit->gui_name);
833 // frontends are not supposed to turn on/off toolbars,
834 // if they cannot update ToolbarBackend::flags. That
835 // is to say, ToolbarsBackend::flags should reflect
836 // the true state of toolbars.
838 // menu is displayed as
842 // in the case of auto.
843 if (cit->flags & ToolbarInfo::AUTO)
844 label += _(" (auto)");
845 tomenu.add(MenuItem(MenuItem::Command, label,
846 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
851 void expandBranches(Menu & tomenu, Buffer const * buf)
854 tomenu.add(MenuItem(MenuItem::Command,
855 _("No Document Open!"),
856 FuncRequest(LFUN_NOACTION)));
860 BufferParams const & params = buf->getMasterBuffer()->params();
861 if (params.branchlist().empty()) {
862 tomenu.add(MenuItem(MenuItem::Command,
863 _("No Branch in Document!"),
864 FuncRequest(LFUN_NOACTION)));
868 BranchList::const_iterator cit = params.branchlist().begin();
869 BranchList::const_iterator end = params.branchlist().end();
871 for (int ii = 1; cit != end; ++cit, ++ii) {
872 docstring label = cit->getBranch();
874 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
875 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
876 FuncRequest(LFUN_BRANCH_INSERT,
885 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
886 Buffer const * buf) const
891 for (Menu::const_iterator cit = frommenu.begin();
892 cit != frommenu.end() ; ++cit) {
893 switch (cit->kind()) {
894 case MenuItem::Lastfiles:
895 expandLastfiles(tomenu);
898 case MenuItem::Documents:
899 expandDocuments(tomenu);
902 case MenuItem::Bookmarks:
903 expandBookmarks(tomenu);
906 case MenuItem::ImportFormats:
907 case MenuItem::ViewFormats:
908 case MenuItem::UpdateFormats:
909 case MenuItem::ExportFormats:
910 expandFormats(cit->kind(), tomenu, buf);
913 case MenuItem::CharStyles:
914 expandFlexInsert(tomenu, buf, "charstyle");
917 case MenuItem::Custom:
918 expandFlexInsert(tomenu, buf, "custom");
921 case MenuItem::Elements:
922 expandFlexInsert(tomenu, buf, "element");
925 case MenuItem::FloatListInsert:
926 expandFloatListInsert(tomenu, buf);
929 case MenuItem::FloatInsert:
930 expandFloatInsert(tomenu, buf);
933 case MenuItem::PasteRecent:
934 expandPasteRecent(tomenu, buf);
937 case MenuItem::Toolbars:
938 expandToolbars(tomenu);
941 case MenuItem::Branches:
942 expandBranches(tomenu, buf);
946 expandToc(tomenu, buf);
949 case MenuItem::Submenu: {
951 item.submenu(new Menu(cit->submenuname()));
952 expand(getMenu(cit->submenuname()),
953 *item.submenu(), buf);
954 tomenu.addWithStatusCheck(item);
958 case MenuItem::Separator:
959 tomenu.addWithStatusCheck(*cit);
962 case MenuItem::Command:
963 if (!specialmenu_.hasFunc(cit->func()))
964 tomenu.addWithStatusCheck(*cit);
968 // we do not want the menu to end with a separator
970 && tomenu.items_.back().kind() == MenuItem::Separator)
971 tomenu.items_.pop_back();
973 // Check whether the shortcuts are unique
974 tomenu.checkShortcuts();
978 void MenuBackend::read(Lexer & lex)
987 struct keyword_item menutags[md_last - 1] = {
988 { "end", md_endmenuset },
990 { "menubar", md_menubar }
994 if (compare_ascii_no_case(lex.getString(), "menuset")) {
995 lyxerr << "Menubackend::read: ERROR wrong token:`"
996 << lex.getString() << '\'' << endl;
999 lex.pushTable(menutags, md_last - 1);
1000 if (lyxerr.debugging(Debug::PARSER))
1001 lex.printTable(lyxerr);
1005 while (lex.isOK() && !quit) {
1006 switch (lex.lex()) {
1012 docstring const name = lex.getDocString();
1013 if (hasMenu(name)) {
1014 getMenu(name).read(lex);
1026 lex.printError("menubackend::read: "
1027 "Unknown menu tag: `$$Token'");
1035 void MenuBackend::add(Menu const & menu)
1037 menulist_.push_back(menu);
1041 bool MenuBackend::hasMenu(docstring const & name) const
1043 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1047 Menu const & MenuBackend::getMenu(docstring const & name) const
1049 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1051 lyxerr << "No submenu named " << to_utf8(name) << endl;
1052 BOOST_ASSERT(cit != end());
1057 Menu & MenuBackend::getMenu(docstring const & name)
1059 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1061 lyxerr << "No submenu named " << to_utf8(name) << endl;
1062 BOOST_ASSERT(it != end());
1067 Menu const & MenuBackend::getMenubar() const