]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
Unify LFUN naming.
[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 expandFlexInsert(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();
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 = LyX::cref().session().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->isClean())
684                                 label += "*";
685                         if (ii < 10)
686                                 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
687                         add(MenuItem(MenuItem::Command, label,
688                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
689                         
690                         b = theBufferList().next(b);
691                         ++ii;
692                 } while (b != first); 
693         } else {
694                 add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
695                            FuncRequest(LFUN_NOACTION)));
696         }
697 }
698
699
700 void MenuDefinition::expandBookmarks()
701 {
702         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
703
704         for (size_t i = 1; i <= bm.size(); ++i) {
705                 if (bm.isValid(i)) {
706                         string const file = bm.bookmark(i).filename.absFilename();
707                         QString const label = QString("%1. %2|%3").arg(i)
708                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
709                         add(MenuItem(MenuItem::Command, label,
710                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
711                 }
712         }
713 }
714
715
716 void MenuDefinition::expandFormats(MenuItem::Kind kind, Buffer const * buf)
717 {
718         if (!buf && kind != MenuItem::ImportFormats) {
719                 add(MenuItem(MenuItem::Command,
720                                     qt_("No Document Open!"),
721                                     FuncRequest(LFUN_NOACTION)));
722                 return;
723         }
724
725         typedef vector<Format const *> Formats;
726         Formats formats;
727         FuncCode action;
728
729         switch (kind) {
730         case MenuItem::ImportFormats:
731                 formats = theConverters().importableFormats();
732                 action = LFUN_BUFFER_IMPORT;
733                 break;
734         case MenuItem::ViewFormats:
735                 formats = buf->exportableFormats(true);
736                 action = LFUN_BUFFER_VIEW;
737                 break;
738         case MenuItem::UpdateFormats:
739                 formats = buf->exportableFormats(true);
740                 action = LFUN_BUFFER_UPDATE;
741                 break;
742         default:
743                 formats = buf->exportableFormats(false);
744                 action = LFUN_BUFFER_EXPORT;
745         }
746         sort(formats.begin(), formats.end(), &compareFormat);
747
748         Formats::const_iterator fit = formats.begin();
749         Formats::const_iterator end = formats.end();
750         for (; fit != end ; ++fit) {
751                 if ((*fit)->dummy())
752                         continue;
753
754                 docstring lab = from_utf8((*fit)->prettyname());
755                 docstring scut = from_utf8((*fit)->shortcut());
756                 docstring const tmplab = lab;
757  
758                 if (!scut.empty())
759                         lab += char_type('|') + scut;
760                 docstring lab_i18n = translateIfPossible(lab);
761                 bool const untranslated = (lab == lab_i18n);
762                 QString const shortcut = toqstr(split(lab_i18n, lab, '|'));
763                 QString label = toqstr(lab);
764                 if (untranslated)
765                         // this might happen if the shortcut
766                         // has been redefined
767                         label = toqstr(translateIfPossible(tmplab));
768
769                 switch (kind) {
770                 case MenuItem::ImportFormats:
771                         label += "...";
772                         break;
773                 case MenuItem::ViewFormats:
774                 case MenuItem::ExportFormats:
775                 case MenuItem::UpdateFormats:
776                         if (!(*fit)->documentFormat())
777                                 continue;
778                         break;
779                 default:
780                         LASSERT(false, /**/);
781                         break;
782                 }
783                 if (!shortcut.isEmpty())
784                         label += '|' + shortcut;
785
786                 if (buf)
787                         addWithStatusCheck(MenuItem(MenuItem::Command, label,
788                                 FuncRequest(action, (*fit)->name())));
789                 else
790                         add(MenuItem(MenuItem::Command, label,
791                                 FuncRequest(action, (*fit)->name())));
792         }
793 }
794
795
796 void MenuDefinition::expandFloatListInsert(Buffer const * buf)
797 {
798         if (!buf) {
799                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
800                                     FuncRequest(LFUN_NOACTION)));
801                 return;
802         }
803
804         FloatList const & floats = buf->params().documentClass().floats();
805         FloatList::const_iterator cit = floats.begin();
806         FloatList::const_iterator end = floats.end();
807         for (; cit != end; ++cit) {
808                 addWithStatusCheck(MenuItem(MenuItem::Command,
809                                     qt_(cit->second.listName()),
810                                     FuncRequest(LFUN_FLOAT_LIST_INSERT,
811                                                 cit->second.type())));
812         }
813 }
814
815
816 void MenuDefinition::expandFloatInsert(Buffer const * buf)
817 {
818         if (!buf) {
819                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
820                                     FuncRequest(LFUN_NOACTION)));
821                 return;
822         }
823
824         FloatList const & floats = buf->params().documentClass().floats();
825         FloatList::const_iterator cit = floats.begin();
826         FloatList::const_iterator end = floats.end();
827         for (; cit != end; ++cit) {
828                 // normal float
829                 QString const label = qt_(cit->second.name());
830                 addWithStatusCheck(MenuItem(MenuItem::Command, label,
831                                     FuncRequest(LFUN_FLOAT_INSERT,
832                                                 cit->second.type())));
833         }
834 }
835
836
837 void MenuDefinition::expandFlexInsert(Buffer const * buf, string s)
838 {
839         if (!buf) {
840                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
841                                     FuncRequest(LFUN_NOACTION)));
842                 return;
843         }
844         TextClass::InsetLayouts const & insetLayouts =
845                 buf->params().documentClass().insetLayouts();
846         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
847         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
848         for (; cit != end; ++cit) {
849                 docstring const label = cit->first;
850                 if (cit->second.lyxtype() == s)
851                         addWithStatusCheck(MenuItem(MenuItem::Command, 
852                                 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
853                                                 label)));
854         }
855 }
856
857
858 size_t const max_number_of_items = 25;
859
860 void MenuDefinition::expandToc2(Toc const & toc_list,
861                 size_t from, size_t to, int depth)
862 {
863         int shortcut_count = 0;
864
865         // check whether depth is smaller than the smallest depth in toc.
866         int min_depth = 1000;
867         for (size_t i = from; i < to; ++i)
868                 min_depth = min(min_depth, toc_list[i].depth());
869         if (min_depth > depth)
870                 depth = min_depth;
871
872         if (to - from <= max_number_of_items) {
873                 for (size_t i = from; i < to; ++i) {
874                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
875                         label += limitStringLength(toc_list[i].str());
876                         if (toc_list[i].depth() == depth
877                             && shortcut_count < 9) {
878                                 if (label.contains(QString::number(shortcut_count + 1)))
879                                         label += '|' + QString::number(++shortcut_count);
880                         }
881                         add(MenuItem(MenuItem::Command, label,
882                                             FuncRequest(toc_list[i].action())));
883                 }
884         } else {
885                 size_t pos = from;
886                 while (pos < to) {
887                         size_t new_pos = pos + 1;
888                         while (new_pos < to && toc_list[new_pos].depth() > depth)
889                                 ++new_pos;
890
891                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
892                         label += limitStringLength(toc_list[pos].str());
893                         if (toc_list[pos].depth() == depth &&
894                             shortcut_count < 9) {
895                                 if (label.contains(QString::number(shortcut_count + 1)))
896                                         label += '|' + QString::number(++shortcut_count);
897                         }
898                         if (new_pos == pos + 1) {
899                                 add(MenuItem(MenuItem::Command,
900                                                     label, FuncRequest(toc_list[pos].action())));
901                         } else {
902                                 MenuDefinition sub;
903                                 sub.expandToc2(toc_list, pos, new_pos, depth + 1);
904                                 MenuItem item(MenuItem::Submenu, label);
905                                 item.setSubmenu(sub);
906                                 add(item);
907                         }
908                         pos = new_pos;
909                 }
910         }
911 }
912
913
914 void MenuDefinition::expandToc(Buffer const * buf)
915 {
916         // To make things very cleanly, we would have to pass buf to
917         // all MenuItem constructors and to expandToc2. However, we
918         // know that all the entries in a TOC will be have status_ ==
919         // OK, so we avoid this unnecessary overhead (JMarc)
920
921         if (!buf) {
922                 add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
923                                     FuncRequest(LFUN_NOACTION)));
924                 return;
925         }
926
927         Buffer* cbuf = const_cast<Buffer*>(buf);
928         cbuf->tocBackend().update();
929         cbuf->structureChanged();
930
931         // Add an entry for the master doc if this is a child doc
932         Buffer const * const master = buf->masterBuffer();
933         if (buf != master) {
934                 ParIterator const pit = par_iterator_begin(master->inset());
935                 string const arg = convert<string>(pit->id());
936                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
937                 add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
938         }
939
940         MenuDefinition other_lists;
941         
942         FloatList const & floatlist = buf->params().documentClass().floats();
943         TocList const & toc_list = buf->tocBackend().tocs();
944         TocList::const_iterator cit = toc_list.begin();
945         TocList::const_iterator end = toc_list.end();
946         for (; cit != end; ++cit) {
947                 // Handle this later
948                 if (cit->first == "tableofcontents")
949                         continue;
950
951                 MenuDefinition submenu;
952                 if (cit->second.size() >= 30) {
953                         FuncRequest f(LFUN_DIALOG_SHOW, "toc " + cit->first);
954                         submenu.add(MenuItem(MenuItem::Command, qt_("Open Navigator..."), f));
955                 } else {
956                         TocIterator ccit = cit->second.begin();
957                         TocIterator eend = cit->second.end();
958                         for (; ccit != eend; ++ccit) {
959                                 submenu.add(MenuItem(MenuItem::Command,
960                                         limitStringLength(ccit->str()),
961                                         FuncRequest(ccit->action())));
962                         }
963                 }
964
965                 MenuItem item(MenuItem::Submenu, guiName(cit->first, buf->params()));
966                 item.setSubmenu(submenu);
967                 if (floatlist.typeExist(cit->first) || cit->first == "child") {
968                         // Those two types deserve to be in the main menu.
969                         item.setSubmenu(submenu);
970                         add(item);
971                 } else
972                         other_lists.add(item);
973         }
974         if (!other_lists.empty()) {
975                 MenuItem item(MenuItem::Submenu, qt_("Other Lists"));
976                 item.setSubmenu(other_lists);
977                 add(item);
978         }
979
980         // Handle normal TOC
981         cit = toc_list.find("tableofcontents");
982         if (cit == end) {
983                 addWithStatusCheck(MenuItem(MenuItem::Command,
984                                     qt_("No Table of contents"),
985                                     FuncRequest()));
986         } else
987                 expandToc2(cit->second, 0, cit->second.size(), 0);
988 }
989
990
991 void MenuDefinition::expandPasteRecent()
992 {
993         docstring_list const sel = cap::availableSelections();
994
995         docstring_list::const_iterator cit = sel.begin();
996         docstring_list::const_iterator end = sel.end();
997
998         for (unsigned int index = 0; cit != end; ++cit, ++index) {
999                 add(MenuItem(MenuItem::Command, toqstr(*cit),
1000                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
1001         }
1002 }
1003
1004
1005 void MenuDefinition::expandToolbars()
1006 {
1007         // extracts the toolbars from the backend
1008         Toolbars::Infos::const_iterator cit = guiApp->toolbars().begin();
1009         Toolbars::Infos::const_iterator end = guiApp->toolbars().end();
1010         for (; cit != end; ++cit) {
1011                 add(MenuItem(MenuItem::Command, qt_(cit->gui_name),
1012                         FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name)));
1013         }
1014 }
1015
1016
1017 void MenuDefinition::expandBranches(Buffer const * buf)
1018 {
1019         if (!buf) {
1020                 add(MenuItem(MenuItem::Command,
1021                                     qt_("No Document Open!"),
1022                                     FuncRequest(LFUN_NOACTION)));
1023                 return;
1024         }
1025
1026         BufferParams const & params = buf->masterBuffer()->params();
1027         if (params.branchlist().empty()) {
1028                 add(MenuItem(MenuItem::Command,
1029                                     qt_("No Branch in Document!"),
1030                                     FuncRequest(LFUN_NOACTION)));
1031                 return;
1032         }
1033
1034         BranchList::const_iterator cit = params.branchlist().begin();
1035         BranchList::const_iterator end = params.branchlist().end();
1036
1037         for (int ii = 1; cit != end; ++cit, ++ii) {
1038                 docstring label = cit->getBranch();
1039                 if (ii < 10)
1040                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1041                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1042                                     FuncRequest(LFUN_BRANCH_INSERT,
1043                                                 cit->getBranch())));
1044         }
1045 }
1046
1047
1048 void MenuDefinition::expandCiteStyles(BufferView const * bv)
1049 {
1050         if (!bv) {
1051                 add(MenuItem(MenuItem::Command,
1052                                     qt_("No Document Open!"),
1053                                     FuncRequest(LFUN_NOACTION)));
1054                 return;
1055         }
1056
1057         Inset const * inset = bv->cursor().nextInset();
1058         if (!inset || inset->lyxCode() != CITE_CODE) {
1059                 add(MenuItem(MenuItem::Command,
1060                                     qt_("No Citation in Scope!"),
1061                                     FuncRequest(LFUN_NOACTION)));
1062                 return;
1063         }
1064         InsetCommand const * citinset =
1065                                 static_cast<InsetCommand const *>(inset);
1066         
1067         Buffer const * buf = &bv->buffer();
1068         docstring key = citinset->getParam("key");
1069         // we can only handle one key currently
1070         if (contains(key, ','))
1071                 key = qstring_to_ucs4(toqstr(key).split(',')[0]);
1072
1073         vector<CiteStyle> citeStyleList = citeStyles(buf->params().citeEngine());
1074         docstring_list citeStrings =
1075                 buf->masterBibInfo().getCiteStrings(key, bv->buffer());
1076
1077         docstring_list::const_iterator cit = citeStrings.begin();
1078         docstring_list::const_iterator end = citeStrings.end();
1079
1080         for (int ii = 1; cit != end; ++cit, ++ii) {
1081                 docstring label = *cit;
1082                 CitationStyle cs;
1083                 CiteStyle cst = citeStyleList[ii - 1];
1084                 cs.style = cst;
1085                 addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1086                                     FuncRequest(LFUN_NEXT_INSET_MODIFY,
1087                                                 "changetype " + from_utf8(citationStyleToString(cs)))));
1088         }
1089 }
1090
1091 } // namespace anon
1092
1093
1094 /////////////////////////////////////////////////////////////////////
1095 // Menu::Impl definition and implementation
1096 /////////////////////////////////////////////////////////////////////
1097
1098 struct Menu::Impl
1099 {
1100         /// populates the menu or one of its submenu
1101         /// This is used as a recursive function
1102         void populate(QMenu & qMenu, MenuDefinition const & menu);
1103
1104         /// Only needed for top level menus.
1105         MenuDefinition * top_level_menu;
1106         /// our owning view
1107         GuiView * view;
1108         /// the name of this menu
1109         QString name;
1110 };
1111
1112
1113
1114 /// Get a MenuDefinition item label from the menu backend
1115 static QString label(MenuItem const & mi)
1116 {
1117         QString label = mi.label();
1118         label.replace("&", "&&");
1119
1120         QString shortcut = mi.shortcut();
1121         if (!shortcut.isEmpty()) {
1122                 int pos = label.indexOf(shortcut);
1123                 if (pos != -1)
1124                         //label.insert(pos, 1, char_type('&'));
1125                         label.replace(pos, 0, "&");
1126         }
1127
1128         QString const binding = mi.binding();
1129         if (!binding.isEmpty())
1130                 label += '\t' + binding;
1131
1132         return label;
1133 }
1134
1135 void Menu::Impl::populate(QMenu & qMenu, MenuDefinition const & menu)
1136 {
1137         LYXERR(Debug::GUI, "populating menu " << menu.name());
1138         if (menu.size() == 0) {
1139                 LYXERR(Debug::GUI, "\tERROR: empty menu " << menu.name());
1140                 return;
1141         }
1142         LYXERR(Debug::GUI, " *****  menu entries " << menu.size());
1143         MenuDefinition::const_iterator m = menu.begin();
1144         MenuDefinition::const_iterator end = menu.end();
1145         for (; m != end; ++m) {
1146                 if (m->kind() == MenuItem::Separator)
1147                         qMenu.addSeparator();
1148                 else if (m->kind() == MenuItem::Submenu) {
1149                         QMenu * subMenu = qMenu.addMenu(label(*m));
1150                         populate(*subMenu, m->submenu());
1151                 } else {
1152                         // we have a MenuItem::Command
1153                         qMenu.addAction(new Action(view, QIcon(), label(*m), 
1154                                 m->func(), QString(), &qMenu));
1155                 }
1156         }
1157 }
1158
1159 /////////////////////////////////////////////////////////////////////
1160 // Menu implementation
1161 /////////////////////////////////////////////////////////////////////
1162
1163 Menu::Menu(GuiView * gv, QString const & name, bool top_level)
1164 : QMenu(gv), d(new Menu::Impl)
1165 {
1166         d->top_level_menu = top_level? new MenuDefinition : 0;
1167         d->view = gv;
1168         d->name = name;
1169         setTitle(name);
1170         if (d->top_level_menu)
1171                 connect(this, SIGNAL(aboutToShow()), this, SLOT(updateView()));
1172 }
1173
1174
1175 Menu::~Menu()
1176 {
1177         delete d->top_level_menu;
1178         delete d;
1179 }
1180
1181
1182 void Menu::updateView()
1183 {
1184         guiApp->menus().updateMenu(this);
1185 }
1186
1187
1188 /////////////////////////////////////////////////////////////////////
1189 // Menus::Impl definition and implementation
1190 /////////////////////////////////////////////////////////////////////
1191
1192 struct Menus::Impl {
1193         ///
1194         bool hasMenu(QString const &) const;
1195         ///
1196         MenuDefinition & getMenu(QString const &);
1197         ///
1198         MenuDefinition const & getMenu(QString const &) const;
1199
1200         /// Expands some special entries of the menu
1201         /** The entries with the following kind are expanded to a
1202             sequence of Command MenuItems: Lastfiles, Documents,
1203             ViewFormats, ExportFormats, UpdateFormats, Branches
1204         */
1205         void expand(MenuDefinition const & frommenu, MenuDefinition & tomenu,
1206                 BufferView const *) const;
1207
1208         /// Initialize specific MACOS X menubar
1209         void macxMenuBarInit(GuiView * view, QMenuBar * qmb);
1210
1211         /// Mac special menu.
1212         /** This defines a menu whose entries list the FuncRequests
1213             that will be removed by expand() in other menus. This is
1214             used by the Qt/Mac code
1215         */
1216         MenuDefinition specialmenu_;
1217
1218         ///
1219         MenuList menulist_;
1220         ///
1221         MenuDefinition menubar_;
1222
1223         typedef QMap<GuiView *, QHash<QString, Menu*> > NameMap;
1224
1225         /// name to menu for \c menu() method.
1226         NameMap name_map_;
1227 };
1228
1229 /*
1230   Here is what the Qt documentation says about how a menubar is chosen:
1231
1232      1) If the window has a QMenuBar then it is used. 2) If the window
1233      is a modal then its menubar is used. If no menubar is specified
1234      then a default menubar is used (as documented below) 3) If the
1235      window has no parent then the default menubar is used (as
1236      documented below).
1237
1238      The above 3 steps are applied all the way up the parent window
1239      chain until one of the above are satisifed. If all else fails a
1240      default menubar will be created, the default menubar on Qt/Mac is
1241      an empty menubar, however you can create a different default
1242      menubar by creating a parentless QMenuBar, the first one created
1243      will thus be designated the default menubar, and will be used
1244      whenever a default menubar is needed.
1245
1246   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
1247   that this menubar will be used also when one of LyX' dialogs has
1248   focus. (JMarc)
1249 */
1250 void Menus::Impl::macxMenuBarInit(GuiView * view, QMenuBar * qmb)
1251 {
1252         /* Since Qt 4.2, the qt/mac menu code has special code for
1253            specifying the role of a menu entry. However, it does not
1254            work very well with our scheme of creating menus on demand,
1255            and therefore we need to put these entries in a special
1256            invisible menu. (JMarc)
1257         */
1258
1259         /* The entries of our special mac menu. If we add support for
1260          * special entries in Menus, we could imagine something
1261          * like
1262          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
1263          * and therefore avoid hardcoding. I am not sure it is worth
1264          * the hassle, though. (JMarc)
1265          */
1266         struct MacMenuEntry {
1267                 FuncCode action;
1268                 char const * arg;
1269                 char const * label;
1270                 QAction::MenuRole role;
1271         };
1272
1273         MacMenuEntry entries[] = {
1274                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
1275                  QAction::AboutRole},
1276                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
1277                  QAction::PreferencesRole},
1278                 {LFUN_RECONFIGURE, "", "Reconfigure",
1279                  QAction::ApplicationSpecificRole},
1280                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
1281         };
1282         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
1283
1284         // the special menu for Menus. Fill it up only once.
1285         if (specialmenu_.size() == 0) {
1286                 for (size_t i = 0 ; i < num_entries ; ++i) {
1287                         FuncRequest const func(entries[i].action,
1288                                 from_utf8(entries[i].arg));
1289                         specialmenu_.add(MenuItem(MenuItem::Command, 
1290                                 entries[i].label, func));
1291                 }
1292         }
1293         
1294         // add the entries to a QMenu that will eventually be empty
1295         // and therefore invisible.
1296         QMenu * qMenu = qmb->addMenu("special");
1297         MenuDefinition::const_iterator cit = specialmenu_.begin();
1298         MenuDefinition::const_iterator end = specialmenu_.end();
1299         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
1300                 Action * action = new Action(view, QIcon(), cit->label(),
1301                         cit->func(), QString(), qMenu);
1302                 action->setMenuRole(entries[i].role);
1303                 qMenu->addAction(action);
1304         }
1305 }
1306
1307
1308 void Menus::Impl::expand(MenuDefinition const & frommenu,
1309         MenuDefinition & tomenu, BufferView const * bv) const
1310 {
1311         if (!tomenu.empty())
1312                 tomenu.clear();
1313
1314         for (MenuDefinition::const_iterator cit = frommenu.begin();
1315              cit != frommenu.end() ; ++cit) {
1316                 Buffer const * buf = bv ? &bv->buffer() : 0;
1317                 switch (cit->kind()) {
1318                 case MenuItem::Lastfiles:
1319                         tomenu.expandLastfiles();
1320                         break;
1321
1322                 case MenuItem::Documents:
1323                         tomenu.expandDocuments();
1324                         break;
1325
1326                 case MenuItem::Bookmarks:
1327                         tomenu.expandBookmarks();
1328                         break;
1329
1330                 case MenuItem::ImportFormats:
1331                 case MenuItem::ViewFormats:
1332                 case MenuItem::UpdateFormats:
1333                 case MenuItem::ExportFormats:
1334                         tomenu.expandFormats(cit->kind(), buf);
1335                         break;
1336
1337                 case MenuItem::CharStyles:
1338                         tomenu.expandFlexInsert(buf, "charstyle");
1339                         break;
1340
1341                 case MenuItem::Custom:
1342                         tomenu.expandFlexInsert(buf, "custom");
1343                         break;
1344
1345                 case MenuItem::Elements:
1346                         tomenu.expandFlexInsert(buf, "element");
1347                         break;
1348
1349                 case MenuItem::FloatListInsert:
1350                         tomenu.expandFloatListInsert(buf);
1351                         break;
1352
1353                 case MenuItem::FloatInsert:
1354                         tomenu.expandFloatInsert(buf);
1355                         break;
1356
1357                 case MenuItem::PasteRecent:
1358                         tomenu.expandPasteRecent();
1359                         break;
1360
1361                 case MenuItem::Toolbars:
1362                         tomenu.expandToolbars();
1363                         break;
1364
1365                 case MenuItem::Branches:
1366                         tomenu.expandBranches(buf);
1367                         break;
1368
1369                 case MenuItem::CiteStyles:
1370                         tomenu.expandCiteStyles(bv);
1371                         break;
1372
1373                 case MenuItem::Toc:
1374                         tomenu.expandToc(buf);
1375                         break;
1376
1377                 case MenuItem::GraphicsGroups:
1378                         tomenu.expandGraphicsGroups(bv);
1379                         break;
1380
1381                 case MenuItem::Submenu: {
1382                         MenuItem item(*cit);
1383                         item.setSubmenu(MenuDefinition(cit->submenuname()));
1384                         expand(getMenu(cit->submenuname()), item.submenu(), bv);
1385                         tomenu.addWithStatusCheck(item);
1386                 }
1387                 break;
1388
1389                 case MenuItem::Separator:
1390                         tomenu.addWithStatusCheck(*cit);
1391                         break;
1392
1393                 case MenuItem::Command:
1394                         if (!specialmenu_.hasFunc(cit->func()))
1395                                 tomenu.addWithStatusCheck(*cit);
1396                 }
1397         }
1398
1399         // we do not want the menu to end with a separator
1400         if (!tomenu.empty() && tomenu.items_.back().kind() == MenuItem::Separator)
1401                 tomenu.items_.pop_back();
1402
1403         // Check whether the shortcuts are unique
1404         tomenu.checkShortcuts();
1405 }
1406
1407
1408 bool Menus::Impl::hasMenu(QString const & name) const
1409 {
1410         return find_if(menulist_.begin(), menulist_.end(),
1411                 MenuNamesEqual(name)) != menulist_.end();
1412 }
1413
1414
1415 MenuDefinition const & Menus::Impl::getMenu(QString const & name) const
1416 {
1417         const_iterator cit = find_if(menulist_.begin(), menulist_.end(),
1418                 MenuNamesEqual(name));
1419         if (cit == menulist_.end())
1420                 LYXERR0("No submenu named " << name);
1421         LASSERT(cit != menulist_.end(), /**/);
1422         return (*cit);
1423 }
1424
1425
1426 MenuDefinition & Menus::Impl::getMenu(QString const & name)
1427 {
1428         iterator it = find_if(menulist_.begin(), menulist_.end(),
1429                 MenuNamesEqual(name));
1430         if (it == menulist_.end())
1431                 LYXERR0("No submenu named " << name);
1432         LASSERT(it != menulist_.end(), /**/);
1433         return (*it);
1434 }
1435
1436
1437 /////////////////////////////////////////////////////////////////////
1438 //
1439 // Menus 
1440 //
1441 /////////////////////////////////////////////////////////////////////
1442
1443 Menus::Menus() : d(new Impl) {}
1444
1445 Menus::~Menus()
1446 {
1447   delete d;
1448 }
1449
1450 void Menus::read(Lexer & lex)
1451 {
1452         enum {
1453                 md_menu,
1454                 md_menubar,
1455                 md_endmenuset,
1456         };
1457
1458         LexerKeyword menutags[] = {
1459                 { "end", md_endmenuset },
1460                 { "menu", md_menu },
1461                 { "menubar", md_menubar }
1462         };
1463
1464         // consistency check
1465         if (compare_ascii_no_case(lex.getString(), "menuset"))
1466                 LYXERR0("Menus::read: ERROR wrong token: `" << lex.getString() << '\'');
1467
1468         lex.pushTable(menutags);
1469         lex.setContext("Menus::read");
1470
1471         bool quit = false;
1472
1473         while (lex.isOK() && !quit) {
1474                 switch (lex.lex()) {
1475                 case md_menubar:
1476                         d->menubar_.read(lex);
1477                         break;
1478                 case md_menu: {
1479                         lex.next(true);
1480                         QString const name = toqstr(lex.getDocString());
1481                         if (d->hasMenu(name))
1482                                 d->getMenu(name).read(lex);
1483                         else {
1484                                 MenuDefinition menu(name);
1485                                 menu.read(lex);
1486                                 d->menulist_.push_back(menu);
1487                         }
1488                         break;
1489                 }
1490                 case md_endmenuset:
1491                         quit = true;
1492                         break;
1493                 default:
1494                         lex.printError("Unknown menu tag");
1495                         break;
1496                 }
1497         }
1498         lex.popTable();
1499 }
1500
1501
1502 bool Menus::searchMenu(FuncRequest const & func,
1503         docstring_list & names) const
1504 {
1505         MenuDefinition menu;
1506         d->expand(d->menubar_, menu, 0);
1507         return menu.searchMenu(func, names);
1508 }
1509
1510
1511 void Menus::fillMenuBar(QMenuBar * qmb, GuiView * view, bool initial)
1512 {
1513         if (initial) {
1514 #ifdef Q_WS_MACX
1515                 // setup special mac specific menu item
1516                 d->macxMenuBarInit(view, qmb);
1517 #endif
1518         } else {
1519                 // Clear all menubar contents before filling it.
1520                 qmb->clear();
1521         }
1522
1523         LYXERR(Debug::GUI, "populating menu bar" << d->menubar_.name());
1524
1525         if (d->menubar_.size() == 0) {
1526                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
1527                         << d->menubar_.name());
1528                 return;
1529         }
1530         LYXERR(Debug::GUI, "menu bar entries " << d->menubar_.size());
1531
1532         MenuDefinition menu;
1533         BufferView * bv = 0;
1534         if (view)
1535                 bv = view->view();
1536         d->expand(d->menubar_, menu, bv);
1537
1538         MenuDefinition::const_iterator m = menu.begin();
1539         MenuDefinition::const_iterator end = menu.end();
1540
1541         for (; m != end; ++m) {
1542
1543                 if (m->kind() != MenuItem::Submenu) {
1544                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << m->label());
1545                         continue;
1546                 }
1547
1548                 LYXERR(Debug::GUI, "menu bar item " << m->label()
1549                         << " is a submenu named " << m->submenuname());
1550
1551                 QString name = m->submenuname();
1552                 if (!d->hasMenu(name)) {
1553                         LYXERR(Debug::GUI, "\tERROR: " << name
1554                                 << " submenu has no menu!");
1555                         continue;
1556                 }
1557
1558                 Menu * menu = new Menu(view, m->submenuname(), true);
1559                 menu->setTitle(label(*m));
1560                 qmb->addMenu(menu);
1561
1562                 d->name_map_[view][name] = menu;
1563         }
1564 }
1565
1566
1567 void Menus::updateMenu(Menu * qmenu)
1568 {
1569         LYXERR(Debug::GUI, "Triggered menu: " << qmenu->d->name);
1570         qmenu->clear();
1571
1572         if (qmenu->d->name.isEmpty())
1573                 return;
1574
1575         // Here, We make sure that theLyXFunc points to the correct LyXView.
1576         theLyXFunc().setLyXView(qmenu->d->view);
1577
1578         if (!d->hasMenu(qmenu->d->name)) {
1579                 qmenu->addAction(qt_("No action defined!"));
1580                 LYXERR(Debug::GUI, "\tWARNING: non existing menu: "
1581                         << qmenu->d->name);
1582                 return;
1583         }
1584
1585         MenuDefinition const & fromLyxMenu = d->getMenu(qmenu->d->name);
1586         BufferView * bv = 0;
1587         if (qmenu->d->view)
1588                 bv = qmenu->d->view->view();
1589         d->expand(fromLyxMenu, *qmenu->d->top_level_menu, bv);
1590         qmenu->d->populate(*qmenu, *qmenu->d->top_level_menu);
1591 }
1592
1593
1594 Menu * Menus::menu(QString const & name, GuiView & view)
1595 {
1596         LYXERR(Debug::GUI, "Context menu requested: " << name);
1597         Menu * menu = d->name_map_[&view].value(name, 0);
1598         if (!menu && !name.startsWith("context-")) {
1599                 LYXERR0("requested context menu not found: " << name);
1600                 return 0;
1601         }
1602
1603         menu = new Menu(&view, name, true);
1604         d->name_map_[&view][name] = menu;
1605         return menu;
1606 }
1607
1608 } // namespace frontend
1609 } // namespace lyx
1610
1611 #include "Menus_moc.cpp"