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