]> git.lyx.org Git - features.git/blob - src/frontends/qt4/Menus.cpp
249d742013cb6d2d5fed90bd59e36c5c2c454c4b
[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 #include "insets/InsetQuotes.h"
64
65 #include "support/lassert.h"
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/docstring_list.h"
69 #include "support/filetools.h"
70 #include "support/gettext.h"
71 #include "support/lstrings.h"
72
73 #include <QCursor>
74 #include <QHash>
75 #include <QList>
76 #include <QMenuBar>
77 #include <QString>
78 #if QT_VERSION >= 0x040600
79 #include <QProxyStyle>
80 #endif
81
82 #include <algorithm>
83 #include <memory>
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                 /** This is the list of quotation marks available */
194                 SwitchQuotes
195         };
196
197         explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
198
199         MenuItem(Kind kind,
200                  QString const & label,
201                  QString const & submenu = QString(),
202                  QString const & tooltip = QString(),
203                  bool optional = false)
204                 : kind_(kind), label_(label), func_(make_shared<FuncRequest>()),
205                   submenuname_(submenu), tooltip_(tooltip), optional_(optional)
206         {
207                 LATTEST(kind == Submenu || kind == Help || kind == Info);
208         }
209
210         MenuItem(Kind kind,
211                  QString const & label,
212                  FuncRequest const & func,
213                  QString const & tooltip = QString(),
214                  bool optional = false,
215                  FuncRequest::Origin origin = FuncRequest::MENU)
216                 : kind_(kind), label_(label), func_(make_shared<FuncRequest>(func)),
217                   tooltip_(tooltip), optional_(optional)
218         {
219                 func_->setOrigin(origin);
220         }
221
222         /// The label of a given menuitem
223         QString label() const
224         {
225                 int const index = label_.lastIndexOf('|');
226                 return index == -1 ? label_ : label_.left(index);
227         }
228
229         /// The keyboard shortcut (usually underlined in the entry)
230         QString shortcut() const
231         {
232                 int const index = label_.lastIndexOf('|');
233                 return index == -1 ? QString() : label_.mid(index + 1);
234         }
235         /// The complete label, with label and shortcut separated by a '|'
236         QString fulllabel() const { return label_; }
237         /// The kind of entry
238         Kind kind() const { return kind_; }
239         /// the action (if relevant)
240         shared_ptr<FuncRequest const> func() const { return func_; }
241         /// the tooltip
242         QString const & tooltip() const { return tooltip_; }
243         /// returns true if the entry should be omitted when disabled
244         bool optional() const { return optional_; }
245         /// returns the status of the lfun associated with this entry
246         FuncStatus const & status() const { return status_; }
247         /// returns the status of the lfun associated with this entry
248         FuncStatus & status() { return status_; }
249         /// returns the status of the lfun associated with this entry
250         void status(FuncStatus const & status) { status_ = status; }
251
252         ///returns the binding associated to this action.
253         QString binding() const
254         {
255                 if (kind_ != Command)
256                         return QString();
257                 // Get the keys bound to this action, but keep only the
258                 // first one later
259                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(*func_);
260                 if (!bindings.empty())
261                         return toqstr(bindings.begin()->print(KeySequence::ForGui));
262
263                 LYXERR(Debug::KBMAP, "No binding for "
264                         << lyxaction.getActionName(func_->action())
265                         << '(' << func_->argument() << ')');
266                 return QString();
267         }
268
269         /// the description of the  submenu (if relevant)
270         QString const & submenuname() const { return submenuname_; }
271         /// set the description of the  submenu
272         void submenuname(QString const & name) { submenuname_ = name; }
273         ///
274         bool hasSubmenu() const { return !submenu_.isEmpty(); }
275         ///
276         MenuDefinition const & submenu() const { return submenu_.at(0); }
277         MenuDefinition & submenu() { return submenu_[0]; }
278         ///
279         void setSubmenu(MenuDefinition const & menu)
280         {
281                 submenu_.clear();
282                 submenu_.append(menu);
283         }
284
285 private:
286         ///
287         Kind kind_;
288         ///
289         QString label_;
290         ///
291         shared_ptr<FuncRequest> func_;// non-null
292         ///
293         QString submenuname_;
294         ///
295         QString tooltip_;
296         ///
297         bool optional_;
298         ///
299         FuncStatus status_;
300         /// contains 0 or 1 item.
301         QList<MenuDefinition> submenu_;
302 };
303
304 ///
305 class MenuDefinition {
306 public:
307         ///
308         typedef std::vector<MenuItem> ItemList;
309         ///
310         typedef ItemList::const_iterator const_iterator;
311         ///
312         explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
313
314         ///
315         void read(Lexer &);
316         ///
317         QString const & name() const { return name_; }
318         ///
319         bool empty() const { return items_.empty(); }
320         /// Clear the menu content.
321         void clear() { items_.clear(); }
322         ///
323         size_t size() const { return items_.size(); }
324         ///
325         const_iterator begin() const { return items_.begin(); }
326         ///
327         const_iterator end() const { return items_.end(); }
328         ///
329         void cat(MenuDefinition const & other);
330         ///
331         void catSub(docstring const & name);
332
333         // search for func in this menu iteratively, and put menu
334         // names in a stack.
335         bool searchMenu(FuncRequest const & func, docstring_list & names)
336                 const;
337         ///
338         bool hasFunc(FuncRequest const &) const;
339         /// Add the menu item unconditionally
340         void add(MenuItem const & item) { items_.push_back(item); }
341         /// Checks the associated FuncRequest status before adding the
342         /// menu item.
343         void addWithStatusCheck(MenuItem const &);
344         // Check whether the menu shortcuts are unique
345         void checkShortcuts() const;
346         ///
347         void expandLastfiles();
348         void expandDocuments();
349         void expandBookmarks();
350         void expandFormats(MenuItem::Kind const kind, Buffer const * buf);
351         void expandFloatListInsert(Buffer const * buf);
352         void expandFloatInsert(Buffer const * buf);
353         void expandFlexInsert(Buffer const * buf, InsetLayout::InsetLyXType type);
354         void expandTocSubmenu(std::string const & type, Toc const & toc_list);
355         void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth, string toc_type);
356         void expandToc(Buffer const * buf);
357         void expandPasteRecent(Buffer const * buf);
358         void expandToolbars();
359         void expandBranches(Buffer const * buf);
360         void expandIndices(Buffer const * buf, bool listof = false);
361         void expandIndicesContext(Buffer const * buf, bool listof = false);
362         void expandCiteStyles(BufferView const *);
363         void expandGraphicsGroups(BufferView const *);
364         void expandSpellingSuggestions(BufferView const *);
365         void expandLanguageSelector(Buffer const * buf);
366         void expandArguments(BufferView const *, bool switcharg = false);
367         void expandCaptions(Buffer const * buf, bool switchcap = false);
368         void expandEnvironmentSeparators(BufferView const *);
369         void expandQuotes(BufferView const *);
370         ///
371         ItemList items_;
372         ///
373         QString name_;
374 };
375
376
377 /// Helper for std::find_if
378 class MenuNamesEqual
379 {
380 public:
381         MenuNamesEqual(QString const & name) : name_(name) {}
382         bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
383 private:
384         QString name_;
385 };
386
387
388 ///
389 typedef std::vector<MenuDefinition> MenuList;
390 ///
391 typedef MenuList::const_iterator const_iterator;
392 ///
393 typedef MenuList::iterator iterator;
394
395 /////////////////////////////////////////////////////////////////////
396 // MenuDefinition implementation
397 /////////////////////////////////////////////////////////////////////
398
399 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
400 {
401         switch (i.kind()) {
402
403         case MenuItem::Command: {
404                 FuncStatus status = lyx::getStatus(*i.func());
405                 if (status.unknown() || (!status.enabled() && i.optional()))
406                         break;
407                 items_.push_back(i);
408                 items_.back().status(status);
409                 break;
410         }
411
412         case MenuItem::Submenu: {
413                 bool enabled = false;
414                 if (i.hasSubmenu()) {
415                         for (const_iterator cit = i.submenu().begin();
416                                   cit != i.submenu().end(); ++cit) {
417                                 // Only these kind of items affect the status of the submenu
418                                 if ((cit->kind() == MenuItem::Command
419                                      || cit->kind() == MenuItem::Submenu
420                                      || cit->kind() == MenuItem::Help)
421                                     && cit->status().enabled()) {
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                 md_switchquotes
484         };
485
486         LexerKeyword menutags[] = {
487                 { "arguments", md_arguments },
488                 { "bookmarks", md_bookmarks },
489                 { "branches", md_branches },
490                 { "captions", md_captions },
491                 { "charstyles", md_charstyles },
492                 { "citestyles", md_citestyles },
493                 { "custom", md_custom },
494                 { "documents", md_documents },
495                 { "elements", md_elements },
496                 { "end", md_endmenu },
497                 { "environmentseparators", md_env_separators },
498                 { "exportformats", md_exportformats },
499                 { "floatinsert", md_floatinsert },
500                 { "floatlistinsert", md_floatlistinsert },
501                 { "graphicsgroups", md_graphicsgroups },
502                 { "importformats", md_importformats },
503                 { "indices", md_indices },
504                 { "indicescontext", md_indicescontext },
505                 { "indiceslists", md_indiceslists },
506                 { "indiceslistscontext", md_indiceslistscontext },
507                 { "item", md_item },
508                 { "languageselector", md_languageselector },
509                 { "lastfiles", md_lastfiles },
510                 { "optitem", md_optitem },
511                 { "optsubmenu", md_optsubmenu },
512                 { "pasterecent", md_pasterecent },
513                 { "separator", md_separator },
514                 { "spellingsuggestions", md_spellingsuggestions },
515                 { "submenu", md_submenu },
516                 { "switcharguments", md_switcharguments },
517                 { "switchcaptions", md_switchcaptions },
518                 { "switchquotes", md_switchquotes },
519                 { "toc", md_toc },
520                 { "toolbars", md_toolbars },
521                 { "updateformats", md_updateformats },
522                 { "viewformats", md_viewformats }
523         };
524
525         lex.pushTable(menutags);
526         lex.setContext("MenuDefinition::read: ");
527
528         int md_type = 0;
529         while (lex.isOK() && md_type != md_endmenu) {
530                 switch (md_type = lex.lex()) {
531                 case md_optitem:
532                 case md_item: {
533                         lex.next(true);
534                         docstring const name = translateIfPossible(lex.getDocString());
535                         lex.next(true);
536                         string const command = lex.getString();
537                         FuncRequest func = lyxaction.lookupFunc(command);
538                         FuncRequest::Origin origin = FuncRequest::MENU;
539                         if (name_.startsWith("context-toc-"))
540                                 origin = FuncRequest::TOC;
541                         bool const optional = (md_type == md_optitem);
542                         add(MenuItem(MenuItem::Command, toqstr(name), func, QString(), optional, origin));
543                         break;
544                 }
545
546                 case md_separator:
547                         add(MenuItem(MenuItem::Separator));
548                         break;
549
550                 case md_lastfiles:
551                         add(MenuItem(MenuItem::Lastfiles));
552                         break;
553
554                 case md_charstyles:
555                         add(MenuItem(MenuItem::CharStyles));
556                         break;
557
558                 case md_custom:
559                         add(MenuItem(MenuItem::Custom));
560                         break;
561
562                 case md_elements:
563                         add(MenuItem(MenuItem::Elements));
564                         break;
565
566                 case md_documents:
567                         add(MenuItem(MenuItem::Documents));
568                         break;
569
570                 case md_bookmarks:
571                         add(MenuItem(MenuItem::Bookmarks));
572                         break;
573
574                 case md_toc:
575                         add(MenuItem(MenuItem::Toc));
576                         break;
577
578                 case md_viewformats:
579                         add(MenuItem(MenuItem::ViewFormats));
580                         break;
581
582                 case md_updateformats:
583                         add(MenuItem(MenuItem::UpdateFormats));
584                         break;
585
586                 case md_exportformats:
587                         add(MenuItem(MenuItem::ExportFormats));
588                         break;
589
590                 case md_importformats:
591                         add(MenuItem(MenuItem::ImportFormats));
592                         break;
593
594                 case md_floatlistinsert:
595                         add(MenuItem(MenuItem::FloatListInsert));
596                         break;
597
598                 case md_floatinsert:
599                         add(MenuItem(MenuItem::FloatInsert));
600                         break;
601
602                 case md_pasterecent:
603                         add(MenuItem(MenuItem::PasteRecent));
604                         break;
605
606                 case md_toolbars:
607                         add(MenuItem(MenuItem::Toolbars));
608                         break;
609
610                 case md_branches:
611                         add(MenuItem(MenuItem::Branches));
612                         break;
613
614                 case md_citestyles:
615                         add(MenuItem(MenuItem::CiteStyles));
616                         break;
617
618                 case md_graphicsgroups:
619                         add(MenuItem(MenuItem::GraphicsGroups));
620                         break;
621
622                 case md_spellingsuggestions:
623                         add(MenuItem(MenuItem::SpellingSuggestions));
624                         break;
625
626                 case md_languageselector:
627                         add(MenuItem(MenuItem::LanguageSelector));
628                         break;
629
630                 case md_indices:
631                         add(MenuItem(MenuItem::Indices));
632                         break;
633
634                 case md_indicescontext:
635                         add(MenuItem(MenuItem::IndicesContext));
636                         break;
637
638                 case md_indiceslists:
639                         add(MenuItem(MenuItem::IndicesLists));
640                         break;
641
642                 case md_indiceslistscontext:
643                         add(MenuItem(MenuItem::IndicesListsContext));
644                         break;
645
646                 case md_arguments:
647                         add(MenuItem(MenuItem::Arguments));
648                         break;
649
650                 case md_switcharguments:
651                         add(MenuItem(MenuItem::SwitchArguments));
652                         break;
653
654                 case md_captions:
655                         add(MenuItem(MenuItem::Captions));
656                         break;
657
658                 case md_switchcaptions:
659                         add(MenuItem(MenuItem::SwitchCaptions));
660                         break;
661
662                 case md_env_separators:
663                         add(MenuItem(MenuItem::EnvironmentSeparators));
664                         break;
665
666                 case md_switchquotes:
667                         add(MenuItem(MenuItem::SwitchQuotes));
668                         break;
669
670                 case md_optsubmenu:
671                 case md_submenu: {
672                         lex.next(true);
673                         docstring const mlabel = translateIfPossible(lex.getDocString());
674                         lex.next(true);
675                         docstring const mname = lex.getDocString();
676                         bool const optional = (md_type == md_optsubmenu);
677                         add(MenuItem(MenuItem::Submenu,
678                                 toqstr(mlabel), toqstr(mname), QString(), optional));
679                         break;
680                 }
681
682                 case md_endmenu:
683                         break;
684
685                 default:
686                         lex.printError("Unknown menu tag");
687                         break;
688                 }
689         }
690         lex.popTable();
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         FormatList formats;
1041         FuncCode action = LFUN_NOACTION;
1042
1043         switch (kind) {
1044         case MenuItem::ImportFormats:
1045                 formats = theConverters().importableFormats();
1046                 action = LFUN_BUFFER_IMPORT;
1047                 break;
1048         case MenuItem::ViewFormats:
1049                 formats = buf->params().exportableFormats(true);
1050                 action = LFUN_BUFFER_VIEW;
1051                 break;
1052         case MenuItem::UpdateFormats:
1053                 formats = buf->params().exportableFormats(true);
1054                 action = LFUN_BUFFER_UPDATE;
1055                 break;
1056         case MenuItem::ExportFormats:
1057                 formats = buf->params().exportableFormats(false);
1058                 action = LFUN_BUFFER_EXPORT;
1059                 break;
1060         default:
1061                 LATTEST(false);
1062                 return;
1063         }
1064
1065         bool const view_update = (kind == MenuItem::ViewFormats
1066                         || kind == MenuItem::UpdateFormats);
1067
1068         QString smenue;
1069         if (view_update)
1070                 smenue = (kind == MenuItem::ViewFormats
1071                         ? qt_("View (Other Formats)|F")
1072                         : qt_("Update (Other Formats)|p"));
1073         MenuItem item(MenuItem::Submenu, smenue);
1074         item.setSubmenu(MenuDefinition(smenue));
1075
1076         for (Format const * f : formats) {
1077                 if (f->dummy())
1078                         continue;
1079
1080                 docstring lab = f->prettyname();
1081                 docstring const scut = from_utf8(f->shortcut());
1082                 docstring const tmplab = lab;
1083
1084                 if (!scut.empty())
1085                         lab += char_type('|') + scut;
1086                 docstring const lab_i18n = translateIfPossible(lab);
1087                 docstring const shortcut = split(lab_i18n, lab, '|');
1088
1089                 bool const untranslated = (lab == lab_i18n);
1090                 docstring label = untranslated ? translateIfPossible(tmplab) : lab;
1091
1092                 switch (kind) {
1093                 case MenuItem::ImportFormats:
1094                         label += from_ascii("...");
1095                         break;
1096                 case MenuItem::ViewFormats:
1097                 case MenuItem::UpdateFormats:
1098                         if (f->name() == buf->params().getDefaultOutputFormat()) {
1099                                 docstring lbl = (kind == MenuItem::ViewFormats
1100                                         ? bformat(_("View [%1$s]|V"), label)
1101                                         : bformat(_("Update [%1$s]|U"), label));
1102                                 add(MenuItem(MenuItem::Command, toqstr(lbl), FuncRequest(action)));
1103                                 continue;
1104                         }
1105                 // fall through
1106                 case MenuItem::ExportFormats:
1107                         if (!f->inExportMenu())
1108                                 continue;
1109                         break;
1110                 default:
1111                         // we already asserted earlier in this case
1112                         // LATTEST(false);
1113                         continue;
1114                 }
1115                 if (!shortcut.empty())
1116                         label += '|' + shortcut;
1117
1118                 if (view_update) {
1119                         // note that at this point, we know that buf is not null
1120                         LATTEST(buf);
1121                         item.submenu().addWithStatusCheck(MenuItem(MenuItem::Command,
1122                                 toqstr(label), FuncRequest(action, f->name())));
1123                 } else {
1124                         if (buf)
1125                                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1126                                         FuncRequest(action, f->name())));
1127                         else
1128                                 add(MenuItem(MenuItem::Command, toqstr(label),
1129                                         FuncRequest(action, f->name())));
1130                 }
1131         }
1132         if (view_update)
1133                 add(item);
1134 }
1135
1136
1137 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
1138 {
1139         if (!buf)
1140                 return;
1141
1142         FloatList const & floats = buf->params().documentClass().floats();
1143         FloatList::const_iterator cit = floats.begin();
1144         FloatList::const_iterator end = floats.end();
1145         set<string> seen;
1146         for (; cit != end; ++cit) {
1147                 if (!cit->second.usesFloatPkg()) {
1148                         // Different floats could declare the same ListCommand. We only
1149                         // want it on the list once, though.
1150                         string const & list_cmd = cit->second.listCommand();
1151                         if (list_cmd.empty())
1152                                 // we do not know how to generate such a list
1153                                 continue;
1154                         // This form of insert returns an iterator pointing to the newly
1155                         // inserted element OR the existing element with that value, and
1156                         // a bool indicating whether we inserted a new element. So we can
1157                         // see if one is there and insert it if not all at once.
1158                         pair<set<string>::iterator, bool> ret = seen.insert(list_cmd);
1159                         if (!ret.second)
1160                                 continue;
1161                 }
1162                 string const & list_name = cit->second.listName();
1163                 addWithStatusCheck(MenuItem(MenuItem::Command, qt_(list_name),
1164                         FuncRequest(LFUN_FLOAT_LIST_INSERT, cit->second.floattype())));
1165         }
1166 }
1167
1168
1169 void MenuDefinition::expandFloatInsert(Buffer const * buf)
1170 {
1171         if (!buf)
1172                 return;
1173
1174         FloatList const & floats = buf->params().documentClass().floats();
1175         FloatList::const_iterator cit = floats.begin();
1176         FloatList::const_iterator end = floats.end();
1177         for (; cit != end; ++cit) {
1178                 // normal float
1179                 QString const label = qt_(cit->second.name());
1180                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
1181                                     FuncRequest(LFUN_FLOAT_INSERT,
1182                                                 cit->second.floattype())));
1183         }
1184 }
1185
1186
1187 void MenuDefinition::expandFlexInsert(
1188                 Buffer const * buf, InsetLayout::InsetLyXType type)
1189 {
1190         if (!buf)
1191                 return;
1192
1193         TextClass::InsetLayouts const & insetLayouts =
1194                 buf->params().documentClass().insetLayouts();
1195         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
1196         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
1197         for (; cit != end; ++cit) {
1198                 if (cit->second.lyxtype() == type) {
1199                         if (!cit->second.obsoleted_by().empty())
1200                                 continue;
1201                         docstring label = cit->first;
1202                         // we remove the "Flex:" prefix, if it is present
1203                         if (prefixIs(label, from_ascii("Flex:")))
1204                                 label = label.substr(5);
1205                         addWithStatusCheck(MenuItem(MenuItem::Command,
1206                                 toqstr(translateIfPossible(label)),
1207                                 FuncRequest(LFUN_FLEX_INSERT, Lexer::quoteString(label))));
1208                 }
1209         }
1210         // FIXME This is a little clunky.
1211         if (items_.empty() && type == InsetLayout::CUSTOM && !buf->isReadonly())
1212                 add(MenuItem(MenuItem::Help, qt_("No Custom Insets Defined!")));
1213 }
1214
1215
1216 // Threshold before we stop displaying sub-items alongside items
1217 // (for display purposes). Ideally this should fit on a screen.
1218 size_t const max_number_of_items = 30;
1219 // Size limit for the menu. This is for performance purposes,
1220 // because qt already displays a scrollable menu when necessary.
1221 // Ideally this should be the menu size from which scrollable
1222 // menus become unpractical.
1223 size_t const menu_size_limit = 80;
1224
1225 void MenuDefinition::expandToc2(Toc const & toc_list,
1226                                 size_t from, size_t to, int depth,
1227                                 string toc_type)
1228 {
1229         int shortcut_count = 0;
1230
1231         // check whether depth is smaller than the smallest depth in toc.
1232         int min_depth = 1000;
1233         for (size_t i = from; i < to; ++i)
1234                 min_depth = min(min_depth, toc_list[i].depth());
1235         if (min_depth > depth)
1236                 depth = min_depth;
1237
1238         if (to - from <= max_number_of_items) {
1239                 for (size_t i = from; i < to; ++i) {
1240                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
1241                         label += limitStringLength(toc_list[i].asString());
1242                         if (toc_list[i].depth() == depth) {
1243                                 label += '|';
1244                             if (shortcut_count < 9) {
1245                                         if (label.contains(QString::number(shortcut_count + 1)))
1246                                                 label += QString::number(++shortcut_count);
1247                                 }
1248                         }
1249                         add(MenuItem(MenuItem::Command, label,
1250                                             FuncRequest(toc_list[i].action())));
1251                         // separator after the menu heading
1252                         if (toc_list[i].depth() < depth)
1253                                 add(MenuItem(MenuItem::Separator));
1254                 }
1255         } else {
1256                 size_t pos = from;
1257                 size_t size = 1;
1258                 while (pos < to) {
1259                         size_t new_pos = pos + 1;
1260                         while (new_pos < to && toc_list[new_pos].depth() > depth)
1261                                 ++new_pos;
1262
1263                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
1264                         label += limitStringLength(toc_list[pos].asString());
1265                         if (toc_list[pos].depth() == depth) {
1266                                 label += '|';
1267                             if (shortcut_count < 9) {
1268                                         if (label.contains(QString::number(shortcut_count + 1)))
1269                                                 label += QString::number(++shortcut_count);
1270                                 }
1271                         }
1272                         if (size >= menu_size_limit) {
1273                                 FuncRequest f(LFUN_DIALOG_SHOW, "toc " + toc_type);
1274                                 add(MenuItem(MenuItem::Command, "...", f));
1275                                 break;
1276                         }
1277                         if (new_pos == pos + 1) {
1278                                 add(MenuItem(MenuItem::Command,
1279                                                     label, FuncRequest(toc_list[pos].action())));
1280                         } else {
1281                                 MenuDefinition sub;
1282                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1, toc_type);
1283                                 MenuItem item(MenuItem::Submenu, label);
1284                                 item.setSubmenu(sub);
1285                                 add(item);
1286                         }
1287                         ++size;
1288                         pos = new_pos;
1289                 }
1290         }
1291 }
1292
1293
1294 void MenuDefinition::expandToc(Buffer const * buf)
1295 {
1296         // To make things very cleanly, we would have to pass buf to
1297         // all MenuItem constructors and to expandToc2. However, we
1298         // know that all the entries in a TOC will be have status_ ==
1299         // OK, so we avoid this unnecessary overhead (JMarc)
1300         if (!buf) {
1301                 add(MenuItem(MenuItem::Info, qt_("(No Document Open)")));
1302                 return;
1303         }
1304         // Add an entry for the master doc if this is a child doc
1305         Buffer const * const master = buf->masterBuffer();
1306         if (buf != master) {
1307                 ParIterator const pit = par_iterator_begin(master->inset());
1308                 string const arg = convert<string>(pit->id());
1309                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
1310                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
1311         }
1312
1313         MenuDefinition other_lists;
1314         TocList const & toc_list = buf->tocBackend().tocs();
1315         TocList::const_iterator cit = toc_list.begin();
1316         TocList::const_iterator end = toc_list.end();
1317         for (; cit != end; ++cit) {
1318                 // Handle table of contents later
1319                 if (cit->first == "tableofcontents" || cit->second->empty())
1320                         continue;
1321                 MenuDefinition submenu;
1322                 submenu.expandTocSubmenu(cit->first, *cit->second);
1323                 docstring const toc_name = buf->tocBackend().outlinerName(cit->first);
1324                 MenuItem item(MenuItem::Submenu, toqstr(toc_name));
1325                 item.setSubmenu(submenu);
1326                 // deserves to be in the main menu?
1327                 if (!TocBackend::isOther(cit->first))
1328                         add(item);
1329                 else
1330                         other_lists.add(item);
1331         }
1332         if (!other_lists.empty()) {
1333                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
1334                 item.setSubmenu(other_lists);
1335                 add(item);
1336         }
1337         // Handle normal TOC
1338         add(MenuItem(MenuItem::Separator));
1339         cit = toc_list.find("tableofcontents");
1340         if (cit == end)
1341                 LYXERR(Debug::GUI, "No table of contents.");
1342         else {
1343                 if (!cit->second->empty())
1344                         expandToc2(*cit->second, 0, cit->second->size(), 0,
1345                                    "tableofcontents");
1346                 else
1347                         add(MenuItem(MenuItem::Info, qt_("(Empty Table of Contents)")));
1348         }
1349 }
1350
1351
1352 void MenuDefinition::expandTocSubmenu(std::string const & type, Toc const & toc)
1353 {
1354         // "Open outliner..." entry
1355         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + type);
1356         add(MenuItem(MenuItem::Command, qt_("Open Outliner..."), f));
1357         add(MenuItem(MenuItem::Separator));
1358         // add entries
1359         expandToc2(toc, 0, toc.size(), 0, type);
1360 }
1361
1362
1363 void MenuDefinition::expandPasteRecent(Buffer const * buf)
1364 {
1365         docstring_list const sel = cap::availableSelections(buf);
1366
1367         docstring_list::const_iterator cit = sel.begin();
1368         docstring_list::const_iterator end = sel.end();
1369
1370         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1371                 add(MenuItem(MenuItem::Command, toqstr(*cit) + '|',
1372                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1373         }
1374 }
1375
1376
1377 void MenuDefinition::expandToolbars()
1378 {
1379         MenuDefinition other_lists;
1380         // extracts the toolbars from the backend
1381         Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1382         Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1383         for (; cit != end; ++cit) {
1384                 MenuItem const item(MenuItem::Command, toqstr(cit->gui_name),
1385                                 FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name));
1386                 if (guiApp->toolbars().isMainToolbar(cit->name))
1387                         add(item);
1388                 else
1389                         other_lists.add(item);
1390         }
1391
1392         if (!other_lists.empty()) {
1393                 MenuItem item(MenuItem::Submenu, qt_("Other Toolbars"));
1394                 item.setSubmenu(other_lists);
1395                 add(item);
1396         }
1397 }
1398
1399
1400 void MenuDefinition::expandBranches(Buffer const * buf)
1401 {
1402         if (!buf || buf->isReadonly())
1403                 return;
1404
1405         BufferParams const & master_params = buf->masterBuffer()->params();
1406         BufferParams const & params = buf->params();
1407         if (params.branchlist().empty() && master_params.branchlist().empty() ) {
1408                 add(MenuItem(MenuItem::Help, qt_("No Branches Set for Document!")));
1409                 return;
1410         }
1411
1412         BranchList::const_iterator cit = master_params.branchlist().begin();
1413         BranchList::const_iterator end = master_params.branchlist().end();
1414
1415         for (int ii = 1; cit != end; ++cit, ++ii) {
1416                 docstring label = cit->branch();
1417                 if (ii < 10) {
1418                         label = convert<docstring>(ii) + ". " + label
1419                                 + char_type('|') + convert<docstring>(ii);
1420                 }
1421                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1422                                     FuncRequest(LFUN_BRANCH_INSERT,
1423                                                 cit->branch())));
1424         }
1425
1426         if (buf == buf->masterBuffer())
1427                 return;
1428
1429         MenuDefinition child_branches;
1430
1431         BranchList::const_iterator ccit = params.branchlist().begin();
1432         BranchList::const_iterator cend = params.branchlist().end();
1433
1434         for (int ii = 1; ccit != cend; ++ccit, ++ii) {
1435                 docstring label = ccit->branch();
1436                 if (ii < 10) {
1437                         label = convert<docstring>(ii) + ". " + label
1438                                 + char_type('|') + convert<docstring>(ii);
1439                 } else
1440                         label += char_type('|');
1441                 child_branches.addWithStatusCheck(MenuItem(MenuItem::Command,
1442                                     toqstr(label),
1443                                     FuncRequest(LFUN_BRANCH_INSERT,
1444                                                 ccit->branch())));
1445         }
1446
1447         if (!child_branches.empty()) {
1448                 MenuItem item(MenuItem::Submenu, qt_("Child Document"));
1449                 item.setSubmenu(child_branches);
1450                 add(item);
1451         }
1452 }
1453
1454
1455 void MenuDefinition::expandIndices(Buffer const * buf, bool listof)
1456 {
1457         if (!buf)
1458                 return;
1459
1460         BufferParams const & params = buf->masterBuffer()->params();
1461         if (!params.use_indices) {
1462                 if (listof)
1463                         addWithStatusCheck(MenuItem(MenuItem::Command,
1464                                            qt_("Index List|I"),
1465                                            FuncRequest(LFUN_INDEX_PRINT,
1466                                                   from_ascii("idx"))));
1467                 else
1468                         addWithStatusCheck(MenuItem(MenuItem::Command,
1469                                            qt_("Index Entry|d"),
1470                                            FuncRequest(LFUN_INDEX_INSERT,
1471                                                   from_ascii("idx"))));
1472                 return;
1473         }
1474
1475         if (params.indiceslist().empty())
1476                 return;
1477
1478         IndicesList::const_iterator cit = params.indiceslist().begin();
1479         IndicesList::const_iterator end = params.indiceslist().end();
1480
1481         for (int ii = 1; cit != end; ++cit, ++ii) {
1482                 if (listof) {
1483                         docstring const label =
1484                                 bformat(_("Index: %1$s"), cit->index());
1485                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1486                                            FuncRequest(LFUN_INDEX_PRINT, cit->shortcut())));
1487                 } else {
1488                         docstring const label =
1489                                 bformat(_("Index Entry (%1$s)"), cit->index());
1490                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1491                                            FuncRequest(LFUN_INDEX_INSERT, cit->shortcut())));
1492                 }
1493         }
1494 }
1495
1496
1497 void MenuDefinition::expandIndicesContext(Buffer const * buf, bool listof)
1498 {
1499         if (!buf)
1500                 return;
1501
1502         BufferParams const & params = buf->masterBuffer()->params();
1503         if (!params.use_indices || params.indiceslist().empty())
1504                 return;
1505
1506         IndicesList::const_iterator cit = params.indiceslist().begin();
1507         IndicesList::const_iterator end = params.indiceslist().end();
1508
1509         for (int ii = 1; cit != end; ++cit, ++ii) {
1510                 if (listof) {
1511                         InsetCommandParams p(INDEX_PRINT_CODE);
1512                         p["type"] = cit->shortcut();
1513                         string const data = InsetCommand::params2string(p);
1514                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(cit->index()),
1515                                            FuncRequest(LFUN_INSET_MODIFY, data)));
1516                 } else {
1517                         docstring const label =
1518                                         bformat(_("Index Entry (%1$s)"), cit->index());
1519                         addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1520                                            FuncRequest(LFUN_INSET_MODIFY,
1521                                                   from_ascii("changetype ") + cit->shortcut())));
1522                 }
1523         }
1524 }
1525
1526
1527 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1528 {
1529         if (!bv)
1530                 return;
1531
1532         Inset const * inset = bv->cursor().nextInset();
1533         if (!inset || inset->lyxCode() != CITE_CODE) {
1534                 add(MenuItem(MenuItem::Command,
1535                                     qt_("No Citation in Scope!"),
1536                                     FuncRequest(LFUN_NOACTION)));
1537                 return;
1538         }
1539         InsetCitation const * citinset =
1540                                 static_cast<InsetCitation const *>(inset);
1541
1542         Buffer const * buf = &bv->buffer();
1543         BufferParams const & bp = buf->params();
1544         string const cmd = citinset->params().getCmdName();
1545
1546         docstring const & key = citinset->getParam("key");
1547         if (key.empty()) {
1548                 add(MenuItem(MenuItem::Command,
1549                                     qt_("No citations selected!"),
1550                                     FuncRequest(LFUN_NOACTION)));
1551                 return;
1552         }
1553
1554         size_t const n = cmd.size();
1555         bool const force = isUpperCase(cmd[0]);
1556         bool const star = cmd[n] == '*';
1557
1558         vector<docstring> const keys = getVectorFromString(key);
1559
1560         vector<CitationStyle> const citeStyleList = buf->params().citeStyles();
1561         CiteItem ci;
1562         ci.textBefore = citinset->getParam("before");
1563         ci.textAfter = citinset->getParam("after");
1564         ci.forceUpperCase = force;
1565         ci.Starred = star;
1566         ci.context = CiteItem::Dialog;
1567         ci.max_size = 40;
1568         vector<docstring> citeStrings =
1569                 buf->masterBibInfo().getCiteStrings(keys, citeStyleList, bv->buffer(), ci);
1570
1571         vector<docstring>::const_iterator cit = citeStrings.begin();
1572         vector<docstring>::const_iterator end = citeStrings.end();
1573
1574         for (int ii = 1; cit != end; ++cit, ++ii) {
1575                 docstring label = *cit;
1576                 CitationStyle cs = citeStyleList[ii - 1];
1577                 cs.forceUpperCase &= force;
1578                 cs.hasStarredVersion &= star;
1579                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1580                                     FuncRequest(LFUN_INSET_MODIFY,
1581                                                 "changetype " + from_utf8(citationStyleToString(cs)))));
1582         }
1583
1584         // Extra features of the citation styles
1585         CitationStyle cs = citinset->getCitationStyle(bp, cmd, citeStyleList);
1586
1587         if (cs.hasStarredVersion) {
1588                 docstring starred = _("All authors|h");
1589                 // Check if we have a custom string/tooltip for the starred version
1590                 if (!cs.stardesc.empty()) {
1591                         string val =
1592                                 bp.documentClass().getCiteMacro(buf->params().citeEngineType(), cs.stardesc);
1593                         if (!val.empty())
1594                                 starred = translateIfPossible(from_utf8(val));
1595                         // Transform qt-style accelerators to menu-style
1596                         int const amps = count_char(starred, '&');
1597                         if (amps > 0) {
1598                                 if (amps > 1)
1599                                         starred = subst(starred, from_ascii("&&"), from_ascii("<:amp:>"));
1600                                 size_t n = starred.find('&');
1601                                 char_type accel = char_type();
1602                                 if (n != docstring::npos && n < starred.size() - 1)
1603                                         accel = starred[n + 1];
1604                                 starred = subst(starred, from_ascii("&"), from_ascii(""));
1605                                 if (amps > 1)
1606                                         starred = subst(starred, from_ascii("<:amp:>"), from_ascii("&&"));
1607                                 if (accel != char_type())
1608                                         starred = starred + '|' + accel;
1609                         }
1610                 }
1611                 add(MenuItem(MenuItem::Separator));
1612                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(starred),
1613                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam star")));
1614         }
1615
1616         if (cs.forceUpperCase) {
1617                 if (!cs.hasStarredVersion)
1618                         add(MenuItem(MenuItem::Separator));
1619                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(_("Force upper case|u")),
1620                                     FuncRequest(LFUN_INSET_MODIFY, "toggleparam casing")));
1621         }
1622 }
1623
1624
1625 void MenuDefinition::expandArguments(BufferView const * bv, bool switcharg)
1626 {
1627         if (!bv)
1628                 return;
1629
1630         if (!bv->cursor().inTexted())
1631                 return;
1632
1633         Inset const * inset = &bv->cursor().inset();
1634         Layout::LaTeXArgMap args = bv->cursor().paragraph().layout().args();
1635         if (inset && args.empty())
1636                 args = inset->getLayout().args();
1637         if (args.empty() || (switcharg && args.size() == 1))
1638                 return;
1639         Layout::LaTeXArgMap::const_iterator lait = args.begin();
1640         Layout::LaTeXArgMap::const_iterator const laend = args.end();
1641         for (; lait != laend; ++lait) {
1642                 Layout::latexarg arg = (*lait).second;
1643                 docstring str = arg.menustring.empty()? arg.labelstring : arg.menustring;
1644                 QString item = toqstr(translateIfPossible(str));
1645                 if (switcharg)
1646                         add(MenuItem(MenuItem::Command, item,
1647                                      FuncRequest(LFUN_INSET_MODIFY,
1648                                                  from_ascii("changetype ")
1649                                                  + from_ascii((*lait).first))));
1650                 else
1651                         add(MenuItem(MenuItem::Command, item,
1652                                      FuncRequest(LFUN_ARGUMENT_INSERT,
1653                                                  from_ascii((*lait).first))));
1654         }
1655 }
1656
1657
1658 void MenuDefinition::expandCaptions(Buffer const * buf, bool switchcap)
1659 {
1660         if (!buf)
1661                 return;
1662
1663         DocumentClass const & dc = buf->params().documentClass();
1664         vector< pair<docstring, FuncRequest> > caps;
1665         for (pair<docstring, InsetLayout> const & il : dc.insetLayouts()) {
1666                 docstring instype;
1667                 docstring const type = split(il.first, instype, ':');
1668                 if (instype == "Caption") {
1669                         // skip forbidden caption types
1670                         FuncRequest const cmd = switchcap
1671                                 ? FuncRequest(LFUN_INSET_MODIFY, from_ascii("changetype ") + type)
1672                                 : FuncRequest(LFUN_CAPTION_INSERT, type);
1673                         if (getStatus(cmd).enabled())
1674                                 caps.push_back(make_pair(type, cmd));
1675                 }
1676         }
1677
1678         if (caps.empty() || (switchcap && caps.size() == 1))
1679                 return;
1680         if (caps.size() == 1) {
1681                 add(MenuItem(MenuItem::Command, qt_("Caption"), caps.front().second));
1682                 return;
1683         }
1684
1685         MenuDefinition captions;
1686         for (pair<docstring, FuncRequest> const & cap : caps) {
1687                 docstring const type = cap.first;
1688                 docstring const trtype = translateIfPossible(type);
1689                 docstring const cmitem = bformat(_("Caption (%1$s)"), trtype);
1690                 if (switchcap)
1691                         add(MenuItem(MenuItem::Command, toqstr(cmitem), cap.second));
1692                 else
1693                         captions.add(MenuItem(MenuItem::Command, toqstr(trtype), cap.second));
1694         }
1695         if (!captions.empty()) {
1696                 MenuItem item(MenuItem::Submenu, qt_("Caption"));
1697                 item.setSubmenu(captions);
1698                 add(item);
1699         }
1700 }
1701
1702
1703 void MenuDefinition::expandQuotes(BufferView const * bv)
1704 {
1705         if (!bv)
1706                 return;
1707
1708         if (!bv->cursor().inTexted())
1709                 return;
1710
1711         Inset const * inset = bv->cursor().nextInset();
1712         if (!inset || inset->lyxCode() != QUOTE_CODE) {
1713                 add(MenuItem(MenuItem::Command,
1714                                     qt_("No Quote in Scope!"),
1715                                     FuncRequest(LFUN_NOACTION)));
1716                 return;
1717         }
1718         InsetQuotes const * qinset =
1719                 static_cast<InsetQuotes const *>(inset);
1720
1721         map<string, docstring> styles = quoteparams.getTypes();
1722         string const qtype = qinset->getType();
1723
1724         map<string, docstring>::const_iterator qq = styles.begin();
1725         map<string, docstring>::const_iterator end = styles.end();
1726
1727         MenuDefinition aqs;
1728
1729         BufferParams const & bp = bv->buffer().masterBuffer()->params();
1730
1731         // The global setting
1732         InsetQuotesParams::QuoteStyle globalqs = bp.quotes_style;
1733         char const globalqsc = quoteparams.getStyleChar(globalqs);
1734
1735         // The current language's default
1736         InsetQuotesParams::QuoteStyle langdefqs =
1737                 bp.getQuoteStyle(bv->cursor().current_font.language()->quoteStyle());
1738         char const langqs = quoteparams.getStyleChar(langdefqs);
1739
1740         bool main_global_qs = false;
1741         bool main_langdef_qs = false;
1742         bool main_dynamic_qs = false;
1743         docstring const subcmd = from_ascii("changetype ");
1744         docstring const wildcards = from_ascii("..");
1745         // Add the items
1746         // First the top level menu (all glyphs of the current style) ...
1747         // Begin with dynamic (if they are current style),
1748         if (qtype[0] == 'x') {
1749                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xld"));
1750                 docstring desc = bformat(_("%1$s (dynamic)"),
1751                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ld")));
1752                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1753                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xls"));
1754                 desc = bformat(_("%1$s (dynamic)"),
1755                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("ls")));
1756                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1757                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrd"));
1758                 desc = bformat(_("%1$s (dynamic)"),
1759                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rd")));
1760                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1761                 cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + from_ascii("xrs"));
1762                 desc = bformat(_("%1$s (dynamic)"),
1763                         quoteparams.getShortGuiLabel(globalqsc + from_ascii("rs")));
1764                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1765                 main_dynamic_qs = true;
1766         }
1767         // now traverse through the static styles ...
1768         for (; qq != end; ++qq) {
1769                 docstring const style = from_ascii(qq->first);
1770                 bool langdef = (style[0] == langqs);
1771                 bool globaldef = (style[0] == globalqsc);
1772
1773                 if (prefixIs(style, qtype[0])) {
1774                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style);
1775                         docstring const desc = quoteparams.getShortGuiLabel(style);
1776                         add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1777                         main_global_qs = globaldef;
1778                         main_langdef_qs = langdef;
1779                 }
1780                 else if (!langdef && !globaldef && suffixIs(style, from_ascii("ld"))) {
1781                         docstring const desc =
1782                                 quoteparams.getGuiLabel(quoteparams.getQuoteStyle(to_ascii(style)));
1783                         FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + style[0] + "..");
1784                         aqs.add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1785                 }
1786         }
1787
1788         add(MenuItem(MenuItem::Separator));
1789
1790         bool display_static = false;
1791         // ... then potentially items to reset to the defaults and to dynamic style ...
1792         if (!main_dynamic_qs && globalqsc != 'x') {
1793                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + 'x' + wildcards);
1794                 docstring const desc = bformat(_("Use dynamic quotes (%1$s)|d"),
1795                                                 quoteparams.getGuiLabel(globalqs));
1796                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1797                 display_static = true;
1798         }
1799         if (!main_global_qs && langdefqs != globalqs) {
1800                 docstring const variant = main_dynamic_qs ? _("dynamic[[Quotes]]") : _("static[[Quotes]]");
1801                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1802                 docstring const desc = bformat(_("Reset to document default (%1$s, %2$s)|o"),
1803                                                 quoteparams.getGuiLabel(globalqs), variant);
1804                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1805         }
1806         if (!main_langdef_qs) {
1807                 FuncRequest cmd = FuncRequest(LFUN_INSET_MODIFY, subcmd + globalqsc + wildcards);
1808                 docstring const desc = (main_dynamic_qs || display_static) 
1809                                         ? bformat(_("Reset to language default (%1$s, %2$s)|l"),
1810                                                   quoteparams.getGuiLabel(langdefqs), _("static[[Quotes]]"))
1811                                         : bformat(_("Reset to language default (%1$s)|l"),
1812                                                   quoteparams.getGuiLabel(langdefqs));
1813                 add(MenuItem(MenuItem::Command, toqstr(desc), cmd));
1814         }
1815
1816         add(MenuItem(MenuItem::Separator));
1817
1818         // ... and a subitem with the rest
1819         MenuItem item(MenuItem::Submenu, qt_("Change Style|y"));
1820         item.setSubmenu(aqs);
1821         add(item);
1822 }
1823
1824
1825 void MenuDefinition::expandEnvironmentSeparators(BufferView const * bv)
1826 {
1827         if (!bv)
1828                 return;
1829         Text const * text = bv->cursor().text();
1830         // no paragraphs and no separators exist in math
1831         if (!text)
1832                 return;
1833
1834         pit_type pit = bv->cursor().selBegin().pit();
1835         Paragraph const & par = text->getPar(pit);
1836         docstring const curlayout = par.layout().name();
1837         docstring outerlayout;
1838         depth_type current_depth = par.params().depth();
1839         // check if we have an environment in our nesting hierarchy
1840         Paragraph cpar = par;
1841         while (true) {
1842                 if (pit == 0 || cpar.params().depth() == 0)
1843                         break;
1844                 --pit;
1845                 cpar = text->getPar(pit);
1846                 if (cpar.params().depth() < current_depth
1847                     && cpar.layout().isEnvironment()) {
1848                                 outerlayout = cpar.layout().name();
1849                                 current_depth = cpar.params().depth();
1850                 }
1851         }
1852         if (par.layout().isEnvironment()) {
1853                 docstring const label =
1854                         bformat(_("Start New Environment (%1$s)"),
1855                                 translateIfPossible(curlayout));
1856                 add(MenuItem(MenuItem::Command, toqstr(label),
1857                              FuncRequest(LFUN_ENVIRONMENT_SPLIT)));
1858         }
1859         if (!outerlayout.empty()) {
1860                 docstring const label =
1861                         bformat(_("Start New Parent Environment (%1$s)"),
1862                                 translateIfPossible(outerlayout));
1863                 add(MenuItem(MenuItem::Command, toqstr(label),
1864                              FuncRequest(LFUN_ENVIRONMENT_SPLIT,
1865                                          from_ascii("outer"))));
1866         }
1867 }
1868
1869 } // namespace anon
1870
1871
1872 /////////////////////////////////////////////////////////////////////
1873 // Menu::Impl definition and implementation
1874 /////////////////////////////////////////////////////////////////////
1875
1876 struct Menu::Impl
1877 {
1878         /// populates the menu or one of its submenu
1879         /// This is used as a recursive function
1880         void populate(QMenu * qMenu, MenuDefinition const & menu);
1881
1882         /// Only needed for top level menus.
1883         MenuDefinition * top_level_menu;
1884         /// our owning view
1885         GuiView * view;
1886         /// the name of this menu
1887         QString name;
1888 };
1889
1890
1891
1892 /// Get a MenuDefinition item label from the menu backend
1893 static QString label(MenuItem const & mi)
1894 {
1895         QString label = mi.label();
1896         label.replace("&", "&&");
1897
1898         QString shortcut = mi.shortcut();
1899         if (!shortcut.isEmpty()) {
1900                 int pos = label.indexOf(shortcut);
1901                 if (pos != -1)
1902                         //label.insert(pos, 1, char_type('&'));
1903                         label.replace(pos, 0, "&");
1904         }
1905
1906         QString const binding = mi.binding();
1907         if (!binding.isEmpty())
1908                 label += '\t' + binding;
1909
1910         return label;
1911 }
1912
1913 void Menu::Impl::populate(QMenu * qMenu, MenuDefinition const & menu)
1914 {
1915         LYXERR(Debug::GUI, "populating menu " << menu.name());
1916         if (menu.empty()) {
1917                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1918                 return;
1919         }
1920         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1921         for (MenuItem const & m : menu)
1922                 switch (m.kind()) {
1923                 case MenuItem::Separator:
1924                         qMenu->addSeparator();
1925                         break;
1926                 case MenuItem::Submenu: {
1927                         QMenu * subMenu = qMenu->addMenu(label(m));
1928                         populate(subMenu, m.submenu());
1929                         subMenu->setEnabled(!subMenu->isEmpty());
1930                         break;
1931                 }
1932                 case MenuItem::Command:
1933                 default:
1934                         // FIXME: A previous comment assured that MenuItem::Command was the
1935                         // only possible case in practice, but this is wrong.  It would be
1936                         // good to document which cases are actually treated here.
1937                         qMenu->addAction(new Action(m.func(), QIcon(), label(m),
1938                                                     m.tooltip(), qMenu));
1939                         break;
1940                 }
1941 }
1942
1943 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
1944 class AlwaysMnemonicStyle : public QProxyStyle {
1945 public:
1946         int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1947                 QStyleHintReturn *returnData = 0) const
1948         {
1949                 if (hint == QStyle::SH_UnderlineShortcut)
1950                         return 1;
1951                 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1952         }
1953 };
1954 #endif
1955
1956 /////////////////////////////////////////////////////////////////////
1957 // Menu implementation
1958 /////////////////////////////////////////////////////////////////////
1959
1960 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1961 : QMenu(gv), d(new Menu::Impl)
1962 {
1963 #if (defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && (QT_VERSION >= 0x040600)
1964         if (keyboard)
1965                 setStyle(new AlwaysMnemonicStyle);
1966 #else
1967         (void) keyboard;
1968 #endif
1969         d->top_level_menu = top_level? new MenuDefinition : 0;
1970         d->view = gv;
1971         d->name = name;
1972         setTitle(name);
1973         if (d->top_level_menu)
1974                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1975 }
1976
1977
1978 Menu::~Menu()
1979 {
1980         delete d->top_level_menu;
1981         delete d;
1982 }
1983
1984
1985 void Menu::updateView()
1986 {
1987         guiApp->menus().updateMenu(this);
1988 }
1989
1990
1991 void Menu::clear()
1992 {
1993         QList<QAction *> items = actions();
1994         for (int i = 0; i != items.size(); ++i) {
1995                 // QAction::menu() returns 0 if there's no submenu.
1996                 delete items.at(i)->menu();
1997         }
1998         QMenu::clear();
1999 }
2000
2001
2002 /////////////////////////////////////////////////////////////////////
2003 // Menus::Impl definition and implementation
2004 /////////////////////////////////////////////////////////////////////
2005
2006 struct Menus::Impl {
2007         ///
2008         bool hasMenu(QString const &) const;
2009         ///
2010         MenuDefinition & getMenu(QString const &);
2011         ///
2012         MenuDefinition const & getMenu(QString const &) const;
2013
2014         /// Expands some special entries of the menu
2015         /** The entries with the following kind are expanded to a
2016             sequence of Command MenuItems: Lastfiles, Documents,
2017             ViewFormats, ExportFormats, UpdateFormats, Branches,
2018             Indices, Arguments, SwitchArguments, Captions, SwitchCaptions,
2019             EnvironmentSeparators
2020         */
2021         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
2022                 BufferView const *) const;
2023
2024         /// Initialize specific MACOS X menubar
2025         void macxMenuBarInit(QMenuBar * qmb);
2026
2027         /// Mac special menu.
2028         /** This defines a menu whose entries list the FuncRequests
2029             that will be removed by expand() in other menus. This is
2030             used by the Qt/Mac code.
2031
2032             NOTE: Qt does not remove the menu items when clearing a QMenuBar,
2033             such that the items will keep accessing the FuncRequests in
2034             the MenuDefinition. While Menus::Impl might be recreated,
2035             we keep mac_special_menu_ in memory by making it static.
2036         */
2037         static MenuDefinition mac_special_menu_;
2038
2039         ///
2040         MenuList menulist_;
2041         ///
2042         MenuDefinition menubar_;
2043
2044         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
2045
2046         /// name to menu for \c menu() method.
2047         NameMap name_map_;
2048 };
2049
2050
2051 MenuDefinition Menus::Impl::mac_special_menu_;
2052
2053
2054 /*
2055   Here is what the Qt documentation says about how a menubar is chosen:
2056
2057      1) If the window has a QMenuBar then it is used. 2) If the window
2058      is a modal then its menubar is used. If no menubar is specified
2059      then a default menubar is used (as documented below) 3) If the
2060      window has no parent then the default menubar is used (as
2061      documented below).
2062
2063      The above 3 steps are applied all the way up the parent window
2064      chain until one of the above are satisifed. If all else fails a
2065      default menubar will be created, the default menubar on Qt/Mac is
2066      an empty menubar, however you can create a different default
2067      menubar by creating a parentless QMenuBar, the first one created
2068      will thus be designated the default menubar, and will be used
2069      whenever a default menubar is needed.
2070
2071   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
2072   that this menubar will be used also when one of LyX' dialogs has
2073   focus. (JMarc)
2074 */
2075 void Menus::Impl::macxMenuBarInit(QMenuBar * qmb)
2076 {
2077         /* Since Qt 4.2, the qt/mac menu code has special code for
2078            specifying the role of a menu entry. However, it does not
2079            work very well with our scheme of creating menus on demand,
2080            and therefore we need to put these entries in a special
2081            invisible menu. (JMarc)
2082         */
2083
2084         /* The entries of our special mac menu. If we add support for
2085          * special entries in Menus, we could imagine something
2086          * like
2087          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
2088          * and therefore avoid hardcoding. I am not sure it is worth
2089          * the hassle, though. (JMarc)
2090          */
2091         struct MacMenuEntry {
2092                 FuncCode action;
2093                 char const * arg;
2094                 char const * label;
2095                 QAction::MenuRole role;
2096         };
2097
2098         static const MacMenuEntry entries[] = {
2099                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
2100                  QAction::AboutRole},
2101                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
2102                  QAction::PreferencesRole},
2103 #if !(defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2104                 /* This doesn't work with Cocoa. */
2105                 {LFUN_RECONFIGURE, "", "Reconfigure",
2106                  QAction::ApplicationSpecificRole},
2107 #endif
2108                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
2109         };
2110         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
2111         const bool first_call = mac_special_menu_.empty();
2112
2113         LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2114         // the special menu for Menus. Fill it up only once.
2115         if (first_call) {
2116                 for (size_t i = 0 ; i < num_entries ; ++i) {
2117                         FuncRequest const func(entries[i].action,
2118                                 from_utf8(entries[i].arg));
2119                         mac_special_menu_.add(MenuItem(MenuItem::Command,
2120                                 entries[i].label, func));
2121                 }
2122         }
2123
2124         // add the entries to a QMenu that will eventually be empty
2125         // and therefore invisible.
2126         QMenu * qMenu = qmb->addMenu("special");
2127         size_t i = 0;
2128         for (MenuItem const & m : mac_special_menu_) {
2129                 Action * action = new Action(m.func(), QIcon(), m.label(),
2130                                              QString(), qMenu);
2131                 action->setMenuRole(entries[i].role);
2132                 qMenu->addAction(action);
2133                 ++i;
2134         }
2135 }
2136
2137
2138 void Menus::Impl::expand(MenuDefinition const & frommenu,
2139         MenuDefinition & tomenu, BufferView const * bv) const
2140 {
2141         if (!tomenu.empty())
2142                 tomenu.clear();
2143
2144         for (MenuDefinition::const_iterator cit = frommenu.begin();
2145              cit != frommenu.end() ; ++cit) {
2146                 Buffer const * buf = bv ? &bv->buffer() : 0;
2147                 switch (cit->kind()) {
2148                 case MenuItem::Lastfiles:
2149                         tomenu.expandLastfiles();
2150                         break;
2151
2152                 case MenuItem::Documents:
2153                         tomenu.expandDocuments();
2154                         break;
2155
2156                 case MenuItem::Bookmarks:
2157                         tomenu.expandBookmarks();
2158                         break;
2159
2160                 case MenuItem::ImportFormats:
2161                 case MenuItem::ViewFormats:
2162                 case MenuItem::UpdateFormats:
2163                 case MenuItem::ExportFormats:
2164                         tomenu.expandFormats(cit->kind(), buf);
2165                         break;
2166
2167                 case MenuItem::CharStyles:
2168                         tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
2169                         break;
2170
2171                 case MenuItem::Custom:
2172                         tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
2173                         break;
2174
2175                 case MenuItem::Elements:
2176                         tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
2177                         break;
2178
2179                 case MenuItem::FloatListInsert:
2180                         tomenu.expandFloatListInsert(buf);
2181                         break;
2182
2183                 case MenuItem::FloatInsert:
2184                         tomenu.expandFloatInsert(buf);
2185                         break;
2186
2187                 case MenuItem::PasteRecent:
2188                         tomenu.expandPasteRecent(buf);
2189                         break;
2190
2191                 case MenuItem::Toolbars:
2192                         tomenu.expandToolbars();
2193                         break;
2194
2195                 case MenuItem::Branches:
2196                         tomenu.expandBranches(buf);
2197                         break;
2198
2199                 case MenuItem::Indices:
2200                         tomenu.expandIndices(buf);
2201                         break;
2202
2203                 case MenuItem::IndicesContext:
2204                         tomenu.expandIndicesContext(buf);
2205                         break;
2206
2207                 case MenuItem::IndicesLists:
2208                         tomenu.expandIndices(buf, true);
2209                         break;
2210
2211                 case MenuItem::IndicesListsContext:
2212                         tomenu.expandIndicesContext(buf, true);
2213                         break;
2214
2215                 case MenuItem::CiteStyles:
2216                         tomenu.expandCiteStyles(bv);
2217                         break;
2218
2219                 case MenuItem::Toc:
2220                         tomenu.expandToc(buf);
2221                         break;
2222
2223                 case MenuItem::GraphicsGroups:
2224                         tomenu.expandGraphicsGroups(bv);
2225                         break;
2226
2227                 case MenuItem::SpellingSuggestions:
2228                         tomenu.expandSpellingSuggestions(bv);
2229                         break;
2230
2231                 case MenuItem::LanguageSelector:
2232                         tomenu.expandLanguageSelector(buf);
2233                         break;
2234
2235                 case MenuItem::Arguments:
2236                         tomenu.expandArguments(bv, false);
2237                         break;
2238
2239                 case MenuItem::SwitchArguments:
2240                         tomenu.expandArguments(bv, true);
2241                         break;
2242
2243                 case MenuItem::Captions:
2244                         tomenu.expandCaptions(buf, false);
2245                         break;
2246
2247                 case MenuItem::SwitchCaptions:
2248                         tomenu.expandCaptions(buf, true);
2249                         break;
2250
2251                 case MenuItem::EnvironmentSeparators:
2252                         tomenu.expandEnvironmentSeparators(bv);
2253                         break;
2254
2255                 case MenuItem::SwitchQuotes:
2256                         tomenu.expandQuotes(bv);
2257                         break;
2258
2259                 case MenuItem::Submenu: {
2260                         MenuItem item(*cit);
2261                         item.setSubmenu(MenuDefinition(cit->submenuname()));
2262                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
2263                         tomenu.addWithStatusCheck(item);
2264                 }
2265                 break;
2266
2267                 case MenuItem::Info:
2268                 case MenuItem::Help:
2269                 case MenuItem::Separator:
2270                         tomenu.addWithStatusCheck(*cit);
2271                         break;
2272
2273                 case MenuItem::Command:
2274                         if (!mac_special_menu_.hasFunc(*cit->func()))
2275                                 tomenu.addWithStatusCheck(*cit);
2276                 }
2277         }
2278
2279         // we do not want the menu to end with a separator
2280         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
2281                 tomenu.items_.pop_back();
2282
2283         // Check whether the shortcuts are unique
2284         tomenu.checkShortcuts();
2285 }
2286
2287
2288 bool Menus::Impl::hasMenu(QString const & name) const
2289 {
2290         return find_if(menulist_.begin(), menulist_.end(),
2291                 MenuNamesEqual(name)) != menulist_.end();
2292 }
2293
2294
2295 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
2296 {
2297         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
2298                 MenuNamesEqual(name));
2299         if (cit == menulist_.end()) {
2300                 LYXERR0("No submenu named " << name);
2301                 LASSERT(false, { static const MenuDefinition m; return m; });
2302         }
2303         return (*cit);
2304 }
2305
2306
2307 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2308 {
2309         iterator it = find_if(menulist_.begin(), menulist_.end(),
2310                 MenuNamesEqual(name));
2311         if (it == menulist_.end()) {
2312                 LYXERR0("No submenu named " << name);
2313                 LASSERT(false, { static MenuDefinition m; return m; });
2314         }
2315         return (*it);
2316 }
2317
2318
2319 /////////////////////////////////////////////////////////////////////
2320 //
2321 // Menus
2322 //
2323 /////////////////////////////////////////////////////////////////////
2324
2325 Menus::Menus() : d(new Impl) {}
2326
2327
2328 Menus::~Menus()
2329 {
2330         delete d;
2331 }
2332
2333
2334 void Menus::reset()
2335 {
2336         delete d;
2337         d = new Impl;
2338 }
2339
2340
2341 void Menus::read(Lexer & lex)
2342 {
2343         enum {
2344                 md_menu,
2345                 md_menubar,
2346                 md_endmenuset
2347         };
2348
2349         LexerKeyword menutags[] = {
2350                 { "end", md_endmenuset },
2351                 { "menu", md_menu },
2352                 { "menubar", md_menubar }
2353         };
2354
2355         // consistency check
2356         if (compare_ascii_no_case(lex.getString(), "menuset"))
2357                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2358
2359         lex.pushTable(menutags);
2360         lex.setContext("Menus::read");
2361
2362         bool quit = false;
2363
2364         while (lex.isOK() && !quit) {
2365                 switch (lex.lex()) {
2366                 case md_menubar:
2367                         d->menubar_.read(lex);
2368                         break;
2369                 case md_menu: {
2370                         lex.next(true);
2371                         QString const name = toqstr(lex.getDocString());
2372                         if (d->hasMenu(name))
2373                                 d->getMenu(name).read(lex);
2374                         else {
2375                                 MenuDefinition menu(name);
2376                                 menu.read(lex);
2377                                 d->menulist_.push_back(menu);
2378                         }
2379                         break;
2380                 }
2381                 case md_endmenuset:
2382                         quit = true;
2383                         break;
2384                 default:
2385                         lex.printError("Unknown menu tag");
2386                         break;
2387                 }
2388         }
2389         lex.popTable();
2390 }
2391
2392
2393 bool Menus::searchMenu(FuncRequest const & func,
2394         docstring_list & names) const
2395 {
2396         MenuDefinition menu;
2397         d->expand(d->menubar_, menu, 0);
2398         return menu.searchMenu(func, names);
2399 }
2400
2401
2402 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2403 {
2404         if (initial) {
2405 #ifdef Q_OS_MAC
2406                 // setup special mac specific menu items, but only do this
2407                 // the first time a QMenuBar is created. Otherwise Qt will
2408                 // create duplicate items in the application menu. It seems
2409                 // that Qt does not remove them when the QMenubar is cleared.
2410                 d->macxMenuBarInit(qmb);
2411 #endif
2412         } else {
2413                 // Clear all menubar contents before filling it.
2414                 qmb->clear();
2415 #if (QT_VERSION >= 0x050000 && defined(Q_OS_MAC))
2416                 d->macxMenuBarInit(qmb);
2417 #endif
2418         }
2419
2420         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2421
2422         if (d->menubar_.empty()) {
2423                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2424                         << d->menubar_.name());
2425                 return;
2426         }
2427         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2428
2429         MenuDefinition menu;
2430         BufferView * bv = 0;
2431         if (view)
2432                 bv = view->currentBufferView();
2433         d->expand(d->menubar_, menu, bv);
2434
2435         MenuDefinition::const_iterator m = menu.begin();
2436         MenuDefinition::const_iterator end = menu.end();
2437
2438         for (; m != end; ++m) {
2439
2440                 if (m->kind() != MenuItem::Submenu) {
2441                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2442                         continue;
2443                 }
2444
2445                 LYXERR(Debug::GUI, "menu bar item " << m->label()
2446                         << " is a submenu named " << m->submenuname());
2447
2448                 QString name = m->submenuname();
2449                 if (!d->hasMenu(name)) {
2450                         LYXERR(Debug::GUI, "\tERROR: " << name
2451                                 << " submenu has no menu!");
2452                         continue;
2453                 }
2454
2455                 Menu * menu = new Menu(view, m->submenuname(), true);
2456                 menu->setTitle(label(*m));
2457
2458 #if defined(Q_OS_MAC) && (defined(QT_MAC_USE_COCOA) || (QT_VERSION >= 0x050000))
2459                 // On Mac OS with QT/cocoa, the menu is not displayed if there is no action
2460                 // so we create a temporary one here
2461                 QAction * action = new QAction(menu);
2462                 menu->addAction(action);
2463 #endif
2464
2465                 qmb->addMenu(menu);
2466
2467                 d->name_map_[view][name] = menu;
2468         }
2469 }
2470
2471
2472 void Menus::updateMenu(Menu * qmenu)
2473 {
2474         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2475         qmenu->clear();
2476
2477         if (qmenu->d->name.isEmpty())
2478                 return;
2479
2480         docstring identifier = qstring_to_ucs4(qmenu->d->name);
2481         MenuDefinition fromLyxMenu(qmenu->d->name);
2482         while (!identifier.empty()) {
2483                 docstring menu_name;
2484                 identifier = split(identifier, menu_name, ';');
2485
2486                 if (!d->hasMenu(toqstr(menu_name))) {
2487                         LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2488                                 << menu_name);
2489                         continue;
2490                 }
2491
2492                 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2493                 //FIXME: 50 is a wild guess. We should take into account here
2494                 //the expansion of menu items, disabled optional items etc.
2495                 bool const in_sub_menu = !fromLyxMenu.empty()
2496                         && fromLyxMenu.size() + cat_menu.size() > 50 ;
2497                 if (in_sub_menu)
2498                         fromLyxMenu.catSub(menu_name);
2499                 else
2500                         fromLyxMenu.cat(cat_menu);
2501                 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2502         }
2503
2504         if (fromLyxMenu.empty()) {
2505                 qmenu->addAction(qt_("No Action Defined!"));
2506                 return;
2507         }
2508
2509         BufferView * bv = 0;
2510         if (qmenu->d->view)
2511                 bv = qmenu->d->view->currentBufferView();
2512         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2513         qmenu->d->populate(qmenu, *qmenu->d->top_level_menu);
2514 }
2515
2516
2517 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2518 {
2519         LYXERR(Debug::GUI, "Context menu requested: " << name);
2520         Menu * menu = d->name_map_[&view].value(name, 0);
2521         if (!menu && !name.startsWith("context-")) {
2522                 LYXERR0("requested context menu not found: " << name);
2523                 return 0;
2524         }
2525
2526         menu = new Menu(&view, name, true, keyboard);
2527         d->name_map_[&view][name] = menu;
2528         return menu;
2529 }
2530
2531 } // namespace frontend
2532 } // namespace lyx
2533
2534 #include "moc_Menus.cpp"