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