]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/Menus.cpp
cosmetics
[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 "GuiPopupMenu.h"
24 #include "GuiView.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 "KeyMap.h"
36 #include "Session.h"
37 #include "LyXAction.h"
38 #include "LyX.h" // for lastfiles
39 #include "LyXFunc.h"
40 #include "Lexer.h"
41 #include "Paragraph.h"
42 #include "TextClass.h"
43 #include "TocBackend.h"
44 #include "ToolbarBackend.h"
45
46 #include "frontends/Application.h"
47
48 #include "support/convert.h"
49 #include "support/debug.h"
50 #include "support/filetools.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h"
53
54 #include "qt_helpers.h"
55
56 #include <QCursor>
57 #include <QMenuBar>
58
59 #include <algorithm>
60 #include <ostream>
61
62 using namespace std;
63 using namespace lyx::support;
64
65
66 namespace lyx {
67 namespace frontend {
68
69 namespace {
70
71 class MenuNamesEqual
72 {
73 public:
74         MenuNamesEqual(QString const & name) : name_(name) {}
75         bool operator()(Menu const & menu) const { return menu.name() == name_; }
76 private:
77         QString name_;
78 };
79
80 } // namespace anon
81
82 // MacOSX specific stuff is at the end.
83
84 void Menus::fillMenuBar(GuiView * view)
85 {
86         // Clear all menubar contents before filling it.
87         view->menuBar()->clear();
88         
89 #ifdef Q_WS_MACX
90         // setup special mac specific menu item
91         macxMenuBarInit(view);
92 #endif
93
94         LYXERR(Debug::GUI, "populating menu bar" << fromqstr(getMenubar().name()));
95
96         if (getMenubar().size() == 0) {
97                 LYXERR(Debug::GUI, "\tERROR: empty menu bar"
98                         << fromqstr(getMenubar().name()));
99                 return;
100         }
101         else {
102                 LYXERR(Debug::GUI, "menu bar entries "
103                         << getMenubar().size());
104         }
105
106         Menu menu;
107         expand(getMenubar(), menu, view->buffer());
108
109         Menu::const_iterator m = menu.begin();
110         Menu::const_iterator end = menu.end();
111
112         for (; m != end; ++m) {
113
114                 if (m->kind() != MenuItem::Submenu) {
115                         LYXERR(Debug::GUI, "\tERROR: not a submenu " << fromqstr(m->label()));
116                         continue;
117                 }
118
119                 LYXERR(Debug::GUI, "menu bar item " << fromqstr(m->label())
120                         << " is a submenu named " << fromqstr(m->submenuname()));
121
122                 QString name = m->submenuname();
123                 if (!hasMenu(name)) {
124                         LYXERR(Debug::GUI, "\tERROR: " << fromqstr(name)
125                                 << " submenu has no menu!");
126                         continue;
127                 }
128
129                 GuiPopupMenu * qMenu = new GuiPopupMenu(view, *m, true);
130                 view->menuBar()->addMenu(qMenu);
131
132                 name_map_[name] = qMenu;
133         }
134 }
135
136
137 QMenu * Menus::menu(QString const & name)
138 {
139         LYXERR(Debug::GUI, "Context menu requested: " << fromqstr(name));
140         GuiPopupMenu * menu = name_map_.value(name, 0);
141         if (!menu)
142                 LYXERR0("resquested context menu not found: " << fromqstr(name));
143         return menu;
144 }
145
146
147 /// Some special Qt/Mac support hacks
148
149 /*
150   Here is what the Qt documentation says about how a menubar is chosen:
151
152      1) If the window has a QMenuBar then it is used. 2) If the window
153      is a modal then its menubar is used. If no menubar is specified
154      then a default menubar is used (as documented below) 3) If the
155      window has no parent then the default menubar is used (as
156      documented below).
157
158      The above 3 steps are applied all the way up the parent window
159      chain until one of the above are satisifed. If all else fails a
160      default menubar will be created, the default menubar on Qt/Mac is
161      an empty menubar, however you can create a different default
162      menubar by creating a parentless QMenuBar, the first one created
163      will thus be designated the default menubar, and will be used
164      whenever a default menubar is needed.
165
166   Thus, for Qt/Mac, we add the menus to a free standing menubar, so
167   that this menubar will be used also when one of LyX' dialogs has
168   focus. (JMarc)
169 */
170
171 void Menus::macxMenuBarInit(GuiView * view)
172 {
173         // The Mac menubar initialisation must be done only once!
174         static bool done = false;
175         if (done)
176                 return;
177         done = true;
178
179         /* Since Qt 4.2, the qt/mac menu code has special code for
180            specifying the role of a menu entry. However, it does not
181            work very well with our scheme of creating menus on demand,
182            and therefore we need to put these entries in a special
183            invisible menu. (JMarc)
184         */
185
186         /* The entries of our special mac menu. If we add support for
187          * special entries in Menus, we could imagine something
188          * like
189          *    SpecialItem About " "About LyX" "dialog-show aboutlyx"
190          * and therefore avoid hardcoding. I am not sure it is worth
191          * the hassle, though. (JMarc)
192          */
193         struct MacMenuEntry {
194                 kb_action action;
195                 char const * arg;
196                 char const * label;
197                 QAction::MenuRole role;
198         };
199
200         MacMenuEntry entries[] = {
201                 {LFUN_DIALOG_SHOW, "aboutlyx", "About LyX",
202                  QAction::AboutRole},
203                 {LFUN_DIALOG_SHOW, "prefs", "Preferences",
204                  QAction::PreferencesRole},
205                 {LFUN_RECONFIGURE, "", "Reconfigure",
206                  QAction::ApplicationSpecificRole},
207                 {LFUN_LYX_QUIT, "", "Quit LyX", QAction::QuitRole}
208         };
209         const size_t num_entries = sizeof(entries) / sizeof(entries[0]);
210
211         // the special menu for Menus.
212         Menu special;
213         for (size_t i = 0 ; i < num_entries ; ++i) {
214                 FuncRequest const func(entries[i].action,
215                                        from_utf8(entries[i].arg));
216                 special.add(MenuItem(MenuItem::Command, entries[i].label, func));
217         }
218         setSpecialMenu(special);
219
220         // add the entries to a QMenu that will eventually be empty
221         // and therefore invisible.
222         QMenu * qMenu = view->menuBar()->addMenu("special");
223
224         // we do not use 'special' because it is a temporary variable,
225         // whereas Menus::specialMenu points to a persistent copy.
226         Menu::const_iterator cit = specialMenu().begin();
227         Menu::const_iterator end = specialMenu().end();
228         for (size_t i = 0 ; cit != end ; ++cit, ++i) {
229                 Action * action = new Action(*view, QIcon(), cit->label(),
230                                              cit->func(), QString());
231                 action->setMenuRole(entries[i].role);
232                 qMenu->addAction(action);
233         }
234 }
235
236
237 MenuItem::MenuItem(Kind kind)
238         : kind_(kind), optional_(false)
239 {}
240
241
242 MenuItem::MenuItem(Kind kind, QString const & label,
243                    QString const & submenu, bool optional)
244         : kind_(kind), label_(label),
245           submenuname_(submenu), optional_(optional)
246 {
247         BOOST_ASSERT(kind == Submenu);
248 }
249
250
251 MenuItem::MenuItem(Kind kind, QString const & label,
252                    FuncRequest const & func, bool optional)
253         : kind_(kind), label_(label), func_(func), optional_(optional)
254 {
255         func_.origin = FuncRequest::MENU;
256 }
257
258
259 MenuItem::~MenuItem()
260 {}
261
262
263 void MenuItem::setSubmenu(Menu * menu)
264 {
265         submenu_.reset(menu);
266 }
267
268
269 QString MenuItem::label() const
270 {
271         return label_.split('|')[0];
272 }
273
274
275 QString MenuItem::shortcut() const
276 {
277         return label_.contains('|') ? label_.split('|')[1] : QString();
278 }
279
280
281 QString MenuItem::binding() const
282 {
283         if (kind_ != Command)
284                 return QString();
285
286         // Get the keys bound to this action, but keep only the
287         // first one later
288         KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func_);
289
290         if (bindings.size())
291                 return toqstr(bindings.begin()->print(KeySequence::ForGui));
292
293         LYXERR(Debug::KBMAP, "No binding for "
294                 << lyxaction.getActionName(func_.action)
295                 << '(' << func_.argument() << ')');
296         return QString();
297 }
298
299
300 void Menu::addWithStatusCheck(MenuItem const & i)
301 {
302         switch (i.kind()) {
303
304         case MenuItem::Command: {
305                 FuncStatus status = lyx::getStatus(i.func());
306                 if (status.unknown() || (!status.enabled() && i.optional()))
307                         break;
308                 items_.push_back(i);
309                 items_.back().status(status);
310                 break;
311         }
312
313         case MenuItem::Submenu: {
314                 if (i.submenu()) {
315                         bool enabled = false;
316                         for (const_iterator cit = i.submenu()->begin();
317                              cit != i.submenu()->end(); ++cit) {
318                                 if ((cit->kind() == MenuItem::Command
319                                      || cit->kind() == MenuItem::Submenu)
320                                     && cit->status().enabled()) {
321                                         enabled = true;
322                                         break;
323                                 }
324                         }
325                         if (enabled || !i.optional()) {
326                                 items_.push_back(i);
327                                 items_.back().status().enabled(enabled);
328                         }
329                 }
330                 else
331                         items_.push_back(i);
332                 break;
333         }
334
335         case MenuItem::Separator:
336                 if (!items_.empty() && items_.back().kind() != MenuItem::Separator)
337                         items_.push_back(i);
338                 break;
339
340         default:
341                 items_.push_back(i);
342         }
343 }
344
345
346 void Menu::read(Lexer & lex)
347 {
348         enum Menutags {
349                 md_item = 1,
350                 md_branches,
351                 md_documents,
352                 md_bookmarks,
353                 md_charstyles,
354                 md_custom,
355                 md_elements,
356                 md_endmenu,
357                 md_exportformats,
358                 md_importformats,
359                 md_lastfiles,
360                 md_optitem,
361                 md_optsubmenu,
362                 md_separator,
363                 md_submenu,
364                 md_toc,
365                 md_updateformats,
366                 md_viewformats,
367                 md_floatlistinsert,
368                 md_floatinsert,
369                 md_pasterecent,
370                 md_toolbars,
371                 md_last
372         };
373
374         struct keyword_item menutags[md_last - 1] = {
375                 { "bookmarks", md_bookmarks },
376                 { "branches", md_branches },
377                 { "charstyles", md_charstyles },
378                 { "custom", md_custom },
379                 { "documents", md_documents },
380                 { "elements", md_elements },
381                 { "end", md_endmenu },
382                 { "exportformats", md_exportformats },
383                 { "floatinsert", md_floatinsert },
384                 { "floatlistinsert", md_floatlistinsert },
385                 { "importformats", md_importformats },
386                 { "item", md_item },
387                 { "lastfiles", md_lastfiles },
388                 { "optitem", md_optitem },
389                 { "optsubmenu", md_optsubmenu },
390                 { "pasterecent", md_pasterecent },
391                 { "separator", md_separator },
392                 { "submenu", md_submenu },
393                 { "toc", md_toc },
394                 { "toolbars", md_toolbars },
395                 { "updateformats", md_updateformats },
396                 { "viewformats", md_viewformats }
397         };
398
399         lex.pushTable(menutags, md_last - 1);
400         if (lyxerr.debugging(Debug::PARSER))
401                 lex.printTable(lyxerr);
402
403         bool quit = false;
404         bool optional = false;
405
406         while (lex.isOK() && !quit) {
407                 switch (lex.lex()) {
408                 case md_optitem:
409                         optional = true;
410                         // fallback to md_item
411                 case md_item: {
412                         lex.next(true);
413                         docstring const name = translateIfPossible(lex.getDocString());
414                         lex.next(true);
415                         string const command = lex.getString();
416                         FuncRequest func = lyxaction.lookupFunc(command);
417                         add(MenuItem(MenuItem::Command, toqstr(name), func, optional));
418                         optional = false;
419                         break;
420                 }
421
422                 case md_separator:
423                         add(MenuItem(MenuItem::Separator));
424                         break;
425
426                 case md_lastfiles:
427                         add(MenuItem(MenuItem::Lastfiles));
428                         break;
429
430                 case md_charstyles:
431                         add(MenuItem(MenuItem::CharStyles));
432                         break;
433
434                 case md_custom:
435                         add(MenuItem(MenuItem::Custom));
436                         break;
437
438                 case md_elements:
439                         add(MenuItem(MenuItem::Elements));
440                         break;
441
442                 case md_documents:
443                         add(MenuItem(MenuItem::Documents));
444                         break;
445
446                 case md_bookmarks:
447                         add(MenuItem(MenuItem::Bookmarks));
448                         break;
449
450                 case md_toc:
451                         add(MenuItem(MenuItem::Toc));
452                         break;
453
454                 case md_viewformats:
455                         add(MenuItem(MenuItem::ViewFormats));
456                         break;
457
458                 case md_updateformats:
459                         add(MenuItem(MenuItem::UpdateFormats));
460                         break;
461
462                 case md_exportformats:
463                         add(MenuItem(MenuItem::ExportFormats));
464                         break;
465
466                 case md_importformats:
467                         add(MenuItem(MenuItem::ImportFormats));
468                         break;
469
470                 case md_floatlistinsert:
471                         add(MenuItem(MenuItem::FloatListInsert));
472                         break;
473
474                 case md_floatinsert:
475                         add(MenuItem(MenuItem::FloatInsert));
476                         break;
477
478                 case md_pasterecent:
479                         add(MenuItem(MenuItem::PasteRecent));
480                         break;
481
482                 case md_toolbars:
483                         add(MenuItem(MenuItem::Toolbars));
484                         break;
485
486                 case md_branches:
487                         add(MenuItem(MenuItem::Branches));
488                         break;
489
490                 case md_optsubmenu:
491                         optional = true;
492                         // fallback to md_submenu
493                 case md_submenu: {
494                         lex.next(true);
495                         docstring const mlabel = translateIfPossible(lex.getDocString());
496                         lex.next(true);
497                         docstring const mname = lex.getDocString();
498                         add(MenuItem(MenuItem::Submenu,
499                                 toqstr(mlabel), toqstr(mname), optional));
500                         optional = false;
501                         break;
502                 }
503
504                 case md_endmenu:
505                         quit = true;
506                         break;
507
508                 default:
509                         lex.printError("Menu::read: "
510                                        "Unknown menu tag: `$$Token'");
511                         break;
512                 }
513         }
514         lex.popTable();
515 }
516
517
518 MenuItem const & Menu::operator[](size_type i) const
519 {
520         return items_[i];
521 }
522
523
524 bool Menu::hasFunc(FuncRequest const & func) const
525 {
526         for (const_iterator it = begin(), et = end(); it != et; ++it)
527                 if (it->func() == func)
528                         return true;
529         return false;
530 }
531
532
533 void Menu::checkShortcuts() const
534 {
535         // This is a quadratic algorithm, but we do not care because
536         // menus are short enough
537         for (const_iterator it1 = begin(); it1 != end(); ++it1) {
538                 QString shortcut = it1->shortcut();
539                 if (shortcut.isEmpty())
540                         continue;
541                 if (!it1->label().contains(shortcut))
542                         lyxerr << "Menu warning: menu entry \""
543                                << fromqstr(it1->label())
544                                << "\" does not contain shortcut `"
545                                << fromqstr(shortcut) << "'." << endl;
546                 for (const_iterator it2 = begin(); it2 != it1 ; ++it2) {
547                         if (!it2->shortcut().compare(shortcut, Qt::CaseInsensitive)) {
548                                 lyxerr << "Menu warning: menu entries "
549                                        << '"' << fromqstr(it1->fulllabel())
550                                        << "\" and \"" << fromqstr(it2->fulllabel())
551                                        << "\" share the same shortcut."
552                                        << endl;
553                         }
554                 }
555         }
556 }
557
558
559 bool Menu::searchMenu(FuncRequest const & func, vector<docstring> & names) const
560 {
561         const_iterator m = begin();
562         const_iterator m_end = end();
563         for (; m != m_end; ++m) {
564                 if (m->kind() == MenuItem::Command && m->func() == func) {
565                         names.push_back(qstring_to_ucs4(m->label()));
566                         return true;
567                 }
568                 if (m->kind() == MenuItem::Submenu) {
569                         names.push_back(qstring_to_ucs4(m->label()));
570                         Menu const & submenu = *m->submenu();
571                         if (submenu.searchMenu(func, names))
572                                 return true;
573                         names.pop_back();
574                 }
575         }
576         return false;
577 }
578
579
580 namespace {
581
582 bool compareFormat(Format const * p1, Format const * p2)
583 {
584         return *p1 < *p2;
585 }
586
587
588 QString limitStringLength(docstring const & str)
589 {
590         size_t const max_item_length = 45;
591
592         if (str.size() > max_item_length)
593                 return toqstr(str.substr(0, max_item_length - 3) + "...");
594
595         return toqstr(str);
596 }
597
598
599 void expandLastfiles(Menu & tomenu)
600 {
601         LastFilesSection::LastFiles const & lf = LyX::cref().session().lastFiles().lastFiles();
602         LastFilesSection::LastFiles::const_iterator lfit = lf.begin();
603
604         int ii = 1;
605
606         for (; lfit != lf.end() && ii < 10; ++lfit, ++ii) {
607                 string const file = lfit->absFilename();
608                 QString const label = QString("%1. %2|%3").arg(ii)
609                         .arg(toqstr(makeDisplayPath(file, 30))).arg(ii);
610                 tomenu.add(MenuItem(MenuItem::Command, label, FuncRequest(LFUN_FILE_OPEN, file)));
611         }
612 }
613
614
615 void expandDocuments(Menu & tomenu)
616 {
617         Buffer * first = theBufferList().first();
618         if (first) {
619                 Buffer * b = first;
620                 int ii = 1;
621                 
622                 // We cannot use a for loop as the buffer list cycles.
623                 do {
624                         QString label = toqstr(b->fileName().displayName(20));
625                         if (!b->isClean())
626                                 label += "*";
627                         if (ii < 10)
628                                 label = QString::number(ii) + ". " + label + '|' + QString::number(ii);
629                         tomenu.add(MenuItem(MenuItem::Command, label,
630                                 FuncRequest(LFUN_BUFFER_SWITCH, b->absFileName())));
631                         
632                         b = theBufferList().next(b);
633                         ++ii;
634                 } while (b != first); 
635         } else {
636                 tomenu.add(MenuItem(MenuItem::Command, qt_("No Documents Open!"),
637                            FuncRequest(LFUN_NOACTION)));
638         }
639 }
640
641
642 void expandBookmarks(Menu & tomenu)
643 {
644         lyx::BookmarksSection const & bm = LyX::cref().session().bookmarks();
645
646         for (size_t i = 1; i <= bm.size(); ++i) {
647                 if (bm.isValid(i)) {
648                         string const file = bm.bookmark(i).filename.absFilename();
649                         QString const label = QString("%1. %2|%3").arg(i)
650                                 .arg(toqstr(makeDisplayPath(file, 20))).arg(i);
651                         tomenu.add(MenuItem(MenuItem::Command, label,
652                                 FuncRequest(LFUN_BOOKMARK_GOTO, convert<docstring>(i))));
653                 }
654         }
655 }
656
657
658 void expandFormats(MenuItem::Kind kind, Menu & tomenu, Buffer const * buf)
659 {
660         if (!buf && kind != MenuItem::ImportFormats) {
661                 tomenu.add(MenuItem(MenuItem::Command,
662                                     qt_("No Document Open!"),
663                                     FuncRequest(LFUN_NOACTION)));
664                 return;
665         }
666
667         typedef vector<Format const *> Formats;
668         Formats formats;
669         kb_action action;
670
671         switch (kind) {
672         case MenuItem::ImportFormats:
673                 formats = theConverters().importableFormats();
674                 action = LFUN_BUFFER_IMPORT;
675                 break;
676         case MenuItem::ViewFormats:
677                 formats = buf->exportableFormats(true);
678                 action = LFUN_BUFFER_VIEW;
679                 break;
680         case MenuItem::UpdateFormats:
681                 formats = buf->exportableFormats(true);
682                 action = LFUN_BUFFER_UPDATE;
683                 break;
684         default:
685                 formats = buf->exportableFormats(false);
686                 action = LFUN_BUFFER_EXPORT;
687         }
688         sort(formats.begin(), formats.end(), &compareFormat);
689
690         Formats::const_iterator fit = formats.begin();
691         Formats::const_iterator end = formats.end();
692         for (; fit != end ; ++fit) {
693                 if ((*fit)->dummy())
694                         continue;
695                 QString label = toqstr((*fit)->prettyname());
696                 QString const shortcut = toqstr((*fit)->shortcut());
697
698                 switch (kind) {
699                 case MenuItem::ImportFormats:
700                         // FIXME: This is a hack, we should rather solve
701                         // FIXME: bug 2488 instead.
702                         if ((*fit)->name() == "text")
703                                 label = qt_("Plain Text");
704                         else if ((*fit)->name() == "textparagraph")
705                                 label = qt_("Plain Text, Join Lines");
706                         label += "...";
707                         break;
708                 case MenuItem::ViewFormats:
709                 case MenuItem::ExportFormats:
710                 case MenuItem::UpdateFormats:
711                         if (!(*fit)->documentFormat())
712                                 continue;
713                         break;
714                 default:
715                         BOOST_ASSERT(false);
716                         break;
717                 }
718                 // FIXME: if we had proper support for translating the
719                 // format names defined in configure.py, there would
720                 // not be a need to check whether the shortcut is
721                 // correct. If we add it uncondiitonally, it would
722                 // create useless warnings on bad shortcuts
723                 if (!shortcut.isEmpty() && label.contains(shortcut))
724                         label += '|' + shortcut;
725
726                 if (buf)
727                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
728                                 FuncRequest(action, (*fit)->name())));
729                 else
730                         tomenu.add(MenuItem(MenuItem::Command, label,
731                                 FuncRequest(action, (*fit)->name())));
732         }
733 }
734
735
736 void expandFloatListInsert(Menu & tomenu, Buffer const * buf)
737 {
738         if (!buf) {
739                 tomenu.add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
740                                     FuncRequest(LFUN_NOACTION)));
741                 return;
742         }
743
744         FloatList const & floats = buf->params().documentClass().floats();
745         FloatList::const_iterator cit = floats.begin();
746         FloatList::const_iterator end = floats.end();
747         for (; cit != end; ++cit) {
748                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
749                                     qt_(cit->second.listName()),
750                                     FuncRequest(LFUN_FLOAT_LIST,
751                                                 cit->second.type())));
752         }
753 }
754
755
756 void expandFloatInsert(Menu & tomenu, Buffer const * buf)
757 {
758         if (!buf) {
759                 tomenu.add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
760                                     FuncRequest(LFUN_NOACTION)));
761                 return;
762         }
763
764         FloatList const & floats = buf->params().documentClass().floats();
765         FloatList::const_iterator cit = floats.begin();
766         FloatList::const_iterator end = floats.end();
767         for (; cit != end; ++cit) {
768                 // normal float
769                 QString const label = qt_(cit->second.name());
770                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, label,
771                                     FuncRequest(LFUN_FLOAT_INSERT,
772                                                 cit->second.type())));
773         }
774 }
775
776
777 void expandFlexInsert(Menu & tomenu, Buffer const * buf, string s)
778 {
779         if (!buf) {
780                 tomenu.add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
781                                     FuncRequest(LFUN_NOACTION)));
782                 return;
783         }
784         TextClass::InsetLayouts const & insetLayouts =
785                 buf->params().documentClass().insetLayouts();
786         TextClass::InsetLayouts::const_iterator cit = insetLayouts.begin();
787         TextClass::InsetLayouts::const_iterator end = insetLayouts.end();
788         for (; cit != end; ++cit) {
789                 docstring const label = cit->first;
790                 if (cit->second.lyxtype() == s)
791                         tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, 
792                                 toqstr(label), FuncRequest(LFUN_FLEX_INSERT,
793                                                 label)));
794         }
795 }
796
797
798 size_t const max_number_of_items = 25;
799
800 void expandToc2(Menu & tomenu, Toc const & toc_list,
801                 size_t from, size_t to, int depth)
802 {
803         int shortcut_count = 0;
804
805         // check whether depth is smaller than the smallest depth in toc.
806         int min_depth = 1000;
807         for (size_t i = from; i < to; ++i)
808                 min_depth = min(min_depth, toc_list[i].depth());
809         if (min_depth > depth)
810                 depth = min_depth;
811
812         if (to - from <= max_number_of_items) {
813                 for (size_t i = from; i < to; ++i) {
814                         QString label(4 * max(0, toc_list[i].depth() - depth), ' ');
815                         label += limitStringLength(toc_list[i].str());
816                         if (toc_list[i].depth() == depth
817                             && shortcut_count < 9) {
818                                 if (label.contains(QString::number(shortcut_count + 1)))
819                                         label += '|' + QString::number(++shortcut_count);
820                         }
821                         tomenu.add(MenuItem(MenuItem::Command, label,
822                                             FuncRequest(toc_list[i].action())));
823                 }
824         } else {
825                 size_t pos = from;
826                 while (pos < to) {
827                         size_t new_pos = pos + 1;
828                         while (new_pos < to &&
829                                toc_list[new_pos].depth() > depth)
830                                 ++new_pos;
831
832                         QString label(4 * max(0, toc_list[pos].depth() - depth), ' ');
833                         label += limitStringLength(toc_list[pos].str());
834                         if (toc_list[pos].depth() == depth &&
835                             shortcut_count < 9) {
836                                 if (label.contains(QString::number(shortcut_count + 1)))
837                                         label += '|' + QString::number(++shortcut_count);
838                         }
839                         if (new_pos == pos + 1) {
840                                 tomenu.add(MenuItem(MenuItem::Command,
841                                                     label, FuncRequest(toc_list[pos].action())));
842                         } else {
843                                 MenuItem item(MenuItem::Submenu, label);
844                                 item.setSubmenu(new Menu);
845                                 expandToc2(*item.submenu(),
846                                            toc_list, pos, new_pos, depth + 1);
847                                 tomenu.add(item);
848                         }
849                         pos = new_pos;
850                 }
851         }
852 }
853
854
855 void expandToc(Menu & tomenu, Buffer const * buf)
856 {
857         // To make things very cleanly, we would have to pass buf to
858         // all MenuItem constructors and to expandToc2. However, we
859         // know that all the entries in a TOC will be have status_ ==
860         // OK, so we avoid this unnecessary overhead (JMarc)
861
862         if (!buf) {
863                 tomenu.add(MenuItem(MenuItem::Command, qt_("No Document Open!"),
864                                     FuncRequest(LFUN_NOACTION)));
865                 return;
866         }
867
868         Buffer* cbuf = const_cast<Buffer*>(buf);
869         cbuf->tocBackend().update();
870         cbuf->structureChanged();
871
872         // Add an entry for the master doc if this is a child doc
873         Buffer const * const master = buf->masterBuffer();
874         if (buf != master) {
875                 ParIterator const pit = par_iterator_begin(master->inset());
876                 string const arg = convert<string>(pit->id());
877                 FuncRequest f(LFUN_PARAGRAPH_GOTO, arg);
878                 tomenu.add(MenuItem(MenuItem::Command, qt_("Master Document"), f));
879         }
880
881         FloatList const & floatlist = buf->params().documentClass().floats();
882         TocList const & toc_list = buf->tocBackend().tocs();
883         TocList::const_iterator cit = toc_list.begin();
884         TocList::const_iterator end = toc_list.end();
885         for (; cit != end; ++cit) {
886                 // Handle this later
887                 if (cit->first == "tableofcontents")
888                         continue;
889
890                 // All the rest is for floats
891                 auto_ptr<Menu> menu(new Menu);
892                 TocIterator ccit = cit->second.begin();
893                 TocIterator eend = cit->second.end();
894                 for (; ccit != eend; ++ccit) {
895                         QString const label = limitStringLength(ccit->str());
896                         menu->add(MenuItem(MenuItem::Command, label,
897                                            FuncRequest(ccit->action())));
898                 }
899                 string const & floatName = floatlist.getType(cit->first).listName();
900                 QString label;
901                 if (!floatName.empty())
902                         label = qt_(floatName);
903                 // BUG3633: listings is not a proper float so its name
904                 // is not shown in floatlist.
905                 else if (cit->first == "equation")
906                         label = qt_("List of Equations");
907                 else if (cit->first == "index")
908                         label = qt_("List of Indexes");
909                 else if (cit->first == "listing")
910                         label = qt_("List of Listings");
911                 else if (cit->first == "marginalnote")
912                         label = qt_("List of Marginal notes");
913                 else if (cit->first == "note")
914                         label = qt_("List of Notes");
915                 else if (cit->first == "footnote")
916                         label = qt_("List of Foot notes");
917                 else if (cit->first == "label")
918                         label = qt_("Labels and References");
919                 else if (cit->first == "citation")
920                         label = qt_("List of Citations");
921                 // this should not happen now, but if something else like
922                 // listings is added later, this can avoid an empty menu name.
923                 else
924                         label = qt_("Other floats");
925                 MenuItem item(MenuItem::Submenu, label);
926                 item.setSubmenu(menu.release());
927                 tomenu.add(item);
928         }
929
930         // Handle normal TOC
931         cit = toc_list.find("tableofcontents");
932         if (cit == end) {
933                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command,
934                                     qt_("No Table of contents"),
935                                     FuncRequest()));
936         } else {
937                 expandToc2(tomenu, cit->second, 0, cit->second.size(), 0);
938         }
939 }
940
941
942 void expandPasteRecent(Menu & tomenu)
943 {
944         vector<docstring> const sel = cap::availableSelections();
945
946         vector<docstring>::const_iterator cit = sel.begin();
947         vector<docstring>::const_iterator end = sel.end();
948
949         for (unsigned int index = 0; cit != end; ++cit, ++index) {
950                 tomenu.add(MenuItem(MenuItem::Command, toqstr(*cit),
951                                     FuncRequest(LFUN_PASTE, convert<string>(index))));
952         }
953 }
954
955
956 void expandToolbars(Menu & tomenu)
957 {
958         //
959         // extracts the toolbars from the backend
960         ToolbarBackend::Toolbars::const_iterator cit = toolbarbackend.begin();
961         ToolbarBackend::Toolbars::const_iterator end = toolbarbackend.end();
962
963         for (; cit != end; ++cit) {
964                 QString label = qt_(cit->gui_name);
965                 // frontends are not supposed to turn on/off toolbars,
966                 // if they cannot update ToolbarBackend::flags. That
967                 // is to say, ToolbarsBackend::flags should reflect
968                 // the true state of toolbars.
969                 //
970                 // menu is displayed as
971                 //       on/off review
972                 // and
973                 //              review (auto)
974                 // in the case of auto.
975                 if (cit->flags & ToolbarInfo::AUTO)
976                         label += qt_(" (auto)");
977                 tomenu.add(MenuItem(MenuItem::Command, label,
978                                     FuncRequest(LFUN_TOOLBAR_TOGGLE, cit->name + " allowauto")));
979         }
980 }
981
982
983 void expandBranches(Menu & tomenu, Buffer const * buf)
984 {
985         if (!buf) {
986                 tomenu.add(MenuItem(MenuItem::Command,
987                                     qt_("No Document Open!"),
988                                     FuncRequest(LFUN_NOACTION)));
989                 return;
990         }
991
992         BufferParams const & params = buf->masterBuffer()->params();
993         if (params.branchlist().empty()) {
994                 tomenu.add(MenuItem(MenuItem::Command,
995                                     qt_("No Branch in Document!"),
996                                     FuncRequest(LFUN_NOACTION)));
997                 return;
998         }
999
1000         BranchList::const_iterator cit = params.branchlist().begin();
1001         BranchList::const_iterator end = params.branchlist().end();
1002
1003         for (int ii = 1; cit != end; ++cit, ++ii) {
1004                 docstring label = cit->getBranch();
1005                 if (ii < 10)
1006                         label = convert<docstring>(ii) + ". " + label + char_type('|') + convert<docstring>(ii);
1007                 tomenu.addWithStatusCheck(MenuItem(MenuItem::Command, toqstr(label),
1008                                     FuncRequest(LFUN_BRANCH_INSERT,
1009                                                 cit->getBranch())));
1010         }
1011 }
1012
1013
1014 } // namespace anon
1015
1016
1017 void Menus::expand(Menu const & frommenu, Menu & tomenu,
1018                          Buffer const * buf) const
1019 {
1020         if (!tomenu.empty())
1021                 tomenu.clear();
1022
1023         for (Menu::const_iterator cit = frommenu.begin();
1024              cit != frommenu.end() ; ++cit) {
1025                 switch (cit->kind()) {
1026                 case MenuItem::Lastfiles:
1027                         expandLastfiles(tomenu);
1028                         break;
1029
1030                 case MenuItem::Documents:
1031                         expandDocuments(tomenu);
1032                         break;
1033
1034                 case MenuItem::Bookmarks:
1035                         expandBookmarks(tomenu);
1036                         break;
1037
1038                 case MenuItem::ImportFormats:
1039                 case MenuItem::ViewFormats:
1040                 case MenuItem::UpdateFormats:
1041                 case MenuItem::ExportFormats:
1042                         expandFormats(cit->kind(), tomenu, buf);
1043                         break;
1044
1045                 case MenuItem::CharStyles:
1046                         expandFlexInsert(tomenu, buf, "charstyle");
1047                         break;
1048
1049                 case MenuItem::Custom:
1050                         expandFlexInsert(tomenu, buf, "custom");
1051                         break;
1052
1053                 case MenuItem::Elements:
1054                         expandFlexInsert(tomenu, buf, "element");
1055                         break;
1056
1057                 case MenuItem::FloatListInsert:
1058                         expandFloatListInsert(tomenu, buf);
1059                         break;
1060
1061                 case MenuItem::FloatInsert:
1062                         expandFloatInsert(tomenu, buf);
1063                         break;
1064
1065                 case MenuItem::PasteRecent:
1066                         expandPasteRecent(tomenu);
1067                         break;
1068
1069                 case MenuItem::Toolbars:
1070                         expandToolbars(tomenu);
1071                         break;
1072
1073                 case MenuItem::Branches:
1074                         expandBranches(tomenu, buf);
1075                         break;
1076
1077                 case MenuItem::Toc:
1078                         expandToc(tomenu, buf);
1079                         break;
1080
1081                 case MenuItem::Submenu: {
1082                         MenuItem item(*cit);
1083                         item.setSubmenu(new Menu(cit->submenuname()));
1084                         expand(getMenu(cit->submenuname()),
1085                                *item.submenu(), buf);
1086                         tomenu.addWithStatusCheck(item);
1087                 }
1088                 break;
1089
1090                 case MenuItem::Separator:
1091                         tomenu.addWithStatusCheck(*cit);
1092                         break;
1093
1094                 case MenuItem::Command:
1095                         if (!specialmenu_.hasFunc(cit->func()))
1096                                 tomenu.addWithStatusCheck(*cit);
1097                 }
1098         }
1099
1100         // we do not want the menu to end with a separator
1101         if (!tomenu.empty()
1102             && tomenu.items_.back().kind() == MenuItem::Separator)
1103                 tomenu.items_.pop_back();
1104
1105         // Check whether the shortcuts are unique
1106         tomenu.checkShortcuts();
1107 }
1108
1109
1110 void Menus::read(Lexer & lex)
1111 {
1112         enum Menutags {
1113                 md_menu = 1,
1114                 md_menubar,
1115                 md_endmenuset,
1116                 md_last
1117         };
1118
1119         struct keyword_item menutags[md_last - 1] = {
1120                 { "end", md_endmenuset },
1121                 { "menu", md_menu },
1122                 { "menubar", md_menubar }
1123         };
1124
1125         //consistency check
1126         if (compare_ascii_no_case(lex.getString(), "menuset")) {
1127                 lyxerr << "Menubackend::read: ERROR wrong token:`"
1128                        << lex.getString() << '\'' << endl;
1129         }
1130
1131         lex.pushTable(menutags, md_last - 1);
1132         if (lyxerr.debugging(Debug::PARSER))
1133                 lex.printTable(lyxerr);
1134
1135         bool quit = false;
1136
1137         while (lex.isOK() && !quit) {
1138                 switch (lex.lex()) {
1139                 case md_menubar:
1140                         menubar_.read(lex);
1141                         break;
1142                 case md_menu: {
1143                         lex.next(true);
1144                         QString const name = toqstr(lex.getDocString());
1145                         if (hasMenu(name)) {
1146                                 getMenu(name).read(lex);
1147                         } else {
1148                                 Menu menu(name);
1149                                 menu.read(lex);
1150                                 add(menu);
1151                         }
1152                         break;
1153                 }
1154                 case md_endmenuset:
1155                         quit = true;
1156                         break;
1157                 default:
1158                         lex.printError("menubackend::read: "
1159                                        "Unknown menu tag: `$$Token'");
1160                         break;
1161                 }
1162         }
1163         lex.popTable();
1164 }
1165
1166
1167 void Menus::add(Menu const & menu)
1168 {
1169         menulist_.push_back(menu);
1170 }
1171
1172
1173 bool Menus::hasMenu(QString const & name) const
1174 {
1175         return find_if(begin(), end(), MenuNamesEqual(name)) != end();
1176 }
1177
1178
1179 Menu const & Menus::getMenu(QString const & name) const
1180 {
1181         const_iterator cit = find_if(begin(), end(), MenuNamesEqual(name));
1182         if (cit == end())
1183                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1184         BOOST_ASSERT(cit != end());
1185         return (*cit);
1186 }
1187
1188
1189 Menu & Menus::getMenu(QString const & name)
1190 {
1191         iterator it = find_if(begin(), end(), MenuNamesEqual(name));
1192         if (it == end())
1193                 lyxerr << "No submenu named " << fromqstr(name) << endl;
1194         BOOST_ASSERT(it != end());
1195         return (*it);
1196 }
1197
1198
1199 Menu const & Menus::getMenubar() const
1200 {
1201         return menubar_;
1202 }
1203
1204
1205 } // namespace frontend
1206 } // namespace lyx
1207
1208 #include "Menus_moc.cpp"