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