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