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