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