]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
Set window title correctly at start up
[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             && bv->cursor().paragraph().layout().itemargs().empty())
1560                 args = inset->getLayout().latexargs();
1561         else {
1562                 args = bv->cursor().paragraph().layout().latexargs();
1563                 Layout::LaTeXArgMap itemargs = bv->cursor().paragraph().layout().itemargs();
1564                 if (!itemargs.empty())
1565                         args.insert(itemargs.begin(), itemargs.end());
1566         }
1567         if (args.empty() || (switcharg && args.size() == 1))
1568                 return;
1569         Layout::LaTeXArgMap::const_iterator lait = args.begin();
1570         Layout::LaTeXArgMap::const_iterator const laend = args.end();
1571         for (; lait != laend; ++lait) {
1572                 Layout::latexarg arg = (*lait).second;
1573                 QString item = toqstr(translateIfPossible(arg.labelstring));
1574                 if (switcharg)
1575                         add(MenuItem(MenuItem::Command, item,
1576                                      FuncRequest(LFUN_INSET_MODIFY,
1577                                                  from_ascii("changetype ")
1578                                                  + from_ascii((*lait).first))));
1579                 else
1580                         add(MenuItem(MenuItem::Command, item,
1581                                      FuncRequest(LFUN_ARGUMENT_INSERT,
1582                                                  from_ascii((*lait).first))));
1583         }
1584 }
1585
1586 } // namespace anon
1587
1588
1589 /////////////////////////////////////////////////////////////////////
1590 // Menu::Impl definition and implementation
1591 /////////////////////////////////////////////////////////////////////
1592
1593 struct Menu::Impl
1594 {
1595         /// populates the menu or one of its submenu
1596         /// This is used as a recursive function
1597         void populate(QMenu & qMenu, MenuDefinition const & menu);
1598
1599         /// Only needed for top level menus.
1600         MenuDefinition * top_level_menu;
1601         /// our owning view
1602         GuiView * view;
1603         /// the name of this menu
1604         QString name;
1605 };
1606
1607
1608
1609 /// Get a MenuDefinition item label from the menu backend
1610 static QString label(MenuItem const & mi)
1611 {
1612         QString label = mi.label();
1613         label.replace("&", "&&");
1614
1615         QString shortcut = mi.shortcut();
1616         if (!shortcut.isEmpty()) {
1617                 int pos = label.indexOf(shortcut);
1618                 if (pos != -1)
1619                         //label.insert(pos, 1, char_type('&'));
1620                         label.replace(pos, 0, "&");
1621         }
1622
1623         QString const binding = mi.binding();
1624         if (!binding.isEmpty())
1625                 label += '\t' + binding;
1626
1627         return label;
1628 }
1629
1630 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1631 {
1632         LYXERR(Debug::GUI, "populating menu " << menu.name());
1633         if (menu.empty()) {
1634                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1635                 return;
1636         }
1637         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1638         MenuDefinition::const_iterator m = menu.begin();
1639         MenuDefinition::const_iterator end = menu.end();
1640         for (; m != end; ++m) {
1641                 if (m->kind() == MenuItem::Separator)
1642                         qMenu.addSeparator();
1643                 else if (m->kind() == MenuItem::Submenu) {
1644                         QMenu * subMenu = qMenu.addMenu(label(*m));
1645                         populate(*subMenu, m->submenu());
1646                         subMenu->setEnabled(m->status().enabled());
1647                 } else {
1648                         // we have a MenuItem::Command
1649                         qMenu.addAction(new Action(view, QIcon(), label(*m),
1650                                 m->func(), m->tooltip(), &qMenu));
1651                 }
1652         }
1653 }
1654
1655 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1656 class AlwaysMnemonicStyle : public QProxyStyle {
1657 public:
1658         int styleHint(StyleHint hint, const QStyleOption *opt = 0, const QWidget *widget = 0,
1659                 QStyleHintReturn *returnData = 0) const
1660         {
1661                 if (hint == QStyle::SH_UnderlineShortcut)
1662                         return 1;
1663                 return QProxyStyle::styleHint(hint, opt, widget, returnData);
1664         }
1665 };
1666 #endif
1667
1668 /////////////////////////////////////////////////////////////////////
1669 // Menu implementation
1670 /////////////////////////////////////////////////////////////////////
1671
1672 Menu::Menu(GuiView * gv, QString const & name, bool top_level, bool keyboard)
1673 : QMenu(gv), d(new Menu::Impl)
1674 {
1675 #if defined(Q_WS_WIN) && (QT_VERSION >= 0x040600)
1676         if (keyboard)
1677                 setStyle(new AlwaysMnemonicStyle);
1678 #else
1679         (void) keyboard;
1680 #endif
1681         d->top_level_menu = top_level? new MenuDefinition : 0;
1682         d->view = gv;
1683         d->name = name;
1684         setTitle(name);
1685         if (d->top_level_menu)
1686                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1687 }
1688
1689
1690 Menu::~Menu()
1691 {
1692         delete d->top_level_menu;
1693         delete d;
1694 }
1695
1696
1697 void Menu::updateView()
1698 {
1699         guiApp->menus().updateMenu(this);
1700 }
1701
1702
1703 void Menu::clear()
1704 {
1705         QList<QAction *> items = actions();
1706         for (int i = 0; i != items.size(); ++i) {
1707                 // QAction::menu() returns 0 if there's no submenu.
1708                 delete items.at(i)->menu();
1709         }
1710         QMenu::clear();
1711 }
1712
1713
1714 /////////////////////////////////////////////////////////////////////
1715 // Menus::Impl definition and implementation
1716 /////////////////////////////////////////////////////////////////////
1717
1718 struct Menus::Impl {
1719         ///
1720         bool hasMenu(QString const &) const;
1721         ///
1722         MenuDefinition & getMenu(QString const &);
1723         ///
1724         MenuDefinition const & getMenu(QString const &) const;
1725
1726         /// Expands some special entries of the menu
1727         /** The entries with the following kind are expanded to a
1728             sequence of Command MenuItems: Lastfiles, Documents,
1729             ViewFormats, ExportFormats, UpdateFormats, Branches,
1730             Indices, Arguments, SwitchArguments
1731         */
1732         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1733                 BufferView const *) const;
1734
1735         /// Initialize specific MACOS X menubar
1736         void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1737
1738         /// Mac special menu.
1739         /** This defines a menu whose entries list the FuncRequests
1740             that will be removed by expand() in other menus. This is
1741             used by the Qt/Mac code.
1742
1743             NOTE: Qt does not remove the menu items when clearing a QMenuBar,
1744             such that the items will keep accessing the FuncRequests in
1745             the MenuDefinition. While Menus::Impl might be recreated,
1746             we keep mac_special_menu_ in memory by making it static.
1747         */
1748         static MenuDefinition mac_special_menu_;
1749
1750         ///
1751         MenuList menulist_;
1752         ///
1753         MenuDefinition menubar_;
1754
1755         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1756
1757         /// name to menu for \c menu() method.
1758         NameMap name_map_;
1759 };
1760
1761
1762 MenuDefinition Menus::Impl::mac_special_menu_;
1763
1764
1765 /*
1766   Here is what the Qt documentation says about how a menubar is chosen:
1767
1768      1) If the window has a QMenuBar then it is used. 2) If the window
1769      is a modal then its menubar is used. If no menubar is specified
1770      then a default menubar is used (as documented below) 3) If the
1771      window has no parent then the default menubar is used (as
1772      documented below).
1773
1774      The above 3 steps are applied all the way up the parent window
1775      chain until one of the above are satisifed. If all else fails a
1776      default menubar will be created, the default menubar on Qt/Mac is
1777      an empty menubar, however you can create a different default
1778      menubar by creating a parentless QMenuBar, the first one created
1779      will thus be designated the default menubar, and will be used
1780      whenever a default menubar is needed.
1781
1782   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1783   that this menubar will be used also when one of LyX' dialogs has
1784   focus. (JMarc)
1785 */
1786 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1787 {
1788         /* Since Qt 4.2, the qt/mac menu code has special code for
1789            specifying the role of a menu entry. However, it does not
1790            work very well with our scheme of creating menus on demand,
1791            and therefore we need to put these entries in a special
1792            invisible menu. (JMarc)
1793         */
1794
1795         /* The entries of our special mac menu. If we add support for
1796          * special entries in Menus, we could imagine something
1797          * like
1798          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
1799          * and therefore avoid hardcoding. I am not sure it is worth
1800          * the hassle, though. (JMarc)
1801          */
1802         struct MacMenuEntry {
1803                 FuncCode action;
1804                 char const * arg;
1805                 char const * label;
1806                 QAction::MenuRole role;
1807         };
1808
1809         MacMenuEntry entries[] = {
1810                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1811                  QAction::AboutRole},
1812                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1813                  QAction::PreferencesRole},
1814                 /* {LFUN_RECONFIGURE, "", "Reconfigure",
1815                  QAction::ApplicationSpecificRole}, */
1816                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1817         };
1818         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1819         const bool first_call = mac_special_menu_.empty();
1820
1821         // the special menu for Menus. Fill it up only once.
1822         if (first_call) {
1823                 for (size_t i = 0 ; i < num_entries ; ++i) {
1824                         FuncRequest const func(entries[i].action,
1825                                 from_utf8(entries[i].arg));
1826                         mac_special_menu_.add(MenuItem(MenuItem::Command,
1827                                 entries[i].label, func));
1828                 }
1829         }
1830
1831         // add the entries to a QMenu that will eventually be empty
1832         // and therefore invisible.
1833         QMenu * qMenu = qmb->addMenu("special");
1834         MenuDefinition::const_iterator cit = mac_special_menu_.begin();
1835         MenuDefinition::const_iterator end = mac_special_menu_.end();
1836         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1837 #if defined(QT_MAC_USE_COCOA) && (QT_MAC_USE_COCOA > 0)
1838                 if (first_call || entries[i].role != QAction::ApplicationSpecificRole) {
1839                         Action * action = new Action(view, QIcon(), cit->label(),
1840                                  cit->func(), QString(), qMenu);
1841                         action->setMenuRole(entries[i].role);
1842                         qMenu->addAction(action);
1843                 }
1844 #else
1845                 Action * action = new Action(view, QIcon(), cit->label(),
1846                         cit->func(), QString(), qMenu);
1847                 action->setMenuRole(entries[i].role);
1848                 qMenu->addAction(action);
1849 #endif
1850         }
1851 }
1852
1853
1854 void Menus::Impl::expand(MenuDefinition const & frommenu,
1855         MenuDefinition & tomenu, BufferView const * bv) const
1856 {
1857         if (!tomenu.empty())
1858                 tomenu.clear();
1859
1860         for (MenuDefinition::const_iterator cit = frommenu.begin();
1861              cit != frommenu.end() ; ++cit) {
1862                 Buffer const * buf = bv ? &bv->buffer() : 0;
1863                 switch (cit->kind()) {
1864                 case MenuItem::Lastfiles:
1865                         tomenu.expandLastfiles();
1866                         break;
1867
1868                 case MenuItem::Documents:
1869                         tomenu.expandDocuments();
1870                         break;
1871
1872                 case MenuItem::Bookmarks:
1873                         tomenu.expandBookmarks();
1874                         break;
1875
1876                 case MenuItem::ImportFormats:
1877                 case MenuItem::ViewFormats:
1878                 case MenuItem::UpdateFormats:
1879                 case MenuItem::ExportFormats:
1880                         tomenu.expandFormats(cit->kind(), buf);
1881                         break;
1882
1883                 case MenuItem::CharStyles:
1884                         tomenu.expandFlexInsert(buf, InsetLayout::CHARSTYLE);
1885                         break;
1886
1887                 case MenuItem::Custom:
1888                         tomenu.expandFlexInsert(buf, InsetLayout::CUSTOM);
1889                         break;
1890
1891                 case MenuItem::Elements:
1892                         tomenu.expandFlexInsert(buf, InsetLayout::ELEMENT);
1893                         break;
1894
1895                 case MenuItem::FloatListInsert:
1896                         tomenu.expandFloatListInsert(buf);
1897                         break;
1898
1899                 case MenuItem::FloatInsert:
1900                         tomenu.expandFloatInsert(buf);
1901                         break;
1902
1903                 case MenuItem::PasteRecent:
1904                         tomenu.expandPasteRecent(buf);
1905                         break;
1906
1907                 case MenuItem::Toolbars:
1908                         tomenu.expandToolbars();
1909                         break;
1910
1911                 case MenuItem::Branches:
1912                         tomenu.expandBranches(buf);
1913                         break;
1914
1915                 case MenuItem::Indices:
1916                         tomenu.expandIndices(buf);
1917                         break;
1918
1919                 case MenuItem::IndicesContext:
1920                         tomenu.expandIndicesContext(buf);
1921                         break;
1922
1923                 case MenuItem::IndicesLists:
1924                         tomenu.expandIndices(buf, true);
1925                         break;
1926
1927                 case MenuItem::IndicesListsContext:
1928                         tomenu.expandIndicesContext(buf, true);
1929                         break;
1930
1931                 case MenuItem::CiteStyles:
1932                         tomenu.expandCiteStyles(bv);
1933                         break;
1934
1935                 case MenuItem::Toc:
1936                         tomenu.expandToc(buf);
1937                         break;
1938
1939                 case MenuItem::GraphicsGroups:
1940                         tomenu.expandGraphicsGroups(bv);
1941                         break;
1942
1943                 case MenuItem::SpellingSuggestions:
1944                         tomenu.expandSpellingSuggestions(bv);
1945                         break;
1946
1947                 case MenuItem::LanguageSelector:
1948                         tomenu.expandLanguageSelector(buf);
1949                         break;
1950
1951                 case MenuItem::Arguments:
1952                         tomenu.expandArguments(bv, false);
1953                         break;
1954
1955                 case MenuItem::SwitchArguments:
1956                         tomenu.expandArguments(bv, true);
1957                         break;
1958
1959                 case MenuItem::Submenu: {
1960                         MenuItem item(*cit);
1961                         item.setSubmenu(MenuDefinition(cit->submenuname()));
1962                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
1963                         tomenu.addWithStatusCheck(item);
1964                 }
1965                 break;
1966
1967                 case MenuItem::Info:
1968                 case MenuItem::Help:
1969                 case MenuItem::Separator:
1970                         tomenu.addWithStatusCheck(*cit);
1971                         break;
1972
1973                 case MenuItem::Command:
1974                         if (!mac_special_menu_.hasFunc(cit->func()))
1975                                 tomenu.addWithStatusCheck(*cit);
1976                 }
1977         }
1978
1979         // we do not want the menu to end with a separator
1980         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1981                 tomenu.items_.pop_back();
1982
1983         // Check whether the shortcuts are unique
1984         tomenu.checkShortcuts();
1985 }
1986
1987
1988 bool Menus::Impl::hasMenu(QString const & name) const
1989 {
1990         return find_if(menulist_.begin(), menulist_.end(),
1991                 MenuNamesEqual(name)) != menulist_.end();
1992 }
1993
1994
1995 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1996 {
1997         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1998                 MenuNamesEqual(name));
1999         if (cit == menulist_.end())
2000                 LYXERR0("No submenu named " << name);
2001         LASSERT(cit != menulist_.end(), /**/);
2002         return (*cit);
2003 }
2004
2005
2006 MenuDefinition & Menus::Impl::getMenu(QString const & name)
2007 {
2008         iterator it = find_if(menulist_.begin(), menulist_.end(),
2009                 MenuNamesEqual(name));
2010         if (it == menulist_.end())
2011                 LYXERR0("No submenu named " << name);
2012         LASSERT(it != menulist_.end(), /**/);
2013         return (*it);
2014 }
2015
2016
2017 /////////////////////////////////////////////////////////////////////
2018 //
2019 // Menus
2020 //
2021 /////////////////////////////////////////////////////////////////////
2022
2023 Menus::Menus() : d(new Impl) {}
2024
2025
2026 Menus::~Menus()
2027 {
2028   delete d;
2029 }
2030
2031
2032 void Menus::reset()
2033 {
2034         delete d;
2035         d = new Impl;
2036 }
2037
2038
2039 void Menus::read(Lexer & lex)
2040 {
2041         enum {
2042                 md_menu,
2043                 md_menubar,
2044                 md_endmenuset
2045         };
2046
2047         LexerKeyword menutags[] = {
2048                 { "end", md_endmenuset },
2049                 { "menu", md_menu },
2050                 { "menubar", md_menubar }
2051         };
2052
2053         // consistency check
2054         if (compare_ascii_no_case(lex.getString(), "menuset"))
2055                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
2056
2057         lex.pushTable(menutags);
2058         lex.setContext("Menus::read");
2059
2060         bool quit = false;
2061
2062         while (lex.isOK() && !quit) {
2063                 switch (lex.lex()) {
2064                 case md_menubar:
2065                         d->menubar_.read(lex);
2066                         break;
2067                 case md_menu: {
2068                         lex.next(true);
2069                         QString const name = toqstr(lex.getDocString());
2070                         if (d->hasMenu(name))
2071                                 d->getMenu(name).read(lex);
2072                         else {
2073                                 MenuDefinition menu(name);
2074                                 menu.read(lex);
2075                                 d->menulist_.push_back(menu);
2076                         }
2077                         break;
2078                 }
2079                 case md_endmenuset:
2080                         quit = true;
2081                         break;
2082                 default:
2083                         lex.printError("Unknown menu tag");
2084                         break;
2085                 }
2086         }
2087         lex.popTable();
2088 }
2089
2090
2091 bool Menus::searchMenu(FuncRequest const & func,
2092         docstring_list & names) const
2093 {
2094         MenuDefinition menu;
2095         d->expand(d->menubar_, menu, 0);
2096         return menu.searchMenu(func, names);
2097 }
2098
2099
2100 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
2101 {
2102         if (initial) {
2103 #ifdef Q_WS_MACX
2104                 // setup special mac specific menu items, but only do this
2105                 // the first time a QMenuBar is created. Otherwise Qt will
2106                 // create duplicate items in the application menu. It seems
2107                 // that Qt does not remove them when the QMenubar is cleared.
2108                 LYXERR(Debug::GUI, "Creating Mac OS X special menu bar");
2109                 d->macxMenuBarInit(view, qmb);
2110 #endif
2111         } else {
2112                 // Clear all menubar contents before filling it.
2113                 qmb->clear();
2114         }
2115
2116         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
2117
2118         if (d->menubar_.empty()) {
2119                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
2120                         << d->menubar_.name());
2121                 return;
2122         }
2123         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
2124
2125         MenuDefinition menu;
2126         BufferView * bv = 0;
2127         if (view)
2128                 bv = view->currentBufferView();
2129         d->expand(d->menubar_, menu, bv);
2130
2131         MenuDefinition::const_iterator m = menu.begin();
2132         MenuDefinition::const_iterator end = menu.end();
2133
2134         for (; m != end; ++m) {
2135
2136                 if (m->kind() != MenuItem::Submenu) {
2137                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
2138                         continue;
2139                 }
2140
2141                 LYXERR(Debug::GUI, "menu bar item " << m->label()
2142                         << " is a submenu named " << m->submenuname());
2143
2144                 QString name = m->submenuname();
2145                 if (!d->hasMenu(name)) {
2146                         LYXERR(Debug::GUI, "\tERROR: " << name
2147                                 << " submenu has no menu!");
2148                         continue;
2149                 }
2150
2151                 Menu * menu = new Menu(view, m->submenuname(), true);
2152                 menu->setTitle(label(*m));
2153                 qmb->addMenu(menu);
2154
2155                 d->name_map_[view][name] = menu;
2156         }
2157 }
2158
2159
2160 void Menus::updateMenu(Menu * qmenu)
2161 {
2162         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
2163         qmenu->clear();
2164
2165         if (qmenu->d->name.isEmpty())
2166                 return;
2167
2168         docstring identifier = qstring_to_ucs4(qmenu->d->name);
2169         MenuDefinition fromLyxMenu(qmenu->d->name);
2170         while (!identifier.empty()) {
2171                 docstring menu_name;
2172                 identifier = split(identifier, menu_name, ';');
2173
2174                 if (!d->hasMenu(toqstr(menu_name))) {
2175                         LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
2176                                 << menu_name);
2177                         continue;
2178                 }
2179
2180                 MenuDefinition cat_menu = d->getMenu(toqstr(menu_name));
2181                 //FIXME: 50 is a wild guess. We should take into account here
2182                 //the expansion of menu items, disabled optional items etc.
2183                 bool const in_sub_menu = !fromLyxMenu.empty()
2184                         && fromLyxMenu.size() + cat_menu.size() > 50 ;
2185                 if (in_sub_menu)
2186                         fromLyxMenu.catSub(menu_name);
2187                 else
2188                         fromLyxMenu.cat(cat_menu);
2189                 fromLyxMenu.add(MenuItem(MenuItem::Separator));
2190         }
2191
2192         if (fromLyxMenu.empty()) {
2193                 qmenu->addAction(qt_("No Action Defined!"));
2194                 return;
2195         }
2196
2197         BufferView * bv = 0;
2198         if (qmenu->d->view)
2199                 bv = qmenu->d->view->currentBufferView();
2200         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
2201         qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
2202 }
2203
2204
2205 Menu * Menus::menu(QString const & name, GuiView & view, bool keyboard)
2206 {
2207         LYXERR(Debug::GUI, "Context menu requested: " << name);
2208         Menu * menu = d->name_map_[&view].value(name, 0);
2209         if (!menu && !name.startsWith("context-")) {
2210                 LYXERR0("requested context menu not found: " << name);
2211                 return 0;
2212         }
2213
2214         menu = new Menu(&view, name, true, keyboard);
2215         d->name_map_[&view][name] = menu;
2216         return menu;
2217 }
2218
2219 } // namespace frontend
2220 } // namespace lyx
2221
2222 #include "moc_Menus.cpp"