]> git.lyx.org Git - features.git/blob - src/frontends/qt4/Menus.cpp
Limit the size of navigation menus for performance.
[features.git] / src / frontends / qt4 / Menus.cpp
1 /**
2  * \file qt4/Menus.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Asger Alstrup
8  * \author Lars Gullik Bjønnes
9  * \author Jean-Marc Lasgouttes
10  * \author André Pönitz
11  * \author Dekel Tsur
12  * \author Martin Vermeer
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "Menus.h"
20
21 #include "Action.h"
22 #include "GuiApplication.h"
23 #include "GuiView.h"
24 #include "GuiWorkArea.h"
25 #include "qt_helpers.h"
26
27 #include "BiblioInfo.h"
28 #include "BranchList.h"
29 #include "Buffer.h"
30 #include "BufferList.h"
31 #include "BufferParams.h"
32 #include "BufferView.h"
33 #include "Converter.h"
34 #include "CutAndPaste.h"
35 #include "Floating.h"
36 #include "FloatList.h"
37 #include "Format.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "IndicesList.h"
41 #include "KeyMap.h"
42 #include "Language.h"
43 #include "Layout.h"
44 #include "Lexer.h"
45 #include "LyXAction.h"
46 #include "LyX.h"
47 #include "LyXRC.h"
48 #include "lyxfind.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "Session.h"
53 #include "SpellChecker.h"
54 #include "TextClass.h"
55 #include "Text.h"
56 #include "TocBackend.h"
57 #include "Toolbars.h"
58 #include "WordLangTuple.h"
59
60 #include "insets/Inset.h"
61 #include "insets/InsetCitation.h"
62 #include "insets/InsetGraphics.h"
63
64 #include "support/lassert.h"
65 #include "support/convert.h"
66 #include "support/debug.h"
67 #include "support/docstring_list.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/lstrings.h"
71
72 #include <QCursor>
73 #include <QHash>
74 #include <QList>
75 #include <QMenuBar>
76 #include <QString>
77 #if QT_VERSION >= 0x040600
78 #include <QProxyStyle>
79 #endif
80
81 #include "support/shared_ptr.h"
82
83 #include <algorithm>
84 #include <vector>
85
86 using namespace std;
87 using namespace lyx::support;
88
89
90 namespace lyx {
91 namespace frontend {
92
93 namespace {
94
95 // MacOSX specific stuff is at the end.
96
97 class MenuDefinition;
98
99 ///
100 class MenuItem {
101 public:
102         /// The type of elements that can be in a menu
103         enum Kind {
104                 ///
105                 Command,
106                 ///
107                 Submenu,
108                 ///
109                 Separator,
110                 /** This type of item explains why something is unavailable. If this
111                     menuitem is in a submenu, the submenu is enabled to make sure the
112                     user sees the information. */
113                 Help,
114                 /** This type of item merely shows that there might be a list or
115                     something alike at this position, but the list is still empty.
116                     If this item is in a submenu, the submenu will not always be
117                     enabled. */
118                 Info,
119                 /** This is the list of last opened file,
120                     typically for the File menu. */
121                 Lastfiles,
122                 /** This is the list of opened Documents,
123                     typically for the Documents menu. */
124                 Documents,
125                 /** This is the bookmarks */
126                 Bookmarks,
127                 ///
128                 Toc,
129                 /** This is a list of viewable formats
130                     typically for the File->View menu. */
131                 ViewFormats,
132                 /** This is a list of updatable formats
133                     typically for the File->Update menu. */
134                 UpdateFormats,
135                 /** This is a list of exportable formats
136                     typically for the File->Export menu. */
137                 ExportFormats,
138                 /** This is a list of importable formats
139                     typically for the File->Import menu. */
140                 ImportFormats,
141                 /** This is the list of elements available
142                  * for insertion into document. */
143                 CharStyles,
144                 /** This is the list of user-configurable
145                 insets to insert into document */
146                 Custom,
147                 /** This is the list of XML elements to
148                 insert into the document */
149                 Elements,
150                 /** This is the list of floats that we can
151                     insert a list for. */
152                 FloatListInsert,
153                 /** This is the list of floats that we can
154                     insert. */
155                 FloatInsert,
156                 /** This is the list of selections that can
157                     be pasted. */
158                 PasteRecent,
159                 /** toolbars */
160                 Toolbars,
161                 /** Available branches in document */
162                 Branches,
163                 /** Available indices in document */
164                 Indices,
165                 /** Context menu for indices in document */
166                 IndicesContext,
167                 /** Available index lists in document */
168                 IndicesLists,
169                 /** Context menu for available indices lists in document */
170                 IndicesListsContext,
171                 /** Available citation styles for a given citation */
172                 CiteStyles,
173                 /** Available graphics groups */
174                 GraphicsGroups,
175                 /// Words suggested by the spellchecker.
176                 SpellingSuggestions,
177                 /** Used Languages */
178                 LanguageSelector,
179                 /** This is the list of arguments available
180                     for insertion into the current layout. */
181                 Arguments,
182                 /** This is the list of arguments available
183                     in the InsetArgument context menu. */
184                 SwitchArguments,
185                 /** This is the list of captions available
186                 in the current layout. */
187                 Captions,
188                 /** This is the list of captions available
189                 in the InsetCaption context menu. */
190                 SwitchCaptions,
191                 /** Commands to separate environments. */
192                 EnvironmentSeparators
193         };
194
195         explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
196
197         MenuItem(Kind kind,
198                  QString const & label,
199                  QString const & submenu = QString(),
200                  QString const & tooltip = QString(),
201                  bool optional = false)
202                 : kind_(kind), label_(label), submenuname_(submenu),
203                   tooltip_(tooltip), optional_(optional)
204         {
205                 LATTEST(kind == Submenu || kind == Help || kind == Info);
206         }
207
208         MenuItem(Kind kind,
209                  QString const & label,
210                  FuncRequest const & func,
211                  QString const & tooltip = QString(),
212                  bool optional = false,
213                  FuncRequest::Origin origin = FuncRequest::MENU)
214                 : kind_(kind), label_(label), func_(func),
215                   tooltip_(tooltip), optional_(optional)
216         {
217                 func_.setOrigin(origin);
218         }
219
220         // shared_ptr<MenuDefinition> needs this apprently...
221         ~MenuItem() {}
222
223         /// The label of a given menuitem
224         QString label() const
225         {
226                 int const index = label_.lastIndexOf('|');
227                 return index == -1 ? label_ : label_.left(index);
228         }
229
230         /// The keyboard shortcut (usually underlined in the entry)
231         QString shortcut() const
232         {
233                 int const index = label_.lastIndexOf('|');
234                 return index == -1 ? QString() : label_.mid(index + 1);
235         }
236         /// The complete label, with label and shortcut separated by a '|'
237         QString fulllabel() const { return label_; }
238         /// The kind of entry
239         Kind kind() const { return kind_; }
240         /// the action (if relevant)
241         FuncRequest const & func() const { return func_; }
242         /// the tooltip
243         QString const & tooltip() const { return tooltip_; }
244         /// returns true if the entry should be omitted when disabled
245         bool optional() const { return optional_; }
246         /// returns the status of the lfun associated with this entry
247         FuncStatus const & status() const { return status_; }
248         /// returns the status of the lfun associated with this entry
249         FuncStatus & status() { return status_; }
250         /// returns the status of the lfun associated with this entry
251         void status(FuncStatus const & status) { status_ = status; }
252
253         ///returns the binding associated to this action.
254         QString binding() const
255         {
256                 if (kind_ != Command)
257                         return QString();
258                 // Get the keys bound to this action, but keep only the
259                 // first one later
260                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
261                 if (!bindings.empty())
262                         return toqstr(bindings.begin()->print(KeySequence::ForGui));
263
264                 LYXERR(Debug::KBMAP, "No binding for "
265                         << lyxaction.getActionName(func_.action())
266                         << '(' << func_.argument() << ')');
267                 return QString();
268         }
269
270         /// the description of the  submenu (if relevant)
271         QString const & submenuname() const { return submenuname_; }
272         /// set the description of the  submenu
273         void submenuname(QString const & name) { submenuname_ = name; }
274         ///
275         bool hasSubmenu() const { return !submenu_.isEmpty(); }
276         ///
277         MenuDefinition const & submenu() const { return submenu_.at(0); }
278         MenuDefinition & submenu() { return submenu_[0]; }
279         ///
280         void setSubmenu(MenuDefinition const & menu)
281         {
282                 submenu_.clear();
283                 submenu_.append(menu);
284         }
285
286 private:
287         ///
288         Kind kind_;
289         ///
290         QString label_;
291         ///
292         FuncRequest func_;
293         ///
294         QString submenuname_;
295         ///
296         QString tooltip_;
297         ///
298         bool optional_;
299         ///
300         FuncStatus status_;
301         /// contains 0 or 1 item.
302         QList<MenuDefinition> submenu_;
303 };
304
305 ///
306 class MenuDefinition {
307 public:
308         ///
309         typedef std::vector<MenuItem> ItemList;
310         ///
311         typedef ItemList::const_iterator const_iterator;
312         ///
313         explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
314
315         ///
316         void read(Lexer &);
317         ///
318         QString const & name() const { return name_; }
319         ///
320         bool empty() const { return items_.empty(); }
321         /// Clear the menu content.
322         void clear() { items_.clear(); }
323         ///
324         size_t size() const { return items_.size(); }
325         ///
326         MenuItem const & operator[](size_t) const;
327         ///
328         const_iterator begin() const { return items_.begin(); }
329         ///
330         const_iterator end() const { return items_.end(); }
331         ///
332         void cat(MenuDefinition const & other);
333         ///
334         void catSub(docstring const & name);
335
336         // search for func in this menu iteratively, and put menu
337         // names in a stack.
338         bool searchMenu(FuncRequest const & func, docstring_list & names)
339                 const;
340         ///
341         bool hasFunc(FuncRequest const &) const;
342         /// Add the menu item unconditionally
343         void add(MenuItem const & item) { items_.push_back(item); }
344         /// Checks the associated FuncRequest status before adding the
345         /// menu item.
346         void addWithStatusCheck(MenuItem const &);
347         // Check whether the menu shortcuts are unique
348         void checkShortcuts() const;
349         ///
350         void expandLastfiles();
351         void expandDocuments();
352         void expandBookmarks();
353         void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
354         void expandFloatListInsert(Buffer const * buf);
355         void expandFloatInsert(Buffer const * buf);
356         void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
357         void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
358         void expandToc(Buffer const * buf);
359         void expandPasteRecent(Buffer const * buf);
360         void expandToolbars();
361         void expandBranches(Buffer const * buf);
362         void expandIndices(Buffer const * buf, bool listof = false);
363         void expandIndicesContext(Buffer const * buf, bool listof = false);
364         void expandCiteStyles(BufferView const *);
365         void expandGraphicsGroups(BufferView const *);
366         void expandSpellingSuggestions(BufferView const *);
367         void expandLanguageSelector(Buffer const * buf);
368         void expandArguments(BufferView const *, bool switcharg = false);
369         void expandCaptions(Buffer const * buf, bool switchcap = false);
370         void expandEnvironmentSeparators(BufferView const *);
371         ///
372         ItemList items_;
373         ///
374         QString name_;
375 };
376
377
378 /// Helper for std::find_if
379 class MenuNamesEqual
380 {
381 public:
382         MenuNamesEqual(QString const & name) : name_(name) {}
383         bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
384 private:
385         QString name_;
386 };
387
388
389 ///
390 typedef std::vector<MenuDefinition> MenuList;
391 ///
392 typedef MenuList::const_iterator const_iterator;
393 ///
394 typedef MenuList::iterator iterator;
395
396 /////////////////////////////////////////////////////////////////////
397 // MenuDefinition implementation
398 /////////////////////////////////////////////////////////////////////
399
400 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
401 {
402         switch (i.kind()) {
403
404         case MenuItem::Command: {
405                 FuncStatus status = lyx::getStatus(i.func());
406                 if (status.unknown() || (!status.enabled() && i.optional()))
407                         break;
408                 items_.push_back(i);
409                 items_.back().status(status);
410                 break;
411         }
412
413         case MenuItem::Submenu: {
414                 bool enabled = false;
415                 if (i.hasSubmenu()) {
416                         for (const_iterator cit = i.submenu().begin();
417                                   cit != i.submenu().end(); ++cit) {
418                                 // Only these kind of items affect the status of the submenu
419                                 if ((cit->kind() == MenuItem::Command
420                                         || cit->kind() == MenuItem::Submenu
421                                         || cit->kind() == MenuItem::Help)) {
422                                         enabled = true;
423                                         break;
424                                 }
425                         }
426                 }
427                 if (enabled || !i.optional()) {
428                         items_.push_back(i);
429                         items_.back().status().setEnabled(enabled);
430                 }
431                 break;
432         }
433
434         case MenuItem::Separator:
435                 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
436                         items_.push_back(i);
437                 break;
438
439         default:
440                 items_.push_back(i);
441         }
442 }
443
444
445 void MenuDefinition::read(Lexer & lex)
446 {
447         enum {
448                 md_item = 1,
449                 md_branches,
450                 md_citestyles,
451                 md_documents,
452                 md_bookmarks,
453                 md_charstyles,
454                 md_custom,
455                 md_elements,
456                 md_endmenu,
457                 md_exportformats,
458                 md_importformats,
459                 md_indices,
460                 md_indicescontext,
461                 md_indiceslists,
462                 md_indiceslistscontext,
463                 md_lastfiles,
464                 md_optitem,
465                 md_optsubmenu,
466                 md_separator,
467                 md_submenu,
468                 md_toc,
469                 md_updateformats,
470                 md_viewformats,
471                 md_floatlistinsert,
472                 md_floatinsert,
473                 md_pasterecent,
474                 md_toolbars,
475                 md_graphicsgroups,
476                 md_spellingsuggestions,
477                 md_languageselector,
478                 md_arguments,
479                 md_switcharguments,
480                 md_captions,
481                 md_switchcaptions,
482                 md_env_separators
483         };
484
485         LexerKeyword menutags[] = {
486                 { "arguments", md_arguments },
487                 { "bookmarks", md_bookmarks },
488                 { "branches", md_branches },
489                 { "captions", md_captions },
490                 { "charstyles", md_charstyles },
491                 { "citestyles", md_citestyles },
492                 { "custom", md_custom },
493                 { "documents", md_documents },
494                 { "elements", md_elements },
495                 { "end", md_endmenu },
496                 { "environmentseparators", md_env_separators },
497                 { "exportformats", md_exportformats },
498                 { "floatinsert", md_floatinsert },
499                 { "floatlistinsert", md_floatlistinsert },
500                 { "graphicsgroups", md_graphicsgroups },
501                 { "importformats", md_importformats },
502                 { "indices", md_indices },
503                 { "indicescontext", md_indicescontext },
504                 { "indiceslists", md_indiceslists },
505                 { "indiceslistscontext", md_indiceslistscontext },
506                 { "item", md_item },
507                 { "languageselector", md_languageselector },
508                 { "lastfiles", md_lastfiles },
509                 { "optitem", md_optitem },
510                 { "optsubmenu", md_optsubmenu },
511                 { "pasterecent", md_pasterecent },
512                 { "separator", md_separator },
513                 { "spellingsuggestions", md_spellingsuggestions },
514                 { "submenu", md_submenu },
515                 { "switcharguments", md_switcharguments },
516                 { "switchcaptions", md_switchcaptions },
517                 { "toc", md_toc },
518                 { "toolbars", md_toolbars },
519                 { "updateformats", md_updateformats },
520                 { "viewformats", md_viewformats }
521         };
522
523         lex.pushTable(menutags);
524         lex.setContext("MenuDefinition::read: ");
525
526         int md_type = 0;
527         while (lex.isOK() && md_type != md_endmenu) {
528                 switch (md_type = lex.lex()) {
529                 case md_optitem:
530                 case md_item: {
531                         lex.next(true);
532                         docstring const name = translateIfPossible(lex.getDocString());
533                         lex.next(true);
534                         string const command = lex.getString();
535                         FuncRequest func = lyxaction.lookupFunc(command);
536                         FuncRequest::Origin origin = FuncRequest::MENU;
537                         if (name_.startsWith("context-toc-"))
538                                 origin = FuncRequest::TOC;
539                         bool const optional = (md_type == md_optitem);
540                         add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
541                         break;
542                 }
543
544                 case md_separator:
545                         add(MenuItem(MenuItem::Separator));
546                         break;
547
548                 case md_lastfiles:
549                         add(MenuItem(MenuItem::Lastfiles));
550                         break;
551
552                 case md_charstyles:
553                         add(MenuItem(MenuItem::CharStyles));
554                         break;
555
556                 case md_custom:
557                         add(MenuItem(MenuItem::Custom));
558                         break;
559
560                 case md_elements:
561                         add(MenuItem(MenuItem::Elements));
562                         break;
563
564                 case md_documents:
565                         add(MenuItem(MenuItem::Documents));
566                         break;
567
568                 case md_bookmarks:
569                         add(MenuItem(MenuItem::Bookmarks));
570                         break;
571
572                 case md_toc:
573                         add(MenuItem(MenuItem::Toc));
574                         break;
575
576                 case md_viewformats:
577                         add(MenuItem(MenuItem::ViewFormats));
578                         break;
579
580                 case md_updateformats:
581                         add(MenuItem(MenuItem::UpdateFormats));
582                         break;
583
584                 case md_exportformats:
585                         add(MenuItem(MenuItem::ExportFormats));
586                         break;
587
588                 case md_importformats:
589                         add(MenuItem(MenuItem::ImportFormats));
590                         break;
591
592                 case md_floatlistinsert:
593                         add(MenuItem(MenuItem::FloatListInsert));
594                         break;
595
596                 case md_floatinsert:
597                         add(MenuItem(MenuItem::FloatInsert));
598                         break;
599
600                 case md_pasterecent:
601                         add(MenuItem(MenuItem::PasteRecent));
602                         break;
603
604                 case md_toolbars:
605                         add(MenuItem(MenuItem::Toolbars));
606                         break;
607
608                 case md_branches:
609                         add(MenuItem(MenuItem::Branches));
610                         break;
611
612                 case md_citestyles:
613                         add(MenuItem(MenuItem::CiteStyles));
614                         break;
615
616                 case md_graphicsgroups:
617                         add(MenuItem(MenuItem::GraphicsGroups));
618                         break;
619
620                 case md_spellingsuggestions:
621                         add(MenuItem(MenuItem::SpellingSuggestions));
622                         break;
623
624                 case md_languageselector:
625                         add(MenuItem(MenuItem::LanguageSelector));
626                         break;
627
628                 case md_indices:
629                         add(MenuItem(MenuItem::Indices));
630                         break;
631
632                 case md_indicescontext:
633                         add(MenuItem(MenuItem::IndicesContext));
634                         break;
635
636                 case md_indiceslists:
637                         add(MenuItem(MenuItem::IndicesLists));
638                         break;
639
640                 case md_indiceslistscontext:
641                         add(MenuItem(MenuItem::IndicesListsContext));
642                         break;
643
644                 case md_arguments:
645                         add(MenuItem(MenuItem::Arguments));
646                         break;
647
648                 case md_switcharguments:
649                         add(MenuItem(MenuItem::SwitchArguments));
650                         break;
651
652                 case md_captions:
653                         add(MenuItem(MenuItem::Captions));
654                         break;
655
656                 case md_switchcaptions:
657                         add(MenuItem(MenuItem::SwitchCaptions));
658                         break;
659
660                 case md_env_separators:
661                         add(MenuItem(MenuItem::EnvironmentSeparators));
662                         break;
663
664                 case md_optsubmenu:
665                 case md_submenu: {
666                         lex.next(true);
667                         docstring const mlabel = translateIfPossible(lex.getDocString());
668                         lex.next(true);
669                         docstring const mname = lex.getDocString();
670                         bool const optional = (md_type == md_optsubmenu);
671                         add(MenuItem(MenuItem::Submenu,
672                                 toqstr(mlabel), toqstr(mname), QString(), optional));
673                         break;
674                 }
675
676                 case md_endmenu:
677                         break;
678
679                 default:
680                         lex.printError("Unknown menu tag");
681                         break;
682                 }
683         }
684         lex.popTable();
685 }
686
687
688 MenuItem const & MenuDefinition::operator[](size_type i) const
689 {
690         return items_[i];
691 }
692
693
694 bool MenuDefinition::hasFunc(FuncRequest const & func) const
695 {
696         for (const_iterator it = begin(), et = end(); it != et; ++it)
697                 if (it->func() == func)
698                         return true;
699         return false;
700 }
701
702
703 void MenuDefinition::catSub(docstring const & name)
704 {
705         add(MenuItem(MenuItem::Submenu,
706                      qt_("More...|M"), toqstr(name), QString(), false));
707 }
708
709 void MenuDefinition::cat(MenuDefinition const & other)
710 {
711         const_iterator et = other.end();
712         for (const_iterator it = other.begin(); it != et; ++it)
713                 add(*it);
714 }
715
716
717 void MenuDefinition::checkShortcuts() const
718 {
719         // This is a quadratic algorithm, but we do not care because
720         // menus are short enough
721         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
722                 QString shortcut = it1->shortcut();
723                 if (shortcut.isEmpty())
724                         continue;
725                 if (!it1->label().contains(shortcut))
726                         LYXERR0("Menu warning: menu entry \""
727                                << it1->label()
728                                << "\" does not contain shortcut `"
729                                << shortcut << "'.");
730                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
731                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
732                                 LYXERR0("Menu warning: menu entries "
733                                        << '"' << it1->fulllabel()
734                                        << "\" and \"" << it2->fulllabel()
735                                        << "\" share the same shortcut.");
736                         }
737                 }
738         }
739 }
740
741
742 bool MenuDefinition::searchMenu(FuncRequest const & func, docstring_list & names) const
743 {
744         const_iterator m = begin();
745         const_iterator m_end = end();
746         for (; m != m_end; ++m) {
747                 if (m->kind() == MenuItem::Command && m->func() == func) {
748                         names.push_back(qstring_to_ucs4(m->label()));
749                         return true;
750                 }
751                 if (m->kind() == MenuItem::Submenu) {
752                         names.push_back(qstring_to_ucs4(m->label()));
753                         if (!m->hasSubmenu()) {
754                                 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
755                                         << m->label() << " name=" << m->submenuname());
756                                 names.pop_back();
757                                 continue;
758                         }
759                         if (m->submenu().searchMenu(func, names))
760                                 return true;
761                         names.pop_back();
762                 }
763         }
764         return false;
765 }
766
767
768 QString limitStringLength(docstring const & str)
769 {
770         size_t const max_item_length = 45;
771         docstring ret = str.substr(0, max_item_length + 1);
772         support::truncateWithEllipsis(ret, max_item_length);
773         return toqstr(ret);
774 }
775
776
777 void MenuDefinition::expandGraphicsGroups(BufferView const * bv)
778 {
779         if (!bv)
780                 return;
781         set<string> grp;
782         graphics::getGraphicsGroups(bv->buffer(), grp);
783         if (grp.empty())
784                 return;
785
786         set<string>::const_iterator it = grp.begin();
787         set<string>::const_iterator end = grp.end();
788         add(MenuItem(MenuItem::Command, qt_("No Group"),
789                      FuncRequest(LFUN_SET_GRAPHICS_GROUP)));
790         for (; it != end; ++it) {
791                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(*it) + '|',
792                                 FuncRequest(LFUN_SET_GRAPHICS_GROUP, *it)));
793         }
794 }
795
796
797 void MenuDefinition::expandSpellingSuggestions(BufferView const * bv)
798 {
799         if (!bv)
800                 return;
801         Cursor const & cur = bv->cursor();
802         if (!cur.inTexted())
803                 return;
804         WordLangTuple wl;
805         docstring_list suggestions;
806         Paragraph const & par = cur.paragraph();
807         pos_type from = cur.pos();
808         pos_type to = from;
809         SpellChecker::Result res = par.spellCheck(from, to, wl, suggestions, true, true);
810         switch (res) {
811         case SpellChecker::UNKNOWN_WORD:
812                 if (lyxrc.spellcheck_continuously) {
813                         LYXERR(Debug::GUI, "Misspelled Word! Suggested Words = ");
814                         docstring const & selection = cur.selectionAsString(false);
815                         if (!cur.selection() || selection == wl.word()) {
816                                 size_t i = 0;
817                                 size_t m = 10; // first submenu index
818                                 MenuItem item(MenuItem::Submenu, qt_("More Spelling Suggestions"));
819                                 item.setSubmenu(MenuDefinition(qt_("More Spelling Suggestions")));
820                                 for (; i != suggestions.size(); ++i) {
821                                         docstring const & suggestion = suggestions[i];
822                                         LYXERR(Debug::GUI, suggestion);
823                                         MenuItem w(MenuItem::Command, toqstr(suggestion),
824                                                 FuncRequest(LFUN_WORD_REPLACE,
825                                                         replace2string(suggestion, selection,
826                                                                 true,     // case sensitive
827                                                                 true,     // match word
828                                                                 false,    // all words
829                                                                 true,     // forward
830                                                                 false))); // find next
831                                         if (i < m)
832                                                 add(w);
833                                         else
834                                                 item.submenu().add(w);
835                                 }
836                                 if (i > m)
837                                         add(item);
838                                 if (i > 0)
839                                         add(MenuItem(MenuItem::Separator));
840                                 docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
841                                 add(MenuItem(MenuItem::Command, qt_("Add to personal dictionary|n"),
842                                                 FuncRequest(LFUN_SPELLING_ADD, arg)));
843                                 add(MenuItem(MenuItem::Command, qt_("Ignore all|I"),
844                                                 FuncRequest(LFUN_SPELLING_IGNORE, arg)));
845                         }
846                 }
847                 break;
848         case SpellChecker::LEARNED_WORD: {
849                         LYXERR(Debug::GUI, "Learned Word.");
850                         docstring const arg = wl.word() + " " + from_ascii(wl.lang()->lang());
851                         add(MenuItem(MenuItem::Command, qt_("Remove from personal dictionary|r"),
852                                         FuncRequest(LFUN_SPELLING_REMOVE, arg)));
853                 }
854                 break;
855         case SpellChecker::NO_DICTIONARY:
856                 LYXERR(Debug::GUI, "No dictionary for language " + from_ascii(wl.lang()->lang()));
857                 // FALLTHROUGH
858         case SpellChecker::WORD_OK:
859         case SpellChecker::COMPOUND_WORD:
860         case SpellChecker::ROOT_FOUND:
861         case SpellChecker::IGNORED_WORD:
862                 break;
863         }
864 }
865
866 struct sortLanguageByName {
867         bool operator()(const Language * a, const Language * b) const {
868                 return qt_(a->display()).localeAwareCompare(qt_(b->display())) < 0;
869         }
870 };
871
872 void MenuDefinition::expandLanguageSelector(Buffer const * buf)
873 {
874         if (!buf)
875                 return;
876
877         std::set<Language const *> languages_buffer =
878                 buf->masterBuffer()->getLanguages();
879
880         if (languages_buffer.size() < 2)
881                 return;
882
883         std::set<Language const *, sortLanguageByName> languages;
884
885         std::set<Language const *>::const_iterator const beg =
886                 languages_buffer.begin();
887         for (std::set<Language const *>::const_iterator cit = beg;
888              cit != languages_buffer.end(); ++cit) {
889                 languages.insert(*cit);
890         }
891
892         MenuItem item(MenuItem::Submenu, qt_("Language|L"));
893         item.setSubmenu(MenuDefinition(qt_("Language")));
894         QString morelangs = qt_("More Languages ...|M");
895         QStringList accelerators;
896         if (morelangs.contains('|'))
897                 accelerators.append(morelangs.section('|', -1));
898         std::set<Language const *, sortLanguageByName>::const_iterator const begin = languages.begin();
899         for (std::set<Language const *, sortLanguageByName>::const_iterator cit = begin;
900              cit != languages.end(); ++cit) {
901                 QString label = qt_((*cit)->display());
902                 // try to add an accelerator
903                 bool success = false;
904                 // try capitals first
905                 for (int i = 0; i < label.size(); ++i) {
906                         QChar const ch = label[i];
907                         if (!ch.isUpper())
908                                 continue;
909                         if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
910                                 label = label + toqstr("|") + ch;
911                                 accelerators.append(ch);
912                                 success = true;
913                                 break;
914                         }
915                 }
916                 // if all capitals are taken, try the rest
917                 if (!success) {
918                         for (int i = 0; i < label.size(); ++i) {
919                                 if (label[i].isSpace())
920                                         continue;
921                                 QString const ch = QString(label[i]);
922                                 if (!accelerators.contains(ch, Qt::CaseInsensitive)) {
923                                         label = label + toqstr("|") + ch;
924                                         accelerators.append(ch);
925                                         break;
926                                 }
927                         }
928                 }
929                 MenuItem w(MenuItem::Command, label,
930                         FuncRequest(LFUN_LANGUAGE, (*cit)->lang() + " set"));
931                 item.submenu().addWithStatusCheck(w);
932         }
933         item.submenu().add(MenuItem(MenuItem::Separator));
934         item.submenu().add(MenuItem(MenuItem::Command, morelangs,
935                         FuncRequest(LFUN_DIALOG_SHOW, "character")));
936         add(item);
937 }
938
939
940 void MenuDefinition::expandLastfiles()
941 {
942         LastFilesSection::LastFiles const & lf = theSession().lastFiles().lastFiles();
943         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
944
945         unsigned int ii = 1;
946
947         for (; lfit != lf.end() && ii <= lyxrc.num_lastfiles; ++lfit, ++ii) {
948                 string const file = lfit->absFileName();
949                 QString const short_path = toqstr(makeDisplayPath(file, 30));
950                 QString const long_path = toqstr(makeDisplayPath(file));
951                 QString label;
952                 if (ii < 10)
953                         label = QString("%1. %2|%3").arg(ii).arg(short_path).arg(ii);
954                 else
955                         label = QString("%1. %2").arg(ii).arg(short_path);
956                 add(MenuItem(MenuItem::Command, label,
957                         FuncRequest(LFUN_FILE_OPEN, file), long_path));
958         }
959 }
960
961
962 void MenuDefinition::expandDocuments()
963 {
964         MenuItem item(MenuItem::Submenu, qt_("Hidden|H"));
965         item.setSubmenu(MenuDefinition(qt_("Hidden|H")));
966
967         Buffer * first = theBufferList().first();
968         if (!first) {
969                 add(MenuItem(MenuItem::Info, qt_("<No Documents Open>")));
970                 return;
971         }
972
973         int i = 0;
974         while (true) {
975                 if (!guiApp->currentView())
976                         break;
977                 GuiWorkArea * wa = guiApp->currentView()->workArea(i);
978                 if (!wa)
979                         break;
980                 Buffer const & b = wa->bufferView().buffer();
981                 QString label = toqstr(b.fileName().displayName(20));
982                 if (!b.isClean())
983                         label += "*";
984                 if (i < 10)
985                         label = QString::number(i) + ". " + label + '|' + QString::number(i);
986                 add(MenuItem(MenuItem::Command, label,
987                         FuncRequest(LFUN_BUFFER_SWITCH, b.absFileName())));
988                 ++i;
989         }
990
991
992         i = 0;
993         Buffer * b = first;
994         // We cannot use a for loop as the buffer list cycles.
995         do {
996                 if (!(guiApp->currentView()
997                     && guiApp->currentView()->workArea(*b))) {
998                         QString label = toqstr(b->fileName().displayName(20));
999                         if (!b->isClean())
1000                                 label += "*";
1001                         if (i < 10)
1002                                 label = QString::number(i) + ". " + label + '|' + QString::number(i);
1003                         item.submenu().add(MenuItem(MenuItem::Command, label,
1004                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
1005                         ++i;
1006                 }
1007                 b = theBufferList().next(b);
1008         } while (b != first);
1009
1010         if (!item.submenu().empty())
1011                 add(item);
1012 }
1013
1014
1015 void MenuDefinition::expandBookmarks()
1016 {
1017         lyx::BookmarksSection const & bm = theSession().bookmarks();
1018
1019         bool empty = true;
1020         for (size_t i = 1; i <= bm.size(); ++i) {
1021                 if (bm.isValid(i)) {
1022                         string const file = bm.bookmark(i).filename.absFileName();
1023                         QString const label = QString("%1. %2|%3").arg(i)
1024                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
1025                         add(MenuItem(MenuItem::Command, label,
1026                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
1027                         empty = false;
1028                 }
1029         }
1030         if (empty)
1031                 add(MenuItem(MenuItem::Info, qt_("<No Bookmarks Saved Yet>")));
1032 }
1033
1034
1035 void MenuDefinition::expandFormats(MenuItem::Kind const kind, Buffer const * buf)
1036 {
1037         if (!buf && kind != MenuItem::ImportFormats)
1038                 return;
1039
1040         typedef vector<Format const *> Formats;
1041         Formats formats;
1042         FuncCode action = LFUN_NOACTION;
1043
1044         switch (kind) {
1045         case MenuItem::ImportFormats:
1046                 formats = theConverters().importableFormats();
1047                 action = LFUN_BUFFER_IMPORT;
1048                 break;
1049         case MenuItem::ViewFormats:
1050                 formats = buf->params().exportableFormats(true);
1051                 action = LFUN_BUFFER_VIEW;
1052                 break;
1053         case MenuItem::UpdateFormats:
1054                 formats = buf->params().exportableFormats(true);
1055                 action = LFUN_BUFFER_UPDATE;
1056                 break;
1057         case MenuItem::ExportFormats:
1058                 formats = buf->params().exportableFormats(false);
1059                 action = LFUN_BUFFER_EXPORT;
1060                 break;
1061         default:
1062                 LATTEST(false);
1063                 return;
1064         }
1065         sort(formats.begin(), formats.end(), Format::formatSorter);
1066
1067         bool const view_update = (kind == MenuItem::ViewFormats
1068                         || kind == MenuItem::UpdateFormats);
1069
1070         QString smenue;
1071         if (view_update)
1072                 smenue = (kind == MenuItem::ViewFormats
1073                         ? qt_("View (Other Formats)|F")
1074                         : qt_("Update (Other Formats)|p"));
1075         MenuItem item(MenuItem::Submenu, smenue);
1076         item.setSubmenu(MenuDefinition(smenue));
1077
1078         Formats::const_iterator fit = formats.begin();
1079         Formats::const_iterator end = formats.end();
1080         for (; fit != end ; ++fit) {
1081                 if ((*fit)->dummy())
1082                         continue;
1083
1084                 docstring lab = from_utf8((*fit)->prettyname());
1085                 docstring const scut = from_utf8((*fit)->shortcut());
1086                 docstring const tmplab = lab;
1087
1088                 if (!scut.empty())
1089                         lab += char_type('|') + scut;
1090                 docstring const lab_i18n = translateIfPossible(lab);
1091                 docstring const shortcut = split(lab_i18n, lab, '|');
1092
1093                 bool const untranslated = (lab == lab_i18n);
1094                 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1095
1096                 switch (kind) {
1097                 case MenuItem::ImportFormats:
1098                         label += from_ascii("...");
1099                         break;
1100                 case MenuItem::ViewFormats:
1101                 case MenuItem::UpdateFormats:
1102                         if ((*fit)->name() == buf->params().getDefaultOutputFormat()) {
1103                                 docstring lbl = (kind == MenuItem::ViewFormats
1104                                         ? bformat(_("View [%1$s]|V"), label)
1105                                         : bformat(_("Update [%1$s]|U"), label));
1106                                 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1107                                 continue;
1108                         }
1109                 // fall through
1110                 case MenuItem::ExportFormats:
1111                         if (!(*fit)->inExportMenu())
1112                                 continue;
1113                         break;
1114                 default:
1115                         // we already asserted earlier in this case
1116                         // LATTEST(false);
1117                         continue;
1118                 }
1119                 if (!shortcut.empty())
1120                         label += '|' + shortcut;
1121
1122                 if (view_update) {
1123                         // note that at this point, we know that buf is not null
1124                         LATTEST(buf);
1125                         item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1126                                 toqstr(label), FuncRequest(action, (*fit)->name())));
1127                 } else {
1128                         if (buf)
1129                                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1130                                         FuncRequest(action, (*fit)->name())));
1131                         else
1132                                 add(MenuItem(MenuItem::Command, toqstr(label),
1133                                         FuncRequest(action, (*fit)->name())));
1134                 }
1135         }
1136         if (view_update)
1137                 add(item);
1138 }
1139
1140
1141 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1142 {
1143         if (!buf)
1144                 return;
1145
1146         FloatList const & floats = buf->params().documentClass().floats();
1147         FloatList::const_iterator cit = floats.begin();
1148         FloatList::const_iterator end = floats.end();
1149         set<string> seen;
1150         for (; cit != end; ++cit) {
1151                 if (!cit->second.usesFloatPkg()) {
1152                         // Different floats could declare the same ListCommand. We only
1153                         // want it on the list once, though.
1154                         string const & list_cmd = cit->second.listCommand();
1155                         if (list_cmd.empty())
1156                                 // we do not know how to generate such a list
1157                                 continue;
1158                         // This form of insert returns an iterator pointing to the newly
1159                         // inserted element OR the existing element with that value, and
1160                         // a bool indicating whether we inserted a new element. So we can
1161                         // see if one is there and insert it if not all at once.
1162                         pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1163                         if (!ret.second)
1164                                 continue;
1165                 }
1166                 string const & list_name = cit->second.listName();
1167                 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1168                         FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1169         }
1170 }
1171
1172
1173 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1174 {
1175         if (!buf)
1176                 return;
1177
1178         FloatList const & floats = buf->params().documentClass().floats();
1179         FloatList::const_iterator cit = floats.begin();
1180         FloatList::const_iterator end = floats.end();
1181         for (; cit != end; ++cit) {
1182                 // normal float
1183                 QString const label = qt_(cit->second.name());
1184                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1185                                     FuncRequest(LFUN_FLOAT_INSERT,
1186                                                 cit->second.floattype())));
1187         }
1188 }
1189
1190
1191 void MenuDefinition::expandFlexInsert(
1192                 Buffer const * buf, InsetLayout::InsetLyXType type)
1193 {
1194         if (!buf)
1195                 return;
1196
1197         TextClass::InsetLayouts const & insetLayouts =
1198                 buf->params().documentClass().insetLayouts();
1199         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1200         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1201         for (; cit != end; ++cit) {
1202                 if (cit->second.lyxtype() == type) {
1203                         if (!cit->second.obsoleted_by().empty())
1204                                 continue;
1205                         docstring label = cit->first;
1206                         // we remove the "Flex:" prefix, if it is present
1207                         if (prefixIs(label, from_ascii("Flex:")))
1208                                 label = label.substr(5);
1209                         addWithStatusCheck(MenuItem(MenuItem::Command,
1210                                 toqstr(translateIfPossible(label)),
1211                                 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1212                 }
1213         }
1214         // FIXME This is a little clunky.
1215         if (items_.empty() && type == InsetLayout::CUSTOM && !buf->isReadonly())
1216                 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1217 }
1218
1219
1220 // Threshold before we stop displaying sub-items alongside items
1221 // (for display purposes). Ideally this should fit on a screen.
1222 size_t const max_number_of_items = 30;
1223 // Size limit for the menu. This is for performance purposes,
1224 // because qt already displays a scrollable menu when necessary.
1225 // Ideally this should be the menu size from which scrollable
1226 // menus become unpractical.
1227 size_t const menu_size_limit = 80;
1228
1229 void MenuDefinition::expandToc2(Toc const & toc_list,
1230                                 size_t from, size_t to, int depth,
1231                                 string toc_type)
1232 {
1233         int shortcut_count = 0;
1234
1235         // check whether depth is smaller than the smallest depth in toc.
1236         int min_depth = 1000;
1237         for (size_t i = from; i < to; ++i)
1238                 min_depth = min(min_depth, toc_list[i].depth());
1239         if (min_depth > depth)
1240                 depth = min_depth;
1241
1242         if (to - from <= max_number_of_items) {
1243                 for (size_t i = from; i < to; ++i) {
1244                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1245                         label += limitStringLength(toc_list[i].asString());
1246                         if (toc_list[i].depth() == depth) {
1247                                 label += '|';
1248                             if (shortcut_count < 9) {
1249                                         if (label.contains(QString::number(shortcut_count + 1)))
1250                                                 label += QString::number(++shortcut_count);
1251                                 }
1252                         }
1253                         add(MenuItem(MenuItem::Command, label,
1254                                             FuncRequest(toc_list[i].action())));
1255                         // separator after the menu heading
1256                         if (toc_list[i].depth() < depth)
1257                                 add(MenuItem(MenuItem::Separator));
1258                 }
1259         } else {
1260                 size_t pos = from;
1261                 size_t size = 1;
1262                 while (pos < to) {
1263                         size_t new_pos = pos + 1;
1264                         while (new_pos < to && toc_list[new_pos].depth() > depth)
1265                                 ++new_pos;
1266
1267                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1268                         label += limitStringLength(toc_list[pos].asString());
1269                         if (toc_list[pos].depth() == depth) {
1270                                 label += '|';
1271                             if (shortcut_count < 9) {
1272                                         if (label.contains(QString::number(shortcut_count + 1)))
1273                                                 label += QString::number(++shortcut_count);
1274                                 }
1275                         }
1276                         if (size >= menu_size_limit) {
1277                                 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1278                                 add(MenuItem(MenuItem::Command, "...", f));
1279                                 break;
1280                         }
1281                         if (new_pos == pos + 1) {
1282                                 add(MenuItem(MenuItem::Command,
1283                                                     label, FuncRequest(toc_list[pos].action())));
1284                         } else {
1285                                 MenuDefinition sub;
1286                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1287                                 MenuItem item(MenuItem::Submenu, label);
1288                                 item.setSubmenu(sub);
1289                                 add(item);
1290                         }
1291                         ++size;
1292                         pos = new_pos;
1293                 }
1294         }
1295 }
1296
1297
1298 void MenuDefinition::expandToc(Buffer const * buf)
1299 {
1300         // To make things very cleanly, we would have to pass buf to
1301         // all MenuItem constructors and to expandToc2. However, we
1302         // know that all the entries in a TOC will be have status_ ==
1303         // OK, so we avoid this unnecessary overhead (JMarc)
1304         if (!buf) {
1305                 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1306                 return;
1307         }
1308         // Add an entry for the master doc if this is a child doc
1309         Buffer const * const master = buf->masterBuffer();
1310         if (buf != master) {
1311                 ParIterator const pit = par_iterator_begin(master->inset());
1312                 string const arg = convert<string>(pit->id());
1313                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1314                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1315         }
1316
1317         MenuDefinition other_lists;
1318         FloatList const & floatlist = buf->params().documentClass().floats();
1319         TocList const & toc_list = buf->tocBackend().tocs();
1320         TocList::const_iterator cit = toc_list.begin();
1321         TocList::const_iterator end = toc_list.end();
1322         for (; cit != end; ++cit) {
1323                 // Handle table of contents later
1324                 if (cit->first == "tableofcontents" || cit->second->empty())
1325                         continue;
1326                 MenuDefinition submenu;
1327                 // "Open outliner..." entry
1328                 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
1329                 submenu.add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1330                 submenu.add(MenuItem(MenuItem::Separator));
1331                 // add entries
1332                 submenu.expandToc2(*cit->second, 0, cit->second->size(), 0, cit->first);
1333                 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
1334                 item.setSubmenu(submenu);
1335                 // deserves to be in the main menu?
1336                 if (floatlist.typeExist(cit->first) || cit->first == "child")
1337                         add(item);
1338                 else
1339                         other_lists.add(item);
1340         }
1341         if (!other_lists.empty()) {
1342                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1343                 item.setSubmenu(other_lists);
1344                 add(item);
1345         }
1346         // Handle normal TOC
1347         add(MenuItem(MenuItem::Separator));
1348         cit = toc_list.find("tableofcontents");
1349         if (cit == end)
1350                 LYXERR(Debug::GUI, "No table of contents.");
1351         else {
1352                 if (!cit->second->empty())
1353                         expandToc2(*cit->second, 0, cit->second->size(), 0,
1354                                    "tableofcontents");
1355                 else
1356                         add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1357         }
1358 }
1359
1360
1361 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1362 {
1363         docstring_list const sel = cap::availableSelections(buf);
1364
1365         docstring_list::const_iterator cit = sel.begin();
1366         docstring_list::const_iterator end = sel.end();
1367
1368         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1369                 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1370                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1371         }
1372 }
1373
1374
1375 void MenuDefinition::expandToolbars()
1376 {
1377         MenuDefinition other_lists;
1378         // extracts the toolbars from the backend
1379         Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1380         Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1381         for (; cit != end; ++cit) {
1382                 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1383                                 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1384                 if (guiApp->toolbars().isMainToolbar(cit->name))
1385                         add(item);
1386                 else
1387                         other_lists.add(item);
1388         }
1389
1390         if (!other_lists.empty()) {
1391                 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1392                 item.setSubmenu(other_lists);
1393                 add(item);
1394         }
1395 }
1396
1397
1398 void MenuDefinition::expandBranches(Buffer const * buf)
1399 {
1400         if (!buf || buf->isReadonly())
1401                 return;
1402
1403         BufferParams const & master_params = buf->masterBuffer()->params();
1404         BufferParams const & params = buf->params();
1405         if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1406                 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1407                 return;
1408         }
1409
1410         BranchList::const_iterator cit = master_params.branchlist().begin();
1411         BranchList::const_iterator end = master_params.branchlist().end();
1412
1413         for (int ii = 1; cit != end; ++cit, ++ii) {
1414                 docstring label = cit->branch();
1415                 if (ii < 10) {
1416                         label = convert<docstring>(ii) + ". " + label
1417                                 + char_type('|') + convert<docstring>(ii);
1418                 }
1419                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1420                                     FuncRequest(LFUN_BRANCH_INSERT,
1421                                                 cit->branch())));
1422         }
1423
1424         if (buf == buf->masterBuffer())
1425                 return;
1426
1427         MenuDefinition child_branches;
1428
1429         BranchList::const_iterator ccit = params.branchlist().begin();
1430         BranchList::const_iterator cend = params.branchlist().end();
1431
1432         for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1433                 docstring label = ccit->branch();
1434                 if (ii < 10) {
1435                         label = convert<docstring>(ii) + ". " + label
1436                                 + char_type('|') + convert<docstring>(ii);
1437                 } else
1438                         label += char_type('|');
1439                 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1440                                     toqstr(label),
1441                                     FuncRequest(LFUN_BRANCH_INSERT,
1442                                                 ccit->branch())));
1443         }
1444
1445         if (!child_branches.empty()) {
1446                 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1447                 item.setSubmenu(child_branches);
1448                 add(item);
1449         }
1450 }
1451
1452
1453 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1454 {
1455         if (!buf)
1456                 return;
1457
1458         BufferParams const & params = buf->masterBuffer()->params();
1459         if (!params.use_indices) {
1460                 if (listof)
1461                         addWithStatusCheck(MenuItem(MenuItem::Command,
1462                                            qt_("Index List|I"),
1463                                            FuncRequest(LFUN_INDEX_PRINT,
1464                                                   from_ascii("idx"))));
1465                 else
1466                         addWithStatusCheck(MenuItem(MenuItem::Command,
1467                                            qt_("Index Entry|d"),
1468                                            FuncRequest(LFUN_INDEX_INSERT,
1469                                                   from_ascii("idx"))));
1470                 return;
1471         }
1472
1473         if (params.indiceslist().empty())
1474                 return;
1475
1476         IndicesList::const_iterator cit = params.indiceslist().begin();
1477         IndicesList::const_iterator end = params.indiceslist().end();
1478
1479         for (int ii = 1; cit != end; ++cit, ++ii) {
1480                 if (listof) {
1481                         docstring const label =
1482                                 bformat(_("Index: %1$s"), cit->index());
1483                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1484                                            FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1485                 } else {
1486                         docstring const label =
1487                                 bformat(_("Index Entry (%1$s)"), cit->index());
1488                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1489                                            FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1490                 }
1491         }
1492 }
1493
1494
1495 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1496 {
1497         if (!buf)
1498                 return;
1499
1500         BufferParams const & params = buf->masterBuffer()->params();
1501         if (!params.use_indices || params.indiceslist().empty())
1502                 return;
1503
1504         IndicesList::const_iterator cit = params.indiceslist().begin();
1505         IndicesList::const_iterator end = params.indiceslist().end();
1506
1507         for (int ii = 1; cit != end; ++cit, ++ii) {
1508                 if (listof) {
1509                         InsetCommandParams p(INDEX_PRINT_CODE);
1510                         p["type"] = cit->shortcut();
1511                         string const data = InsetCommand::params2string(p);
1512                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1513                                            FuncRequest(LFUN_INSET_MODIFY, data)));
1514                 } else {
1515                         docstring const label =
1516                                         bformat(_("Index Entry (%1$s)"), cit->index());
1517                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1518                                            FuncRequest(LFUN_INSET_MODIFY,
1519                                                   from_ascii("changetype ") + cit->shortcut())));
1520                 }
1521         }
1522 }
1523
1524
1525 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1526 {
1527         if (!bv)
1528                 return;
1529
1530         Inset const * inset = bv->cursor().nextInset();
1531         if (!inset || inset->lyxCode() != CITE_CODE) {
1532                 add(MenuItem(MenuItem::Command,
1533                                     qt_("No Citation in Scope!"),
1534                                     FuncRequest(LFUN_NOACTION)));
1535                 return;
1536         }
1537         InsetCommand const * citinset =
1538                                 static_cast<InsetCommand const *>(inset);
1539
1540         Buffer const * buf = &bv->buffer();
1541         string const cmd = citinset->params().getCmdName();
1542
1543         docstring const & key = citinset->getParam("key");
1544         if (key.empty()) {
1545                 add(MenuItem(MenuItem::Command,
1546                                     qt_("No citations selected!"),
1547                                     FuncRequest(LFUN_NOACTION)));
1548                 return;
1549         }
1550
1551         docstring const & before = citinset->getParam("before");
1552         docstring const & after = citinset->getParam("after");
1553
1554         size_t const n = cmd.size();
1555         bool const force = cmd[0] == 'C';
1556         bool const full = cmd[n] == '*';
1557
1558         vector<docstring> const keys = getVectorFromString(key);
1559
1560         vector<CitationStyle> const citeStyleList = buf->params().citeStyles();
1561         static const size_t max_length = 40;
1562         vector<docstring> citeStrings =
1563                 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(),
1564                 before, after, from_utf8("dialog"), max_length);
1565
1566         vector<docstring>::const_iterator cit = citeStrings.begin();
1567         vector<docstring>::const_iterator end = citeStrings.end();
1568
1569         for (int ii = 1; cit != end; ++cit, ++ii) {
1570                 docstring label = *cit;
1571                 CitationStyle cs = citeStyleList[ii - 1];
1572                 cs.forceUpperCase &= force;
1573                 cs.fullAuthorList &= full;
1574                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1575                                     FuncRequest(LFUN_INSET_MODIFY,
1576                                                 "changetype " + from_utf8(citationStyleToString(cs)))));
1577         }
1578 }
1579
1580
1581 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1582 {
1583         if (!bv)
1584                 return;
1585
1586         if (!bv->cursor().inTexted())
1587                 return;
1588
1589         Inset const * inset = &bv->cursor().inset();
1590         Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1591         if (inset && args.empty())
1592                 args = inset->getLayout().args();
1593         if (args.empty() || (switcharg && args.size() == 1))
1594                 return;
1595         Layout::LaTeXArgMap::const_iterator lait = args.begin();
1596         Layout::LaTeXArgMap::const_iterator const laend = args.end();
1597         for (; lait != laend; ++lait) {
1598                 Layout::latexarg arg = (*lait).second;
1599                 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1600                 QString item = toqstr(translateIfPossible(str));
1601                 if (switcharg)
1602                         add(MenuItem(MenuItem::Command, item,
1603                                      FuncRequest(LFUN_INSET_MODIFY,
1604                                                  from_ascii("changetype ")
1605                                                  + from_ascii((*lait).first))));
1606                 else
1607                         add(MenuItem(MenuItem::Command, item,
1608                                      FuncRequest(LFUN_ARGUMENT_INSERT,
1609                                                  from_ascii((*lait).first))));
1610         }
1611 }
1612
1613
1614 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1615 {
1616         if (!buf)
1617                 return;
1618
1619         vector<docstring> caps;
1620         DocumentClass const & dc = buf->params().documentClass();
1621         TextClass::InsetLayouts::const_iterator lit = dc.insetLayouts().begin();
1622         TextClass::InsetLayouts::const_iterator len = dc.insetLayouts().end();
1623         for (; lit != len; ++lit) {
1624                 if (prefixIs(lit->first, from_ascii("Caption:")))
1625                         caps.push_back(lit->first);
1626         }
1627
1628         if (caps.empty() || (switchcap && caps.size() == 1))
1629                 return;
1630         if (caps.size() == 1) {
1631                 docstring dummy;
1632                 docstring const type = split(*caps.begin(), dummy, ':');
1633                 add(MenuItem(MenuItem::Command, qt_("Caption"),
1634                          FuncRequest(LFUN_CAPTION_INSERT, translateIfPossible(type))));
1635                 return;
1636         }
1637
1638         MenuDefinition captions;
1639
1640         vector<docstring>::const_iterator cit = caps.begin();
1641         vector<docstring>::const_iterator end = caps.end();
1642
1643         for (int ii = 1; cit != end; ++cit, ++ii) {
1644                 docstring dummy;
1645                 docstring const type = split(*cit, dummy, ':');
1646                 docstring const trtype = translateIfPossible(type);
1647                 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1648                 // make menu item optional, otherwise we would also see
1649                 // forbidden caption types
1650                 if (switchcap)
1651                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cmitem),
1652                                      FuncRequest(LFUN_INSET_MODIFY,
1653                                                  from_ascii("changetype ")
1654                                                  + type), QString(), true));
1655                 else
1656                         captions.addWithStatusCheck(MenuItem(MenuItem::Command,
1657                                                              toqstr(trtype),
1658                                                              FuncRequest(LFUN_CAPTION_INSERT,
1659                                                              type), QString(), true));
1660         }
1661         if (!captions.empty()) {
1662                 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1663                 item.setSubmenu(captions);
1664                 add(item);
1665         }
1666 }
1667
1668
1669 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv)
1670 {
1671         if (!bv)
1672                 return;
1673         Text const * text = bv->cursor().text();
1674         // no paragraphs and no separators exist in math
1675         if (!text)
1676                 return;
1677
1678         pit_type pit = bv->cursor().selBegin().pit();
1679         Paragraph const & par = text->getPar(pit);
1680         docstring const curlayout = par.layout().name();
1681         docstring outerlayout;
1682         depth_type current_depth = par.params().depth();
1683         // check if we have an environment in our nesting hierarchy
1684         Paragraph cpar = par;
1685         while (true) {
1686                 if (pit == 0 || cpar.params().depth() == 0)
1687                         break;
1688                 --pit;
1689                 cpar = text->getPar(pit);
1690                 if (cpar.params().depth() < current_depth
1691                     && cpar.layout().isEnvironment()) {
1692                                 outerlayout = cpar.layout().name();
1693                                 current_depth = cpar.params().depth();
1694                 }
1695         }
1696         if (par.layout().isEnvironment()) {
1697                 docstring const label =
1698                         bformat(_("Start New Environment (%1$s)"),
1699                                 translateIfPossible(curlayout));
1700                 add(MenuItem(MenuItem::Command, toqstr(label),
1701                              FuncRequest(LFUN_ENVIRONMENT_SPLIT)));
1702         }
1703         if (!outerlayout.empty()) {
1704                 docstring const label =
1705                         bformat(_("Start New Parent Environment (%1$s)"),
1706                                 translateIfPossible(outerlayout));
1707                 add(MenuItem(MenuItem::Command, toqstr(label),
1708                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1709                                          from_ascii("outer"))));
1710         }
1711 }
1712
1713 } // namespace anon
1714
1715
1716 /////////////////////////////////////////////////////////////////////
1717 // Menu::Impl definition and implementation
1718 /////////////////////////////////////////////////////////////////////
1719
1720 struct Menu::Impl
1721 {
1722         /// populates the menu or one of its submenu
1723         /// This is used as a recursive function
1724         void populate(QMenu & qMenu, MenuDefinition const & menu);
1725
1726         /// Only needed for top level menus.
1727         MenuDefinition * top_level_menu;
1728         /// our owning view
1729         GuiView * view;
1730         /// the name of this menu
1731         QString name;
1732 };
1733
1734
1735
1736 /// Get a MenuDefinition item label from the menu backend
1737 static QString label(MenuItem const & mi)
1738 {
1739         QString label = mi.label();
1740         label.replace("&", "&&");
1741
1742         QString shortcut = mi.shortcut();
1743         if (!shortcut.isEmpty()) {
1744                 int pos = label.indexOf(shortcut);
1745                 if (pos != -1)
1746                         //label.insert(pos, 1, char_type('&'));
1747                         label.replace(pos, 0, "&");
1748         }
1749
1750         QString const binding = mi.binding();
1751         if (!binding.isEmpty())
1752                 label += '\t' + binding;
1753
1754         return label;
1755 }
1756
1757 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1758 {
1759         LYXERR(Debug::GUI, "populating menu " << menu.name());
1760         if (menu.empty()) {
1761                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1762                 return;
1763         }
1764         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1765         MenuDefinition::const_iterator m = menu.begin();
1766         MenuDefinition::const_iterator end = menu.end();
1767         for (; m != end; ++m) {
1768                 if (m->kind() == MenuItem::Separator)
1769                         qMenu.addSeparator();
1770                 else if (m->kind() == MenuItem::Submenu) {
1771                         QMenu * subMenu = qMenu.addMenu(label(*m));
1772                         populate(*subMenu, m->submenu());
1773                         subMenu->setEnabled(m->status().enabled());
1774                 } else {
1775                         // we have a MenuItem::Command
1776                         qMenu.addAction(new Action(QIcon(), label(*m),
1777                                 m->func(), m->tooltip(), &qMenu));
1778                 }
1779         }
1780 }
1781
1782 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
1783 class AlwaysMnemonicStyle : public QProxyStyle {
1784 public:
1785         int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1786                 QStyleHintReturn *returnData = 0) const
1787         {
1788                 if (hint == QStyle::SH_UnderlineShortcut)
1789                         return 1;
1790                 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1791         }
1792 };
1793 #endif
1794
1795 /////////////////////////////////////////////////////////////////////
1796 // Menu implementation
1797 /////////////////////////////////////////////////////////////////////
1798
1799 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1800 : QMenu(gv), d(new Menu::Impl)
1801 {
1802 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
1803         if (keyboard)
1804                 setStyle(new AlwaysMnemonicStyle);
1805 #else
1806         (void) keyboard;
1807 #endif
1808         d->top_level_menu = top_level? new MenuDefinition : 0;
1809         d->view = gv;
1810         d->name = name;
1811         setTitle(name);
1812         if (d->top_level_menu)
1813                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1814 }
1815
1816
1817 Menu::~Menu()
1818 {
1819         delete d->top_level_menu;
1820         delete d;
1821 }
1822
1823
1824 void Menu::updateView()
1825 {
1826         guiApp->menus().updateMenu(this);
1827 }
1828
1829
1830 void Menu::clear()
1831 {
1832         QList<QAction *> items = actions();
1833         for (int i = 0; i != items.size(); ++i) {
1834                 // QAction::menu() returns 0 if there's no submenu.
1835                 delete items.at(i)->menu();
1836         }
1837         QMenu::clear();
1838 }
1839
1840
1841 /////////////////////////////////////////////////////////////////////
1842 // Menus::Impl definition and implementation
1843 /////////////////////////////////////////////////////////////////////
1844
1845 struct Menus::Impl {
1846         ///
1847         bool hasMenu(QString const &) const;
1848         ///
1849         MenuDefinition & getMenu(QString const &);
1850         ///
1851         MenuDefinition const & getMenu(QString const &) const;
1852
1853         /// Expands some special entries of the menu
1854         /** The entries with the following kind are expanded to a
1855             sequence of Command MenuItems: Lastfiles, Documents,
1856             ViewFormats, ExportFormats, UpdateFormats, Branches,
1857             Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
1858             EnvironmentSeparators
1859         */
1860         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1861                 BufferView const *) const;
1862
1863         /// Initialize specific MACOS X menubar
1864         void macxMenuBarInit(QMenuBar * qmb);
1865
1866         /// Mac special menu.
1867         /** This defines a menu whose entries list the FuncRequests
1868             that will be removed by expand() in other menus. This is
1869             used by the Qt/Mac code.
1870
1871             NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1872             such that the items will keep accessing the FuncRequests in
1873             the MenuDefinition. While Menus::Impl might be recreated,
1874             we keep mac_special_menu_ in memory by making it static.
1875         */
1876         static MenuDefinition mac_special_menu_;
1877
1878         ///
1879         MenuList menulist_;
1880         ///
1881         MenuDefinition menubar_;
1882
1883         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1884
1885         /// name to menu for \c menu() method.
1886         NameMap name_map_;
1887 };
1888
1889
1890 MenuDefinition Menus::Impl::mac_special_menu_;
1891
1892
1893 /*
1894   Here is what the Qt documentation says about how a menubar is chosen:
1895
1896      1) If the window has a QMenuBar then it is used. 2) If the window
1897      is a modal then its menubar is used. If no menubar is specified
1898      then a default menubar is used (as documented below) 3) If the
1899      window has no parent then the default menubar is used (as
1900      documented below).
1901
1902      The above 3 steps are applied all the way up the parent window
1903      chain until one of the above are satisifed. If all else fails a
1904      default menubar will be created, the default menubar on Qt/Mac is
1905      an empty menubar, however you can create a different default
1906      menubar by creating a parentless QMenuBar, the first one created
1907      will thus be designated the default menubar, and will be used
1908      whenever a default menubar is needed.
1909
1910   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1911   that this menubar will be used also when one of LyX' dialogs has
1912   focus. (JMarc)
1913 */
1914 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
1915 {
1916         /* Since Qt 4.2, the qt/mac menu code has special code for
1917            specifying the role of a menu entry. However, it does not
1918            work very well with our scheme of creating menus on demand,
1919            and therefore we need to put these entries in a special
1920            invisible menu. (JMarc)
1921         */
1922
1923         /* The entries of our special mac menu. If we add support for
1924          * special entries in Menus, we could imagine something
1925          * like
1926          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
1927          * and therefore avoid hardcoding. I am not sure it is worth
1928          * the hassle, though. (JMarc)
1929          */
1930         struct MacMenuEntry {
1931                 FuncCode action;
1932                 char const * arg;
1933                 char const * label;
1934                 QAction::MenuRole role;
1935         };
1936
1937         static MacMenuEntry entries[] = {
1938                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1939                  QAction::AboutRole},
1940                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1941                  QAction::PreferencesRole},
1942 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
1943                 /* This doesn't work with Cocoa. */
1944                 {LFUN_RECONFIGURE, "", "Reconfigure",
1945                  QAction::ApplicationSpecificRole},
1946 #endif
1947                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1948         };
1949         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1950         const bool first_call = mac_special_menu_.empty();
1951
1952         LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
1953         // the special menu for Menus. Fill it up only once.
1954         if (first_call) {
1955                 for (size_t i = 0 ; i < num_entries ; ++i) {
1956                         FuncRequest const func(entries[i].action,
1957                                 from_utf8(entries[i].arg));
1958                         mac_special_menu_.add(MenuItem(MenuItem::Command,
1959                                 entries[i].label, func));
1960                 }
1961         }
1962
1963         // add the entries to a QMenu that will eventually be empty
1964         // and therefore invisible.
1965         QMenu * qMenu = qmb->addMenu("special");
1966         MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1967         MenuDefinition::const_iterator end = mac_special_menu_.end();
1968         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1969                 Action * action = new Action(QIcon(), cit->label(),
1970                         cit->func(), QString(), qMenu);
1971                 action->setMenuRole(entries[i].role);
1972                 qMenu->addAction(action);
1973         }
1974 }
1975
1976
1977 void Menus::Impl::expand(MenuDefinition const & frommenu,
1978         MenuDefinition & tomenu, BufferView const * bv) const
1979 {
1980         if (!tomenu.empty())
1981                 tomenu.clear();
1982
1983         for (MenuDefinition::const_iterator cit = frommenu.begin();
1984              cit != frommenu.end() ; ++cit) {
1985                 Buffer const * buf = bv ? &bv->buffer() : 0;
1986                 switch (cit->kind()) {
1987                 case MenuItem::Lastfiles:
1988                         tomenu.expandLastfiles();
1989                         break;
1990
1991                 case MenuItem::Documents:
1992                         tomenu.expandDocuments();
1993                         break;
1994
1995                 case MenuItem::Bookmarks:
1996                         tomenu.expandBookmarks();
1997                         break;
1998
1999                 case MenuItem::ImportFormats:
2000                 case MenuItem::ViewFormats:
2001                 case MenuItem::UpdateFormats:
2002                 case MenuItem::ExportFormats:
2003                         tomenu.expandFormats(cit->kind(), buf);
2004                         break;
2005
2006                 case MenuItem::CharStyles:
2007                         tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2008                         break;
2009
2010                 case MenuItem::Custom:
2011                         tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2012                         break;
2013
2014                 case MenuItem::Elements:
2015                         tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2016                         break;
2017
2018                 case MenuItem::FloatListInsert:
2019                         tomenu.expandFloatListInsert(buf);
2020                         break;
2021
2022                 case MenuItem::FloatInsert:
2023                         tomenu.expandFloatInsert(buf);
2024                         break;
2025
2026                 case MenuItem::PasteRecent:
2027                         tomenu.expandPasteRecent(buf);
2028                         break;
2029
2030                 case MenuItem::Toolbars:
2031                         tomenu.expandToolbars();
2032                         break;
2033
2034                 case MenuItem::Branches:
2035                         tomenu.expandBranches(buf);
2036                         break;
2037
2038                 case MenuItem::Indices:
2039                         tomenu.expandIndices(buf);
2040                         break;
2041
2042                 case MenuItem::IndicesContext:
2043                         tomenu.expandIndicesContext(buf);
2044                         break;
2045
2046                 case MenuItem::IndicesLists:
2047                         tomenu.expandIndices(buf, true);
2048                         break;
2049
2050                 case MenuItem::IndicesListsContext:
2051                         tomenu.expandIndicesContext(buf, true);
2052                         break;
2053
2054                 case MenuItem::CiteStyles:
2055                         tomenu.expandCiteStyles(bv);
2056                         break;
2057
2058                 case MenuItem::Toc:
2059                         tomenu.expandToc(buf);
2060                         break;
2061
2062                 case MenuItem::GraphicsGroups:
2063                         tomenu.expandGraphicsGroups(bv);
2064                         break;
2065
2066                 case MenuItem::SpellingSuggestions:
2067                         tomenu.expandSpellingSuggestions(bv);
2068                         break;
2069
2070                 case MenuItem::LanguageSelector:
2071                         tomenu.expandLanguageSelector(buf);
2072                         break;
2073
2074                 case MenuItem::Arguments:
2075                         tomenu.expandArguments(bv, false);
2076                         break;
2077
2078                 case MenuItem::SwitchArguments:
2079                         tomenu.expandArguments(bv, true);
2080                         break;
2081
2082                 case MenuItem::Captions:
2083                         tomenu.expandCaptions(buf, false);
2084                         break;
2085
2086                 case MenuItem::SwitchCaptions:
2087                         tomenu.expandCaptions(buf, true);
2088                         break;
2089
2090                 case MenuItem::EnvironmentSeparators:
2091                         tomenu.expandEnvironmentSeparators(bv);
2092                         break;
2093
2094                 case MenuItem::Submenu: {
2095                         MenuItem item(*cit);
2096                         item.setSubmenu(MenuDefinition(cit->submenuname()));
2097                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
2098                         tomenu.addWithStatusCheck(item);
2099                 }
2100                 break;
2101
2102                 case MenuItem::Info:
2103                 case MenuItem::Help:
2104                 case MenuItem::Separator:
2105                         tomenu.addWithStatusCheck(*cit);
2106                         break;
2107
2108                 case MenuItem::Command:
2109                         if (!mac_special_menu_.hasFunc(cit->func()))
2110                                 tomenu.addWithStatusCheck(*cit);
2111                 }
2112         }
2113
2114         // we do not want the menu to end with a separator
2115         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2116                 tomenu.items_.pop_back();
2117
2118         // Check whether the shortcuts are unique
2119         tomenu.checkShortcuts();
2120 }
2121
2122
2123 bool Menus::Impl::hasMenu(QString const & name) const
2124 {
2125         return find_if(menulist_.begin(), menulist_.end(),
2126                 MenuNamesEqual(name)) != menulist_.end();
2127 }
2128
2129
2130 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2131 {
2132         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2133                 MenuNamesEqual(name));
2134         if (cit == menulist_.end()) {
2135                 LYXERR0("No submenu named " << name);
2136                 LASSERT(false, { static const MenuDefinition m; return m; });
2137         }
2138         return (*cit);
2139 }
2140
2141
2142 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2143 {
2144         iterator it = find_if(menulist_.begin(), menulist_.end(),
2145                 MenuNamesEqual(name));
2146         if (it == menulist_.end()) {
2147                 LYXERR0("No submenu named " << name);
2148                 LASSERT(false, { static MenuDefinition m; return m; });
2149         }
2150         return (*it);
2151 }
2152
2153
2154 /////////////////////////////////////////////////////////////////////
2155 //
2156 // Menus
2157 //
2158 /////////////////////////////////////////////////////////////////////
2159
2160 Menus::Menus() : d(new Impl) {}
2161
2162
2163 Menus::~Menus()
2164 {
2165         delete d;
2166 }
2167
2168
2169 void Menus::reset()
2170 {
2171         delete d;
2172         d = new Impl;
2173 }
2174
2175
2176 void Menus::read(Lexer & lex)
2177 {
2178         enum {
2179                 md_menu,
2180                 md_menubar,
2181                 md_endmenuset
2182         };
2183
2184         LexerKeyword menutags[] = {
2185                 { "end", md_endmenuset },
2186                 { "menu", md_menu },
2187                 { "menubar", md_menubar }
2188         };
2189
2190         // consistency check
2191         if (compare_ascii_no_case(lex.getString(), "menuset"))
2192                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2193
2194         lex.pushTable(menutags);
2195         lex.setContext("Menus::read");
2196
2197         bool quit = false;
2198
2199         while (lex.isOK() && !quit) {
2200                 switch (lex.lex()) {
2201                 case md_menubar:
2202                         d->menubar_.read(lex);
2203                         break;
2204                 case md_menu: {
2205                         lex.next(true);
2206                         QString const name = toqstr(lex.getDocString());
2207                         if (d->hasMenu(name))
2208                                 d->getMenu(name).read(lex);
2209                         else {
2210                                 MenuDefinition menu(name);
2211                                 menu.read(lex);
2212                                 d->menulist_.push_back(menu);
2213                         }
2214                         break;
2215                 }
2216                 case md_endmenuset:
2217                         quit = true;
2218                         break;
2219                 default:
2220                         lex.printError("Unknown menu tag");
2221                         break;
2222                 }
2223         }
2224         lex.popTable();
2225 }
2226
2227
2228 bool Menus::searchMenu(FuncRequest const & func,
2229         docstring_list & names) const
2230 {
2231         MenuDefinition menu;
2232         d->expand(d->menubar_, menu, 0);
2233         return menu.searchMenu(func, names);
2234 }
2235
2236
2237 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2238 {
2239         if (initial) {
2240 #ifdef Q_OS_MAC
2241                 // setup special mac specific menu items, but only do this
2242                 // the first time a QMenuBar is created. Otherwise Qt will
2243                 // create duplicate items in the application menu. It seems
2244                 // that Qt does not remove them when the QMenubar is cleared.
2245                 d->macxMenuBarInit(qmb);
2246 #endif
2247         } else {
2248                 // Clear all menubar contents before filling it.
2249                 qmb->clear();
2250 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2251                 d->macxMenuBarInit(qmb);
2252 #endif
2253         }
2254
2255         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2256
2257         if (d->menubar_.empty()) {
2258                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2259                         << d->menubar_.name());
2260                 return;
2261         }
2262         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2263
2264         MenuDefinition menu;
2265         BufferView * bv = 0;
2266         if (view)
2267                 bv = view->currentBufferView();
2268         d->expand(d->menubar_, menu, bv);
2269
2270         MenuDefinition::const_iterator m = menu.begin();
2271         MenuDefinition::const_iterator end = menu.end();
2272
2273         for (; m != end; ++m) {
2274
2275                 if (m->kind() != MenuItem::Submenu) {
2276                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2277                         continue;
2278                 }
2279
2280                 LYXERR(Debug::GUI, "menu bar item " << m->label()
2281                         << " is a submenu named " << m->submenuname());
2282
2283                 QString name = m->submenuname();
2284                 if (!d->hasMenu(name)) {
2285                         LYXERR(Debug::GUI, "\tERROR: " << name
2286                                 << " submenu has no menu!");
2287                         continue;
2288                 }
2289
2290                 Menu * menu = new Menu(view, m->submenuname(), true);
2291                 menu->setTitle(label(*m));
2292
2293 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2294                 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2295                 // so we create a temporary one here
2296                 QAction * action = new QAction(menu);
2297                 menu->addAction(action);
2298 #endif
2299
2300                 qmb->addMenu(menu);
2301
2302                 d->name_map_[view][name] = menu;
2303         }
2304 }
2305
2306
2307 void Menus::updateMenu(Menu * qmenu)
2308 {
2309         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2310         qmenu->clear();
2311
2312         if (qmenu->d->name.isEmpty())
2313                 return;
2314
2315         docstring identifier = qstring_to_ucs4(qmenu->d->name);
2316         MenuDefinition fromLyxMenu(qmenu->d->name);
2317         while (!identifier.empty()) {
2318                 docstring menu_name;
2319                 identifier = split(identifier, menu_name, ';');
2320
2321                 if (!d->hasMenu(toqstr(menu_name))) {
2322                         LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2323                                 << menu_name);
2324                         continue;
2325                 }
2326
2327                 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2328                 //FIXME: 50 is a wild guess. We should take into account here
2329                 //the expansion of menu items, disabled optional items etc.
2330                 bool const in_sub_menu = !fromLyxMenu.empty()
2331                         && fromLyxMenu.size() + cat_menu.size() > 50 ;
2332                 if (in_sub_menu)
2333                         fromLyxMenu.catSub(menu_name);
2334                 else
2335                         fromLyxMenu.cat(cat_menu);
2336                 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2337         }
2338
2339         if (fromLyxMenu.empty()) {
2340                 qmenu->addAction(qt_("No Action Defined!"));
2341                 return;
2342         }
2343
2344         BufferView * bv = 0;
2345         if (qmenu->d->view)
2346                 bv = qmenu->d->view->currentBufferView();
2347         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2348         qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2349 }
2350
2351
2352 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2353 {
2354         LYXERR(Debug::GUI, "Context menu requested: " << name);
2355         Menu * menu = d->name_map_[&view].value(name, 0);
2356         if (!menu && !name.startsWith("context-")) {
2357                 LYXERR0("requested context menu not found: " << name);
2358                 return 0;
2359         }
2360
2361         menu = new Menu(&view, name, true, keyboard);
2362         d->name_map_[&view][name] = menu;
2363         return menu;
2364 }
2365
2366 } // namespace frontend
2367 } // namespace lyx
2368
2369 #include "moc_Menus.cpp"