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