]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
fix some memory leaks
[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/assert.h"
49 #include "support/convert.h"
50 #include "support/debug.h"
51 #include "support/filetools.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h"
54
55 #include <QCursor>
56 #include <QHash>
57 #include <QList>
58 #include <QMenuBar>
59 #include <QString>
60
61 #include <boost/shared_ptr.hpp>
62
63 #include <algorithm>
64 #include <ostream>
65 #include <vector>
66
67 using namespace std;
68 using namespace lyx::support;
69
70
71 namespace lyx {
72 namespace frontend {
73
74 namespace {
75
76 // MacOSX specific stuff is at the end.
77
78 class MenuDefinition;
79
80 ///
81 class MenuItem {
82 public:
83         /// The type of elements that can be in a menu
84         enum Kind {
85                 ///
86                 Command,
87                 ///
88                 Submenu,
89                 ///
90                 Separator,
91                 /** This is the list of last opened file,
92                     typically for the File menu. */
93                 Lastfiles,
94                 /** This is the list of opened Documents,
95                     typically for the Documents menu. */
96                 Documents,
97                 /** This is the bookmarks */
98                 Bookmarks,
99                 ///
100                 Toc,
101                 /** This is a list of viewable formats
102                     typically for the File->View menu. */
103                 ViewFormats,
104                 /** This is a list of updatable formats
105                     typically for the File->Update menu. */
106                 UpdateFormats,
107                 /** This is a list of exportable formats
108                     typically for the File->Export menu. */
109                 ExportFormats,
110                 /** This is a list of importable formats
111                     typically for the File->Export menu. */
112                 ImportFormats,
113                 /** This is the list of elements available
114                  * for insertion into document. */
115                 CharStyles,
116                 /** This is the list of user-configurable
117                 insets to insert into document */
118                 Custom,
119                 /** This is the list of XML elements to
120                 insert into the document */
121                 Elements,
122                 /** This is the list of floats that we can
123                     insert a list for. */
124                 FloatListInsert,
125                 /** This is the list of floats that we can
126                     insert. */
127                 FloatInsert,
128                 /** This is the list of selections that can
129                     be pasted. */
130                 PasteRecent,
131                 /** toolbars */
132                 Toolbars,
133                 /** Available branches in document */
134                 Branches
135         };
136
137         explicit MenuItem(Kind kind) : kind_(kind), optional_(false) {}
138
139         MenuItem(Kind kind,
140                  QString const & label,
141                  QString const & submenu = QString(),
142                  bool optional = false)
143                 : kind_(kind), label_(label), submenuname_(submenu), optional_(optional)
144         {
145                 LASSERT(kind == Submenu, /**/);
146         }
147
148         MenuItem(Kind kind,
149                  QString const & label,
150                  FuncRequest const & func,
151                  bool optional = false)
152                 : kind_(kind), label_(label), func_(func), optional_(optional)
153         {
154                 func_.origin = FuncRequest::MENU;
155         }
156
157         // boost::shared_ptr<MenuDefinition> needs this apprently...
158         ~MenuItem() {}
159
160         /// The label of a given menuitem
161         QString label() const { return label_.split('|')[0]; }
162
163         /// The keyboard shortcut (usually underlined in the entry)
164         QString shortcut() const
165         {
166                 return label_.contains('|') ? label_.split('|')[1] : QString();
167         }
168         /// The complete label, with label and shortcut separated by a '|'
169         QString fulllabel() const { return label_;}
170         /// The kind of entry
171         Kind kind() const { return kind_; }
172         /// the action (if relevant)
173         FuncRequest const & func() const { return func_; }
174         /// returns true if the entry should be ommited when disabled
175         bool optional() const { return optional_; }
176         /// returns the status of the lfun associated with this entry
177         FuncStatus const & status() const { return status_; }
178         /// returns the status of the lfun associated with this entry
179         FuncStatus & status() { return status_; }
180         /// returns the status of the lfun associated with this entry
181         void status(FuncStatus const & status) { status_ = status; }
182
183         ///returns the binding associated to this action.
184         QString binding() const
185         {
186                 if (kind_ != Command)
187                         return QString();
188                 // Get the keys bound to this action, but keep only the
189                 // first one later
190                 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
191                 if (bindings.size())
192                         return toqstr(bindings.begin()->print(KeySequence::ForGui));
193
194                 LYXERR(Debug::KBMAP, "No binding for "
195                         << lyxaction.getActionName(func_.action)
196                         << '(' << func_.argument() << ')');
197                 return QString();
198         }
199
200         /// the description of the  submenu (if relevant)
201         QString const & submenuname() const { return submenuname_; }
202         /// set the description of the  submenu
203         void submenuname(QString const & name) { submenuname_ = name; }
204         ///
205         bool hasSubmenu() const { return submenu_.isEmpty(); }
206         ///
207         MenuDefinition const & submenu() const { return submenu_.at(0); }
208         MenuDefinition & submenu() { return submenu_[0]; }
209         ///
210         void setSubmenu(MenuDefinition const & menu)
211         {
212                 submenu_.clear();
213                 submenu_.append(menu);
214         }
215
216 private:
217         ///
218         Kind kind_;
219         ///
220         QString label_;
221         ///
222         FuncRequest func_;
223         ///
224         QString submenuname_;
225         ///
226         bool optional_;
227         ///
228         FuncStatus status_;
229         /// contains 0 or 1 item.
230         QList<MenuDefinition> submenu_;
231 };
232
233 ///
234 class MenuDefinition {
235 public:
236         ///
237         typedef std::vector<MenuItem> ItemList;
238         ///
239         typedef ItemList::const_iterator const_iterator;
240         ///
241         explicit MenuDefinition(QString const & name = QString()) : name_(name) {}
242
243         ///
244         void read(Lexer &);
245         ///
246         QString const & name() const { return name_; }
247         ///
248         bool empty() const { return items_.empty(); }
249         /// Clear the menu content.
250         void clear() { items_.clear(); }
251         ///
252         size_t size() const { return items_.size(); }
253         ///
254         MenuItem const & operator[](size_t) const;
255         ///
256         const_iterator begin() const { return items_.begin(); }
257         ///
258         const_iterator end() const { return items_.end(); }
259         
260         // search for func in this menu iteratively, and put menu
261         // names in a stack.
262         bool searchMenu(FuncRequest const & func, std::vector<docstring> & names)
263                 const;
264         ///
265         bool hasFunc(FuncRequest const &) const;
266         /// Add the menu item unconditionally
267         void add(MenuItem const & item) { items_.push_back(item); }
268         /// Checks the associated FuncRequest status before adding the
269         /// menu item.
270         void addWithStatusCheck(MenuItem const &);
271         // Check whether the menu shortcuts are unique
272         void checkShortcuts() const;
273         ///
274         void expandLastfiles();
275         void expandDocuments();
276         void expandBookmarks();
277         void expandFormats(MenuItem::Kind kind, Buffer const * buf);
278         void expandFloatListInsert(Buffer const * buf);
279         void expandFloatInsert(Buffer const * buf);
280         void expandFlexInsert(Buffer const * buf, std::string s);
281         void expandToc2(Toc const & toc_list, size_t from, size_t to, int depth);
282         void expandToc(Buffer const * buf);
283         void expandPasteRecent();
284         void expandToolbars();
285         void expandBranches(Buffer const * buf);
286         ///
287         ItemList items_;
288         ///
289         QString name_;
290 };
291
292
293 /// Helper for std::find_if
294 class MenuNamesEqual
295 {
296 public:
297         MenuNamesEqual(QString const & name) : name_(name) {}
298         bool operator()(MenuDefinition const & menu) const { return menu.name() == name_; }
299 private:
300         QString name_;
301 };
302
303
304 ///
305 typedef std::vector<MenuDefinition> MenuList;
306 ///
307 typedef MenuList::const_iterator const_iterator;
308 ///
309 typedef MenuList::iterator iterator;
310
311 /////////////////////////////////////////////////////////////////////
312 // MenuDefinition implementation
313 /////////////////////////////////////////////////////////////////////
314
315 void MenuDefinition::addWithStatusCheck(MenuItem const & i)
316 {
317         switch (i.kind()) {
318
319         case MenuItem::Command: {
320                 FuncStatus status = lyx::getStatus(i.func());
321                 if (status.unknown() || (!status.enabled() && i.optional()))
322                         break;
323                 items_.push_back(i);
324                 items_.back().status(status);
325                 break;
326         }
327
328         case MenuItem::Submenu: {
329                 if (i.hasSubmenu()) {
330                         bool enabled = false;
331                         for (const_iterator cit = i.submenu().begin();
332                              cit != i.submenu().end(); ++cit) {
333                                 if ((cit->kind() == MenuItem::Command
334                                      || cit->kind() == MenuItem::Submenu)
335                                     && cit->status().enabled()) {
336                                         enabled = true;
337                                         break;
338                                 }
339                         }
340                         if (enabled || !i.optional()) {
341                                 items_.push_back(i);
342                                 items_.back().status().enabled(enabled);
343                         }
344                 }
345                 else
346                         items_.push_back(i);
347                 break;
348         }
349
350         case MenuItem::Separator:
351                 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
352                         items_.push_back(i);
353                 break;
354
355         default:
356                 items_.push_back(i);
357         }
358 }
359
360
361 void MenuDefinition::read(Lexer & lex)
362 {
363         enum {
364                 md_item = 1,
365                 md_branches,
366                 md_documents,
367                 md_bookmarks,
368                 md_charstyles,
369                 md_custom,
370                 md_elements,
371                 md_endmenu,
372                 md_exportformats,
373                 md_importformats,
374                 md_lastfiles,
375                 md_optitem,
376                 md_optsubmenu,
377                 md_separator,
378                 md_submenu,
379                 md_toc,
380                 md_updateformats,
381                 md_viewformats,
382                 md_floatlistinsert,
383                 md_floatinsert,
384                 md_pasterecent,
385                 md_toolbars
386         };
387
388         LexerKeyword menutags[] = {
389                 { "bookmarks", md_bookmarks },
390                 { "branches", md_branches },
391                 { "charstyles", md_charstyles },
392                 { "custom", md_custom },
393                 { "documents", md_documents },
394                 { "elements", md_elements },
395                 { "end", md_endmenu },
396                 { "exportformats", md_exportformats },
397                 { "floatinsert", md_floatinsert },
398                 { "floatlistinsert", md_floatlistinsert },
399                 { "importformats", md_importformats },
400                 { "item", md_item },
401                 { "lastfiles", md_lastfiles },
402                 { "optitem", md_optitem },
403                 { "optsubmenu", md_optsubmenu },
404                 { "pasterecent", md_pasterecent },
405                 { "separator", md_separator },
406                 { "submenu", md_submenu },
407                 { "toc", md_toc },
408                 { "toolbars", md_toolbars },
409                 { "updateformats", md_updateformats },
410                 { "viewformats", md_viewformats }
411         };
412
413         lex.pushTable(menutags);
414         lex.setContext("MenuDefinition::read: ");
415
416         bool quit = false;
417         bool optional = false;
418
419         while (lex.isOK() && !quit) {
420                 switch (lex.lex()) {
421                 case md_optitem:
422                         optional = true;
423                         // fallback to md_item
424                 case md_item: {
425                         lex.next(true);
426                         docstring const name = translateIfPossible(lex.getDocString());
427                         lex.next(true);
428                         string const command = lex.getString();
429                         FuncRequest func = lyxaction.lookupFunc(command);
430                         add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
431                         optional = false;
432                         break;
433                 }
434
435                 case md_separator:
436                         add(MenuItem(MenuItem::Separator));
437                         break;
438
439                 case md_lastfiles:
440                         add(MenuItem(MenuItem::Lastfiles));
441                         break;
442
443                 case md_charstyles:
444                         add(MenuItem(MenuItem::CharStyles));
445                         break;
446
447                 case md_custom:
448                         add(MenuItem(MenuItem::Custom));
449                         break;
450
451                 case md_elements:
452                         add(MenuItem(MenuItem::Elements));
453                         break;
454
455                 case md_documents:
456                         add(MenuItem(MenuItem::Documents));
457                         break;
458
459                 case md_bookmarks:
460                         add(MenuItem(MenuItem::Bookmarks));
461                         break;
462
463                 case md_toc:
464                         add(MenuItem(MenuItem::Toc));
465                         break;
466
467                 case md_viewformats:
468                         add(MenuItem(MenuItem::ViewFormats));
469                         break;
470
471                 case md_updateformats:
472                         add(MenuItem(MenuItem::UpdateFormats));
473                         break;
474
475                 case md_exportformats:
476                         add(MenuItem(MenuItem::ExportFormats));
477                         break;
478
479                 case md_importformats:
480                         add(MenuItem(MenuItem::ImportFormats));
481                         break;
482
483                 case md_floatlistinsert:
484                         add(MenuItem(MenuItem::FloatListInsert));
485                         break;
486
487                 case md_floatinsert:
488                         add(MenuItem(MenuItem::FloatInsert));
489                         break;
490
491                 case md_pasterecent:
492                         add(MenuItem(MenuItem::PasteRecent));
493                         break;
494
495                 case md_toolbars:
496                         add(MenuItem(MenuItem::Toolbars));
497                         break;
498
499                 case md_branches:
500                         add(MenuItem(MenuItem::Branches));
501                         break;
502
503                 case md_optsubmenu:
504                         optional = true;
505                         // fallback to md_submenu
506                 case md_submenu: {
507                         lex.next(true);
508                         docstring const mlabel = translateIfPossible(lex.getDocString());
509                         lex.next(true);
510                         docstring const mname = lex.getDocString();
511                         add(MenuItem(MenuItem::Submenu,
512                                 toqstr(mlabel), toqstr(mname), optional));
513                         optional = false;
514                         break;
515                 }
516
517                 case md_endmenu:
518                         quit = true;
519                         break;
520
521                 default:
522                         lex.printError("Unknown menu tag");
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                         LASSERT(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                         // FIXME: the listing navigate menu causes a crash for unknown
927                         // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
928                         // This is a temporary fix:
929                         //label = qt_("List of Listings");
930                         continue;
931                 }
932                 else if (cit->first == "marginalnote")
933                         label = qt_("List of Marginal notes");
934                 else if (cit->first == "note")
935                         label = qt_("List of Notes");
936                 else if (cit->first == "footnote")
937                         label = qt_("List of Foot notes");
938                 else if (cit->first == "label")
939                         label = qt_("Labels and References");
940                 else if (cit->first == "citation")
941                         label = qt_("List of Citations");
942                 else
943                         // This should not happen unless the entry is missing above.
944                         label = qt_("Other floats: ") + toqstr(cit->first);
945
946                 MenuDefinition submenu;
947
948                 if (cit->second.size() >= 30) {
949                         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
950                         submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
951                 } else {
952                         TocIterator ccit = cit->second.begin();
953                         TocIterator eend = cit->second.end();
954                         for (; ccit != eend; ++ccit) {
955                                 QString const label = limitStringLength(ccit->str());
956                                 submenu.add(MenuItem(MenuItem::Command, label,
957                                         FuncRequest(ccit->action())));
958                         }
959                 }
960
961                 MenuItem item(MenuItem::Submenu, label);
962                 item.setSubmenu(submenu);
963                 if (in_other_list)
964                         other_lists.add(item);
965                 else {
966                         item.setSubmenu(submenu);
967                         add(item);
968                 }
969         }
970         if (!other_lists.empty()) {
971                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
972                 item.setSubmenu(other_lists);
973                 add(item);
974         }
975
976
977         // Handle normal TOC
978         cit = toc_list.find("tableofcontents");
979         if (cit == end) {
980                 addWithStatusCheck(MenuItem(MenuItem::Command,
981                                     qt_("No Table of contents"),
982                                     FuncRequest()));
983         } else {
984                 expandToc2(cit->second, 0, cit->second.size(), 0);
985         }
986 }
987
988
989 void MenuDefinition::expandPasteRecent()
990 {
991         vector<docstring> const sel = cap::availableSelections();
992
993         vector<docstring>::const_iterator cit = sel.begin();
994         vector<docstring>::const_iterator end = sel.end();
995
996         for (unsigned int index = 0; cit != end; ++cit, ++index) {
997                 add(MenuItem(MenuItem::Command, toqstr(*cit),
998                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
999         }
1000 }
1001
1002
1003 void MenuDefinition::expandToolbars()
1004 {
1005         //
1006         // extracts the toolbars from the backend
1007         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1008         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1009
1010         for (; cit != end; ++cit) {
1011                 QString label = qt_(cit->gui_name);
1012                 // frontends are not supposed to turn on/off toolbars,
1013                 // if they cannot update ToolbarBackend::flags. That
1014                 // is to say, ToolbarsBackend::flags should reflect
1015                 // the true state of toolbars.
1016                 //
1017                 // menu is displayed as
1018                 //       on/off review
1019                 // and
1020                 //              review (auto)
1021                 // in the case of auto.
1022                 if (cit->flags & ToolbarInfo::AUTO)
1023                         label += qt_(" (auto)");
1024                 add(MenuItem(MenuItem::Command, label,
1025                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1026         }
1027 }
1028
1029
1030 void MenuDefinition::expandBranches(Buffer const * buf)
1031 {
1032         if (!buf) {
1033                 add(MenuItem(MenuItem::Command,
1034                                     qt_("No Document Open!"),
1035                                     FuncRequest(LFUN_NOACTION)));
1036                 return;
1037         }
1038
1039         BufferParams const & params = buf->masterBuffer()->params();
1040         if (params.branchlist().empty()) {
1041                 add(MenuItem(MenuItem::Command,
1042                                     qt_("No Branch in Document!"),
1043                                     FuncRequest(LFUN_NOACTION)));
1044                 return;
1045         }
1046
1047         BranchList::const_iterator cit = params.branchlist().begin();
1048         BranchList::const_iterator end = params.branchlist().end();
1049
1050         for (int ii = 1; cit != end; ++cit, ++ii) {
1051                 docstring label = cit->getBranch();
1052                 if (ii < 10)
1053                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1054                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1055                                     FuncRequest(LFUN_BRANCH_INSERT,
1056                                                 cit->getBranch())));
1057         }
1058 }
1059
1060 } // namespace anon
1061
1062
1063 /////////////////////////////////////////////////////////////////////
1064 // Menu::Impl definition and implementation
1065 /////////////////////////////////////////////////////////////////////
1066
1067 struct Menu::Impl
1068 {
1069         /// populates the menu or one of its submenu
1070         /// This is used as a recursive function
1071         void populate(QMenu & qMenu, MenuDefinition const & menu);
1072
1073         /// Only needed for top level menus.
1074         MenuDefinition * top_level_menu;
1075         /// our owning view
1076         GuiView * view;
1077         /// the name of this menu
1078         QString name;
1079 };
1080
1081
1082
1083 /// Get a MenuDefinition item label from the menu backend
1084 static QString label(MenuItem const & mi)
1085 {
1086         QString label = mi.label();
1087         label.replace("&", "&&");
1088
1089         QString shortcut = mi.shortcut();
1090         if (!shortcut.isEmpty()) {
1091                 int pos = label.indexOf(shortcut);
1092                 if (pos != -1)
1093                         //label.insert(pos, 1, char_type('&'));
1094                         label.replace(pos, 0, "&");
1095         }
1096
1097         QString const binding = mi.binding();
1098         if (!binding.isEmpty())
1099                 label += '\t' + binding;
1100
1101         return label;
1102 }
1103
1104 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1105 {
1106         LYXERR(Debug::GUI, "populating menu " << fromqstr(menu.name()));
1107         if (menu.size() == 0) {
1108                 LYXERR(Debug::GUI, "\tERROR: empty menu " << fromqstr(menu.name()));
1109                 return;
1110         }
1111         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1112         MenuDefinition::const_iterator m = menu.begin();
1113         MenuDefinition::const_iterator end = menu.end();
1114         for (; m != end; ++m) {
1115                 if (m->kind() == MenuItem::Separator)
1116                         qMenu.addSeparator();
1117                 else if (m->kind() == MenuItem::Submenu) {
1118                         QMenu * subMenu = qMenu.addMenu(label(*m));
1119                         populate(*subMenu, m->submenu());
1120                 } else {
1121                         // we have a MenuItem::Command
1122                         qMenu.addAction(new Action(view, QIcon(), label(*m), 
1123                                 m->func(), QString(), &qMenu));
1124                 }
1125         }
1126 }
1127
1128 /////////////////////////////////////////////////////////////////////
1129 // Menu implementation
1130 /////////////////////////////////////////////////////////////////////
1131
1132 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1133 : d(new Menu::Impl)
1134 {
1135         d->top_level_menu = top_level? new MenuDefinition : 0;
1136         d->view = gv;
1137         d->name = name;
1138         setTitle(name);
1139         if (d->top_level_menu)
1140                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1141 }
1142
1143
1144 Menu::~Menu()
1145 {
1146         delete d->top_level_menu;
1147         delete d;
1148 }
1149
1150
1151 void Menu::updateView()
1152 {
1153         guiApp->menus().updateMenu(this);
1154 }
1155
1156
1157 /////////////////////////////////////////////////////////////////////
1158 // Menus::Impl definition and implementation
1159 /////////////////////////////////////////////////////////////////////
1160
1161 struct Menus::Impl {
1162         ///
1163         bool hasMenu(QString const &) const;
1164         ///
1165         MenuDefinition & getMenu(QString const &);
1166         ///
1167         MenuDefinition const & getMenu(QString const &) const;
1168
1169         /// Expands some special entries of the menu
1170         /** The entries with the following kind are expanded to a
1171             sequence of Command MenuItems: Lastfiles, Documents,
1172             ViewFormats, ExportFormats, UpdateFormats, Branches
1173         */
1174         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1175                 Buffer const *) const;
1176
1177         /// Initialize specific MACOS X menubar
1178         void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1179
1180         /// Mac special menu.
1181         /** This defines a menu whose entries list the FuncRequests
1182             that will be removed by expand() in other menus. This is
1183             used by the Qt/Mac code
1184         */
1185         MenuDefinition specialmenu_;
1186
1187         ///
1188         MenuList menulist_;
1189         ///
1190         MenuDefinition menubar_;
1191
1192         typedef QMap<GuiView *, QHash<QString, boost::shared_ptr<Menu> > > NameMap;
1193
1194         /// name to menu for \c menu() method.
1195         NameMap name_map_;
1196 };
1197
1198 /*
1199   Here is what the Qt documentation says about how a menubar is chosen:
1200
1201      1) If the window has a QMenuBar then it is used. 2) If the window
1202      is a modal then its menubar is used. If no menubar is specified
1203      then a default menubar is used (as documented below) 3) If the
1204      window has no parent then the default menubar is used (as
1205      documented below).
1206
1207      The above 3 steps are applied all the way up the parent window
1208      chain until one of the above are satisifed. If all else fails a
1209      default menubar will be created, the default menubar on Qt/Mac is
1210      an empty menubar, however you can create a different default
1211      menubar by creating a parentless QMenuBar, the first one created
1212      will thus be designated the default menubar, and will be used
1213      whenever a default menubar is needed.
1214
1215   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1216   that this menubar will be used also when one of LyX' dialogs has
1217   focus. (JMarc)
1218 */
1219 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1220 {
1221         /* Since Qt 4.2, the qt/mac menu code has special code for
1222            specifying the role of a menu entry. However, it does not
1223            work very well with our scheme of creating menus on demand,
1224            and therefore we need to put these entries in a special
1225            invisible menu. (JMarc)
1226         */
1227
1228         /* The entries of our special mac menu. If we add support for
1229          * special entries in Menus, we could imagine something
1230          * like
1231          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
1232          * and therefore avoid hardcoding. I am not sure it is worth
1233          * the hassle, though. (JMarc)
1234          */
1235         struct MacMenuEntry {
1236                 FuncCode action;
1237                 char const * arg;
1238                 char const * label;
1239                 QAction::MenuRole role;
1240         };
1241
1242         MacMenuEntry entries[] = {
1243                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1244                  QAction::AboutRole},
1245                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1246                  QAction::PreferencesRole},
1247                 {LFUN_RECONFIGURE, "", "Reconfigure",
1248                  QAction::ApplicationSpecificRole},
1249                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1250         };
1251         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1252
1253         // the special menu for Menus. Fill it up only once.
1254         if (specialmenu_.size() == 0) {
1255                 for (size_t i = 0 ; i < num_entries ; ++i) {
1256                         FuncRequest const func(entries[i].action,
1257                                 from_utf8(entries[i].arg));
1258                         specialmenu_.add(MenuItem(MenuItem::Command, 
1259                                 entries[i].label, func));
1260                 }
1261         }
1262         
1263         // add the entries to a QMenu that will eventually be empty
1264         // and therefore invisible.
1265         QMenu * qMenu = qmb->addMenu("special");
1266         MenuDefinition::const_iterator cit = specialmenu_.begin();
1267         MenuDefinition::const_iterator end = specialmenu_.end();
1268         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1269                 Action * action = new Action(view, QIcon(), cit->label(),
1270                         cit->func(), QString(), qMenu);
1271                 action->setMenuRole(entries[i].role);
1272                 qMenu->addAction(action);
1273         }
1274 }
1275
1276
1277 void Menus::Impl::expand(MenuDefinition const & frommenu,
1278         MenuDefinition & tomenu, Buffer const * buf) const
1279 {
1280         if (!tomenu.empty())
1281                 tomenu.clear();
1282
1283         for (MenuDefinition::const_iterator cit = frommenu.begin();
1284              cit != frommenu.end() ; ++cit) {
1285                 switch (cit->kind()) {
1286                 case MenuItem::Lastfiles:
1287                         tomenu.expandLastfiles();
1288                         break;
1289
1290                 case MenuItem::Documents:
1291                         tomenu.expandDocuments();
1292                         break;
1293
1294                 case MenuItem::Bookmarks:
1295                         tomenu.expandBookmarks();
1296                         break;
1297
1298                 case MenuItem::ImportFormats:
1299                 case MenuItem::ViewFormats:
1300                 case MenuItem::UpdateFormats:
1301                 case MenuItem::ExportFormats:
1302                         tomenu.expandFormats(cit->kind(), buf);
1303                         break;
1304
1305                 case MenuItem::CharStyles:
1306                         tomenu.expandFlexInsert(buf, "charstyle");
1307                         break;
1308
1309                 case MenuItem::Custom:
1310                         tomenu.expandFlexInsert(buf, "custom");
1311                         break;
1312
1313                 case MenuItem::Elements:
1314                         tomenu.expandFlexInsert(buf, "element");
1315                         break;
1316
1317                 case MenuItem::FloatListInsert:
1318                         tomenu.expandFloatListInsert(buf);
1319                         break;
1320
1321                 case MenuItem::FloatInsert:
1322                         tomenu.expandFloatInsert(buf);
1323                         break;
1324
1325                 case MenuItem::PasteRecent:
1326                         tomenu.expandPasteRecent();
1327                         break;
1328
1329                 case MenuItem::Toolbars:
1330                         tomenu.expandToolbars();
1331                         break;
1332
1333                 case MenuItem::Branches:
1334                         tomenu.expandBranches(buf);
1335                         break;
1336
1337                 case MenuItem::Toc:
1338                         tomenu.expandToc(buf);
1339                         break;
1340
1341                 case MenuItem::Submenu: {
1342                         MenuItem item(*cit);
1343                         item.setSubmenu(MenuDefinition(cit->submenuname()));
1344                         expand(getMenu(cit->submenuname()), item.submenu(), buf);
1345                         tomenu.addWithStatusCheck(item);
1346                 }
1347                 break;
1348
1349                 case MenuItem::Separator:
1350                         tomenu.addWithStatusCheck(*cit);
1351                         break;
1352
1353                 case MenuItem::Command:
1354                         if (!specialmenu_.hasFunc(cit->func()))
1355                                 tomenu.addWithStatusCheck(*cit);
1356                 }
1357         }
1358
1359         // we do not want the menu to end with a separator
1360         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1361                 tomenu.items_.pop_back();
1362
1363         // Check whether the shortcuts are unique
1364         tomenu.checkShortcuts();
1365 }
1366
1367
1368 bool Menus::Impl::hasMenu(QString const & name) const
1369 {
1370         return find_if(menulist_.begin(), menulist_.end(),
1371                 MenuNamesEqual(name)) != menulist_.end();
1372 }
1373
1374
1375 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1376 {
1377         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1378                 MenuNamesEqual(name));
1379         if (cit == menulist_.end())
1380                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1381         LASSERT(cit != menulist_.end(), /**/);
1382         return (*cit);
1383 }
1384
1385
1386 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1387 {
1388         iterator it = find_if(menulist_.begin(), menulist_.end(),
1389                 MenuNamesEqual(name));
1390         if (it == menulist_.end())
1391                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1392         LASSERT(it != menulist_.end(), /**/);
1393         return (*it);
1394 }
1395
1396
1397 /////////////////////////////////////////////////////////////////////
1398 //
1399 // Menus 
1400 //
1401 /////////////////////////////////////////////////////////////////////
1402
1403 Menus::Menus() : d(new Impl) {}
1404
1405 Menus::~Menus()
1406 {
1407   delete d;
1408 }
1409
1410 void Menus::read(Lexer & lex)
1411 {
1412         enum {
1413                 md_menu,
1414                 md_menubar,
1415                 md_endmenuset,
1416         };
1417
1418         LexerKeyword menutags[] = {
1419                 { "end", md_endmenuset },
1420                 { "menu", md_menu },
1421                 { "menubar", md_menubar }
1422         };
1423
1424         // consistency check
1425         if (compare_ascii_no_case(lex.getString(), "menuset"))
1426                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1427
1428         lex.pushTable(menutags);
1429         lex.setContext("Menus::read");
1430
1431         bool quit = false;
1432
1433         while (lex.isOK() && !quit) {
1434                 switch (lex.lex()) {
1435                 case md_menubar:
1436                         d->menubar_.read(lex);
1437                         break;
1438                 case md_menu: {
1439                         lex.next(true);
1440                         QString const name = toqstr(lex.getDocString());
1441                         if (d->hasMenu(name))
1442                                 d->getMenu(name).read(lex);
1443                         else {
1444                                 MenuDefinition menu(name);
1445                                 menu.read(lex);
1446                                 d->menulist_.push_back(menu);
1447                         }
1448                         break;
1449                 }
1450                 case md_endmenuset:
1451                         quit = true;
1452                         break;
1453                 default:
1454                         lex.printError("Unknown menu tag");
1455                         break;
1456                 }
1457         }
1458         lex.popTable();
1459 }
1460
1461
1462 bool Menus::searchMenu(FuncRequest const & func,
1463         vector<docstring> & names) const
1464 {
1465         MenuDefinition menu;
1466         d->expand(d->menubar_, menu, 0);
1467         return menu.searchMenu(func, names);
1468 }
1469
1470
1471 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1472 {
1473         if (initial) {
1474 #ifdef Q_WS_MACX
1475                 // setup special mac specific menu item
1476                 d->macxMenuBarInit(view, qmb);
1477 #endif
1478         } else {
1479                 // Clear all menubar contents before filling it.
1480                 qmb->clear();
1481         }
1482
1483         LYXERR(Debug::GUI, "populating menu bar" << fromqstr(d->menubar_.name()));
1484
1485         if (d->menubar_.size() == 0) {
1486                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1487                         << fromqstr(d->menubar_.name()));
1488                 return;
1489         }
1490         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1491
1492         MenuDefinition menu;
1493         Buffer * buf = 0;
1494         if (view)
1495                 buf = view->buffer();
1496         d->expand(d->menubar_, menu, buf);
1497
1498         MenuDefinition::const_iterator m = menu.begin();
1499         MenuDefinition::const_iterator end = menu.end();
1500
1501         for (; m != end; ++m) {
1502
1503                 if (m->kind() != MenuItem::Submenu) {
1504                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
1505                         continue;
1506                 }
1507
1508                 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
1509                         << " is a submenu named " << fromqstr(m->submenuname()));
1510
1511                 QString name = m->submenuname();
1512                 if (!d->hasMenu(name)) {
1513                         LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
1514                                 << " submenu has no menu!");
1515                         continue;
1516                 }
1517
1518                 Menu * menu = new Menu(view, m->submenuname(), true);
1519                 menu->setTitle(label(*m));
1520                 qmb->addMenu(menu);
1521
1522                 d->name_map_[view][name] = boost::shared_ptr<Menu>(menu);
1523         }
1524 }
1525
1526
1527 void Menus::updateMenu(Menu * qmenu)
1528 {
1529         LYXERR(Debug::GUI, "Triggered menu: " << fromqstr(qmenu->d->name));
1530         qmenu->clear();
1531
1532         if (qmenu->d->name.isEmpty())
1533                 return;
1534
1535         // Here, We make sure that theLyXFunc points to the correct LyXView.
1536         theLyXFunc().setLyXView(qmenu->d->view);
1537
1538         if (!d->hasMenu(qmenu->d->name)) {
1539                 qmenu->addAction(qt_("No action defined!"));
1540                 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1541                         << fromqstr(qmenu->d->name));
1542                 return;
1543         }
1544
1545         MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1546         Buffer * buf = 0;
1547         if (qmenu->d->view)
1548                 buf = qmenu->d->view->buffer();
1549         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, buf);
1550         qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1551 }
1552
1553
1554 Menu * Menus::menu(QString const & name, GuiView & view)
1555 {
1556         LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
1557         Menu * menu = d->name_map_[&view].value(name, boost::shared_ptr<Menu>()).get();
1558         if (!menu && !name.startsWith("context-")) {
1559                 LYXERR0("requested context menu not found: " << fromqstr(name));
1560                 return 0;
1561         }
1562
1563         menu = new Menu(&view, name, true);
1564         d->name_map_[&view][name] = boost::shared_ptr<Menu>(menu);
1565         return menu;
1566 }
1567
1568 } // namespace frontend
1569 } // namespace lyx
1570
1571 #include "Menus_moc.cpp"