]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
cosmetics
[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 <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                         LYXERR0("Menu warning: menu entry \""
569                                << it1->label()
570                                << "\" does not contain shortcut `"
571                                << shortcut << "'." << endl);
572                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
573                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
574                                 LYXERR0("Menu warning: menu entries "
575                                        << '"' << it1->fulllabel()
576                                        << "\" and \"" << 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                                         << m->label() << " name=" << m->submenuname());
599                                 names.pop_back();
600                                 continue;
601                         }
602                         if (m->submenu().searchMenu(func, names))
603                                 return true;
604                         names.pop_back();
605                 }
606         }
607         return false;
608 }
609
610
611 bool compareFormat(Format const * p1, Format const * p2)
612 {
613         return *p1 < *p2;
614 }
615
616
617 QString limitStringLength(docstring const & str)
618 {
619         size_t const max_item_length = 45;
620
621         if (str.size() > max_item_length)
622                 return toqstr(str.substr(0, max_item_length - 3) + "...");
623
624         return toqstr(str);
625 }
626
627
628 void MenuDefinition::expandLastfiles()
629 {
630         LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
631         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
632
633         int ii = 1;
634
635         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
636                 string const file = lfit->absFilename();
637                 QString const label = QString("%1. %2|%3").arg(ii)
638                         .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
639                 add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
640         }
641 }
642
643
644 void MenuDefinition::expandDocuments()
645 {
646         Buffer * first = theBufferList().first();
647         if (first) {
648                 Buffer * b = first;
649                 int ii = 1;
650                 
651                 // We cannot use a for loop as the buffer list cycles.
652                 do {
653                         QString label = toqstr(b->fileName().displayName(20));
654                         if (!b->isClean())
655                                 label += "*";
656                         if (ii < 10)
657                                 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
658                         add(MenuItem(MenuItem::Command, label,
659                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
660                         
661                         b = theBufferList().next(b);
662                         ++ii;
663                 } while (b != first); 
664         } else {
665                 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
666                            FuncRequest(LFUN_NOACTION)));
667         }
668 }
669
670
671 void MenuDefinition::expandBookmarks()
672 {
673         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
674
675         for (size_t i = 1; i <= bm.size(); ++i) {
676                 if (bm.isValid(i)) {
677                         string const file = bm.bookmark(i).filename.absFilename();
678                         QString const label = QString("%1. %2|%3").arg(i)
679                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
680                         add(MenuItem(MenuItem::Command, label,
681                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
682                 }
683         }
684 }
685
686
687 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
688 {
689         if (!buf && kind != MenuItem::ImportFormats) {
690                 add(MenuItem(MenuItem::Command,
691                                     qt_("No Document Open!"),
692                                     FuncRequest(LFUN_NOACTION)));
693                 return;
694         }
695
696         typedef vector<Format const *> Formats;
697         Formats formats;
698         FuncCode action;
699
700         switch (kind) {
701         case MenuItem::ImportFormats:
702                 formats = theConverters().importableFormats();
703                 action = LFUN_BUFFER_IMPORT;
704                 break;
705         case MenuItem::ViewFormats:
706                 formats = buf->exportableFormats(true);
707                 action = LFUN_BUFFER_VIEW;
708                 break;
709         case MenuItem::UpdateFormats:
710                 formats = buf->exportableFormats(true);
711                 action = LFUN_BUFFER_UPDATE;
712                 break;
713         default:
714                 formats = buf->exportableFormats(false);
715                 action = LFUN_BUFFER_EXPORT;
716         }
717         sort(formats.begin(), formats.end(), &compareFormat);
718
719         Formats::const_iterator fit = formats.begin();
720         Formats::const_iterator end = formats.end();
721         for (; fit != end ; ++fit) {
722                 if ((*fit)->dummy())
723                         continue;
724                 QString label = toqstr((*fit)->prettyname());
725                 QString const shortcut = toqstr((*fit)->shortcut());
726
727                 switch (kind) {
728                 case MenuItem::ImportFormats:
729                         // FIXME: This is a hack, we should rather solve
730                         // FIXME: bug 2488 instead.
731                         if ((*fit)->name() == "text")
732                                 label = qt_("Plain Text");
733                         else if ((*fit)->name() == "textparagraph")
734                                 label = qt_("Plain Text, Join Lines");
735                         label += "...";
736                         break;
737                 case MenuItem::ViewFormats:
738                 case MenuItem::ExportFormats:
739                 case MenuItem::UpdateFormats:
740                         if (!(*fit)->documentFormat())
741                                 continue;
742                         break;
743                 default:
744                         LASSERT(false, /**/);
745                         break;
746                 }
747                 // FIXME: if we had proper support for translating the
748                 // format names defined in configure.py, there would
749                 // not be a need to check whether the shortcut is
750                 // correct. If we add it uncondiitonally, it would
751                 // create useless warnings on bad shortcuts
752                 if (!shortcut.isEmpty() && label.contains(shortcut))
753                         label += '|' + shortcut;
754
755                 if (buf)
756                         addWithStatusCheck(MenuItem(MenuItem::Command, label,
757                                 FuncRequest(action, (*fit)->name())));
758                 else
759                         add(MenuItem(MenuItem::Command, label,
760                                 FuncRequest(action, (*fit)->name())));
761         }
762 }
763
764
765 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
766 {
767         if (!buf) {
768                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
769                                     FuncRequest(LFUN_NOACTION)));
770                 return;
771         }
772
773         FloatList const & floats = buf->params().documentClass().floats();
774         FloatList::const_iterator cit = floats.begin();
775         FloatList::const_iterator end = floats.end();
776         for (; cit != end; ++cit) {
777                 addWithStatusCheck(MenuItem(MenuItem::Command,
778                                     qt_(cit->second.listName()),
779                                     FuncRequest(LFUN_FLOAT_LIST,
780                                                 cit->second.type())));
781         }
782 }
783
784
785 void MenuDefinition::expandFloatInsert(Buffer const * buf)
786 {
787         if (!buf) {
788                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
789                                     FuncRequest(LFUN_NOACTION)));
790                 return;
791         }
792
793         FloatList const & floats = buf->params().documentClass().floats();
794         FloatList::const_iterator cit = floats.begin();
795         FloatList::const_iterator end = floats.end();
796         for (; cit != end; ++cit) {
797                 // normal float
798                 QString const label = qt_(cit->second.name());
799                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
800                                     FuncRequest(LFUN_FLOAT_INSERT,
801                                                 cit->second.type())));
802         }
803 }
804
805
806 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
807 {
808         if (!buf) {
809                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
810                                     FuncRequest(LFUN_NOACTION)));
811                 return;
812         }
813         TextClass::InsetLayouts const & insetLayouts =
814                 buf->params().documentClass().insetLayouts();
815         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
816         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
817         for (; cit != end; ++cit) {
818                 docstring const label = cit->first;
819                 if (cit->second.lyxtype() == s)
820                         addWithStatusCheck(MenuItem(MenuItem::Command, 
821                                 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
822                                                 label)));
823         }
824 }
825
826
827 size_t const max_number_of_items = 25;
828
829 void MenuDefinition::expandToc2(Toc const & toc_list,
830                 size_t from, size_t to, int depth)
831 {
832         int shortcut_count = 0;
833
834         // check whether depth is smaller than the smallest depth in toc.
835         int min_depth = 1000;
836         for (size_t i = from; i < to; ++i)
837                 min_depth = min(min_depth, toc_list[i].depth());
838         if (min_depth > depth)
839                 depth = min_depth;
840
841         if (to - from <= max_number_of_items) {
842                 for (size_t i = from; i < to; ++i) {
843                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
844                         label += limitStringLength(toc_list[i].str());
845                         if (toc_list[i].depth() == depth
846                             && shortcut_count < 9) {
847                                 if (label.contains(QString::number(shortcut_count + 1)))
848                                         label += '|' + QString::number(++shortcut_count);
849                         }
850                         add(MenuItem(MenuItem::Command, label,
851                                             FuncRequest(toc_list[i].action())));
852                 }
853         } else {
854                 size_t pos = from;
855                 while (pos < to) {
856                         size_t new_pos = pos + 1;
857                         while (new_pos < to && toc_list[new_pos].depth() > depth)
858                                 ++new_pos;
859
860                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
861                         label += limitStringLength(toc_list[pos].str());
862                         if (toc_list[pos].depth() == depth &&
863                             shortcut_count < 9) {
864                                 if (label.contains(QString::number(shortcut_count + 1)))
865                                         label += '|' + QString::number(++shortcut_count);
866                         }
867                         if (new_pos == pos + 1) {
868                                 add(MenuItem(MenuItem::Command,
869                                                     label, FuncRequest(toc_list[pos].action())));
870                         } else {
871                                 MenuDefinition sub;
872                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
873                                 MenuItem item(MenuItem::Submenu, label);
874                                 item.setSubmenu(sub);
875                                 add(item);
876                         }
877                         pos = new_pos;
878                 }
879         }
880 }
881
882
883 void MenuDefinition::expandToc(Buffer const * buf)
884 {
885         // To make things very cleanly, we would have to pass buf to
886         // all MenuItem constructors and to expandToc2. However, we
887         // know that all the entries in a TOC will be have status_ ==
888         // OK, so we avoid this unnecessary overhead (JMarc)
889
890         if (!buf) {
891                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
892                                     FuncRequest(LFUN_NOACTION)));
893                 return;
894         }
895
896         Buffer* cbuf = const_cast<Buffer*>(buf);
897         cbuf->tocBackend().update();
898         cbuf->structureChanged();
899
900         // Add an entry for the master doc if this is a child doc
901         Buffer const * const master = buf->masterBuffer();
902         if (buf != master) {
903                 ParIterator const pit = par_iterator_begin(master->inset());
904                 string const arg = convert<string>(pit->id());
905                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
906                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
907         }
908
909         MenuDefinition other_lists;
910         
911         FloatList const & floatlist = buf->params().documentClass().floats();
912         TocList const & toc_list = buf->tocBackend().tocs();
913         TocList::const_iterator cit = toc_list.begin();
914         TocList::const_iterator end = toc_list.end();
915         for (; cit != end; ++cit) {
916                 // Handle this later
917                 if (cit->first == "tableofcontents")
918                         continue;
919
920                 string const & floatName = floatlist.getType(cit->first).listName();
921                 QString label;
922                 bool in_other_list = true;
923                 if (!floatName.empty()) {
924                         label = qt_(floatName);
925                         in_other_list = false;
926                 }
927                 else if (cit->first == "child") {
928                         label = qt_("Child Documents");
929                         in_other_list = false;
930                 } else if (cit->first == "graphics")
931                         label = qt_("List of Graphics");
932                 else if (cit->first == "equation")
933                         label = qt_("List of Equations");
934                 else if (cit->first == "index")
935                         label = qt_("List of Indexes");
936                 else if (cit->first == "listing") {
937                         // FIXME: the listing navigate menu causes a crash for unknown
938                         // reason. See http://bugzilla.lyx.org/show_bug.cgi?id=4613
939                         // This is a temporary fix:
940                         //label = qt_("List of Listings");
941                         continue;
942                 }
943                 else if (cit->first == "marginalnote")
944                         label = qt_("List of Marginal notes");
945                 else if (cit->first == "note")
946                         label = qt_("List of Notes");
947                 else if (cit->first == "footnote")
948                         label = qt_("List of Footnotes");
949                 else if (cit->first == "label")
950                         label = qt_("Labels and References");
951                 else if (cit->first == "citation")
952                         label = qt_("List of Citations");
953                 else
954                         // This should not happen unless the entry is missing above.
955                         label = qt_("Other floats: ") + toqstr(cit->first);
956
957                 MenuDefinition submenu;
958
959                 if (cit->second.size() >= 30) {
960                         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
961                         submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
962                 } else {
963                         TocIterator ccit = cit->second.begin();
964                         TocIterator eend = cit->second.end();
965                         for (; ccit != eend; ++ccit) {
966                                 QString const label = limitStringLength(ccit->str());
967                                 submenu.add(MenuItem(MenuItem::Command, label,
968                                         FuncRequest(ccit->action())));
969                         }
970                 }
971
972                 MenuItem item(MenuItem::Submenu, label);
973                 item.setSubmenu(submenu);
974                 if (in_other_list)
975                         other_lists.add(item);
976                 else {
977                         item.setSubmenu(submenu);
978                         add(item);
979                 }
980         }
981         if (!other_lists.empty()) {
982                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
983                 item.setSubmenu(other_lists);
984                 add(item);
985         }
986
987
988         // Handle normal TOC
989         cit = toc_list.find("tableofcontents");
990         if (cit == end) {
991                 addWithStatusCheck(MenuItem(MenuItem::Command,
992                                     qt_("No Table of contents"),
993                                     FuncRequest()));
994         } else {
995                 expandToc2(cit->second, 0, cit->second.size(), 0);
996         }
997 }
998
999
1000 void MenuDefinition::expandPasteRecent()
1001 {
1002         vector<docstring> const sel = cap::availableSelections();
1003
1004         vector<docstring>::const_iterator cit = sel.begin();
1005         vector<docstring>::const_iterator end = sel.end();
1006
1007         for (unsigned int index = 0; cit != end; ++cit, ++index) {
1008                 add(MenuItem(MenuItem::Command, toqstr(*cit),
1009                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1010         }
1011 }
1012
1013
1014 void MenuDefinition::expandToolbars()
1015 {
1016         //
1017         // extracts the toolbars from the backend
1018         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
1019         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
1020
1021         for (; cit != end; ++cit) {
1022                 QString label = qt_(cit->gui_name);
1023                 // frontends are not supposed to turn on/off toolbars,
1024                 // if they cannot update ToolbarBackend::flags. That
1025                 // is to say, ToolbarsBackend::flags should reflect
1026                 // the true state of toolbars.
1027                 //
1028                 // menu is displayed as
1029                 //       on/off review
1030                 // and
1031                 //              review (auto)
1032                 // in the case of auto.
1033                 if (cit->flags & ToolbarInfo::AUTO)
1034                         label += qt_(" (auto)");
1035                 add(MenuItem(MenuItem::Command, label,
1036                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
1037         }
1038 }
1039
1040
1041 void MenuDefinition::expandBranches(Buffer const * buf)
1042 {
1043         if (!buf) {
1044                 add(MenuItem(MenuItem::Command,
1045                                     qt_("No Document Open!"),
1046                                     FuncRequest(LFUN_NOACTION)));
1047                 return;
1048         }
1049
1050         BufferParams const & params = buf->masterBuffer()->params();
1051         if (params.branchlist().empty()) {
1052                 add(MenuItem(MenuItem::Command,
1053                                     qt_("No Branch in Document!"),
1054                                     FuncRequest(LFUN_NOACTION)));
1055                 return;
1056         }
1057
1058         BranchList::const_iterator cit = params.branchlist().begin();
1059         BranchList::const_iterator end = params.branchlist().end();
1060
1061         for (int ii = 1; cit != end; ++cit, ++ii) {
1062                 docstring label = cit->getBranch();
1063                 if (ii < 10)
1064                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1065                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1066                                     FuncRequest(LFUN_BRANCH_INSERT,
1067                                                 cit->getBranch())));
1068         }
1069 }
1070
1071
1072 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1073 {
1074         if (!bv) {
1075                 add(MenuItem(MenuItem::Command,
1076                                     qt_("No Document Open!"),
1077                                     FuncRequest(LFUN_NOACTION)));
1078                 return;
1079         }
1080
1081         Inset const * inset = bv->cursor().nextInset();
1082         if (!inset || inset->lyxCode() != CITE_CODE) {
1083                 add(MenuItem(MenuItem::Command,
1084                                     qt_("No Citation in Scope!"),
1085                                     FuncRequest(LFUN_NOACTION)));
1086                 return;
1087         }
1088         InsetCommand const * citinset =
1089                                 static_cast<InsetCommand const *>(inset);
1090         
1091         Buffer const * buf = &bv->buffer();
1092         docstring key = citinset->getParam("key");
1093         // we can only handle one key currently
1094         if (contains(key, ','))
1095                 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1096
1097         vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1098         vector<docstring> citeStrings =
1099                 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1100
1101         vector<docstring>::const_iterator cit = citeStrings.begin();
1102         vector<docstring>::const_iterator end = citeStrings.end();
1103
1104         for (int ii = 1; cit != end; ++cit, ++ii) {
1105                 docstring label = *cit;
1106                 CitationStyle cs;
1107                 CiteStyle cst = citeStyleList[ii - 1];
1108                 cs.style = cst;
1109                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1110                                     FuncRequest(LFUN_NEXT_INSET_MODIFY,
1111                                                 "changetype " + from_utf8(citationStyleToString(cs)))));
1112         }
1113 }
1114
1115 } // namespace anon
1116
1117
1118 /////////////////////////////////////////////////////////////////////
1119 // Menu::Impl definition and implementation
1120 /////////////////////////////////////////////////////////////////////
1121
1122 struct Menu::Impl
1123 {
1124         /// populates the menu or one of its submenu
1125         /// This is used as a recursive function
1126         void populate(QMenu & qMenu, MenuDefinition const & menu);
1127
1128         /// Only needed for top level menus.
1129         MenuDefinition * top_level_menu;
1130         /// our owning view
1131         GuiView * view;
1132         /// the name of this menu
1133         QString name;
1134 };
1135
1136
1137
1138 /// Get a MenuDefinition item label from the menu backend
1139 static QString label(MenuItem const & mi)
1140 {
1141         QString label = mi.label();
1142         label.replace("&", "&&");
1143
1144         QString shortcut = mi.shortcut();
1145         if (!shortcut.isEmpty()) {
1146                 int pos = label.indexOf(shortcut);
1147                 if (pos != -1)
1148                         //label.insert(pos, 1, char_type('&'));
1149                         label.replace(pos, 0, "&");
1150         }
1151
1152         QString const binding = mi.binding();
1153         if (!binding.isEmpty())
1154                 label += '\t' + binding;
1155
1156         return label;
1157 }
1158
1159 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1160 {
1161         LYXERR(Debug::GUI, "populating menu " << menu.name());
1162         if (menu.size() == 0) {
1163                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1164                 return;
1165         }
1166         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1167         MenuDefinition::const_iterator m = menu.begin();
1168         MenuDefinition::const_iterator end = menu.end();
1169         for (; m != end; ++m) {
1170                 if (m->kind() == MenuItem::Separator)
1171                         qMenu.addSeparator();
1172                 else if (m->kind() == MenuItem::Submenu) {
1173                         QMenu * subMenu = qMenu.addMenu(label(*m));
1174                         populate(*subMenu, m->submenu());
1175                 } else {
1176                         // we have a MenuItem::Command
1177                         qMenu.addAction(new Action(view, QIcon(), label(*m), 
1178                                 m->func(), QString(), &qMenu));
1179                 }
1180         }
1181 }
1182
1183 /////////////////////////////////////////////////////////////////////
1184 // Menu implementation
1185 /////////////////////////////////////////////////////////////////////
1186
1187 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1188 : QMenu(gv), d(new Menu::Impl)
1189 {
1190         d->top_level_menu = top_level? new MenuDefinition : 0;
1191         d->view = gv;
1192         d->name = name;
1193         setTitle(name);
1194         if (d->top_level_menu)
1195                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1196 }
1197
1198
1199 Menu::~Menu()
1200 {
1201         delete d->top_level_menu;
1202         delete d;
1203 }
1204
1205
1206 void Menu::updateView()
1207 {
1208         guiApp->menus().updateMenu(this);
1209 }
1210
1211
1212 /////////////////////////////////////////////////////////////////////
1213 // Menus::Impl definition and implementation
1214 /////////////////////////////////////////////////////////////////////
1215
1216 struct Menus::Impl {
1217         ///
1218         bool hasMenu(QString const &) const;
1219         ///
1220         MenuDefinition & getMenu(QString const &);
1221         ///
1222         MenuDefinition const & getMenu(QString const &) const;
1223
1224         /// Expands some special entries of the menu
1225         /** The entries with the following kind are expanded to a
1226             sequence of Command MenuItems: Lastfiles, Documents,
1227             ViewFormats, ExportFormats, UpdateFormats, Branches
1228         */
1229         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1230                 BufferView const *) const;
1231
1232         /// Initialize specific MACOS X menubar
1233         void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1234
1235         /// Mac special menu.
1236         /** This defines a menu whose entries list the FuncRequests
1237             that will be removed by expand() in other menus. This is
1238             used by the Qt/Mac code
1239         */
1240         MenuDefinition specialmenu_;
1241
1242         ///
1243         MenuList menulist_;
1244         ///
1245         MenuDefinition menubar_;
1246
1247         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1248
1249         /// name to menu for \c menu() method.
1250         NameMap name_map_;
1251 };
1252
1253 /*
1254   Here is what the Qt documentation says about how a menubar is chosen:
1255
1256      1) If the window has a QMenuBar then it is used. 2) If the window
1257      is a modal then its menubar is used. If no menubar is specified
1258      then a default menubar is used (as documented below) 3) If the
1259      window has no parent then the default menubar is used (as
1260      documented below).
1261
1262      The above 3 steps are applied all the way up the parent window
1263      chain until one of the above are satisifed. If all else fails a
1264      default menubar will be created, the default menubar on Qt/Mac is
1265      an empty menubar, however you can create a different default
1266      menubar by creating a parentless QMenuBar, the first one created
1267      will thus be designated the default menubar, and will be used
1268      whenever a default menubar is needed.
1269
1270   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1271   that this menubar will be used also when one of LyX' dialogs has
1272   focus. (JMarc)
1273 */
1274 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1275 {
1276         /* Since Qt 4.2, the qt/mac menu code has special code for
1277            specifying the role of a menu entry. However, it does not
1278            work very well with our scheme of creating menus on demand,
1279            and therefore we need to put these entries in a special
1280            invisible menu. (JMarc)
1281         */
1282
1283         /* The entries of our special mac menu. If we add support for
1284          * special entries in Menus, we could imagine something
1285          * like
1286          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
1287          * and therefore avoid hardcoding. I am not sure it is worth
1288          * the hassle, though. (JMarc)
1289          */
1290         struct MacMenuEntry {
1291                 FuncCode action;
1292                 char const * arg;
1293                 char const * label;
1294                 QAction::MenuRole role;
1295         };
1296
1297         MacMenuEntry entries[] = {
1298                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1299                  QAction::AboutRole},
1300                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1301                  QAction::PreferencesRole},
1302                 {LFUN_RECONFIGURE, "", "Reconfigure",
1303                  QAction::ApplicationSpecificRole},
1304                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1305         };
1306         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1307
1308         // the special menu for Menus. Fill it up only once.
1309         if (specialmenu_.size() == 0) {
1310                 for (size_t i = 0 ; i < num_entries ; ++i) {
1311                         FuncRequest const func(entries[i].action,
1312                                 from_utf8(entries[i].arg));
1313                         specialmenu_.add(MenuItem(MenuItem::Command, 
1314                                 entries[i].label, func));
1315                 }
1316         }
1317         
1318         // add the entries to a QMenu that will eventually be empty
1319         // and therefore invisible.
1320         QMenu * qMenu = qmb->addMenu("special");
1321         MenuDefinition::const_iterator cit = specialmenu_.begin();
1322         MenuDefinition::const_iterator end = specialmenu_.end();
1323         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1324                 Action * action = new Action(view, QIcon(), cit->label(),
1325                         cit->func(), QString(), qMenu);
1326                 action->setMenuRole(entries[i].role);
1327                 qMenu->addAction(action);
1328         }
1329 }
1330
1331
1332 void Menus::Impl::expand(MenuDefinition const & frommenu,
1333         MenuDefinition & tomenu, BufferView const * bv) const
1334 {
1335         if (!tomenu.empty())
1336                 tomenu.clear();
1337
1338         for (MenuDefinition::const_iterator cit = frommenu.begin();
1339              cit != frommenu.end() ; ++cit) {
1340                 Buffer const * buf = bv ? &bv->buffer() : 0;
1341                 switch (cit->kind()) {
1342                 case MenuItem::Lastfiles:
1343                         tomenu.expandLastfiles();
1344                         break;
1345
1346                 case MenuItem::Documents:
1347                         tomenu.expandDocuments();
1348                         break;
1349
1350                 case MenuItem::Bookmarks:
1351                         tomenu.expandBookmarks();
1352                         break;
1353
1354                 case MenuItem::ImportFormats:
1355                 case MenuItem::ViewFormats:
1356                 case MenuItem::UpdateFormats:
1357                 case MenuItem::ExportFormats:
1358                         tomenu.expandFormats(cit->kind(), buf);
1359                         break;
1360
1361                 case MenuItem::CharStyles:
1362                         tomenu.expandFlexInsert(buf, "charstyle");
1363                         break;
1364
1365                 case MenuItem::Custom:
1366                         tomenu.expandFlexInsert(buf, "custom");
1367                         break;
1368
1369                 case MenuItem::Elements:
1370                         tomenu.expandFlexInsert(buf, "element");
1371                         break;
1372
1373                 case MenuItem::FloatListInsert:
1374                         tomenu.expandFloatListInsert(buf);
1375                         break;
1376
1377                 case MenuItem::FloatInsert:
1378                         tomenu.expandFloatInsert(buf);
1379                         break;
1380
1381                 case MenuItem::PasteRecent:
1382                         tomenu.expandPasteRecent();
1383                         break;
1384
1385                 case MenuItem::Toolbars:
1386                         tomenu.expandToolbars();
1387                         break;
1388
1389                 case MenuItem::Branches:
1390                         tomenu.expandBranches(buf);
1391                         break;
1392
1393                 case MenuItem::CiteStyles:
1394                         tomenu.expandCiteStyles(bv);
1395                         break;
1396
1397                 case MenuItem::Toc:
1398                         tomenu.expandToc(buf);
1399                         break;
1400
1401                 case MenuItem::Submenu: {
1402                         MenuItem item(*cit);
1403                         item.setSubmenu(MenuDefinition(cit->submenuname()));
1404                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
1405                         tomenu.addWithStatusCheck(item);
1406                 }
1407                 break;
1408
1409                 case MenuItem::Separator:
1410                         tomenu.addWithStatusCheck(*cit);
1411                         break;
1412
1413                 case MenuItem::Command:
1414                         if (!specialmenu_.hasFunc(cit->func()))
1415                                 tomenu.addWithStatusCheck(*cit);
1416                 }
1417         }
1418
1419         // we do not want the menu to end with a separator
1420         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1421                 tomenu.items_.pop_back();
1422
1423         // Check whether the shortcuts are unique
1424         tomenu.checkShortcuts();
1425 }
1426
1427
1428 bool Menus::Impl::hasMenu(QString const & name) const
1429 {
1430         return find_if(menulist_.begin(), menulist_.end(),
1431                 MenuNamesEqual(name)) != menulist_.end();
1432 }
1433
1434
1435 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1436 {
1437         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1438                 MenuNamesEqual(name));
1439         if (cit == menulist_.end())
1440                 lyxerr << "No submenu named " << name << endl;
1441         LASSERT(cit != menulist_.end(), /**/);
1442         return (*cit);
1443 }
1444
1445
1446 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1447 {
1448         iterator it = find_if(menulist_.begin(), menulist_.end(),
1449                 MenuNamesEqual(name));
1450         if (it == menulist_.end())
1451                 lyxerr << "No submenu named " << name << endl;
1452         LASSERT(it != menulist_.end(), /**/);
1453         return (*it);
1454 }
1455
1456
1457 /////////////////////////////////////////////////////////////////////
1458 //
1459 // Menus 
1460 //
1461 /////////////////////////////////////////////////////////////////////
1462
1463 Menus::Menus() : d(new Impl) {}
1464
1465 Menus::~Menus()
1466 {
1467   delete d;
1468 }
1469
1470 void Menus::read(Lexer & lex)
1471 {
1472         enum {
1473                 md_menu,
1474                 md_menubar,
1475                 md_endmenuset,
1476         };
1477
1478         LexerKeyword menutags[] = {
1479                 { "end", md_endmenuset },
1480                 { "menu", md_menu },
1481                 { "menubar", md_menubar }
1482         };
1483
1484         // consistency check
1485         if (compare_ascii_no_case(lex.getString(), "menuset"))
1486                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1487
1488         lex.pushTable(menutags);
1489         lex.setContext("Menus::read");
1490
1491         bool quit = false;
1492
1493         while (lex.isOK() && !quit) {
1494                 switch (lex.lex()) {
1495                 case md_menubar:
1496                         d->menubar_.read(lex);
1497                         break;
1498                 case md_menu: {
1499                         lex.next(true);
1500                         QString const name = toqstr(lex.getDocString());
1501                         if (d->hasMenu(name))
1502                                 d->getMenu(name).read(lex);
1503                         else {
1504                                 MenuDefinition menu(name);
1505                                 menu.read(lex);
1506                                 d->menulist_.push_back(menu);
1507                         }
1508                         break;
1509                 }
1510                 case md_endmenuset:
1511                         quit = true;
1512                         break;
1513                 default:
1514                         lex.printError("Unknown menu tag");
1515                         break;
1516                 }
1517         }
1518         lex.popTable();
1519 }
1520
1521
1522 bool Menus::searchMenu(FuncRequest const & func,
1523         vector<docstring> & names) const
1524 {
1525         MenuDefinition menu;
1526         d->expand(d->menubar_, menu, 0);
1527         return menu.searchMenu(func, names);
1528 }
1529
1530
1531 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1532 {
1533         if (initial) {
1534 #ifdef Q_WS_MACX
1535                 // setup special mac specific menu item
1536                 d->macxMenuBarInit(view, qmb);
1537 #endif
1538         } else {
1539                 // Clear all menubar contents before filling it.
1540                 qmb->clear();
1541         }
1542
1543         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1544
1545         if (d->menubar_.size() == 0) {
1546                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1547                         << d->menubar_.name());
1548                 return;
1549         }
1550         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1551
1552         MenuDefinition menu;
1553         BufferView * bv = 0;
1554         if (view)
1555                 bv = view->view();
1556         d->expand(d->menubar_, menu, bv);
1557
1558         MenuDefinition::const_iterator m = menu.begin();
1559         MenuDefinition::const_iterator end = menu.end();
1560
1561         for (; m != end; ++m) {
1562
1563                 if (m->kind() != MenuItem::Submenu) {
1564                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1565                         continue;
1566                 }
1567
1568                 LYXERR(Debug::GUI, "menu bar item " << m->label()
1569                         << " is a submenu named " << m->submenuname());
1570
1571                 QString name = m->submenuname();
1572                 if (!d->hasMenu(name)) {
1573                         LYXERR(Debug::GUI, "\tERROR: " << name
1574                                 << " submenu has no menu!");
1575                         continue;
1576                 }
1577
1578                 Menu * menu = new Menu(view, m->submenuname(), true);
1579                 menu->setTitle(label(*m));
1580                 qmb->addMenu(menu);
1581
1582                 d->name_map_[view][name] = menu;
1583         }
1584 }
1585
1586
1587 void Menus::updateMenu(Menu * qmenu)
1588 {
1589         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1590         qmenu->clear();
1591
1592         if (qmenu->d->name.isEmpty())
1593                 return;
1594
1595         // Here, We make sure that theLyXFunc points to the correct LyXView.
1596         theLyXFunc().setLyXView(qmenu->d->view);
1597
1598         if (!d->hasMenu(qmenu->d->name)) {
1599                 qmenu->addAction(qt_("No action defined!"));
1600                 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1601                         << qmenu->d->name);
1602                 return;
1603         }
1604
1605         MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1606         BufferView * bv = 0;
1607         if (qmenu->d->view)
1608                 bv = qmenu->d->view->view();
1609         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1610         qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1611 }
1612
1613
1614 Menu * Menus::menu(QString const & name, GuiView & view)
1615 {
1616         LYXERR(Debug::GUI, "Context menu requested: " << name);
1617         Menu * menu = d->name_map_[&view].value(name, 0);
1618         if (!menu && !name.startsWith("context-")) {
1619                 LYXERR0("requested context menu not found: " << name);
1620                 return 0;
1621         }
1622
1623         menu = new Menu(&view, name, true);
1624         d->name_map_[&view][name] = menu;
1625         return menu;
1626 }
1627
1628 } // namespace frontend
1629 } // namespace lyx
1630
1631 #include "Menus_moc.cpp"