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