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