]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
lexer cosmetics
[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         lex.setContext("MenuDefinition::read: ");
412
413         bool quit = false;
414         bool optional = false;
415
416         while (lex.isOK() && !quit) {
417                 switch (lex.lex()) {
418                 case md_optitem:
419                         optional = true;
420                         // fallback to md_item
421                 case md_item: {
422                         lex.next(true);
423                         docstring const name = translateIfPossible(lex.getDocString());
424                         lex.next(true);
425                         string const command = lex.getString();
426                         FuncRequest func = lyxaction.lookupFunc(command);
427                         add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
428                         optional = false;
429                         break;
430                 }
431
432                 case md_separator:
433                         add(MenuItem(MenuItem::Separator));
434                         break;
435
436                 case md_lastfiles:
437                         add(MenuItem(MenuItem::Lastfiles));
438                         break;
439
440                 case md_charstyles:
441                         add(MenuItem(MenuItem::CharStyles));
442                         break;
443
444                 case md_custom:
445                         add(MenuItem(MenuItem::Custom));
446                         break;
447
448                 case md_elements:
449                         add(MenuItem(MenuItem::Elements));
450                         break;
451
452                 case md_documents:
453                         add(MenuItem(MenuItem::Documents));
454                         break;
455
456                 case md_bookmarks:
457                         add(MenuItem(MenuItem::Bookmarks));
458                         break;
459
460                 case md_toc:
461                         add(MenuItem(MenuItem::Toc));
462                         break;
463
464                 case md_viewformats:
465                         add(MenuItem(MenuItem::ViewFormats));
466                         break;
467
468                 case md_updateformats:
469                         add(MenuItem(MenuItem::UpdateFormats));
470                         break;
471
472                 case md_exportformats:
473                         add(MenuItem(MenuItem::ExportFormats));
474                         break;
475
476                 case md_importformats:
477                         add(MenuItem(MenuItem::ImportFormats));
478                         break;
479
480                 case md_floatlistinsert:
481                         add(MenuItem(MenuItem::FloatListInsert));
482                         break;
483
484                 case md_floatinsert:
485                         add(MenuItem(MenuItem::FloatInsert));
486                         break;
487
488                 case md_pasterecent:
489                         add(MenuItem(MenuItem::PasteRecent));
490                         break;
491
492                 case md_toolbars:
493                         add(MenuItem(MenuItem::Toolbars));
494                         break;
495
496                 case md_branches:
497                         add(MenuItem(MenuItem::Branches));
498                         break;
499
500                 case md_optsubmenu:
501                         optional = true;
502                         // fallback to md_submenu
503                 case md_submenu: {
504                         lex.next(true);
505                         docstring const mlabel = translateIfPossible(lex.getDocString());
506                         lex.next(true);
507                         docstring const mname = lex.getDocString();
508                         add(MenuItem(MenuItem::Submenu,
509                                 toqstr(mlabel), toqstr(mname), optional));
510                         optional = false;
511                         break;
512                 }
513
514                 case md_endmenu:
515                         quit = true;
516                         break;
517
518                 default:
519                         lex.printError("Unknown menu tag");
520                         break;
521                 }
522         }
523         lex.popTable();
524 }
525
526
527 MenuItem const & MenuDefinition::operator[](size_type i) const
528 {
529         return items_[i];
530 }
531
532
533 bool MenuDefinition::hasFunc(FuncRequest const & func) const
534 {
535         for (const_iterator it = begin(), et = end(); it != et; ++it)
536                 if (it->func() == func)
537                         return true;
538         return false;
539 }
540
541
542 void MenuDefinition::checkShortcuts() const
543 {
544         // This is a quadratic algorithm, but we do not care because
545         // menus are short enough
546         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
547                 QString shortcut = it1->shortcut();
548                 if (shortcut.isEmpty())
549                         continue;
550                 if (!it1->label().contains(shortcut))
551                         lyxerr << "Menu warning: menu entry \""
552                                << fromqstr(it1->label())
553                                << "\" does not contain shortcut `"
554                                << fromqstr(shortcut) << "'." << endl;
555                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
556                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
557                                 lyxerr << "Menu warning: menu entries "
558                                        << '"' << fromqstr(it1->fulllabel())
559                                        << "\" and \"" << fromqstr(it2->fulllabel())
560                                        << "\" share the same shortcut."
561                                        << endl;
562                         }
563                 }
564         }
565 }
566
567
568 bool MenuDefinition::searchMenu(FuncRequest const & func, vector<docstring> & names) const
569 {
570         const_iterator m = begin();
571         const_iterator m_end = end();
572         for (; m != m_end; ++m) {
573                 if (m->kind() == MenuItem::Command && m->func() == func) {
574                         names.push_back(qstring_to_ucs4(m->label()));
575                         return true;
576                 }
577                 if (m->kind() == MenuItem::Submenu) {
578                         names.push_back(qstring_to_ucs4(m->label()));
579                         if (!m->hasSubmenu()) {
580                                 LYXERR(Debug::GUI, "Warning: non existing sub menu label="
581                                         << fromqstr(m->label())
582                                         << " name=" << fromqstr(m->submenuname()));
583                                 names.pop_back();
584                                 continue;
585                         }
586                         if (m->submenu().searchMenu(func, names))
587                                 return true;
588                         names.pop_back();
589                 }
590         }
591         return false;
592 }
593
594
595 bool compareFormat(Format const * p1, Format const * p2)
596 {
597         return *p1 < *p2;
598 }
599
600
601 QString limitStringLength(docstring const & str)
602 {
603         size_t const max_item_length = 45;
604
605         if (str.size() > max_item_length)
606                 return toqstr(str.substr(0, max_item_length - 3) + "...");
607
608         return toqstr(str);
609 }
610
611
612 void MenuDefinition::expandLastfiles()
613 {
614         LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
615         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
616
617         int ii = 1;
618
619         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
620                 string const file = lfit->absFilename();
621                 QString const label = QString("%1. %2|%3").arg(ii)
622                         .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
623                 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
624         }
625 }
626
627
628 void MenuDefinition::expandDocuments()
629 {
630         Buffer * first = theBufferList().first();
631         if (first) {
632                 Buffer * b = first;
633                 int ii = 1;
634                 
635                 // We cannot use a for loop as the buffer list cycles.
636                 do {
637                         QString label = toqstr(b->fileName().displayName(20));
638                         if (!b->isClean())
639                                 label += "*";
640                         if (ii < 10)
641                                 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
642                         add(MenuItem(MenuItem::Command, label,
643                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
644                         
645                         b = theBufferList().next(b);
646                         ++ii;
647                 } while (b != first); 
648         } else {
649                 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
650                            FuncRequest(LFUN_NOACTION)));
651         }
652 }
653
654
655 void MenuDefinition::expandBookmarks()
656 {
657         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
658
659         for (size_t i = 1; i <= bm.size(); ++i) {
660                 if (bm.isValid(i)) {
661                         string const file = bm.bookmark(i).filename.absFilename();
662                         QString const label = QString("%1. %2|%3").arg(i)
663                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
664                         add(MenuItem(MenuItem::Command, label,
665                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
666                 }
667         }
668 }
669
670
671 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
672 {
673         if (!buf && kind != MenuItem::ImportFormats) {
674                 add(MenuItem(MenuItem::Command,
675                                     qt_("No Document Open!"),
676                                     FuncRequest(LFUN_NOACTION)));
677                 return;
678         }
679
680         typedef vector<Format const *> Formats;
681         Formats formats;
682         FuncCode action;
683
684         switch (kind) {
685         case MenuItem::ImportFormats:
686                 formats = theConverters().importableFormats();
687                 action = LFUN_BUFFER_IMPORT;
688                 break;
689         case MenuItem::ViewFormats:
690                 formats = buf->exportableFormats(true);
691                 action = LFUN_BUFFER_VIEW;
692                 break;
693         case MenuItem::UpdateFormats:
694                 formats = buf->exportableFormats(true);
695                 action = LFUN_BUFFER_UPDATE;
696                 break;
697         default:
698                 formats = buf->exportableFormats(false);
699                 action = LFUN_BUFFER_EXPORT;
700         }
701         sort(formats.begin(), formats.end(), &compareFormat);
702
703         Formats::const_iterator fit = formats.begin();
704         Formats::const_iterator end = formats.end();
705         for (; fit != end ; ++fit) {
706                 if ((*fit)->dummy())
707                         continue;
708                 QString label = toqstr((*fit)->prettyname());
709                 QString const shortcut = toqstr((*fit)->shortcut());
710
711                 switch (kind) {
712                 case MenuItem::ImportFormats:
713                         // FIXME: This is a hack, we should rather solve
714                         // FIXME: bug 2488 instead.
715                         if ((*fit)->name() == "text")
716                                 label = qt_("Plain Text");
717                         else if ((*fit)->name() == "textparagraph")
718                                 label = qt_("Plain Text, Join Lines");
719                         label += "...";
720                         break;
721                 case MenuItem::ViewFormats:
722                 case MenuItem::ExportFormats:
723                 case MenuItem::UpdateFormats:
724                         if (!(*fit)->documentFormat())
725                                 continue;
726                         break;
727                 default:
728                         BOOST_ASSERT(false);
729                         break;
730                 }
731                 // FIXME: if we had proper support for translating the
732                 // format names defined in configure.py, there would
733                 // not be a need to check whether the shortcut is
734                 // correct. If we add it uncondiitonally, it would
735                 // create useless warnings on bad shortcuts
736                 if (!shortcut.isEmpty() && label.contains(shortcut))
737                         label += '|' + shortcut;
738
739                 if (buf)
740                         addWithStatusCheck(MenuItem(MenuItem::Command, label,
741                                 FuncRequest(action, (*fit)->name())));
742                 else
743                         add(MenuItem(MenuItem::Command, label,
744                                 FuncRequest(action, (*fit)->name())));
745         }
746 }
747
748
749 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
750 {
751         if (!buf) {
752                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
753                                     FuncRequest(LFUN_NOACTION)));
754                 return;
755         }
756
757         FloatList const & floats = buf->params().documentClass().floats();
758         FloatList::const_iterator cit = floats.begin();
759         FloatList::const_iterator end = floats.end();
760         for (; cit != end; ++cit) {
761                 addWithStatusCheck(MenuItem(MenuItem::Command,
762                                     qt_(cit->second.listName()),
763                                     FuncRequest(LFUN_FLOAT_LIST,
764                                                 cit->second.type())));
765         }
766 }
767
768
769 void MenuDefinition::expandFloatInsert(Buffer const * buf)
770 {
771         if (!buf) {
772                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
773                                     FuncRequest(LFUN_NOACTION)));
774                 return;
775         }
776
777         FloatList const & floats = buf->params().documentClass().floats();
778         FloatList::const_iterator cit = floats.begin();
779         FloatList::const_iterator end = floats.end();
780         for (; cit != end; ++cit) {
781                 // normal float
782                 QString const label = qt_(cit->second.name());
783                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
784                                     FuncRequest(LFUN_FLOAT_INSERT,
785                                                 cit->second.type())));
786         }
787 }
788
789
790 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
791 {
792         if (!buf) {
793                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
794                                     FuncRequest(LFUN_NOACTION)));
795                 return;
796         }
797         TextClass::InsetLayouts const & insetLayouts =
798                 buf->params().documentClass().insetLayouts();
799         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
800         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
801         for (; cit != end; ++cit) {
802                 docstring const label = cit->first;
803                 if (cit->second.lyxtype() == s)
804                         addWithStatusCheck(MenuItem(MenuItem::Command, 
805                                 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
806                                                 label)));
807         }
808 }
809
810
811 size_t const max_number_of_items = 25;
812
813 void MenuDefinition::expandToc2(Toc const & toc_list,
814                 size_t from, size_t to, int depth)
815 {
816         int shortcut_count = 0;
817
818         // check whether depth is smaller than the smallest depth in toc.
819         int min_depth = 1000;
820         for (size_t i = from; i < to; ++i)
821                 min_depth = min(min_depth, toc_list[i].depth());
822         if (min_depth > depth)
823                 depth = min_depth;
824
825         if (to - from <= max_number_of_items) {
826                 for (size_t i = from; i < to; ++i) {
827                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
828                         label += limitStringLength(toc_list[i].str());
829                         if (toc_list[i].depth() == depth
830                             && shortcut_count < 9) {
831                                 if (label.contains(QString::number(shortcut_count + 1)))
832                                         label += '|' + QString::number(++shortcut_count);
833                         }
834                         add(MenuItem(MenuItem::Command, label,
835                                             FuncRequest(toc_list[i].action())));
836                 }
837         } else {
838                 size_t pos = from;
839                 while (pos < to) {
840                         size_t new_pos = pos + 1;
841                         while (new_pos < to && toc_list[new_pos].depth() > depth)
842                                 ++new_pos;
843
844                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
845                         label += limitStringLength(toc_list[pos].str());
846                         if (toc_list[pos].depth() == depth &&
847                             shortcut_count < 9) {
848                                 if (label.contains(QString::number(shortcut_count + 1)))
849                                         label += '|' + QString::number(++shortcut_count);
850                         }
851                         if (new_pos == pos + 1) {
852                                 add(MenuItem(MenuItem::Command,
853                                                     label, FuncRequest(toc_list[pos].action())));
854                         } else {
855                                 MenuDefinition sub;
856                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
857                                 MenuItem item(MenuItem::Submenu, label);
858                                 item.setSubmenu(sub);
859                                 add(item);
860                         }
861                         pos = new_pos;
862                 }
863         }
864 }
865
866
867 void MenuDefinition::expandToc(Buffer const * buf)
868 {
869         // To make things very cleanly, we would have to pass buf to
870         // all MenuItem constructors and to expandToc2. However, we
871         // know that all the entries in a TOC will be have status_ ==
872         // OK, so we avoid this unnecessary overhead (JMarc)
873
874         if (!buf) {
875                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
876                                     FuncRequest(LFUN_NOACTION)));
877                 return;
878         }
879
880         Buffer* cbuf = const_cast<Buffer*>(buf);
881         cbuf->tocBackend().update();
882         cbuf->structureChanged();
883
884         // Add an entry for the master doc if this is a child doc
885         Buffer const * const master = buf->masterBuffer();
886         if (buf != master) {
887                 ParIterator const pit = par_iterator_begin(master->inset());
888                 string const arg = convert<string>(pit->id());
889                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
890                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
891         }
892
893         MenuDefinition other_lists;
894         
895         FloatList const & floatlist = buf->params().documentClass().floats();
896         TocList const & toc_list = buf->tocBackend().tocs();
897         TocList::const_iterator cit = toc_list.begin();
898         TocList::const_iterator end = toc_list.end();
899         for (; cit != end; ++cit) {
900                 // Handle this later
901                 if (cit->first == "tableofcontents")
902                         continue;
903
904                 string const & floatName = floatlist.getType(cit->first).listName();
905                 QString label;
906                 bool in_other_list = true;
907                 if (!floatName.empty()) {
908                         label = qt_(floatName);
909                         in_other_list = false;
910                 }
911                 else if (cit->first == "child") {
912                         label = qt_("Child Documents");
913                         in_other_list = false;
914                 } else if (cit->first == "embedded")
915                         label = qt_("Embedded Files");
916                 else if (cit->first == "graphics")
917                         label = qt_("List of Graphics");
918                 else if (cit->first == "equation")
919                         label = qt_("List of Equations");
920                 else if (cit->first == "index")
921                         label = qt_("List of Indexes");
922                 else if (cit->first == "listing") {
923                         // FIXME: the listing navigate menu causes a crash for unknown
924                         // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
925                         // This is a temporary fix:
926                         //label = qt_("List of Listings");
927                         continue;
928                 }
929                 else if (cit->first == "marginalnote")
930                         label = qt_("List of Marginal notes");
931                 else if (cit->first == "note")
932                         label = qt_("List of Notes");
933                 else if (cit->first == "footnote")
934                         label = qt_("List of Foot notes");
935                 else if (cit->first == "label")
936                         label = qt_("Labels and References");
937                 else if (cit->first == "citation")
938                         label = qt_("List of Citations");
939                 else
940                         // This should not happen unless the entry is missing above.
941                         label = qt_("Other floats: ") + toqstr(cit->first);
942
943                 MenuDefinition submenu;
944
945                 if (cit->second.size() >= 30) {
946                         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
947                         submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
948                 } else {
949                         TocIterator ccit = cit->second.begin();
950                         TocIterator eend = cit->second.end();
951                         for (; ccit != eend; ++ccit) {
952                                 QString const label = limitStringLength(ccit->str());
953                                 submenu.add(MenuItem(MenuItem::Command, label,
954                                         FuncRequest(ccit->action())));
955                         }
956                 }
957
958                 MenuItem item(MenuItem::Submenu, label);
959                 item.setSubmenu(submenu);
960                 if (in_other_list)
961                         other_lists.add(item);
962                 else {
963                         item.setSubmenu(submenu);
964                         add(item);
965                 }
966         }
967         if (!other_lists.empty()) {
968                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
969                 item.setSubmenu(other_lists);
970                 add(item);
971         }
972
973
974         // Handle normal TOC
975         cit = toc_list.find("tableofcontents");
976         if (cit == end) {
977                 addWithStatusCheck(MenuItem(MenuItem::Command,
978                                     qt_("No Table of contents"),
979                                     FuncRequest()));
980         } else {
981                 expandToc2(cit->second, 0, cit->second.size(), 0);
982         }
983 }
984
985
986 void MenuDefinition::expandPasteRecent()
987 {
988         vector<docstring> const sel = cap::availableSelections();
989
990         vector<docstring>::const_iterator cit = sel.begin();
991         vector<docstring>::const_iterator end = sel.end();
992
993         for (unsigned int index = 0; cit != end; ++cit, ++index) {
994                 add(MenuItem(MenuItem::Command, toqstr(*cit),
995                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
996         }
997 }
998
999
1000 void MenuDefinition::expandToolbars()
1001 {
1002         //
1003         // extracts the toolbars from the backend
1004         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1005         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1006
1007         for (; cit != end; ++cit) {
1008                 QString label = qt_(cit->gui_name);
1009                 // frontends are not supposed to turn on/off toolbars,
1010                 // if they cannot update ToolbarBackend::flags. That
1011                 // is to say, ToolbarsBackend::flags should reflect
1012                 // the true state of toolbars.
1013                 //
1014                 // menu is displayed as
1015                 //       on/off review
1016                 // and
1017                 //              review (auto)
1018                 // in the case of auto.
1019                 if (cit->flags & ToolbarInfo::AUTO)
1020                         label += qt_(" (auto)");
1021                 add(MenuItem(MenuItem::Command, label,
1022                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1023         }
1024 }
1025
1026
1027 void MenuDefinition::expandBranches(Buffer const * buf)
1028 {
1029         if (!buf) {
1030                 add(MenuItem(MenuItem::Command,
1031                                     qt_("No Document Open!"),
1032                                     FuncRequest(LFUN_NOACTION)));
1033                 return;
1034         }
1035
1036         BufferParams const & params = buf->masterBuffer()->params();
1037         if (params.branchlist().empty()) {
1038                 add(MenuItem(MenuItem::Command,
1039                                     qt_("No Branch in Document!"),
1040                                     FuncRequest(LFUN_NOACTION)));
1041                 return;
1042         }
1043
1044         BranchList::const_iterator cit = params.branchlist().begin();
1045         BranchList::const_iterator end = params.branchlist().end();
1046
1047         for (int ii = 1; cit != end; ++cit, ++ii) {
1048                 docstring label = cit->getBranch();
1049                 if (ii < 10)
1050                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1051                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1052                                     FuncRequest(LFUN_BRANCH_INSERT,
1053                                                 cit->getBranch())));
1054         }
1055 }
1056
1057 } // namespace anon
1058
1059
1060 /////////////////////////////////////////////////////////////////////
1061 // Menu::Impl definition and implementation
1062 /////////////////////////////////////////////////////////////////////
1063
1064 struct Menu::Impl
1065 {
1066         /// populates the menu or one of its submenu
1067         /// This is used as a recursive function
1068         void populate(QMenu & qMenu, MenuDefinition const & menu);
1069
1070         /// Only needed for top level menus.
1071         MenuDefinition * top_level_menu;
1072         /// our owning view
1073         GuiView * view;
1074         /// the name of this menu
1075         QString name;
1076 };
1077
1078
1079
1080 /// Get a MenuDefinition item label from the menu backend
1081 static QString label(MenuItem const & mi)
1082 {
1083         QString label = mi.label();
1084         label.replace("&", "&&");
1085
1086         QString shortcut = mi.shortcut();
1087         if (!shortcut.isEmpty()) {
1088                 int pos = label.indexOf(shortcut);
1089                 if (pos != -1)
1090                         //label.insert(pos, 1, char_type('&'));
1091                         label.replace(pos, 0, "&");
1092         }
1093
1094         QString const binding = mi.binding();
1095         if (!binding.isEmpty())
1096                 label += '\t' + binding;
1097
1098         return label;
1099 }
1100
1101 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1102 {
1103         LYXERR(Debug::GUI, "populating menu " << fromqstr(menu.name()));
1104         if (menu.size() == 0) {
1105                 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu.name()));
1106                 return;
1107         }
1108         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1109         MenuDefinition::const_iterator m = menu.begin();
1110         MenuDefinition::const_iterator end = menu.end();
1111         for (; m != end; ++m) {
1112                 if (m->kind() == MenuItem::Separator)
1113                         qMenu.addSeparator();
1114                 else if (m->kind() == MenuItem::Submenu) {
1115                         QMenu * subMenu = qMenu.addMenu(label(*m));
1116                         populate(*subMenu, m->submenu());
1117                 } else {
1118                         // we have a MenuItem::Command
1119                         qMenu.addAction(new Action(view, QIcon(), label(*m), 
1120                                 m->func(), QString(), &qMenu));
1121                 }
1122         }
1123 }
1124
1125 /////////////////////////////////////////////////////////////////////
1126 // Menu implementation
1127 /////////////////////////////////////////////////////////////////////
1128
1129 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1130 : d(new Menu::Impl)
1131 {
1132         d->top_level_menu = top_level? new MenuDefinition : 0;
1133         d->view = gv;
1134         d->name = name;
1135         setTitle(name);
1136         if (d->top_level_menu)
1137                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1138 }
1139
1140
1141 Menu::~Menu()
1142 {
1143         delete d->top_level_menu;
1144         delete d;
1145 }
1146
1147
1148 void Menu::updateView()
1149 {
1150         guiApp->menus().updateMenu(this);
1151 }
1152
1153
1154 /////////////////////////////////////////////////////////////////////
1155 // Menus::Impl definition and implementation
1156 /////////////////////////////////////////////////////////////////////
1157
1158 struct Menus::Impl {
1159         ///
1160         bool hasMenu(QString const &) const;
1161         ///
1162         MenuDefinition & getMenu(QString const &);
1163         ///
1164         MenuDefinition const & getMenu(QString const &) const;
1165
1166         /// Expands some special entries of the menu
1167         /** The entries with the following kind are expanded to a
1168             sequence of Command MenuItems: Lastfiles, Documents,
1169             ViewFormats, ExportFormats, UpdateFormats, Branches
1170         */
1171         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1172                 Buffer const *) const;
1173
1174         /// Initialize specific MACOS X menubar
1175         void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1176
1177         /// Mac special menu.
1178         /** This defines a menu whose entries list the FuncRequests
1179             that will be removed by expand() in other menus. This is
1180             used by the Qt/Mac code
1181         */
1182         MenuDefinition specialmenu_;
1183
1184         ///
1185         MenuList menulist_;
1186         ///
1187         MenuDefinition menubar_;
1188
1189         typedef QMap<GuiView *, QHash<QString, Menu *> > NameMap;
1190
1191         /// name to menu for \c menu() method.
1192         NameMap name_map_;
1193 };
1194
1195 /*
1196   Here is what the Qt documentation says about how a menubar is chosen:
1197
1198      1) If the window has a QMenuBar then it is used. 2) If the window
1199      is a modal then its menubar is used. If no menubar is specified
1200      then a default menubar is used (as documented below) 3) If the
1201      window has no parent then the default menubar is used (as
1202      documented below).
1203
1204      The above 3 steps are applied all the way up the parent window
1205      chain until one of the above are satisifed. If all else fails a
1206      default menubar will be created, the default menubar on Qt/Mac is
1207      an empty menubar, however you can create a different default
1208      menubar by creating a parentless QMenuBar, the first one created
1209      will thus be designated the default menubar, and will be used
1210      whenever a default menubar is needed.
1211
1212   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1213   that this menubar will be used also when one of LyX' dialogs has
1214   focus. (JMarc)
1215 */
1216 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1217 {
1218         /* Since Qt 4.2, the qt/mac menu code has special code for
1219            specifying the role of a menu entry. However, it does not
1220            work very well with our scheme of creating menus on demand,
1221            and therefore we need to put these entries in a special
1222            invisible menu. (JMarc)
1223         */
1224
1225         /* The entries of our special mac menu. If we add support for
1226          * special entries in Menus, we could imagine something
1227          * like
1228          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
1229          * and therefore avoid hardcoding. I am not sure it is worth
1230          * the hassle, though. (JMarc)
1231          */
1232         struct MacMenuEntry {
1233                 FuncCode action;
1234                 char const * arg;
1235                 char const * label;
1236                 QAction::MenuRole role;
1237         };
1238
1239         MacMenuEntry entries[] = {
1240                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1241                  QAction::AboutRole},
1242                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1243                  QAction::PreferencesRole},
1244                 {LFUN_RECONFIGURE, "", "Reconfigure",
1245                  QAction::ApplicationSpecificRole},
1246                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1247         };
1248         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1249
1250         // the special menu for Menus. Fill it up only once.
1251         if (specialmenu_.size() == 0) {
1252                 for (size_t i = 0 ; i < num_entries ; ++i) {
1253                         FuncRequest const func(entries[i].action,
1254                                 from_utf8(entries[i].arg));
1255                         specialmenu_.add(MenuItem(MenuItem::Command, 
1256                                 entries[i].label, func));
1257                 }
1258         }
1259         
1260         // add the entries to a QMenu that will eventually be empty
1261         // and therefore invisible.
1262         QMenu * qMenu = qmb->addMenu("special");
1263         MenuDefinition::const_iterator cit = specialmenu_.begin();
1264         MenuDefinition::const_iterator end = specialmenu_.end();
1265         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1266                 Action * action = new Action(view, QIcon(), cit->label(),
1267                         cit->func(), QString(), qMenu);
1268                 action->setMenuRole(entries[i].role);
1269                 qMenu->addAction(action);
1270         }
1271 }
1272
1273
1274 void Menus::Impl::expand(MenuDefinition const & frommenu,
1275         MenuDefinition & tomenu, Buffer const * buf) const
1276 {
1277         if (!tomenu.empty())
1278                 tomenu.clear();
1279
1280         for (MenuDefinition::const_iterator cit = frommenu.begin();
1281              cit != frommenu.end() ; ++cit) {
1282                 switch (cit->kind()) {
1283                 case MenuItem::Lastfiles:
1284                         tomenu.expandLastfiles();
1285                         break;
1286
1287                 case MenuItem::Documents:
1288                         tomenu.expandDocuments();
1289                         break;
1290
1291                 case MenuItem::Bookmarks:
1292                         tomenu.expandBookmarks();
1293                         break;
1294
1295                 case MenuItem::ImportFormats:
1296                 case MenuItem::ViewFormats:
1297                 case MenuItem::UpdateFormats:
1298                 case MenuItem::ExportFormats:
1299                         tomenu.expandFormats(cit->kind(), buf);
1300                         break;
1301
1302                 case MenuItem::CharStyles:
1303                         tomenu.expandFlexInsert(buf, "charstyle");
1304                         break;
1305
1306                 case MenuItem::Custom:
1307                         tomenu.expandFlexInsert(buf, "custom");
1308                         break;
1309
1310                 case MenuItem::Elements:
1311                         tomenu.expandFlexInsert(buf, "element");
1312                         break;
1313
1314                 case MenuItem::FloatListInsert:
1315                         tomenu.expandFloatListInsert(buf);
1316                         break;
1317
1318                 case MenuItem::FloatInsert:
1319                         tomenu.expandFloatInsert(buf);
1320                         break;
1321
1322                 case MenuItem::PasteRecent:
1323                         tomenu.expandPasteRecent();
1324                         break;
1325
1326                 case MenuItem::Toolbars:
1327                         tomenu.expandToolbars();
1328                         break;
1329
1330                 case MenuItem::Branches:
1331                         tomenu.expandBranches(buf);
1332                         break;
1333
1334                 case MenuItem::Toc:
1335                         tomenu.expandToc(buf);
1336                         break;
1337
1338                 case MenuItem::Submenu: {
1339                         MenuItem item(*cit);
1340                         item.setSubmenu(MenuDefinition(cit->submenuname()));
1341                         expand(getMenu(cit->submenuname()), item.submenu(), buf);
1342                         tomenu.addWithStatusCheck(item);
1343                 }
1344                 break;
1345
1346                 case MenuItem::Separator:
1347                         tomenu.addWithStatusCheck(*cit);
1348                         break;
1349
1350                 case MenuItem::Command:
1351                         if (!specialmenu_.hasFunc(cit->func()))
1352                                 tomenu.addWithStatusCheck(*cit);
1353                 }
1354         }
1355
1356         // we do not want the menu to end with a separator
1357         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1358                 tomenu.items_.pop_back();
1359
1360         // Check whether the shortcuts are unique
1361         tomenu.checkShortcuts();
1362 }
1363
1364
1365 bool Menus::Impl::hasMenu(QString const & name) const
1366 {
1367         return find_if(menulist_.begin(), menulist_.end(),
1368                 MenuNamesEqual(name)) != menulist_.end();
1369 }
1370
1371
1372 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1373 {
1374         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1375                 MenuNamesEqual(name));
1376         if (cit == menulist_.end())
1377                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1378         BOOST_ASSERT(cit != menulist_.end());
1379         return (*cit);
1380 }
1381
1382
1383 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1384 {
1385         iterator it = find_if(menulist_.begin(), menulist_.end(),
1386                 MenuNamesEqual(name));
1387         if (it == menulist_.end())
1388                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1389         BOOST_ASSERT(it != menulist_.end());
1390         return (*it);
1391 }
1392
1393
1394 /////////////////////////////////////////////////////////////////////
1395 //
1396 // Menus 
1397 //
1398 /////////////////////////////////////////////////////////////////////
1399
1400 Menus::Menus() : d(new Impl) {}
1401
1402
1403 void Menus::read(Lexer & lex)
1404 {
1405         enum {
1406                 md_menu,
1407                 md_menubar,
1408                 md_endmenuset,
1409         };
1410
1411         LexerKeyword menutags[] = {
1412                 { "end", md_endmenuset },
1413                 { "menu", md_menu },
1414                 { "menubar", md_menubar }
1415         };
1416
1417         // consistency check
1418         if (compare_ascii_no_case(lex.getString(), "menuset"))
1419                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1420
1421         lex.pushTable(menutags);
1422         lex.setContext("Menus::read");
1423
1424         bool quit = false;
1425
1426         while (lex.isOK() && !quit) {
1427                 switch (lex.lex()) {
1428                 case md_menubar:
1429                         d->menubar_.read(lex);
1430                         break;
1431                 case md_menu: {
1432                         lex.next(true);
1433                         QString const name = toqstr(lex.getDocString());
1434                         if (d->hasMenu(name))
1435                                 d->getMenu(name).read(lex);
1436                         else {
1437                                 MenuDefinition menu(name);
1438                                 menu.read(lex);
1439                                 d->menulist_.push_back(menu);
1440                         }
1441                         break;
1442                 }
1443                 case md_endmenuset:
1444                         quit = true;
1445                         break;
1446                 default:
1447                         lex.printError("Unknown menu tag");
1448                         break;
1449                 }
1450         }
1451         lex.popTable();
1452 }
1453
1454
1455 bool Menus::searchMenu(FuncRequest const & func,
1456         vector<docstring> & names) const
1457 {
1458         MenuDefinition menu;
1459         d->expand(d->menubar_, menu, 0);
1460         return menu.searchMenu(func, names);
1461 }
1462
1463
1464 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1465 {
1466         if (initial) {
1467 #ifdef Q_WS_MACX
1468                 // setup special mac specific menu item
1469                 d->macxMenuBarInit(view, qmb);
1470 #endif
1471         } else {
1472                 // Clear all menubar contents before filling it.
1473                 qmb->clear();
1474         }
1475
1476         LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
1477
1478         if (d->menubar_.size() == 0) {
1479                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1480                         << fromqstr(d->menubar_.name()));
1481                 return;
1482         }
1483         else {
1484                 LYXERR(Debug::GUI, "menu bar entries "
1485                         << d->menubar_.size());
1486         }
1487
1488         MenuDefinition menu;
1489         Buffer * buf = 0;
1490         if (view)
1491                 buf = view->buffer();
1492         d->expand(d->menubar_, menu, buf);
1493
1494         MenuDefinition::const_iterator m = menu.begin();
1495         MenuDefinition::const_iterator end = menu.end();
1496
1497         for (; m != end; ++m) {
1498
1499                 if (m->kind() != MenuItem::Submenu) {
1500                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
1501                         continue;
1502                 }
1503
1504                 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
1505                         << " is a submenu named " << fromqstr(m->submenuname()));
1506
1507                 QString name = m->submenuname();
1508                 if (!d->hasMenu(name)) {
1509                         LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
1510                                 << " submenu has no menu!");
1511                         continue;
1512                 }
1513
1514                 Menu * menu = new Menu(view, m->submenuname(), true);
1515                 menu->setTitle(label(*m));
1516                 qmb->addMenu(menu);
1517
1518                 d->name_map_[view][name] = menu;
1519         }
1520 }
1521
1522
1523 void Menus::updateMenu(Menu * qmenu)
1524 {
1525         LYXERR(Debug::GUI, "Triggered menu: " << fromqstr(qmenu->d->name));
1526         qmenu->clear();
1527
1528         if (qmenu->d->name.isEmpty())
1529                 return;
1530
1531         // Here, We make sure that theLyXFunc points to the correct LyXView.
1532         theLyXFunc().setLyXView(qmenu->d->view);
1533
1534         if (!d->hasMenu(qmenu->d->name)) {
1535                 qmenu->addAction(qt_("No action defined!"));
1536                 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1537                         << fromqstr(qmenu->d->name));
1538                 return;
1539         }
1540
1541         MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1542         Buffer * buf = 0;
1543         if (qmenu->d->view)
1544                 buf = qmenu->d->view->buffer();
1545         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, buf);
1546         qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1547 }
1548
1549
1550 Menu * Menus::menu(QString const & name, GuiView & view)
1551 {
1552         LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
1553         Menu * menu = d->name_map_[&view].value(name, 0);
1554         if (!menu && !name.startsWith("context-")) {
1555                 LYXERR0("requested context menu not found: " << fromqstr(name));
1556                 return 0;
1557         }
1558
1559         menu = new Menu(&view, name, true);
1560         d->name_map_[&view][name] = menu;
1561         return menu;
1562 }
1563
1564 } // namespace frontend
1565 } // namespace lyx
1566
1567 #include "Menus_moc.cpp"