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