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