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)
240 struct keyword_item menutags[md_last - 1] = {
241 { "bookmarks", md_bookmarks },
242 { "branches", md_branches },
243 { "charstyles", md_charstyles },
244 { "custom", md_custom },
245 { "documents", md_documents },
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::Documents));
308 add(MenuItem(MenuItem::Bookmarks));
312 add(MenuItem(MenuItem::Toc));
316 add(MenuItem(MenuItem::ViewFormats));
319 case md_updateformats:
320 add(MenuItem(MenuItem::UpdateFormats));
323 case md_exportformats:
324 add(MenuItem(MenuItem::ExportFormats));
327 case md_importformats:
328 add(MenuItem(MenuItem::ImportFormats));
331 case md_floatlistinsert:
332 add(MenuItem(MenuItem::FloatListInsert));
336 add(MenuItem(MenuItem::FloatInsert));
340 add(MenuItem(MenuItem::PasteRecent));
344 add(MenuItem(MenuItem::Toolbars));
348 add(MenuItem(MenuItem::Branches));
353 // fallback to md_submenu
356 docstring const mlabel = translateIfPossible(lex.getDocString());
358 docstring const mname = lex.getDocString();
359 add(MenuItem(MenuItem::Submenu, mlabel, mname,
370 lex.printError("Menu::read: "
371 "Unknown menu tag: `$$Token'");
380 MenuItem const & Menu::operator[](size_type i) const
386 bool Menu::hasFunc(FuncRequest const & func) const
388 return find_if(begin(), end(),
389 bind(std::equal_to<FuncRequest>(),
390 bind(&MenuItem::func, _1),
394 void Menu::checkShortcuts() const
396 // This is a quadratic algorithm, but we do not care because
397 // menus are short enough
398 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
399 docstring shortcut = it1->shortcut();
400 if (shortcut.empty())
402 if (!contains(it1->label(), shortcut))
403 lyxerr << "Menu warning: menu entry \""
404 << to_utf8(it1->label())
405 << "\" does not contain shortcut `"
406 << to_utf8(shortcut) << "'." << endl;
407 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
408 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
409 lyxerr << "Menu warning: menu entries "
410 << '"' << to_utf8(it1->fulllabel())
411 << "\" and \"" << to_utf8(it2->fulllabel())
412 << "\" share the same shortcut."
420 void MenuBackend::specialMenu(Menu const & menu)
428 class compare_format {
430 bool operator()(Format const * p1, Format const * p2) {
435 docstring const limit_string_length(docstring const & str)
437 docstring::size_type const max_item_length = 45;
439 if (str.size() > max_item_length)
440 return str.substr(0, max_item_length - 3) + "...";
446 void expandLastfiles(Menu & tomenu)
448 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
449 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
453 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
454 string const file = lfit->absFilename();
455 docstring const label = convert<docstring>(ii) + ". "
456 + makeDisplayPath(file, 30)
457 + char_type('|') + convert<docstring>(ii);
458 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
463 void expandDocuments(Menu & tomenu)
465 Buffer * first = theBufferList().first();
470 // We cannot use a for loop as the buffer list cycles.
472 docstring label = makeDisplayPath(b->fileName(), 20);
473 if (!b->isClean()) label = label + "*";
475 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
476 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BUFFER_SWITCH, b->fileName())));
478 b = theBufferList().next(b);
480 } while (b != first);
482 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
483 FuncRequest(LFUN_NOACTION)));
489 void expandBookmarks(Menu & tomenu)
491 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
493 for (size_t i = 1; i <= bm.size(); ++i) {
495 docstring const label = convert<docstring>(i) + ". "
496 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
497 + char_type('|') + convert<docstring>(i);
498 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
499 convert<docstring>(i))));
505 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
507 if (!buf && kind != MenuItem::ImportFormats) {
508 tomenu.add(MenuItem(MenuItem::Command,
509 _("No Document Open!"),
510 FuncRequest(LFUN_NOACTION)));
514 typedef vector<Format const *> Formats;
519 case MenuItem::ImportFormats:
520 formats = Importer::GetImportableFormats();
521 action = LFUN_BUFFER_IMPORT;
523 case MenuItem::ViewFormats:
524 formats = Exporter::getExportableFormats(*buf, true);
525 action = LFUN_BUFFER_VIEW;
527 case MenuItem::UpdateFormats:
528 formats = Exporter::getExportableFormats(*buf, true);
529 action = LFUN_BUFFER_UPDATE;
532 formats = Exporter::getExportableFormats(*buf, false);
533 action = LFUN_BUFFER_EXPORT;
535 sort(formats.begin(), formats.end(), compare_format());
537 Formats::const_iterator fit = formats.begin();
538 Formats::const_iterator end = formats.end();
539 for (; fit != end ; ++fit) {
542 docstring label = from_utf8((*fit)->prettyname());
545 case MenuItem::ImportFormats:
546 // FIXME: This is a hack, we should rather solve
547 // FIXME: bug 2488 instead.
548 if ((*fit)->name() == "text")
549 label = _("Plain Text");
550 else if ((*fit)->name() == "textparagraph")
551 label = _("Plain Text, Join Lines");
554 case MenuItem::ViewFormats:
555 case MenuItem::ExportFormats:
556 case MenuItem::UpdateFormats:
557 if (!(*fit)->documentFormat())
564 if (!(*fit)->shortcut().empty())
565 label += char_type('|') + from_utf8((*fit)->shortcut());
568 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
569 FuncRequest(action, (*fit)->name())));
571 tomenu.add(MenuItem(MenuItem::Command, label,
572 FuncRequest(action, (*fit)->name())));
577 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
580 tomenu.add(MenuItem(MenuItem::Command,
581 _("No Document Open!"),
582 FuncRequest(LFUN_NOACTION)));
586 FloatList const & floats =
587 buf->params().getTextClass().floats();
588 FloatList::const_iterator cit = floats.begin();
589 FloatList::const_iterator end = floats.end();
590 for (; cit != end; ++cit) {
591 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
592 _(cit->second.listName()),
593 FuncRequest(LFUN_FLOAT_LIST,
594 cit->second.type())));
599 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
602 tomenu.add(MenuItem(MenuItem::Command,
603 _("No Document Open!"),
604 FuncRequest(LFUN_NOACTION)));
608 FloatList const & floats =
609 buf->params().getTextClass().floats();
610 FloatList::const_iterator cit = floats.begin();
611 FloatList::const_iterator end = floats.end();
612 for (; cit != end; ++cit) {
614 docstring const label = _(cit->second.name());
615 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
616 FuncRequest(LFUN_FLOAT_INSERT,
617 cit->second.type())));
622 void expandCharStyleInsert(Menu & tomenu, Buffer const * buf, std::string s)
625 tomenu.add(MenuItem(MenuItem::Command,
626 _("No Document Open!"),
627 FuncRequest(LFUN_NOACTION)));
630 InsetLayouts const & insetlayouts =
631 buf->params().getTextClass().insetlayouts();
632 InsetLayouts::const_iterator cit = insetlayouts.begin();
633 InsetLayouts::const_iterator end = insetlayouts.end();
634 for (; cit != end; ++cit) {
635 docstring const label = cit->first;
636 if (cit->second.lyxtype == s)
637 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
638 label, FuncRequest(LFUN_CHARSTYLE_INSERT,
644 Menu::size_type const max_number_of_items = 25;
646 void expandToc2(Menu & tomenu,
647 Toc const & toc_list,
649 Toc::size_type to, int depth)
651 int shortcut_count = 0;
653 // check whether depth is smaller than the smallest depth in toc.
654 int min_depth = 1000;
655 for (Toc::size_type i = from; i < to; ++i)
656 min_depth = std::min(min_depth, toc_list[i].depth());
657 if (min_depth > depth)
661 if (to - from <= max_number_of_items) {
662 for (Toc::size_type i = from; i < to; ++i) {
663 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
664 label += limit_string_length(toc_list[i].str());
665 if (toc_list[i].depth() == depth
666 && shortcut_count < 9) {
667 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
668 label += char_type('|') + convert<docstring>(++shortcut_count);
670 tomenu.add(MenuItem(MenuItem::Command, label,
671 FuncRequest(toc_list[i].action())));
674 Toc::size_type pos = from;
676 Toc::size_type new_pos = pos + 1;
677 while (new_pos < to &&
678 toc_list[new_pos].depth() > depth)
681 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
682 label += limit_string_length(toc_list[pos].str());
683 if (toc_list[pos].depth() == depth &&
684 shortcut_count < 9) {
685 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
686 label += char_type('|') + convert<docstring>(++shortcut_count);
688 if (new_pos == pos + 1) {
689 tomenu.add(MenuItem(MenuItem::Command,
690 label, FuncRequest(toc_list[pos].action())));
692 MenuItem item(MenuItem::Submenu, label);
693 item.submenu(new Menu);
694 expandToc2(*item.submenu(),
695 toc_list, pos, new_pos, depth + 1);
704 void expandToc(Menu & tomenu, Buffer const * buf)
706 // To make things very cleanly, we would have to pass buf to
707 // all MenuItem constructors and to expandToc2. However, we
708 // know that all the entries in a TOC will be have status_ ==
709 // OK, so we avoid this unnecessary overhead (JMarc)
712 tomenu.add(MenuItem(MenuItem::Command,
713 _("No Document Open!"),
714 FuncRequest(LFUN_NOACTION)));
718 Buffer* cbuf = const_cast<Buffer*>(buf);
719 cbuf->tocBackend().update();
720 cbuf->structureChanged();
722 // Add an entry for the master doc if this is a child doc
723 Buffer const * const master = buf->getMasterBuffer();
725 ParIterator const pit = par_iterator_begin(master->inset());
726 string const arg = convert<string>(pit->id());
727 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
728 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
731 FloatList const & floatlist = buf->params().getTextClass().floats();
732 TocList const & toc_list = buf->tocBackend().tocs();
733 TocList::const_iterator cit = toc_list.begin();
734 TocList::const_iterator end = toc_list.end();
735 for (; cit != end; ++cit) {
737 if (cit->first == "tableofcontents")
740 // All the rest is for floats
741 auto_ptr<Menu> menu(new Menu);
742 TocIterator ccit = cit->second.begin();
743 TocIterator eend = cit->second.end();
744 for (; ccit != eend; ++ccit) {
745 docstring const label = limit_string_length(ccit->str());
746 menu->add(MenuItem(MenuItem::Command,
748 FuncRequest(ccit->action())));
750 string const & floatName = floatlist.getType(cit->first).listName();
752 if (!floatName.empty())
753 label = _(floatName);
754 // BUG3633: listings is not a proper float so its name
755 // is not shown in floatlist.
756 else if (cit->first == "listing")
757 label = _("List of listings");
758 // this should not happen now, but if something else like
759 // listings is added later, this can avoid an empty menu name.
761 label = _("Other floats");
762 MenuItem item(MenuItem::Submenu, label);
763 item.submenu(menu.release());
768 cit = toc_list.find("tableofcontents");
770 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
771 _("No Table of contents"),
774 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
779 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
784 vector<docstring> const sel =
785 cap::availableSelections(*buf);
787 vector<docstring>::const_iterator cit = sel.begin();
788 vector<docstring>::const_iterator end = sel.end();
790 for (unsigned int index = 0; cit != end; ++cit, ++index) {
791 tomenu.add(MenuItem(MenuItem::Command, *cit,
792 FuncRequest(LFUN_PASTE, convert<string>(index))));
797 void expandToolbars(Menu & tomenu)
800 // extracts the toolbars from the backend
801 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
802 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
804 for (; cit != end; ++cit) {
805 docstring label = _(cit->gui_name);
806 // frontends are not supposed to turn on/off toolbars,
807 // if they cannot update ToolbarBackend::flags. That
808 // is to say, ToolbarsBackend::flags should reflect
809 // the true state of toolbars.
811 // menu is displayed as
815 // in the case of auto.
816 if (cit->flags & ToolbarInfo::AUTO)
817 label += _(" (auto)");
818 tomenu.add(MenuItem(MenuItem::Command, label,
819 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
824 void expandBranches(Menu & tomenu, Buffer const * buf)
827 tomenu.add(MenuItem(MenuItem::Command,
828 _("No Document Open!"),
829 FuncRequest(LFUN_NOACTION)));
833 BufferParams const & params = buf->getMasterBuffer()->params();
834 if (params.branchlist().empty()) {
835 tomenu.add(MenuItem(MenuItem::Command,
836 _("No Branch in Document!"),
837 FuncRequest(LFUN_NOACTION)));
841 BranchList::const_iterator cit = params.branchlist().begin();
842 BranchList::const_iterator end = params.branchlist().end();
844 for (int ii = 1; cit != end; ++cit, ++ii) {
845 docstring label = cit->getBranch();
847 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
848 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
849 FuncRequest(LFUN_BRANCH_INSERT,
858 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
859 Buffer const * buf) const
864 for (Menu::const_iterator cit = frommenu.begin();
865 cit != frommenu.end() ; ++cit) {
866 switch (cit->kind()) {
867 case MenuItem::Lastfiles:
868 expandLastfiles(tomenu);
871 case MenuItem::Documents:
872 expandDocuments(tomenu);
875 case MenuItem::Bookmarks:
876 expandBookmarks(tomenu);
879 case MenuItem::ImportFormats:
880 case MenuItem::ViewFormats:
881 case MenuItem::UpdateFormats:
882 case MenuItem::ExportFormats:
883 expandFormats(cit->kind(), tomenu, buf);
886 case MenuItem::CharStyles:
887 expandCharStyleInsert(tomenu, buf, "charstyle");
890 case MenuItem::Custom:
891 expandCharStyleInsert(tomenu, buf, "custom");
894 case MenuItem::FloatListInsert:
895 expandFloatListInsert(tomenu, buf);
898 case MenuItem::FloatInsert:
899 expandFloatInsert(tomenu, buf);
902 case MenuItem::PasteRecent:
903 expandPasteRecent(tomenu, buf);
906 case MenuItem::Toolbars:
907 expandToolbars(tomenu);
910 case MenuItem::Branches:
911 expandBranches(tomenu, buf);
915 expandToc(tomenu, buf);
918 case MenuItem::Submenu: {
920 item.submenu(new Menu(cit->submenuname()));
921 expand(getMenu(cit->submenuname()),
922 *item.submenu(), buf);
923 tomenu.addWithStatusCheck(item);
927 case MenuItem::Separator:
928 tomenu.addWithStatusCheck(*cit);
931 case MenuItem::Command:
932 if (!specialmenu_.hasFunc(cit->func()))
933 tomenu.addWithStatusCheck(*cit);
937 // we do not want the menu to end with a separator
939 && tomenu.items_.back().kind() == MenuItem::Separator)
940 tomenu.items_.pop_back();
942 // Check whether the shortcuts are unique
943 tomenu.checkShortcuts();
947 void MenuBackend::read(Lexer & lex)
956 struct keyword_item menutags[md_last - 1] = {
957 { "end", md_endmenuset },
959 { "menubar", md_menubar }
963 if (compare_ascii_no_case(lex.getString(), "menuset")) {
964 lyxerr << "Menubackend::read: ERROR wrong token:`"
965 << lex.getString() << '\'' << endl;
968 lex.pushTable(menutags, md_last - 1);
969 if (lyxerr.debugging(Debug::PARSER))
970 lex.printTable(lyxerr);
974 while (lex.isOK() && !quit) {
981 docstring const name = lex.getDocString();
983 getMenu(name).read(lex);
995 lex.printError("menubackend::read: "
996 "Unknown menu tag: `$$Token'");
1004 void MenuBackend::add(Menu const & menu)
1006 menulist_.push_back(menu);
1010 bool MenuBackend::hasMenu(docstring const & name) const
1012 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1016 Menu const & MenuBackend::getMenu(docstring const & name) const
1018 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1020 lyxerr << "No submenu named " << to_utf8(name) << endl;
1021 BOOST_ASSERT(cit != end());
1026 Menu & MenuBackend::getMenu(docstring const & name)
1028 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1030 lyxerr << "No submenu named " << to_utf8(name) << endl;
1031 BOOST_ASSERT(it != end());
1036 Menu const & MenuBackend::getMenubar() const