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