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 void MenuBackend::specialMenu(Menu const & menu)
434 class compare_format {
436 bool operator()(Format const * p1, Format const * p2) {
441 docstring const limit_string_length(docstring const & str)
443 docstring::size_type const max_item_length = 45;
445 if (str.size() > max_item_length)
446 return str.substr(0, max_item_length - 3) + "...";
452 void expandLastfiles(Menu & tomenu)
454 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
455 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
459 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
460 string const file = lfit->absFilename();
461 docstring const label = convert<docstring>(ii) + ". "
462 + makeDisplayPath(file, 30)
463 + char_type('|') + convert<docstring>(ii);
464 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
469 void expandDocuments(Menu & tomenu)
471 Buffer * first = theBufferList().first();
476 // We cannot use a for loop as the buffer list cycles.
478 docstring label = makeDisplayPath(b->fileName(), 20);
479 if (!b->isClean()) label = label + "*";
481 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
482 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BUFFER_SWITCH, b->fileName())));
484 b = theBufferList().next(b);
486 } while (b != first);
488 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
489 FuncRequest(LFUN_NOACTION)));
495 void expandBookmarks(Menu & tomenu)
497 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
499 for (size_t i = 1; i <= bm.size(); ++i) {
501 docstring const label = convert<docstring>(i) + ". "
502 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
503 + char_type('|') + convert<docstring>(i);
504 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
505 convert<docstring>(i))));
511 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
513 if (!buf && kind != MenuItem::ImportFormats) {
514 tomenu.add(MenuItem(MenuItem::Command,
515 _("No Document Open!"),
516 FuncRequest(LFUN_NOACTION)));
520 typedef vector<Format const *> Formats;
525 case MenuItem::ImportFormats:
526 formats = Importer::GetImportableFormats();
527 action = LFUN_BUFFER_IMPORT;
529 case MenuItem::ViewFormats:
530 formats = Exporter::getExportableFormats(*buf, true);
531 action = LFUN_BUFFER_VIEW;
533 case MenuItem::UpdateFormats:
534 formats = Exporter::getExportableFormats(*buf, true);
535 action = LFUN_BUFFER_UPDATE;
538 formats = Exporter::getExportableFormats(*buf, false);
539 action = LFUN_BUFFER_EXPORT;
541 sort(formats.begin(), formats.end(), compare_format());
543 Formats::const_iterator fit = formats.begin();
544 Formats::const_iterator end = formats.end();
545 for (; fit != end ; ++fit) {
548 docstring label = from_utf8((*fit)->prettyname());
551 case MenuItem::ImportFormats:
552 // FIXME: This is a hack, we should rather solve
553 // FIXME: bug 2488 instead.
554 if ((*fit)->name() == "text")
555 label = _("Plain Text");
556 else if ((*fit)->name() == "textparagraph")
557 label = _("Plain Text, Join Lines");
560 case MenuItem::ViewFormats:
561 case MenuItem::ExportFormats:
562 case MenuItem::UpdateFormats:
563 if (!(*fit)->documentFormat())
570 if (!(*fit)->shortcut().empty())
571 label += char_type('|') + from_utf8((*fit)->shortcut());
574 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
575 FuncRequest(action, (*fit)->name())));
577 tomenu.add(MenuItem(MenuItem::Command, label,
578 FuncRequest(action, (*fit)->name())));
583 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
586 tomenu.add(MenuItem(MenuItem::Command,
587 _("No Document Open!"),
588 FuncRequest(LFUN_NOACTION)));
592 FloatList const & floats =
593 buf->params().getTextClass().floats();
594 FloatList::const_iterator cit = floats.begin();
595 FloatList::const_iterator end = floats.end();
596 for (; cit != end; ++cit) {
597 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
598 _(cit->second.listName()),
599 FuncRequest(LFUN_FLOAT_LIST,
600 cit->second.type())));
605 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
608 tomenu.add(MenuItem(MenuItem::Command,
609 _("No Document Open!"),
610 FuncRequest(LFUN_NOACTION)));
614 FloatList const & floats =
615 buf->params().getTextClass().floats();
616 FloatList::const_iterator cit = floats.begin();
617 FloatList::const_iterator end = floats.end();
618 for (; cit != end; ++cit) {
620 docstring const label = _(cit->second.name());
621 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
622 FuncRequest(LFUN_FLOAT_INSERT,
623 cit->second.type())));
628 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
631 tomenu.add(MenuItem(MenuItem::Command,
632 _("No Document Open!"),
633 FuncRequest(LFUN_NOACTION)));
636 InsetLayouts const & insetlayouts =
637 buf->params().getTextClass().insetlayouts();
638 InsetLayouts::const_iterator cit = insetlayouts.begin();
639 InsetLayouts::const_iterator end = insetlayouts.end();
640 for (; cit != end; ++cit) {
641 docstring const label = cit->first;
642 if (cit->second.lyxtype == s)
643 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
644 label, FuncRequest(LFUN_FLEX_INSERT,
650 Menu::size_type const max_number_of_items = 25;
652 void expandToc2(Menu & tomenu,
653 Toc const & toc_list,
655 Toc::size_type to, int depth)
657 int shortcut_count = 0;
659 // check whether depth is smaller than the smallest depth in toc.
660 int min_depth = 1000;
661 for (Toc::size_type i = from; i < to; ++i)
662 min_depth = std::min(min_depth, toc_list[i].depth());
663 if (min_depth > depth)
667 if (to - from <= max_number_of_items) {
668 for (Toc::size_type i = from; i < to; ++i) {
669 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
670 label += limit_string_length(toc_list[i].str());
671 if (toc_list[i].depth() == depth
672 && shortcut_count < 9) {
673 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
674 label += char_type('|') + convert<docstring>(++shortcut_count);
676 tomenu.add(MenuItem(MenuItem::Command, label,
677 FuncRequest(toc_list[i].action())));
680 Toc::size_type pos = from;
682 Toc::size_type new_pos = pos + 1;
683 while (new_pos < to &&
684 toc_list[new_pos].depth() > depth)
687 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
688 label += limit_string_length(toc_list[pos].str());
689 if (toc_list[pos].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 if (new_pos == pos + 1) {
695 tomenu.add(MenuItem(MenuItem::Command,
696 label, FuncRequest(toc_list[pos].action())));
698 MenuItem item(MenuItem::Submenu, label);
699 item.submenu(new Menu);
700 expandToc2(*item.submenu(),
701 toc_list, pos, new_pos, depth + 1);
710 void expandToc(Menu & tomenu, Buffer const * buf)
712 // To make things very cleanly, we would have to pass buf to
713 // all MenuItem constructors and to expandToc2. However, we
714 // know that all the entries in a TOC will be have status_ ==
715 // OK, so we avoid this unnecessary overhead (JMarc)
718 tomenu.add(MenuItem(MenuItem::Command,
719 _("No Document Open!"),
720 FuncRequest(LFUN_NOACTION)));
724 Buffer* cbuf = const_cast<Buffer*>(buf);
725 cbuf->tocBackend().update();
726 cbuf->structureChanged();
728 // Add an entry for the master doc if this is a child doc
729 Buffer const * const master = buf->getMasterBuffer();
731 ParIterator const pit = par_iterator_begin(master->inset());
732 string const arg = convert<string>(pit->id());
733 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
734 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
737 FloatList const & floatlist = buf->params().getTextClass().floats();
738 TocList const & toc_list = buf->tocBackend().tocs();
739 TocList::const_iterator cit = toc_list.begin();
740 TocList::const_iterator end = toc_list.end();
741 for (; cit != end; ++cit) {
743 if (cit->first == "tableofcontents")
746 // All the rest is for floats
747 auto_ptr<Menu> menu(new Menu);
748 TocIterator ccit = cit->second.begin();
749 TocIterator eend = cit->second.end();
750 for (; ccit != eend; ++ccit) {
751 docstring const label = limit_string_length(ccit->str());
752 menu->add(MenuItem(MenuItem::Command,
754 FuncRequest(ccit->action())));
756 string const & floatName = floatlist.getType(cit->first).listName();
758 if (!floatName.empty())
759 label = _(floatName);
760 // BUG3633: listings is not a proper float so its name
761 // is not shown in floatlist.
762 else if (cit->first == "listing")
763 label = _("List of listings");
764 // this should not happen now, but if something else like
765 // listings is added later, this can avoid an empty menu name.
767 label = _("Other floats");
768 MenuItem item(MenuItem::Submenu, label);
769 item.submenu(menu.release());
774 cit = toc_list.find("tableofcontents");
776 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
777 _("No Table of contents"),
780 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
785 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
790 vector<docstring> const sel =
791 cap::availableSelections(*buf);
793 vector<docstring>::const_iterator cit = sel.begin();
794 vector<docstring>::const_iterator end = sel.end();
796 for (unsigned int index = 0; cit != end; ++cit, ++index) {
797 tomenu.add(MenuItem(MenuItem::Command, *cit,
798 FuncRequest(LFUN_PASTE, convert<string>(index))));
803 void expandToolbars(Menu & tomenu)
806 // extracts the toolbars from the backend
807 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
808 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
810 for (; cit != end; ++cit) {
811 docstring label = _(cit->gui_name);
812 // frontends are not supposed to turn on/off toolbars,
813 // if they cannot update ToolbarBackend::flags. That
814 // is to say, ToolbarsBackend::flags should reflect
815 // the true state of toolbars.
817 // menu is displayed as
821 // in the case of auto.
822 if (cit->flags & ToolbarInfo::AUTO)
823 label += _(" (auto)");
824 tomenu.add(MenuItem(MenuItem::Command, label,
825 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
830 void expandBranches(Menu & tomenu, Buffer const * buf)
833 tomenu.add(MenuItem(MenuItem::Command,
834 _("No Document Open!"),
835 FuncRequest(LFUN_NOACTION)));
839 BufferParams const & params = buf->getMasterBuffer()->params();
840 if (params.branchlist().empty()) {
841 tomenu.add(MenuItem(MenuItem::Command,
842 _("No Branch in Document!"),
843 FuncRequest(LFUN_NOACTION)));
847 BranchList::const_iterator cit = params.branchlist().begin();
848 BranchList::const_iterator end = params.branchlist().end();
850 for (int ii = 1; cit != end; ++cit, ++ii) {
851 docstring label = cit->getBranch();
853 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
854 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
855 FuncRequest(LFUN_BRANCH_INSERT,
864 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
865 Buffer const * buf) const
870 for (Menu::const_iterator cit = frommenu.begin();
871 cit != frommenu.end() ; ++cit) {
872 switch (cit->kind()) {
873 case MenuItem::Lastfiles:
874 expandLastfiles(tomenu);
877 case MenuItem::Documents:
878 expandDocuments(tomenu);
881 case MenuItem::Bookmarks:
882 expandBookmarks(tomenu);
885 case MenuItem::ImportFormats:
886 case MenuItem::ViewFormats:
887 case MenuItem::UpdateFormats:
888 case MenuItem::ExportFormats:
889 expandFormats(cit->kind(), tomenu, buf);
892 case MenuItem::CharStyles:
893 expandFlexInsert(tomenu, buf, "charstyle");
896 case MenuItem::Custom:
897 expandFlexInsert(tomenu, buf, "custom");
900 case MenuItem::Elements:
901 expandFlexInsert(tomenu, buf, "element");
904 case MenuItem::FloatListInsert:
905 expandFloatListInsert(tomenu, buf);
908 case MenuItem::FloatInsert:
909 expandFloatInsert(tomenu, buf);
912 case MenuItem::PasteRecent:
913 expandPasteRecent(tomenu, buf);
916 case MenuItem::Toolbars:
917 expandToolbars(tomenu);
920 case MenuItem::Branches:
921 expandBranches(tomenu, buf);
925 expandToc(tomenu, buf);
928 case MenuItem::Submenu: {
930 item.submenu(new Menu(cit->submenuname()));
931 expand(getMenu(cit->submenuname()),
932 *item.submenu(), buf);
933 tomenu.addWithStatusCheck(item);
937 case MenuItem::Separator:
938 tomenu.addWithStatusCheck(*cit);
941 case MenuItem::Command:
942 if (!specialmenu_.hasFunc(cit->func()))
943 tomenu.addWithStatusCheck(*cit);
947 // we do not want the menu to end with a separator
949 && tomenu.items_.back().kind() == MenuItem::Separator)
950 tomenu.items_.pop_back();
952 // Check whether the shortcuts are unique
953 tomenu.checkShortcuts();
957 void MenuBackend::read(Lexer & lex)
966 struct keyword_item menutags[md_last - 1] = {
967 { "end", md_endmenuset },
969 { "menubar", md_menubar }
973 if (compare_ascii_no_case(lex.getString(), "menuset")) {
974 lyxerr << "Menubackend::read: ERROR wrong token:`"
975 << lex.getString() << '\'' << endl;
978 lex.pushTable(menutags, md_last - 1);
979 if (lyxerr.debugging(Debug::PARSER))
980 lex.printTable(lyxerr);
984 while (lex.isOK() && !quit) {
991 docstring const name = lex.getDocString();
993 getMenu(name).read(lex);
1005 lex.printError("menubackend::read: "
1006 "Unknown menu tag: `$$Token'");
1014 void MenuBackend::add(Menu const & menu)
1016 menulist_.push_back(menu);
1020 bool MenuBackend::hasMenu(docstring const & name) const
1022 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1026 Menu const & MenuBackend::getMenu(docstring const & name) const
1028 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1030 lyxerr << "No submenu named " << to_utf8(name) << endl;
1031 BOOST_ASSERT(cit != end());
1036 Menu & MenuBackend::getMenu(docstring const & name)
1038 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1040 lyxerr << "No submenu named " << to_utf8(name) << endl;
1041 BOOST_ASSERT(it != end());
1046 Menu const & MenuBackend::getMenubar() const