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