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