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