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)
239 struct keyword_item menutags[md_last - 1] = {
240 { "bookmarks", md_bookmarks },
241 { "branches", md_branches },
242 { "charstyles", md_charstyles },
243 { "documents", md_documents },
244 { "end", md_endmenu },
245 { "exportformats", md_exportformats },
246 { "floatinsert", md_floatinsert },
247 { "floatlistinsert", md_floatlistinsert },
248 { "importformats", md_importformats },
250 { "lastfiles", md_lastfiles },
251 { "optitem", md_optitem },
252 { "optsubmenu", md_optsubmenu },
253 { "pasterecent", md_pasterecent },
254 { "separator", md_separator },
255 { "submenu", md_submenu },
257 { "toolbars", md_toolbars },
258 { "updateformats", md_updateformats },
259 { "viewformats", md_viewformats }
262 lex.pushTable(menutags, md_last - 1);
263 if (lyxerr.debugging(Debug::PARSER))
264 lex.printTable(lyxerr);
267 bool optional = false;
269 while (lex.isOK() && !quit) {
273 // fallback to md_item
276 docstring const name = translateIfPossible(lex.getDocString());
278 string const command = lex.getString();
279 FuncRequest func = lyxaction.lookupFunc(command);
280 add(MenuItem(MenuItem::Command, name, func, optional));
286 add(MenuItem(MenuItem::Separator));
290 add(MenuItem(MenuItem::Lastfiles));
294 add(MenuItem(MenuItem::CharStyles));
298 add(MenuItem(MenuItem::Documents));
302 add(MenuItem(MenuItem::Bookmarks));
306 add(MenuItem(MenuItem::Toc));
310 add(MenuItem(MenuItem::ViewFormats));
313 case md_updateformats:
314 add(MenuItem(MenuItem::UpdateFormats));
317 case md_exportformats:
318 add(MenuItem(MenuItem::ExportFormats));
321 case md_importformats:
322 add(MenuItem(MenuItem::ImportFormats));
325 case md_floatlistinsert:
326 add(MenuItem(MenuItem::FloatListInsert));
330 add(MenuItem(MenuItem::FloatInsert));
334 add(MenuItem(MenuItem::PasteRecent));
338 add(MenuItem(MenuItem::Toolbars));
342 add(MenuItem(MenuItem::Branches));
347 // fallback to md_submenu
350 docstring const mlabel = translateIfPossible(lex.getDocString());
352 docstring const mname = lex.getDocString();
353 add(MenuItem(MenuItem::Submenu, mlabel, mname,
364 lex.printError("Menu::read: "
365 "Unknown menu tag: `$$Token'");
374 MenuItem const & Menu::operator[](size_type i) const
380 bool Menu::hasFunc(FuncRequest const & func) const
382 return find_if(begin(), end(),
383 bind(std::equal_to<FuncRequest>(),
384 bind(&MenuItem::func, _1),
388 void Menu::checkShortcuts() const
390 // This is a quadratic algorithm, but we do not care because
391 // menus are short enough
392 for (const_iterator it1 = begin(); it1 != end(); ++it1) {
393 docstring shortcut = it1->shortcut();
394 if (shortcut.empty())
396 if (!contains(it1->label(), shortcut))
397 lyxerr << "Menu warning: menu entry \""
398 << to_utf8(it1->label())
399 << "\" does not contain shortcut `"
400 << to_utf8(shortcut) << "'." << endl;
401 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
402 if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
403 lyxerr << "Menu warning: menu entries "
404 << '"' << to_utf8(it1->fulllabel())
405 << "\" and \"" << to_utf8(it2->fulllabel())
406 << "\" share the same shortcut."
414 void MenuBackend::specialMenu(Menu const & menu)
422 class compare_format {
424 bool operator()(Format const * p1, Format const * p2) {
429 docstring const limit_string_length(docstring const & str)
431 docstring::size_type const max_item_length = 45;
433 if (str.size() > max_item_length)
434 return str.substr(0, max_item_length - 3) + "...";
440 void expandLastfiles(Menu & tomenu)
442 lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
443 lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
447 for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
448 string const file = lfit->absFilename();
449 docstring const label = convert<docstring>(ii) + ". "
450 + makeDisplayPath(file, 30)
451 + char_type('|') + convert<docstring>(ii);
452 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
457 void expandDocuments(Menu & tomenu)
459 Buffer * first = theBufferList().first();
464 // We cannot use a for loop as the buffer list cycles.
466 docstring label = makeDisplayPath(b->fileName(), 20);
467 if (!b->isClean()) label = label + "*";
469 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
470 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BUFFER_SWITCH, b->fileName())));
472 b = theBufferList().next(b);
474 } while (b != first);
476 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
477 FuncRequest(LFUN_NOACTION)));
483 void expandBookmarks(Menu & tomenu)
485 lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
487 for (size_t i = 1; i <= bm.size(); ++i) {
489 docstring const label = convert<docstring>(i) + ". "
490 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
491 + char_type('|') + convert<docstring>(i);
492 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
493 convert<docstring>(i))));
499 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
501 if (!buf && kind != MenuItem::ImportFormats) {
502 tomenu.add(MenuItem(MenuItem::Command,
503 _("No Document Open!"),
504 FuncRequest(LFUN_NOACTION)));
508 typedef vector<Format const *> Formats;
513 case MenuItem::ImportFormats:
514 formats = Importer::GetImportableFormats();
515 action = LFUN_BUFFER_IMPORT;
517 case MenuItem::ViewFormats:
518 formats = Exporter::getExportableFormats(*buf, true);
519 action = LFUN_BUFFER_VIEW;
521 case MenuItem::UpdateFormats:
522 formats = Exporter::getExportableFormats(*buf, true);
523 action = LFUN_BUFFER_UPDATE;
526 formats = Exporter::getExportableFormats(*buf, false);
527 action = LFUN_BUFFER_EXPORT;
529 sort(formats.begin(), formats.end(), compare_format());
531 Formats::const_iterator fit = formats.begin();
532 Formats::const_iterator end = formats.end();
533 for (; fit != end ; ++fit) {
536 docstring label = from_utf8((*fit)->prettyname());
539 case MenuItem::ImportFormats:
540 // FIXME: This is a hack, we should rather solve
541 // FIXME: bug 2488 instead.
542 if ((*fit)->name() == "text")
543 label = _("Plain Text");
544 else if ((*fit)->name() == "textparagraph")
545 label = _("Plain Text, Join Lines");
548 case MenuItem::ViewFormats:
549 case MenuItem::ExportFormats:
550 case MenuItem::UpdateFormats:
551 if (!(*fit)->documentFormat())
558 if (!(*fit)->shortcut().empty())
559 label += char_type('|') + from_utf8((*fit)->shortcut());
562 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
563 FuncRequest(action, (*fit)->name())));
565 tomenu.add(MenuItem(MenuItem::Command, label,
566 FuncRequest(action, (*fit)->name())));
571 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
574 tomenu.add(MenuItem(MenuItem::Command,
575 _("No Document Open!"),
576 FuncRequest(LFUN_NOACTION)));
580 FloatList const & floats =
581 buf->params().getTextClass().floats();
582 FloatList::const_iterator cit = floats.begin();
583 FloatList::const_iterator end = floats.end();
584 for (; cit != end; ++cit) {
585 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
586 _(cit->second.listName()),
587 FuncRequest(LFUN_FLOAT_LIST,
588 cit->second.type())));
593 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
596 tomenu.add(MenuItem(MenuItem::Command,
597 _("No Document Open!"),
598 FuncRequest(LFUN_NOACTION)));
602 FloatList const & floats =
603 buf->params().getTextClass().floats();
604 FloatList::const_iterator cit = floats.begin();
605 FloatList::const_iterator end = floats.end();
606 for (; cit != end; ++cit) {
608 docstring const label = _(cit->second.name());
609 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
610 FuncRequest(LFUN_FLOAT_INSERT,
611 cit->second.type())));
616 void expandCharStyleInsert(Menu & tomenu, Buffer const * buf)
619 tomenu.add(MenuItem(MenuItem::Command,
620 _("No Document Open!"),
621 FuncRequest(LFUN_NOACTION)));
624 CharStyles & charstyles =
625 buf->params().getTextClass().charstyles();
626 CharStyles::iterator cit = charstyles.begin();
627 CharStyles::iterator end = charstyles.end();
628 for (; cit != end; ++cit) {
629 docstring const label = from_utf8(cit->name);
630 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
631 FuncRequest(LFUN_CHARSTYLE_INSERT,
637 Menu::size_type const max_number_of_items = 25;
639 void expandToc2(Menu & tomenu,
640 Toc const & toc_list,
642 Toc::size_type to, int depth)
644 int shortcut_count = 0;
646 // check whether depth is smaller than the smallest depth in toc.
647 int min_depth = 1000;
648 for (Toc::size_type i = from; i < to; ++i)
649 min_depth = std::min(min_depth, toc_list[i].depth());
650 if (min_depth > depth)
654 if (to - from <= max_number_of_items) {
655 for (Toc::size_type i = from; i < to; ++i) {
656 docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
657 label += limit_string_length(toc_list[i].str());
658 if (toc_list[i].depth() == depth
659 && shortcut_count < 9) {
660 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
661 label += char_type('|') + convert<docstring>(++shortcut_count);
663 tomenu.add(MenuItem(MenuItem::Command, label,
664 FuncRequest(toc_list[i].action())));
667 Toc::size_type pos = from;
669 Toc::size_type new_pos = pos + 1;
670 while (new_pos < to &&
671 toc_list[new_pos].depth() > depth)
674 docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
675 label += limit_string_length(toc_list[pos].str());
676 if (toc_list[pos].depth() == depth &&
677 shortcut_count < 9) {
678 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
679 label += char_type('|') + convert<docstring>(++shortcut_count);
681 if (new_pos == pos + 1) {
682 tomenu.add(MenuItem(MenuItem::Command,
683 label, FuncRequest(toc_list[pos].action())));
685 MenuItem item(MenuItem::Submenu, label);
686 item.submenu(new Menu);
687 expandToc2(*item.submenu(),
688 toc_list, pos, new_pos, depth + 1);
697 void expandToc(Menu & tomenu, Buffer const * buf)
699 // To make things very cleanly, we would have to pass buf to
700 // all MenuItem constructors and to expandToc2. However, we
701 // know that all the entries in a TOC will be have status_ ==
702 // OK, so we avoid this unnecessary overhead (JMarc)
705 tomenu.add(MenuItem(MenuItem::Command,
706 _("No Document Open!"),
707 FuncRequest(LFUN_NOACTION)));
711 Buffer* cbuf = const_cast<Buffer*>(buf);
712 cbuf->tocBackend().update();
713 cbuf->structureChanged();
715 // Add an entry for the master doc if this is a child doc
716 Buffer const * const master = buf->getMasterBuffer();
718 ParIterator const pit = par_iterator_begin(master->inset());
719 string const arg = convert<string>(pit->id());
720 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
721 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
724 FloatList const & floatlist = buf->params().getTextClass().floats();
725 TocList const & toc_list = buf->tocBackend().tocs();
726 TocList::const_iterator cit = toc_list.begin();
727 TocList::const_iterator end = toc_list.end();
728 for (; cit != end; ++cit) {
730 if (cit->first == "tableofcontents")
733 // All the rest is for floats
734 auto_ptr<Menu> menu(new Menu);
735 TocIterator ccit = cit->second.begin();
736 TocIterator eend = cit->second.end();
737 for (; ccit != eend; ++ccit) {
738 docstring const label = limit_string_length(ccit->str());
739 menu->add(MenuItem(MenuItem::Command,
741 FuncRequest(ccit->action())));
743 string const & floatName = floatlist.getType(cit->first).listName();
745 if (!floatName.empty())
746 label = _(floatName);
747 // BUG3633: listings is not a proper float so its name
748 // is not shown in floatlist.
749 else if (cit->first == "listing")
750 label = _("List of listings");
751 // this should not happen now, but if something else like
752 // listings is added later, this can avoid an empty menu name.
754 label = _("Other floats");
755 MenuItem item(MenuItem::Submenu, label);
756 item.submenu(menu.release());
761 cit = toc_list.find("tableofcontents");
763 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
764 _("No Table of contents"),
767 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
772 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
777 vector<docstring> const sel =
778 cap::availableSelections(*buf);
780 vector<docstring>::const_iterator cit = sel.begin();
781 vector<docstring>::const_iterator end = sel.end();
783 for (unsigned int index = 0; cit != end; ++cit, ++index) {
784 tomenu.add(MenuItem(MenuItem::Command, *cit,
785 FuncRequest(LFUN_PASTE, convert<string>(index))));
790 void expandToolbars(Menu & tomenu)
793 // extracts the toolbars from the backend
794 ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
795 ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
797 for (; cit != end; ++cit) {
798 docstring label = _(cit->gui_name);
799 // frontends are not supposed to turn on/off toolbars,
800 // if they cannot update ToolbarBackend::flags. That
801 // is to say, ToolbarsBackend::flags should reflect
802 // the true state of toolbars.
804 // menu is displayed as
808 // in the case of auto.
809 if (cit->flags & ToolbarInfo::AUTO)
810 label += _(" (auto)");
811 tomenu.add(MenuItem(MenuItem::Command, label,
812 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
817 void expandBranches(Menu & tomenu, Buffer const * buf)
820 tomenu.add(MenuItem(MenuItem::Command,
821 _("No Document Open!"),
822 FuncRequest(LFUN_NOACTION)));
826 BufferParams const & params = buf->getMasterBuffer()->params();
827 if (params.branchlist().empty()) {
828 tomenu.add(MenuItem(MenuItem::Command,
829 _("No Branch in Document!"),
830 FuncRequest(LFUN_NOACTION)));
834 BranchList::const_iterator cit = params.branchlist().begin();
835 BranchList::const_iterator end = params.branchlist().end();
837 for (int ii = 1; cit != end; ++cit, ++ii) {
838 docstring label = cit->getBranch();
840 label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
841 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
842 FuncRequest(LFUN_BRANCH_INSERT,
851 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
852 Buffer const * buf) const
857 for (Menu::const_iterator cit = frommenu.begin();
858 cit != frommenu.end() ; ++cit) {
859 switch (cit->kind()) {
860 case MenuItem::Lastfiles:
861 expandLastfiles(tomenu);
864 case MenuItem::Documents:
865 expandDocuments(tomenu);
868 case MenuItem::Bookmarks:
869 expandBookmarks(tomenu);
872 case MenuItem::ImportFormats:
873 case MenuItem::ViewFormats:
874 case MenuItem::UpdateFormats:
875 case MenuItem::ExportFormats:
876 expandFormats(cit->kind(), tomenu, buf);
879 case MenuItem::CharStyles:
880 expandCharStyleInsert(tomenu, buf);
883 case MenuItem::FloatListInsert:
884 expandFloatListInsert(tomenu, buf);
887 case MenuItem::FloatInsert:
888 expandFloatInsert(tomenu, buf);
891 case MenuItem::PasteRecent:
892 expandPasteRecent(tomenu, buf);
895 case MenuItem::Toolbars:
896 expandToolbars(tomenu);
899 case MenuItem::Branches:
900 expandBranches(tomenu, buf);
904 expandToc(tomenu, buf);
907 case MenuItem::Submenu: {
909 item.submenu(new Menu(cit->submenuname()));
910 expand(getMenu(cit->submenuname()),
911 *item.submenu(), buf);
912 tomenu.addWithStatusCheck(item);
916 case MenuItem::Separator:
917 tomenu.addWithStatusCheck(*cit);
920 case MenuItem::Command:
921 if (!specialmenu_.hasFunc(cit->func()))
922 tomenu.addWithStatusCheck(*cit);
926 // we do not want the menu to end with a separator
928 && tomenu.items_.back().kind() == MenuItem::Separator)
929 tomenu.items_.pop_back();
931 // Check whether the shortcuts are unique
932 tomenu.checkShortcuts();
936 void MenuBackend::read(Lexer & lex)
945 struct keyword_item menutags[md_last - 1] = {
946 { "end", md_endmenuset },
948 { "menubar", md_menubar }
952 if (compare_ascii_no_case(lex.getString(), "menuset")) {
953 lyxerr << "Menubackend::read: ERROR wrong token:`"
954 << lex.getString() << '\'' << endl;
957 lex.pushTable(menutags, md_last - 1);
958 if (lyxerr.debugging(Debug::PARSER))
959 lex.printTable(lyxerr);
963 while (lex.isOK() && !quit) {
970 docstring const name = lex.getDocString();
972 getMenu(name).read(lex);
984 lex.printError("menubackend::read: "
985 "Unknown menu tag: `$$Token'");
993 void MenuBackend::add(Menu const & menu)
995 menulist_.push_back(menu);
999 bool MenuBackend::hasMenu(docstring const & name) const
1001 return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1005 Menu const & MenuBackend::getMenu(docstring const & name) const
1007 const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1009 lyxerr << "No submenu named " << to_utf8(name) << endl;
1010 BOOST_ASSERT(cit != end());
1015 Menu & MenuBackend::getMenu(docstring const & name)
1017 iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1019 lyxerr << "No submenu named " << to_utf8(name) << endl;
1020 BOOST_ASSERT(it != end());
1025 Menu const & MenuBackend::getMenubar() const