]> git.lyx.org Git - lyx.git/blob - src/MenuBackend.cpp
'using namespace std' instead of 'using std::xxx'
[lyx.git] / src / MenuBackend.cpp
1 /**
2  * \file MenuBackend.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author André Pönitz
10  * \author Dekel Tsur
11  * \author Martin Vermeer
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "MenuBackend.h"
19
20 #include "BranchList.h"
21 #include "Buffer.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "Converter.h"
25 #include "CutAndPaste.h"
26 #include "support/debug.h"
27 #include "Floating.h"
28 #include "FloatList.h"
29 #include "Format.h"
30 #include "support/gettext.h"
31 #include "KeyMap.h"
32 #include "Session.h"
33 #include "LyXAction.h"
34 #include "LyX.h" // for lastfiles
35 #include "LyXFunc.h"
36 #include "Lexer.h"
37 #include "Paragraph.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
40 #include "ToolbarBackend.h"
41
42 #include "support/filetools.h"
43 #include "support/lstrings.h"
44 #include "support/convert.h"
45
46 #include <boost/bind.hpp>
47
48 #include <algorithm>
49 #include <ostream>
50
51 using namespace std;
52 using boost::bind;
53
54 namespace lyx {
55
56 using support::compare_ascii_no_case;
57 using support::contains;
58 using support::makeDisplayPath;
59 using support::token;
60
61 namespace {
62
63 class MenuNamesEqual : public std::unary_function<Menu, bool> {
64 public:
65         MenuNamesEqual(docstring const & name)
66                 : name_(name) {}
67         bool operator()(Menu const & menu) const {
68                 return menu.name() == name_;
69         }
70 private:
71         docstring name_;
72 };
73
74 } // namespace anon
75
76
77 // This is the global menu definition
78 MenuBackend menubackend;
79
80
81 MenuItem::MenuItem(Kind kind)
82         : kind_(kind), optional_(false)
83 {}
84
85
86 MenuItem::MenuItem(Kind kind, docstring const & label,
87                    docstring const & submenu, bool optional)
88         : kind_(kind), label_(label),
89           submenuname_(submenu), optional_(optional)
90 {
91         BOOST_ASSERT(kind == Submenu);
92 }
93
94
95 MenuItem::MenuItem(Kind kind, docstring const & label,
96                    FuncRequest const & func, bool optional)
97         : kind_(kind), label_(label), func_(func), optional_(optional)
98 {
99         func_.origin = FuncRequest::MENU;
100 }
101
102
103 MenuItem::~MenuItem()
104 {}
105
106
107 void MenuItem::submenu(Menu * menu)
108 {
109         submenu_.reset(menu);
110 }
111
112
113 docstring const MenuItem::label() const
114 {
115         return token(label_, char_type('|'), 0);
116 }
117
118
119 docstring const MenuItem::shortcut() const
120 {
121         return token(label_, char_type('|'), 1);
122 }
123
124
125 docstring const MenuItem::binding(bool forgui) const
126 {
127         if (kind_ != Command)
128                 return docstring();
129
130         // Get the keys bound to this action, but keep only the
131         // first one later
132         KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
133
134         if (bindings.size())
135                 return bindings.begin()->print(KeySequence::ForGui);
136
137         LYXERR(Debug::KBMAP, "No binding for "
138                 << lyxaction.getActionName(func_.action)
139                 << '(' << to_utf8(func_.argument()) << ')');
140         return docstring();
141 }
142
143
144 Menu & Menu::add(MenuItem const & i)
145 {
146         items_.push_back(i);
147         return *this;
148 }
149
150
151 Menu & Menu::addWithStatusCheck(MenuItem const & i)
152 {
153         switch (i.kind()) {
154
155         case MenuItem::Command: {
156                 FuncStatus status = lyx::getStatus(i.func());
157                 if (status.unknown() || (!status.enabled() && i.optional()))
158                         break;
159                 items_.push_back(i);
160                 items_.back().status(status);
161                 break;
162         }
163
164         case MenuItem::Submenu: {
165                 if (i.submenu()) {
166                         bool enabled = false;
167                         for (const_iterator cit = i.submenu()->begin();
168                              cit != i.submenu()->end(); ++cit) {
169                                 if ((cit->kind() == MenuItem::Command
170                                      || cit->kind() == MenuItem::Submenu)
171                                     && cit->status().enabled()) {
172                                         enabled = true;
173                                         break;
174                                 }
175                         }
176                         if (enabled || !i.optional()) {
177                                 items_.push_back(i);
178                                 items_.back().status().enabled(enabled);
179                         }
180                 }
181                 else
182                         items_.push_back(i);
183                 break;
184         }
185
186         case MenuItem::Separator:
187                 if (!items_.empty()
188                     && items_.back().kind() != MenuItem::Separator)
189                         items_.push_back(i);
190                 break;
191
192         default:
193                 items_.push_back(i);
194         }
195
196         return *this;
197 }
198
199
200 Menu & Menu::read(Lexer & lex)
201 {
202         enum Menutags {
203                 md_item = 1,
204                 md_branches,
205                 md_documents,
206                 md_bookmarks,
207                 md_charstyles,
208                 md_custom,
209                 md_elements,
210                 md_endmenu,
211                 md_exportformats,
212                 md_importformats,
213                 md_lastfiles,
214                 md_optitem,
215                 md_optsubmenu,
216                 md_separator,
217                 md_submenu,
218                 md_toc,
219                 md_updateformats,
220                 md_viewformats,
221                 md_floatlistinsert,
222                 md_floatinsert,
223                 md_pasterecent,
224                 md_toolbars,
225                 md_last
226         };
227
228         struct keyword_item menutags[md_last - 1] = {
229                 { "bookmarks", md_bookmarks },
230                 { "branches", md_branches },
231                 { "charstyles", md_charstyles },
232                 { "custom", md_custom },
233                 { "documents", md_documents },
234                 { "elements", md_elements },
235                 { "end", md_endmenu },
236                 { "exportformats", md_exportformats },
237                 { "floatinsert", md_floatinsert },
238                 { "floatlistinsert", md_floatlistinsert },
239                 { "importformats", md_importformats },
240                 { "item", md_item },
241                 { "lastfiles", md_lastfiles },
242                 { "optitem", md_optitem },
243                 { "optsubmenu", md_optsubmenu },
244                 { "pasterecent", md_pasterecent },
245                 { "separator", md_separator },
246                 { "submenu", md_submenu },
247                 { "toc", md_toc },
248                 { "toolbars", md_toolbars },
249                 { "updateformats", md_updateformats },
250                 { "viewformats", md_viewformats }
251         };
252
253         lex.pushTable(menutags, md_last - 1);
254         if (lyxerr.debugging(Debug::PARSER))
255                 lex.printTable(lyxerr);
256
257         bool quit = false;
258         bool optional = false;
259
260         while (lex.isOK() && !quit) {
261                 switch (lex.lex()) {
262                 case md_optitem:
263                         optional = true;
264                         // fallback to md_item
265                 case md_item: {
266                         lex.next(true);
267                         docstring const name = translateIfPossible(lex.getDocString());
268                         lex.next(true);
269                         string const command = lex.getString();
270                         FuncRequest func = lyxaction.lookupFunc(command);
271                         add(MenuItem(MenuItem::Command, name, func, optional));
272                         optional = false;
273                         break;
274                 }
275
276                 case md_separator:
277                         add(MenuItem(MenuItem::Separator));
278                         break;
279
280                 case md_lastfiles:
281                         add(MenuItem(MenuItem::Lastfiles));
282                         break;
283
284                 case md_charstyles:
285                         add(MenuItem(MenuItem::CharStyles));
286                         break;
287
288                 case md_custom:
289                         add(MenuItem(MenuItem::Custom));
290                         break;
291
292                 case md_elements:
293                         add(MenuItem(MenuItem::Elements));
294                         break;
295
296                 case md_documents:
297                         add(MenuItem(MenuItem::Documents));
298                         break;
299
300                 case md_bookmarks:
301                         add(MenuItem(MenuItem::Bookmarks));
302                         break;
303
304                 case md_toc:
305                         add(MenuItem(MenuItem::Toc));
306                         break;
307
308                 case md_viewformats:
309                         add(MenuItem(MenuItem::ViewFormats));
310                         break;
311
312                 case md_updateformats:
313                         add(MenuItem(MenuItem::UpdateFormats));
314                         break;
315
316                 case md_exportformats:
317                         add(MenuItem(MenuItem::ExportFormats));
318                         break;
319
320                 case md_importformats:
321                         add(MenuItem(MenuItem::ImportFormats));
322                         break;
323
324                 case md_floatlistinsert:
325                         add(MenuItem(MenuItem::FloatListInsert));
326                         break;
327
328                 case md_floatinsert:
329                         add(MenuItem(MenuItem::FloatInsert));
330                         break;
331
332                 case md_pasterecent:
333                         add(MenuItem(MenuItem::PasteRecent));
334                         break;
335
336                 case md_toolbars:
337                         add(MenuItem(MenuItem::Toolbars));
338                         break;
339
340                 case md_branches:
341                         add(MenuItem(MenuItem::Branches));
342                         break;
343
344                 case md_optsubmenu:
345                         optional = true;
346                         // fallback to md_submenu
347                 case md_submenu: {
348                         lex.next(true);
349                         docstring const mlabel = translateIfPossible(lex.getDocString());
350                         lex.next(true);
351                         docstring const mname = lex.getDocString();
352                         add(MenuItem(MenuItem::Submenu, mlabel, mname,
353                                      optional));
354                         optional = false;
355                         break;
356                 }
357
358                 case md_endmenu:
359                         quit = true;
360                         break;
361
362                 default:
363                         lex.printError("Menu::read: "
364                                        "Unknown menu tag: `$$Token'");
365                         break;
366                 }
367         }
368         lex.popTable();
369         return *this;
370 }
371
372
373 MenuItem const & Menu::operator[](size_type i) const
374 {
375         return items_[i];
376 }
377
378
379 bool Menu::hasFunc(FuncRequest const & func) const
380 {
381         return find_if(begin(), end(),
382                        bind(std::equal_to<FuncRequest>(),
383                             bind(&MenuItem::func, _1),
384                             func)) != end();
385 }
386
387 void Menu::checkShortcuts() const
388 {
389         // This is a quadratic algorithm, but we do not care because
390         // menus are short enough
391         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
392                 docstring shortcut = it1->shortcut();
393                 if (shortcut.empty())
394                         continue;
395                 if (!contains(it1->label(), shortcut))
396                         lyxerr << "Menu warning: menu entry \""
397                                << to_utf8(it1->label())
398                                << "\" does not contain shortcut `"
399                                << to_utf8(shortcut) << "'." << endl;
400                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
401                         if (!compare_ascii_no_case(it2->shortcut(), shortcut)) {
402                                 lyxerr << "Menu warning: menu entries "
403                                        << '"' << to_utf8(it1->fulllabel())
404                                        << "\" and \"" << to_utf8(it2->fulllabel())
405                                        << "\" share the same shortcut."
406                                        << endl;
407                         }
408                 }
409         }
410 }
411
412
413 bool Menu::searchFunc(FuncRequest & func, stack<docstring> & names)
414 {
415         const_iterator m = begin();
416         const_iterator m_end = end();
417         for (; m != m_end; ++m) {
418                 if (m->kind() == MenuItem::Command && m->func() == func) {
419                         names.push(m->label());
420                         return true;
421                 } else if (m->kind() == MenuItem::Submenu) {
422                         names.push(m->label());
423                         Menu submenu = menubackend.getMenu(m->submenuname());
424                         if (submenu.searchFunc(func, names))
425                                 return true;
426                         else
427                                 names.pop();
428                 }
429         }
430         return false;
431 }
432
433
434 void MenuBackend::specialMenu(Menu const & menu)
435 {
436         specialmenu_ = menu;
437 }
438
439
440 namespace {
441
442 class compare_format {
443 public:
444         bool operator()(Format const * p1, Format const * p2) {
445                 return *p1 < *p2;
446         }
447 };
448
449 docstring const limit_string_length(docstring const & str)
450 {
451         docstring::size_type const max_item_length = 45;
452
453         if (str.size() > max_item_length)
454                 return str.substr(0, max_item_length - 3) + "...";
455         else
456                 return str;
457 }
458
459
460 void expandLastfiles(Menu & tomenu)
461 {
462         lyx::LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
463         lyx::LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
464
465         int ii = 1;
466
467         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
468                 string const file = lfit->absFilename();
469                 docstring const label = convert<docstring>(ii) + ". "
470                         + makeDisplayPath(file, 30)
471                         + char_type('|') + convert<docstring>(ii);
472                 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
473         }
474 }
475
476
477 void expandDocuments(Menu & tomenu)
478 {
479         Buffer * first = theBufferList().first();
480         if (first) {
481                 Buffer * b = first;
482                 int ii = 1;
483                 
484                 // We cannot use a for loop as the buffer list cycles.
485                 do {
486                         docstring label = b->fileName().displayName(20);
487                         if (!b->isClean())
488                                 label = label + "*";
489                         if (ii < 10)
490                                 label = convert<docstring>(ii) + ". " + label + '|' + convert<docstring>(ii);
491                         tomenu.add(MenuItem(MenuItem::Command, label,
492                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
493                         
494                         b = theBufferList().next(b);
495                         ++ii;
496                 } while (b != first); 
497         } else {
498                 tomenu.add(MenuItem(MenuItem::Command, _("No Documents Open!"),
499                            FuncRequest(LFUN_NOACTION)));
500         }
501 }
502
503
504 void expandBookmarks(Menu & tomenu)
505 {
506         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
507
508         for (size_t i = 1; i <= bm.size(); ++i) {
509                 if (bm.isValid(i)) {
510                         docstring const label = convert<docstring>(i) + ". "
511                                 + makeDisplayPath(bm.bookmark(i).filename.absFilename(), 20)
512                                 + char_type('|') + convert<docstring>(i);
513                         tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_BOOKMARK_GOTO,
514                                 convert<docstring>(i))));
515                 }
516         }
517 }
518
519
520 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
521 {
522         if (!buf && kind != MenuItem::ImportFormats) {
523                 tomenu.add(MenuItem(MenuItem::Command,
524                                     _("No Document Open!"),
525                                     FuncRequest(LFUN_NOACTION)));
526                 return;
527         }
528
529         typedef vector<Format const *> Formats;
530         Formats formats;
531         kb_action action;
532
533         switch (kind) {
534         case MenuItem::ImportFormats:
535                 formats = theConverters().importableFormats();
536                 action = LFUN_BUFFER_IMPORT;
537                 break;
538         case MenuItem::ViewFormats:
539                 formats = buf->exportableFormats(true);
540                 action = LFUN_BUFFER_VIEW;
541                 break;
542         case MenuItem::UpdateFormats:
543                 formats = buf->exportableFormats(true);
544                 action = LFUN_BUFFER_UPDATE;
545                 break;
546         default:
547                 formats = buf->exportableFormats(false);
548                 action = LFUN_BUFFER_EXPORT;
549         }
550         sort(formats.begin(), formats.end(), compare_format());
551
552         Formats::const_iterator fit = formats.begin();
553         Formats::const_iterator end = formats.end();
554         for (; fit != end ; ++fit) {
555                 if ((*fit)->dummy())
556                         continue;
557                 docstring label = from_utf8((*fit)->prettyname());
558
559                 switch (kind) {
560                 case MenuItem::ImportFormats:
561                         // FIXME: This is a hack, we should rather solve
562                         // FIXME: bug 2488 instead.
563                         if ((*fit)->name() == "text")
564                                 label = _("Plain Text");
565                         else if ((*fit)->name() == "textparagraph")
566                                 label = _("Plain Text, Join Lines");
567                         label += "...";
568                         break;
569                 case MenuItem::ViewFormats:
570                 case MenuItem::ExportFormats:
571                 case MenuItem::UpdateFormats:
572                         if (!(*fit)->documentFormat())
573                                 continue;
574                         break;
575                 default:
576                         BOOST_ASSERT(false);
577                         break;
578                 }
579                 if (!(*fit)->shortcut().empty())
580                         label += char_type('|') + from_utf8((*fit)->shortcut());
581
582                 if (buf)
583                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
584                                 FuncRequest(action, (*fit)->name())));
585                 else
586                         tomenu.add(MenuItem(MenuItem::Command, label,
587                                 FuncRequest(action, (*fit)->name())));
588         }
589 }
590
591
592 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
593 {
594         if (!buf) {
595                 tomenu.add(MenuItem(MenuItem::Command,
596                                     _("No Document Open!"),
597                                     FuncRequest(LFUN_NOACTION)));
598                 return;
599         }
600
601         FloatList const & floats =
602                 buf->params().getTextClass().floats();
603         FloatList::const_iterator cit = floats.begin();
604         FloatList::const_iterator end = floats.end();
605         for (; cit != end; ++cit) {
606                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
607                                     _(cit->second.listName()),
608                                     FuncRequest(LFUN_FLOAT_LIST,
609                                                 cit->second.type())));
610         }
611 }
612
613
614 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
615 {
616         if (!buf) {
617                 tomenu.add(MenuItem(MenuItem::Command,
618                                     _("No Document Open!"),
619                                     FuncRequest(LFUN_NOACTION)));
620                 return;
621         }
622
623         FloatList const & floats =
624                 buf->params().getTextClass().floats();
625         FloatList::const_iterator cit = floats.begin();
626         FloatList::const_iterator end = floats.end();
627         for (; cit != end; ++cit) {
628                 // normal float
629                 docstring const label = _(cit->second.name());
630                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
631                                     FuncRequest(LFUN_FLOAT_INSERT,
632                                                 cit->second.type())));
633         }
634 }
635
636
637 void expandFlexInsert(Menu & tomenu, Buffer const * buf, std::string s)
638 {
639         if (!buf) {
640                 tomenu.add(MenuItem(MenuItem::Command,
641                                     _("No Document Open!"),
642                                     FuncRequest(LFUN_NOACTION)));
643                 return;
644         }
645         InsetLayouts const & insetlayouts =
646                 buf->params().getTextClass().insetlayouts();
647         InsetLayouts::const_iterator cit = insetlayouts.begin();
648         InsetLayouts::const_iterator end = insetlayouts.end();
649         for (; cit != end; ++cit) {
650                 docstring const label = cit->first;
651                 if (cit->second.lyxtype == s)
652                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, 
653                                 label, FuncRequest(LFUN_FLEX_INSERT,
654                                                 label)));
655         }
656 }
657
658
659 Menu::size_type const max_number_of_items = 25;
660
661 void expandToc2(Menu & tomenu,
662                 Toc const & toc_list,
663                 Toc::size_type from,
664                 Toc::size_type to, int depth)
665 {
666         int shortcut_count = 0;
667
668         // check whether depth is smaller than the smallest depth in toc.
669         int min_depth = 1000;
670         for (Toc::size_type i = from; i < to; ++i)
671                 min_depth = std::min(min_depth, toc_list[i].depth());
672         if (min_depth > depth)
673                 depth = min_depth;
674
675
676         if (to - from <= max_number_of_items) {
677                 for (Toc::size_type i = from; i < to; ++i) {
678                         docstring label(4 * max(0, toc_list[i].depth() - depth), char_type(' '));
679                         label += limit_string_length(toc_list[i].str());
680                         if (toc_list[i].depth() == depth
681                             && shortcut_count < 9) {
682                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
683                                         label += char_type('|') + convert<docstring>(++shortcut_count);
684                         }
685                         tomenu.add(MenuItem(MenuItem::Command, label,
686                                             FuncRequest(toc_list[i].action())));
687                 }
688         } else {
689                 Toc::size_type pos = from;
690                 while (pos < to) {
691                         Toc::size_type new_pos = pos + 1;
692                         while (new_pos < to &&
693                                toc_list[new_pos].depth() > depth)
694                                 ++new_pos;
695
696                         docstring label(4 * max(0, toc_list[pos].depth() - depth), ' ');
697                         label += limit_string_length(toc_list[pos].str());
698                         if (toc_list[pos].depth() == depth &&
699                             shortcut_count < 9) {
700                                 if (label.find(convert<docstring>(shortcut_count + 1)) != docstring::npos)
701                                         label += char_type('|') + convert<docstring>(++shortcut_count);
702                         }
703                         if (new_pos == pos + 1) {
704                                 tomenu.add(MenuItem(MenuItem::Command,
705                                                     label, FuncRequest(toc_list[pos].action())));
706                         } else {
707                                 MenuItem item(MenuItem::Submenu, label);
708                                 item.submenu(new Menu);
709                                 expandToc2(*item.submenu(),
710                                            toc_list, pos, new_pos, depth + 1);
711                                 tomenu.add(item);
712                         }
713                         pos = new_pos;
714                 }
715         }
716 }
717
718
719 void expandToc(Menu & tomenu, Buffer const * buf)
720 {
721         // To make things very cleanly, we would have to pass buf to
722         // all MenuItem constructors and to expandToc2. However, we
723         // know that all the entries in a TOC will be have status_ ==
724         // OK, so we avoid this unnecessary overhead (JMarc)
725
726         if (!buf) {
727                 tomenu.add(MenuItem(MenuItem::Command,
728                                     _("No Document Open!"),
729                                     FuncRequest(LFUN_NOACTION)));
730                 return;
731         }
732
733         Buffer* cbuf = const_cast<Buffer*>(buf);
734         cbuf->tocBackend().update();
735         cbuf->structureChanged();
736
737         // Add an entry for the master doc if this is a child doc
738         Buffer const * const master = buf->masterBuffer();
739         if (buf != master) {
740                 ParIterator const pit = par_iterator_begin(master->inset());
741                 string const arg = convert<string>(pit->id());
742                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
743                 tomenu.add(MenuItem(MenuItem::Command, _("Master Document"), f));
744         }
745
746         FloatList const & floatlist = buf->params().getTextClass().floats();
747         TocList const & toc_list = buf->tocBackend().tocs();
748         TocList::const_iterator cit = toc_list.begin();
749         TocList::const_iterator end = toc_list.end();
750         for (; cit != end; ++cit) {
751                 // Handle this later
752                 if (cit->first == "tableofcontents")
753                         continue;
754
755                 // All the rest is for floats
756                 auto_ptr<Menu> menu(new Menu);
757                 TocIterator ccit = cit->second.begin();
758                 TocIterator eend = cit->second.end();
759                 for (; ccit != eend; ++ccit) {
760                         docstring const label = limit_string_length(ccit->str());
761                         menu->add(MenuItem(MenuItem::Command,
762                                            label,
763                                            FuncRequest(ccit->action())));
764                 }
765                 string const & floatName = floatlist.getType(cit->first).listName();
766                 docstring label;
767                 if (!floatName.empty())
768                         label = _(floatName);
769                 // BUG3633: listings is not a proper float so its name
770                 // is not shown in floatlist.
771                 else if (cit->first == "listing")
772                         label = _("List of listings");
773                 // this should not happen now, but if something else like
774                 // listings is added later, this can avoid an empty menu name.
775                 else
776                         label = _("Other floats");
777                 MenuItem item(MenuItem::Submenu, label);
778                 item.submenu(menu.release());
779                 tomenu.add(item);
780         }
781
782         // Handle normal TOC
783         cit = toc_list.find("tableofcontents");
784         if (cit == end) {
785                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
786                                     _("No Table of contents"),
787                                     FuncRequest()));
788         } else {
789                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
790         }
791 }
792
793
794 void expandPasteRecent(Menu & tomenu, Buffer const * buf)
795 {
796         if (!buf)
797                 return;
798
799         vector<docstring> const sel =
800                 cap::availableSelections(*buf);
801
802         vector<docstring>::const_iterator cit = sel.begin();
803         vector<docstring>::const_iterator end = sel.end();
804
805         for (unsigned int index = 0; cit != end; ++cit, ++index) {
806                 tomenu.add(MenuItem(MenuItem::Command, *cit,
807                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
808         }
809 }
810
811
812 void expandToolbars(Menu & tomenu)
813 {
814         //
815         // extracts the toolbars from the backend
816         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
817         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
818
819         for (; cit != end; ++cit) {
820                 docstring label = _(cit->gui_name);
821                 // frontends are not supposed to turn on/off toolbars,
822                 // if they cannot update ToolbarBackend::flags. That
823                 // is to say, ToolbarsBackend::flags should reflect
824                 // the true state of toolbars.
825                 //
826                 // menu is displayed as
827                 //       on/off review
828                 // and
829                 //              review (auto)
830                 // in the case of auto.
831                 if (cit->flags & ToolbarInfo::AUTO)
832                         label += _(" (auto)");
833                 tomenu.add(MenuItem(MenuItem::Command, label,
834                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
835         }
836 }
837
838
839 void expandBranches(Menu & tomenu, Buffer const * buf)
840 {
841         if (!buf) {
842                 tomenu.add(MenuItem(MenuItem::Command,
843                                     _("No Document Open!"),
844                                     FuncRequest(LFUN_NOACTION)));
845                 return;
846         }
847
848         BufferParams const & params = buf->masterBuffer()->params();
849         if (params.branchlist().empty()) {
850                 tomenu.add(MenuItem(MenuItem::Command,
851                                     _("No Branch in Document!"),
852                                     FuncRequest(LFUN_NOACTION)));
853                 return;
854         }
855
856         BranchList::const_iterator cit = params.branchlist().begin();
857         BranchList::const_iterator end = params.branchlist().end();
858
859         for (int ii = 1; cit != end; ++cit, ++ii) {
860                 docstring label = cit->getBranch();
861                 if (ii < 10)
862                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
863                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
864                                     FuncRequest(LFUN_BRANCH_INSERT,
865                                                 cit->getBranch())));
866         }
867 }
868
869
870 } // namespace anon
871
872
873 void MenuBackend::expand(Menu const & frommenu, Menu & tomenu,
874                          Buffer const * buf) const
875 {
876         if (!tomenu.empty())
877                 tomenu.clear();
878
879         for (Menu::const_iterator cit = frommenu.begin();
880              cit != frommenu.end() ; ++cit) {
881                 switch (cit->kind()) {
882                 case MenuItem::Lastfiles:
883                         expandLastfiles(tomenu);
884                         break;
885
886                 case MenuItem::Documents:
887                         expandDocuments(tomenu);
888                         break;
889
890                 case MenuItem::Bookmarks:
891                         expandBookmarks(tomenu);
892                         break;
893
894                 case MenuItem::ImportFormats:
895                 case MenuItem::ViewFormats:
896                 case MenuItem::UpdateFormats:
897                 case MenuItem::ExportFormats:
898                         expandFormats(cit->kind(), tomenu, buf);
899                         break;
900
901                 case MenuItem::CharStyles:
902                         expandFlexInsert(tomenu, buf, "charstyle");
903                         break;
904
905                 case MenuItem::Custom:
906                         expandFlexInsert(tomenu, buf, "custom");
907                         break;
908
909                 case MenuItem::Elements:
910                         expandFlexInsert(tomenu, buf, "element");
911                         break;
912
913                 case MenuItem::FloatListInsert:
914                         expandFloatListInsert(tomenu, buf);
915                         break;
916
917                 case MenuItem::FloatInsert:
918                         expandFloatInsert(tomenu, buf);
919                         break;
920
921                 case MenuItem::PasteRecent:
922                         expandPasteRecent(tomenu, buf);
923                         break;
924
925                 case MenuItem::Toolbars:
926                         expandToolbars(tomenu);
927                         break;
928
929                 case MenuItem::Branches:
930                         expandBranches(tomenu, buf);
931                         break;
932
933                 case MenuItem::Toc:
934                         expandToc(tomenu, buf);
935                         break;
936
937                 case MenuItem::Submenu: {
938                         MenuItem item(*cit);
939                         item.submenu(new Menu(cit->submenuname()));
940                         expand(getMenu(cit->submenuname()),
941                                *item.submenu(), buf);
942                         tomenu.addWithStatusCheck(item);
943                 }
944                 break;
945
946                 case MenuItem::Separator:
947                         tomenu.addWithStatusCheck(*cit);
948                         break;
949
950                 case MenuItem::Command:
951                         if (!specialmenu_.hasFunc(cit->func()))
952                                 tomenu.addWithStatusCheck(*cit);
953                 }
954         }
955
956         // we do not want the menu to end with a separator
957         if (!tomenu.empty()
958             && tomenu.items_.back().kind() == MenuItem::Separator)
959                 tomenu.items_.pop_back();
960
961         // Check whether the shortcuts are unique
962         tomenu.checkShortcuts();
963 }
964
965
966 void MenuBackend::read(Lexer & lex)
967 {
968         enum Menutags {
969                 md_menu = 1,
970                 md_menubar,
971                 md_endmenuset,
972                 md_last
973         };
974
975         struct keyword_item menutags[md_last - 1] = {
976                 { "end", md_endmenuset },
977                 { "menu", md_menu },
978                 { "menubar", md_menubar }
979         };
980
981         //consistency check
982         if (compare_ascii_no_case(lex.getString(), "menuset")) {
983                 lyxerr << "Menubackend::read: ERROR wrong token:`"
984                        << lex.getString() << '\'' << endl;
985         }
986
987         lex.pushTable(menutags, md_last - 1);
988         if (lyxerr.debugging(Debug::PARSER))
989                 lex.printTable(lyxerr);
990
991         bool quit = false;
992
993         while (lex.isOK() && !quit) {
994                 switch (lex.lex()) {
995                 case md_menubar:
996                         menubar_.read(lex);
997                         break;
998                 case md_menu: {
999                         lex.next(true);
1000                         docstring const name = lex.getDocString();
1001                         if (hasMenu(name)) {
1002                                 getMenu(name).read(lex);
1003                         } else {
1004                                 Menu menu(name);
1005                                 menu.read(lex);
1006                                 add(menu);
1007                         }
1008                         break;
1009                 }
1010                 case md_endmenuset:
1011                         quit = true;
1012                         break;
1013                 default:
1014                         lex.printError("menubackend::read: "
1015                                        "Unknown menu tag: `$$Token'");
1016                         break;
1017                 }
1018         }
1019         lex.popTable();
1020 }
1021
1022
1023 void MenuBackend::add(Menu const & menu)
1024 {
1025         menulist_.push_back(menu);
1026 }
1027
1028
1029 bool MenuBackend::hasMenu(docstring const & name) const
1030 {
1031         return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1032 }
1033
1034
1035 Menu const & MenuBackend::getMenu(docstring const & name) const
1036 {
1037         const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1038         if (cit == end())
1039                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1040         BOOST_ASSERT(cit != end());
1041         return (*cit);
1042 }
1043
1044
1045 Menu & MenuBackend::getMenu(docstring const & name)
1046 {
1047         iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1048         if (it == end())
1049                 lyxerr << "No submenu named " << to_utf8(name) << endl;
1050         BOOST_ASSERT(it != end());
1051         return (*it);
1052 }
1053
1054
1055 Menu const & MenuBackend::getMenubar() const
1056 {
1057         return menubar_;
1058 }
1059
1060
1061 } // namespace lyx