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