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