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