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