]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
7166dd4d58ae49206e271155b90c9f6f7a13f298
[features.git] / src / frontends / qt4 / GuiToolbar.cpp
1 /**
2  * \file qt4/GuiToolbar.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Stefan Schimanski
11  * \author Abdelrazak Younes
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "GuiToolbar.h"
19
20 #include "Action.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiView.h"
24 #include "IconPalette.h"
25 #include "InsertTableWidget.h"
26 #include "qt_helpers.h"
27 #include "Toolbars.h"
28
29 #include "Buffer.h"
30 #include "BufferParams.h"
31 #include "BufferView.h"
32 #include "Cursor.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "KeyMap.h"
36 #include "Layout.h"
37 #include "LyXFunc.h"
38 #include "LyXRC.h"
39 #include "Paragraph.h"
40 #include "TextClass.h"
41
42 #include "support/debug.h"
43 #include "support/filetools.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46
47 #include <QAbstractItemDelegate>
48 #include <QAbstractTextDocumentLayout>
49 #include <QApplication>
50 #include <QComboBox>
51 #include <QFontMetrics>
52 #include <QHeaderView>
53 #include <QItemDelegate>
54 #include <QKeyEvent>
55 #include <QList>
56 #include <QListView>
57 #include <QPainter>
58 #include <QPixmap>
59 #include <QSettings>
60 #include <QSortFilterProxyModel>
61 #include <QStandardItem>
62 #include <QStandardItemModel>
63 #include <QString>
64 #include <QTextDocument>
65 #include <QTextFrame>
66 #include <QToolBar>
67 #include <QToolButton>
68 #include <QVariant>
69
70 #include "support/lassert.h"
71
72 using namespace std;
73 using namespace lyx::support;
74
75 namespace lyx {
76 namespace frontend {
77
78 /////////////////////////////////////////////////////////////////////
79 //
80 // GuiLayoutBox
81 //
82 /////////////////////////////////////////////////////////////////////
83
84 class LayoutItemDelegate : public QItemDelegate {
85 public:
86         ///
87         explicit LayoutItemDelegate(QObject * parent = 0)
88                 : QItemDelegate(parent)
89         {}
90         
91         ///
92         void paint(QPainter * painter, QStyleOptionViewItem const & option,
93                 QModelIndex const & index) const
94         {
95                 QStyleOptionViewItem opt = option;
96                 
97                 // default background
98                 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
99                 
100                 // category header?
101                 if (lyxrc.group_layouts) {
102                         QSortFilterProxyModel const * model
103                         = static_cast<QSortFilterProxyModel const *>(index.model());
104                         
105                         QString stdCat = category(*model->sourceModel(), 0);
106                         QString cat = category(*index.model(), index.row());
107                         
108                         // not the standard layout and not the same as in the previous line?
109                         if (stdCat != cat
110                             && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
111                                 painter->save();
112                                 
113                                 // draw unselected background
114                                 QStyle::State state = opt.state;
115                                 opt.state = opt.state & ~QStyle::State_Selected;
116                                 drawBackground(painter, opt, index);
117                                 opt.state = state;
118                                 
119                                 // draw category header
120                                 drawCategoryHeader(painter, opt, 
121                                         category(*index.model(), index.row()));
122
123                                 // move rect down below header
124                                 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
125                                 
126                                 painter->restore();
127                         }
128                 }
129
130                 QItemDelegate::paint(painter, opt, index);
131         }
132         
133         ///
134         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
135                          const QRect & /*rect*/, const QString & text ) const
136         {
137                 QString utext = underlineFilter(text);
138
139                 // Draw the rich text.
140                 painter->save();
141                 QColor col = opt.palette.text().color();
142                 if (opt.state & QStyle::State_Selected)
143                         col = opt.palette.highlightedText().color();
144                 QAbstractTextDocumentLayout::PaintContext context;
145                 context.palette.setColor(QPalette::Text, col);
146                 
147                 QTextDocument doc;
148                 doc.setDefaultFont(opt.font);
149                 doc.setHtml(utext);
150                 
151                 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
152                 fmt.setMargin(0);
153                 doc.rootFrame()->setFrameFormat(fmt);
154                 
155                 painter->translate(opt.rect.x() + 5,
156                         opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
157                 doc.documentLayout()->draw(painter, context);
158                 painter->restore();
159         }
160         
161         ///
162         QSize sizeHint(QStyleOptionViewItem const & opt,
163                 QModelIndex const & index) const
164         {
165                 GuiLayoutBox * combo = static_cast<GuiLayoutBox *>(parent());
166                 QSortFilterProxyModel const * model
167                 = static_cast<QSortFilterProxyModel const *>(index.model());    
168                 QSize size = QItemDelegate::sizeHint(opt, index);
169                 
170                 /// QComboBox uses the first row height to estimate the
171                 /// complete popup height during QComboBox::showPopup().
172                 /// To avoid scrolling we have to sneak in space for the headers.
173                 /// So we tweak this value accordingly. It's not nice, but the
174                 /// only possible way it seems.
175                 if (lyxrc.group_layouts && index.row() == 0 && combo->inShowPopup_) {
176                         int itemHeight = size.height();
177                         
178                         // we have to show \c cats many headers:
179                         unsigned cats = combo->visibleCategories_;
180                         
181                         // and we have \c n items to distribute the needed space over
182                         unsigned n = combo->model()->rowCount();
183                         
184                         // so the needed average height (rounded upwards) is:
185                         size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n); 
186                         return size;
187                 }
188
189                 // Add space for the category headers here?
190                 // Not for the standard layout though.
191                 QString stdCat = category(*model->sourceModel(), 0);
192                 QString cat = category(*index.model(), index.row());
193                 if (lyxrc.group_layouts && stdCat != cat
194                     && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
195                         size.setHeight(size.height() + headerHeight(opt));
196                 }
197
198                 return size;
199         }
200         
201 private:
202         ///
203         QString category(QAbstractItemModel const & model, int row) const
204         {
205                 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
206         }
207                 
208         ///
209         int headerHeight(QStyleOptionViewItem const & opt) const
210         {
211                 return opt.fontMetrics.height() * 8 / 10;
212         }
213         ///
214         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
215                 QString const & category) const
216         {
217                 // slightly blended color
218                 QColor lcol = opt.palette.text().color();
219                 lcol.setAlpha(127);
220                 painter->setPen(lcol);
221                 
222                 // set 80% scaled, bold font
223                 QFont font = opt.font;
224                 font.setBold(true);
225                 font.setWeight(QFont::Black);
226                 font.setPointSize(opt.font.pointSize() * 8 / 10);
227                 painter->setFont(font);
228                 
229                 // draw the centered text
230                 QFontMetrics fm(font);
231                 int w = fm.width(category);
232                 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
233                 int y = opt.rect.y() + fm.ascent();
234                 int left = x;
235                 int right = x + w;
236                 painter->drawText(x, y, category);
237                 
238                 // the vertical position of the line: middle of lower case chars
239                 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
240                 
241                 // draw the horizontal line
242                 if (!category.isEmpty()) {
243                         painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
244                         painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
245                 } else
246                         painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
247         }
248
249         
250         ///
251         QString underlineFilter(QString const & s) const
252         {
253                 // get filter
254                 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
255                 QString const & f = p->filter();
256                 if (f.isEmpty())
257                         return s;
258                 
259                 // step through data item and put "(x)" for every matching character
260                 QString r;
261                 int lastp = -1;
262                 p->filter();
263                 for (int i = 0; i < f.length(); ++i) {
264                         int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
265                         LASSERT(p != -1, /**/);
266                         if (lastp == p - 1 && lastp != -1) {
267                                 // remove ")" and append "x)"
268                                 r = r.left(r.length() - 4) + s[p] + "</u>";
269                         } else {
270                                 // append "(x)"
271                                 r += s.mid(lastp + 1, p - lastp - 1);
272                                 r += QString("<u>") + s[p] + "</u>";
273                         }
274                         lastp = p;
275                 }
276                 r += s.mid(lastp + 1);
277                 return r;
278         }
279 };
280
281
282 class GuiLayoutFilterModel : public QSortFilterProxyModel {
283 public:
284         ///
285         GuiLayoutFilterModel(QObject * parent = 0)
286                 : QSortFilterProxyModel(parent)
287         {}
288         
289         ///
290         void triggerLayoutChange()
291         {
292                 layoutAboutToBeChanged();
293                 layoutChanged();
294         }
295 };
296
297
298 GuiLayoutBox::GuiLayoutBox(GuiToolbar * bar, GuiView & owner)
299         : owner_(owner), bar_(bar), lastSel_(-1),
300           layoutItemDelegate_(new LayoutItemDelegate(this)),
301           visibleCategories_(0), inShowPopup_(false)
302 {
303         setSizeAdjustPolicy(QComboBox::AdjustToContents);
304         setFocusPolicy(Qt::ClickFocus);
305         setMinimumWidth(sizeHint().width());
306         setMaxVisibleItems(100);
307
308         // set the layout model with two columns
309         // 1st: translated layout names
310         // 2nd: raw layout names
311         model_ = new QStandardItemModel(0, 2, this);
312         filterModel_ = new GuiLayoutFilterModel(this);
313         filterModel_->setSourceModel(model_);
314         setModel(filterModel_);
315
316         // for the filtering we have to intercept characters
317         view()->installEventFilter(this);
318         view()->setItemDelegateForColumn(0, layoutItemDelegate_);
319         
320         QObject::connect(this, SIGNAL(activated(int)),
321                 this, SLOT(selected(int)));
322         QObject::connect(bar_, SIGNAL(iconSizeChanged(QSize)),
323                 this, SLOT(setIconSize(QSize)));
324
325         owner_.setLayoutDialog(this);
326         updateContents(true);
327 }
328
329
330 void GuiLayoutBox::setFilter(QString const & s)
331 {
332         bool enabled = view()->updatesEnabled();
333         view()->setUpdatesEnabled(false);
334
335         // remember old selection
336         int sel = currentIndex();
337         if (sel != -1)
338                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
339
340         filter_ = s;
341         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
342         countCategories();
343         
344         // restore old selection
345         if (lastSel_ != -1) {
346                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
347                 if (i.isValid())
348                         setCurrentIndex(i.row());
349         }
350         
351         // Workaround to resize to content size
352         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
353         //        does not help.
354         if (view()->isVisible()) {
355                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
356                 // the hack in the item delegate to make space for the headers.
357                 // We do not call our implementation of showPopup because that
358                 // would reset the filter again. This is only needed if the user clicks
359                 // on the QComboBox.
360                 LASSERT(!inShowPopup_, /**/);
361                 inShowPopup_ = true;
362                 QComboBox::showPopup();
363                 inShowPopup_ = false;
364
365                 // The item delegate hack is off again. So trigger a relayout of the popup.
366                 filterModel_->triggerLayoutChange();
367                 
368                 if (!s.isEmpty())
369                         owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
370                                                  "Press ESC to remove filter."),
371                                                qstring_to_ucs4(s)));
372                 else
373                         owner_.message(_("Enter characters to filter the layout list."));
374         }
375         
376         view()->setUpdatesEnabled(enabled);
377 }
378
379
380 void GuiLayoutBox::countCategories()
381 {
382         int n = filterModel_->rowCount();
383         visibleCategories_ = 0;
384         if (n == 0 || !lyxrc.group_layouts)
385                 return;
386
387         // skip the "Standard" category
388         QString prevCat = model_->index(0, 2).data().toString(); 
389
390         // count categories
391         for (int i = 0; i < n; ++i) {
392                 QString cat = filterModel_->index(i, 2).data().toString();
393                 if (cat != prevCat)
394                         ++visibleCategories_;
395                 prevCat = cat;
396         }
397 }
398
399
400 QString GuiLayoutBox::charFilterRegExp(QString const & filter)
401 {
402         QString re;
403         for (int i = 0; i < filter.length(); ++i) {
404                 QChar c = filter[i];
405                 if (c.isLower())
406                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
407                 else
408                         re += ".*" + QRegExp::escape(c);
409         }
410         return re;
411 }
412
413
414 void GuiLayoutBox::resetFilter()
415 {
416         setFilter(QString());
417 }
418
419
420 void GuiLayoutBox::showPopup()
421 {
422         owner_.message(_("Enter characters to filter the layout list."));
423
424         bool enabled = view()->updatesEnabled();
425         view()->setUpdatesEnabled(false);
426
427         resetFilter();
428
429         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
430         // the hack in the item delegate to make space for the headers.
431         LASSERT(!inShowPopup_, /**/);
432         inShowPopup_ = true;
433         QComboBox::showPopup();
434         inShowPopup_ = false;
435         
436         // The item delegate hack is off again. So trigger a relayout of the popup.
437         filterModel_->triggerLayoutChange();
438         
439         view()->setUpdatesEnabled(enabled);
440 }
441
442
443 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
444 {
445         if (e->type() != QEvent::KeyPress)
446                 return QComboBox::eventFilter(o, e);
447
448         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
449         bool modified = (ke->modifiers() == Qt::ControlModifier)
450                 || (ke->modifiers() == Qt::AltModifier)
451                 || (ke->modifiers() == Qt::MetaModifier);
452         
453         switch (ke->key()) {
454         case Qt::Key_Escape:
455                 if (!modified && !filter_.isEmpty()) {
456                         resetFilter();
457                         return true;
458                 }
459                 break;
460         case Qt::Key_Backspace:
461                 if (!modified) {
462                         // cut off one character
463                         setFilter(filter_.left(filter_.length() - 1));
464                 }
465                 break;
466         default:
467                 if (modified || ke->text().isEmpty())
468                         break;
469                 // find chars for the filter string
470                 QString s;
471                 for (int i = 0; i < ke->text().length(); ++i) {
472                         QChar c = ke->text()[i];
473                         if (c.isLetterOrNumber()
474                             || c.isSymbol()
475                             || c.isPunct()
476                             || c.category() == QChar::Separator_Space) {
477                                 s += c;
478                         }
479                 }
480                 if (!s.isEmpty()) {
481                         // append new chars to the filter string
482                         setFilter(filter_ + s);
483                         return true;
484                 }
485                 break;
486         }
487
488         return QComboBox::eventFilter(o, e);
489 }
490
491         
492 void GuiLayoutBox::setIconSize(QSize size)
493 {
494 #ifdef Q_WS_MACX
495         bool small = size.height() < 20;
496         setAttribute(Qt::WA_MacSmallSize, small);
497         setAttribute(Qt::WA_MacNormalSize, !small);
498 #else
499         (void)size; // suppress warning
500 #endif
501 }
502
503
504 void GuiLayoutBox::set(docstring const & layout)
505 {
506         resetFilter();
507         
508         if (!text_class_)
509                 return;
510
511         Layout const & lay = (*text_class_)[layout];
512         QString newLayout = toqstr(lay.name());
513
514         // If the layout is obsolete, use the new one instead.
515         docstring const & obs = lay.obsoleted_by();
516         if (!obs.empty())
517                 newLayout = toqstr(obs);
518
519         int const curItem = currentIndex();
520         QModelIndex const mindex =
521                 filterModel_->mapToSource(filterModel_->index(curItem, 1));
522         QString const & currentLayout = model_->itemFromIndex(mindex)->text();
523         if (newLayout == currentLayout) {
524                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
525                 return;
526         }
527
528         QList<QStandardItem *> r = model_->findItems(newLayout, Qt::MatchExactly, 1);
529         if (r.empty()) {
530                 LYXERR0("Trying to select non existent layout type " << newLayout);
531                 return;
532         }
533
534         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
535 }
536
537
538 void GuiLayoutBox::addItemSort(docstring const & item, docstring const & category,
539         bool sorted, bool sortedByCat, bool unknown)
540 {
541         QString qitem = toqstr(item);
542         // FIXME This is wrong for RTL, I'd suppose.
543         QString titem = toqstr(translateIfPossible(item) +
544                                (unknown ? _(" (unknown)") : from_ascii("")));
545         QString qcat = toqstr(translateIfPossible(category));
546
547         QList<QStandardItem *> row;
548         row.append(new QStandardItem(titem));
549         row.append(new QStandardItem(qitem));
550         row.append(new QStandardItem(qcat));
551
552         // the first entry is easy
553         int const end = model_->rowCount();
554         if (end == 0) {
555                 model_->appendRow(row);
556                 return;
557         }
558
559         // find category
560         int i = 0;
561         if (sortedByCat) {
562                 while (i < end && model_->item(i, 2)->text() != qcat)
563                         ++i;
564         }
565
566         // skip the Standard layout
567         if (i == 0)
568                 ++i;
569         
570         // the simple unsorted case
571         if (!sorted) {
572                 if (sortedByCat) {
573                         // jump to the end of the category group
574                         while (i < end && model_->item(i, 2)->text() == qcat)
575                                 ++i;
576                         model_->insertRow(i, row);
577                 } else
578                         model_->appendRow(row);
579                 return;
580         }
581
582         // find row to insert the item, after the separator if it exists
583         if (i < end) {
584                 // find alphabetic position
585                 while (i != end
586                        && model_->item(i, 0)->text().localeAwareCompare(titem) < 0 
587                        && (!sortedByCat || model_->item(i, 2)->text() == qcat))
588                         ++i;
589         }
590
591         model_->insertRow(i, row);
592 }
593
594
595 void GuiLayoutBox::updateContents(bool reset)
596 {
597         resetFilter();
598         
599         Buffer const * buffer = owner_.buffer();
600         if (!buffer) {
601                 model_->clear();
602                 setEnabled(false);
603                 text_class_ = 0;
604                 inset_ = 0;
605                 return;
606         }
607
608         // we'll only update the layout list if the text class has changed
609         // or we've moved from one inset to another
610         DocumentClass const * text_class = &buffer->params().documentClass();
611         Inset const * inset = 
612                 &(owner_.view()->cursor().innerParagraph().inInset());
613         if (!reset && text_class_ == text_class && inset_ == inset) {
614                 set(owner_.view()->cursor().innerParagraph().layout().name());
615                 return;
616         }
617
618         inset_ = inset;
619         text_class_ = text_class;
620
621         model_->clear();
622         DocumentClass::const_iterator lit = text_class_->begin();
623         DocumentClass::const_iterator len = text_class_->end();
624
625         for (; lit != len; ++lit) {
626                 docstring const & name = lit->name();
627                 bool const useEmpty = inset_->forcePlainLayout() || inset_->usePlainLayout();
628                 // if this inset requires the empty layout, we skip the default
629                 // layout
630                 if (name == text_class_->defaultLayoutName() && inset_ && useEmpty)
631                         continue;
632                 // if it doesn't require the empty layout, we skip it
633                 if (name == text_class_->plainLayoutName() && inset_ && !useEmpty)
634                         continue;
635                 // obsoleted layouts are skipped as well
636                 if (!lit->obsoleted_by().empty())
637                         continue;
638                 addItemSort(name, lit->category(), lyxrc.sort_layouts, 
639                                 lyxrc.group_layouts, lit->isUnknown());
640         }
641
642         set(owner_.view()->cursor().innerParagraph().layout().name());
643         countCategories();
644         
645         // needed to recalculate size hint
646         hide();
647         setMinimumWidth(sizeHint().width());
648         setEnabled(!buffer->isReadonly() &&
649                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
650         show();
651 }
652
653
654 void GuiLayoutBox::selected(int index)
655 {
656         // get selection
657         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
658         docstring layoutName = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
659         owner_.setFocus();
660
661         if (!text_class_) {
662                 updateContents(false);
663                 resetFilter();
664                 return;
665         }
666
667         // find corresponding text class
668         if (text_class_->hasLayout(layoutName)) {
669                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
670                 theLyXFunc().setLyXView(&owner_);
671                 lyx::dispatch(func);
672                 updateContents(false);
673                 resetFilter();
674                 return;
675         }
676         LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
677 }
678
679
680
681 /////////////////////////////////////////////////////////////////////
682 //
683 // GuiToolbar
684 //
685 /////////////////////////////////////////////////////////////////////
686
687
688 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
689         : QToolBar(toqstr(tbinfo.gui_name), &owner), visibility_(0),
690           allowauto_(false), owner_(owner), layout_(0), command_buffer_(0),
691           tbinfo_(tbinfo), filled_(false)
692 {
693         setIconSize(owner.iconSize());
694         connect(&owner, SIGNAL(iconSizeChanged(QSize)), this,
695                 SLOT(setIconSize(QSize)));
696
697         // Toolbar dragging is allowed.
698         setMovable(true);
699         // This is used by QMainWindow::restoreState for proper main window state
700         // restauration.
701         setObjectName(toqstr(tbinfo.name));
702         restoreSession();
703 }
704
705
706 void GuiToolbar::fill()
707 {
708         if (filled_)
709                 return;
710         ToolbarInfo::item_iterator it = tbinfo_.items.begin();
711         ToolbarInfo::item_iterator end = tbinfo_.items.end();
712         for (; it != end; ++it)
713                 add(*it);       
714         filled_ = true;
715 }
716
717
718 void GuiToolbar::showEvent(QShowEvent * ev)
719 {
720         fill();
721         ev->accept();
722 }
723
724
725 void GuiToolbar::setVisibility(int visibility)
726 {
727         visibility_ = visibility;
728         allowauto_ = visibility_ >= Toolbars::MATH;
729 }
730
731
732 Action * GuiToolbar::addItem(ToolbarItem const & item)
733 {
734         QString text = toqstr(item.label_);
735         // Get the keys bound to this action, but keep only the
736         // first one later
737         KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(item.func_);
738         if (bindings.size())
739                 text += " [" + toqstr(bindings.begin()->print(KeySequence::ForGui)) + "]";
740
741         Action * act = new Action(&owner_, getIcon(item.func_, false),
742                 text, item.func_, text, this);
743         actions_.append(act);
744         return act;
745 }
746
747 namespace {
748
749 class PaletteButton : public QToolButton
750 {
751 private:
752         GuiToolbar * bar_;
753         ToolbarItem const & tbitem_;
754         bool initialized_;
755 public:
756         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
757                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
758         {
759                 QString const label = qt_(to_ascii(tbitem_.label_));
760                 setToolTip(label);
761                 setStatusTip(label);
762                 setText(label);
763                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
764                         this, SLOT(setIconSize(QSize)));
765                 setCheckable(true);
766                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
767                 if (tbinfo)
768                         // use the icon of first action for the toolbar button
769                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
770         }
771
772         void mousePressEvent(QMouseEvent * e)
773         {
774                 if (initialized_) {
775                         QToolButton::mousePressEvent(e);
776                         return;
777                 }
778
779                 initialized_ = true;
780
781                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
782                 if (!tbinfo) {
783                         LYXERR0("Unknown toolbar " << tbitem_.name_);
784                         return;
785                 }
786                 IconPalette * panel = new IconPalette(this);
787                 QString const label = qt_(to_ascii(tbitem_.label_));
788                 panel->setWindowTitle(label);
789                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
790                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
791                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
792                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
793                 for (; it != end; ++it)
794                         if (!getStatus(it->func_).unknown())
795                                 panel->addButton(bar_->addItem(*it));
796
797                 QToolButton::mousePressEvent(e);
798         }
799 };
800
801 }
802
803
804 MenuButton::MenuButton(GuiToolbar * bar, ToolbarItem const & item, bool const sticky)
805         : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
806 {
807         setPopupMode(QToolButton::InstantPopup);
808         QString const label = qt_(to_ascii(tbitem_.label_));
809         setToolTip(label);
810         setStatusTip(label);
811         setText(label);
812         setIcon(QIcon(getPixmap("images/math/", toqstr(tbitem_.name_), "png")));
813         if (sticky)
814                 connect(this, SIGNAL(triggered(QAction *)),
815                         this, SLOT(actionTriggered(QAction *)));
816         connect(bar, SIGNAL(iconSizeChanged(QSize)),
817                 this, SLOT(setIconSize(QSize)));
818 }
819
820 void MenuButton::mousePressEvent(QMouseEvent * e)
821 {
822         if (initialized_) {
823                 QToolButton::mousePressEvent(e);
824                 return;
825         }
826
827         initialized_ = true;
828
829         QString const label = qt_(to_ascii(tbitem_.label_));
830         ButtonMenu * m = new ButtonMenu(label, this);
831         m->setWindowTitle(label);
832         m->setTearOffEnabled(true);
833         connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
834         ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
835         if (!tbinfo) {
836                 LYXERR0("Unknown toolbar " << tbitem_.name_);
837                 return;
838         }
839         ToolbarInfo::item_iterator it = tbinfo->items.begin();
840         ToolbarInfo::item_iterator const end = tbinfo->items.end();
841         for (; it != end; ++it)
842                 if (!getStatus(it->func_).unknown())
843                         m->add(bar_->addItem(*it));
844         setMenu(m);
845
846         QToolButton::mousePressEvent(e);
847 }
848
849
850 void MenuButton::actionTriggered(QAction * action)
851 {
852         QToolButton::setDefaultAction(action);
853         setPopupMode(QToolButton::DelayedPopup);
854 }
855
856
857 void GuiToolbar::add(ToolbarItem const & item)
858 {
859         switch (item.type_) {
860         case ToolbarItem::SEPARATOR:
861                 addSeparator();
862                 break;
863         case ToolbarItem::LAYOUTS:
864                 layout_ = new GuiLayoutBox(this, owner_);
865                 addWidget(layout_);
866                 break;
867         case ToolbarItem::MINIBUFFER:
868                 command_buffer_ = new GuiCommandBuffer(&owner_);
869                 addWidget(command_buffer_);
870                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
871                 //setHorizontalStretchable(true);
872                 break;
873         case ToolbarItem::TABLEINSERT: {
874                 QToolButton * tb = new QToolButton;
875                 tb->setCheckable(true);
876                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
877                 QString const label = qt_(to_ascii(item.label_));
878                 tb->setToolTip(label);
879                 tb->setStatusTip(label);
880                 tb->setText(label);
881                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
882                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
883                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
884                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
885                 addWidget(tb);
886                 break;
887                 }
888         case ToolbarItem::ICONPALETTE:
889                 addWidget(new PaletteButton(this, item));
890                 break;
891
892         case ToolbarItem::POPUPMENU: {
893                 addWidget(new MenuButton(this, item, false));
894                 break;
895                 }
896         case ToolbarItem::STICKYPOPUPMENU: {
897                 addWidget(new MenuButton(this, item, true));
898                 break;
899                 }
900         case ToolbarItem::COMMAND: {
901                 if (!getStatus(item.func_).unknown())
902                         addAction(addItem(item));
903                 break;
904                 }
905         default:
906                 break;
907         }
908 }
909
910
911 void GuiToolbar::update(bool in_math, bool in_table, bool in_review, 
912         bool in_mathmacrotemplate)
913 {
914         if (visibility_ & Toolbars::AUTO) {
915                 bool show_it = (in_math && (visibility_ & Toolbars::MATH))
916                         || (in_table && (visibility_ & Toolbars::TABLE))
917                         || (in_review && (visibility_ & Toolbars::REVIEW))
918                         || (in_mathmacrotemplate && (visibility_ & Toolbars::MATHMACROTEMPLATE));
919                 setVisible(show_it);
920         }
921
922         // update visible toolbars only
923         if (!isVisible())
924                 return;
925
926         // This is a speed bottleneck because this is called on every keypress
927         // and update calls getStatus, which copies the cursor at least two times
928         for (int i = 0; i < actions_.size(); ++i)
929                 actions_[i]->update();
930
931         if (layout_)
932                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
933
934         // emit signal
935         updated();
936 }
937
938
939 QString GuiToolbar::sessionKey() const
940 {
941         return "views/" + QString::number(owner_.id()) + "/" + objectName();
942 }
943
944
945 void GuiToolbar::saveSession() const
946 {
947         QSettings settings;
948         settings.setValue(sessionKey() + "/visibility", visibility_);
949 }
950
951
952 void GuiToolbar::restoreSession()
953 {
954         QSettings settings;
955         setVisibility(settings.value(sessionKey() + "/visibility").toInt());
956 }
957
958
959 void GuiToolbar::toggle()
960 {
961         docstring state;
962         if (allowauto_) {
963                 if (!(visibility_ & Toolbars::AUTO)) {
964                         visibility_ |= Toolbars::AUTO;
965                         hide();
966                         state = _("auto");
967                 } else {
968                         visibility_ &= ~Toolbars::AUTO;
969                         if (isVisible()) {
970                                 hide();
971                                 state = _("off");
972                         } else {
973                                 show();
974                                 state = _("on");
975                         }
976                 }
977         } else {
978                 if (isVisible()) {
979                         hide();
980                         state = _("off");
981                 } else {
982                         show();
983                         state = _("on");
984                 }
985         }
986
987         owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
988                 qstring_to_ucs4(windowTitle()), state));
989 }
990
991 } // namespace frontend
992 } // namespace lyx
993
994 #include "moc_GuiToolbar.cpp"