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