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