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