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