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