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