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