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