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