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