]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
Improve the local layout feature by better handling of unknown textclass, unknown...
[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(_("Filtering layouts with \"" + fromqstr(s) + "\". "
369                                          "Press ESC to remove filter."));
370                 else
371                         owner_.message(_("Enter characters to filter the layout list."));
372         }
373         
374         view()->setUpdatesEnabled(enabled);
375 }
376
377
378 void GuiLayoutBox::countCategories()
379 {
380         int n = filterModel_->rowCount();
381         visibleCategories_ = 0;
382         if (n == 0 || !lyxrc.group_layouts)
383                 return;
384
385         // skip the "Standard" category
386         QString prevCat = model_->index(0, 2).data().toString(); 
387
388         // count categories
389         for (int i = 0; i < n; ++i) {
390                 QString cat = filterModel_->index(i, 2).data().toString();
391                 if (cat != prevCat)
392                         ++visibleCategories_;
393                 prevCat = cat;
394         }
395 }
396
397
398 QString GuiLayoutBox::charFilterRegExp(QString const & filter)
399 {
400         QString re;
401         for (int i = 0; i < filter.length(); ++i) {
402                 QChar c = filter[i];
403                 if (c.isLower())
404                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
405                 else
406                         re += ".*" + QRegExp::escape(c);
407         }
408         return re;
409 }
410
411
412 void GuiLayoutBox::resetFilter()
413 {
414         setFilter(QString());
415 }
416
417
418 void GuiLayoutBox::showPopup()
419 {
420         owner_.message(_("Enter characters to filter the layout list."));
421
422         bool enabled = view()->updatesEnabled();
423         view()->setUpdatesEnabled(false);
424
425         resetFilter();
426
427         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
428         // the hack in the item delegate to make space for the headers.
429         LASSERT(!inShowPopup_, /**/);
430         inShowPopup_ = true;
431         QComboBox::showPopup();
432         inShowPopup_ = false;
433         
434         // The item delegate hack is off again. So trigger a relayout of the popup.
435         filterModel_->triggerLayoutChange();
436         
437         view()->setUpdatesEnabled(enabled);
438 }
439
440
441 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
442 {
443         if (e->type() != QEvent::KeyPress)
444                 return QComboBox::eventFilter(o, e);
445
446         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
447         bool modified = (ke->modifiers() == Qt::ControlModifier)
448                 || (ke->modifiers() == Qt::AltModifier)
449                 || (ke->modifiers() == Qt::MetaModifier);
450         
451         switch (ke->key()) {
452         case Qt::Key_Escape:
453                 if (!modified && !filter_.isEmpty()) {
454                         resetFilter();
455                         return true;
456                 }
457                 break;
458         case Qt::Key_Backspace:
459                 if (!modified) {
460                         // cut off one character
461                         setFilter(filter_.left(filter_.length() - 1));
462                 }
463                 break;
464         default:
465                 if (modified || ke->text().isEmpty())
466                         break;
467                 // find chars for the filter string
468                 QString s;
469                 for (int i = 0; i < ke->text().length(); ++i) {
470                         QChar c = ke->text()[i];
471                         if (c.isLetterOrNumber()
472                             || c.isSymbol()
473                             || c.isPunct()
474                             || c.category() == QChar::Separator_Space) {
475                                 s += c;
476                         }
477                 }
478                 if (!s.isEmpty()) {
479                         // append new chars to the filter string
480                         setFilter(filter_ + s);
481                         return true;
482                 }
483                 break;
484         }
485
486         return QComboBox::eventFilter(o, e);
487 }
488
489         
490 void GuiLayoutBox::setIconSize(QSize size)
491 {
492 #ifdef Q_WS_MACX
493         bool small = size.height() < 20;
494         setAttribute(Qt::WA_MacSmallSize, small);
495         setAttribute(Qt::WA_MacNormalSize, !small);
496 #else
497         (void)size; // suppress warning
498 #endif
499 }
500
501
502 void GuiLayoutBox::set(docstring const & layout)
503 {
504         resetFilter();
505         
506         if (!text_class_)
507                 return;
508
509         Layout const & lay = (*text_class_)[layout];
510         QString const & name = toqstr(lay.name() + (lay.isUnknown() ? " (unknown)" : ""));
511         if (name == currentText())
512                 return;
513
514         QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
515         if (r.empty()) {
516                 LYXERR0("Trying to select non existent layout type " << name);
517                 return;
518         }
519
520         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
521 }
522
523
524 void GuiLayoutBox::addItemSort(docstring const & item, docstring const & category,
525         bool sorted, bool sortedByCat)
526 {
527         QString qitem = toqstr(item);
528         QString titem = toqstr(translateIfPossible(item));
529         QString qcat = toqstr(translateIfPossible(category));
530
531         QList<QStandardItem *> row;
532         row.append(new QStandardItem(titem));
533         row.append(new QStandardItem(qitem));
534         row.append(new QStandardItem(qcat));
535
536         // the first entry is easy
537         int const end = model_->rowCount();
538         if (end == 0) {
539                 model_->appendRow(row);
540                 return;
541         }
542
543         // find category
544         int i = 0;
545         if (sortedByCat) {
546                 while (i < end && model_->item(i, 2)->text() != qcat)
547                         ++i;
548         }
549
550         // skip the Standard layout
551         if (i == 0)
552                 ++i;
553         
554         // the simple unsorted case
555         if (!sorted) {
556                 if (sortedByCat) {
557                         // jump to the end of the category group
558                         while (i < end && model_->item(i, 2)->text() == qcat)
559                                 ++i;
560                         model_->insertRow(i, row);
561                 } else
562                         model_->appendRow(row);
563                 return;
564         }
565
566         // find row to insert the item, after the separator if it exists
567         if (i < end) {
568                 // find alphabetic position
569                 while (i != end
570                        && model_->item(i, 0)->text().localeAwareCompare(titem) < 0 
571                        && (!sortedByCat || model_->item(i, 2)->text() == qcat))
572                         ++i;
573         }
574
575         model_->insertRow(i, row);
576 }
577
578
579 void GuiLayoutBox::updateContents(bool reset)
580 {
581         resetFilter();
582         
583         Buffer const * buffer = owner_.buffer();
584         if (!buffer) {
585                 model_->clear();
586                 setEnabled(false);
587                 text_class_ = 0;
588                 inset_ = 0;
589                 return;
590         }
591
592         // we'll only update the layout list if the text class has changed
593         // or we've moved from one inset to another
594         DocumentClass const * text_class = &buffer->params().documentClass();
595         Inset const * inset = 
596                 owner_.view()->cursor().innerParagraph().inInset();
597         if (!reset && text_class_ == text_class && inset_ == inset) {
598                 set(owner_.view()->cursor().innerParagraph().layout().name());
599                 return;
600         }
601
602         inset_ = inset;
603         text_class_ = text_class;
604
605         model_->clear();
606         DocumentClass::const_iterator lit = text_class_->begin();
607         DocumentClass::const_iterator len = text_class_->end();
608
609         for (; lit != len; ++lit) {
610                 docstring const & name = lit->name();
611                 bool const useEmpty = inset_->forcePlainLayout() || inset_->usePlainLayout();
612                 // if this inset requires the empty layout, we skip the default
613                 // layout
614                 if (name == text_class_->defaultLayoutName() && inset_ && useEmpty)
615                         continue;
616                 // if it doesn't require the empty layout, we skip it
617                 if (name == text_class_->emptyLayoutName() && inset_ && !useEmpty)
618                         continue;
619                 addItemSort(name + (lit->isUnknown() ? " (unknown)" : ""),
620                         lit->category(), lyxrc.sort_layouts, lyxrc.group_layouts);
621         }
622
623         set(owner_.view()->cursor().innerParagraph().layout().name());
624         countCategories();
625         
626         // needed to recalculate size hint
627         hide();
628         setMinimumWidth(sizeHint().width());
629         setEnabled(!buffer->isReadonly());
630         show();
631 }
632
633
634 void GuiLayoutBox::selected(int index)
635 {
636         // get selection
637         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
638         docstring const layoutName = rtrim(
639                 qstring_to_ucs4(model_->itemFromIndex(mindex)->text()), " (unknown)");
640
641         owner_.setFocus();
642
643         if (!text_class_) {
644                 updateContents(false);
645                 resetFilter();
646                 return;
647         }
648
649         // find corresponding text class
650         if (text_class_->hasLayout(layoutName)) {
651                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
652                 theLyXFunc().setLyXView(&owner_);
653                 lyx::dispatch(func);
654                 updateContents(false);
655                 resetFilter();
656                 return;
657         }
658         LYXERR0("ERROR (layoutSelected): layout not found!");
659 }
660
661
662
663 /////////////////////////////////////////////////////////////////////
664 //
665 // GuiToolbar
666 //
667 /////////////////////////////////////////////////////////////////////
668
669
670 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
671         : QToolBar(qt_(tbinfo.gui_name), &owner), visibility_(0),
672           allowauto_(false), owner_(owner), layout_(0), command_buffer_(0),
673           tbinfo_(tbinfo), filled_(false)
674 {
675         setIconSize(owner.iconSize());
676         connect(&owner, SIGNAL(iconSizeChanged(QSize)), this,
677                 SLOT(setIconSize(QSize)));
678
679         // Toolbar dragging is allowed.
680         setMovable(true);
681         // This is used by QMainWindow::restoreState for proper main window state
682         // restauration.
683         setObjectName(toqstr(tbinfo.name));
684         restoreSession();
685 }
686
687
688 void GuiToolbar::fill()
689 {
690         if (filled_)
691                 return;
692         ToolbarInfo::item_iterator it = tbinfo_.items.begin();
693         ToolbarInfo::item_iterator end = tbinfo_.items.end();
694         for (; it != end; ++it)
695                 add(*it);       
696         filled_ = true;
697 }
698
699
700 void GuiToolbar::showEvent(QShowEvent * ev)
701 {
702         fill();
703         ev->accept();
704 }
705
706
707 void GuiToolbar::setVisibility(int visibility)
708 {
709         visibility_ = visibility;
710         allowauto_ = visibility_ >= Toolbars::MATH;
711 }
712
713
714 Action * GuiToolbar::addItem(ToolbarItem const & item)
715 {
716         Action * act = new Action(&owner_, getIcon(item.func_, false),
717                 toqstr(item.label_), item.func_, toqstr(item.label_), this);
718         actions_.append(act);
719         return act;
720 }
721
722 namespace {
723
724 class PaletteButton : public QToolButton
725 {
726 private:
727         GuiToolbar * bar_;
728         ToolbarItem const & tbitem_;
729         bool initialized_;
730 public:
731         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
732                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
733         {
734                 QString const label = qt_(to_ascii(tbitem_.label_));
735                 setToolTip(label);
736                 setStatusTip(label);
737                 setText(label);
738                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
739                         this, SLOT(setIconSize(QSize)));
740                 setCheckable(true);
741                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
742                 if (tbinfo)
743                         // use the icon of first action for the toolbar button
744                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
745         }
746
747         void mousePressEvent(QMouseEvent * e)
748         {
749                 if (initialized_) {
750                         QToolButton::mousePressEvent(e);
751                         return;
752                 }
753
754                 initialized_ = true;
755
756                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
757                 if (!tbinfo) {
758                         LYXERR0("Unknown toolbar " << tbitem_.name_);
759                         return;
760                 }
761                 IconPalette * panel = new IconPalette(this);
762                 QString const label = qt_(to_ascii(tbitem_.label_));
763                 panel->setWindowTitle(label);
764                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
765                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
766                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
767                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
768                 for (; it != end; ++it)
769                         if (!getStatus(it->func_).unknown())
770                                 panel->addButton(bar_->addItem(*it));
771
772                 QToolButton::mousePressEvent(e);
773         }
774 };
775
776 class MenuButton : public QToolButton
777 {
778 private:
779         GuiToolbar * bar_;
780         ToolbarItem const & tbitem_;
781         bool initialized_;
782 public:
783         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
784                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
785         {
786                 setPopupMode(QToolButton::InstantPopup);
787                 QString const label = qt_(to_ascii(tbitem_.label_));
788                 setToolTip(label);
789                 setStatusTip(label);
790                 setText(label);
791                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
792                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
793                         this, SLOT(setIconSize(QSize)));
794         }
795
796         void mousePressEvent(QMouseEvent * e)
797         {
798                 if (initialized_) {
799                         QToolButton::mousePressEvent(e);
800                         return;
801                 }
802
803                 initialized_ = true;
804
805                 QString const label = qt_(to_ascii(tbitem_.label_));
806                 ButtonMenu * m = new ButtonMenu(label, this);
807                 m->setWindowTitle(label);
808                 m->setTearOffEnabled(true);
809                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
810                 ToolbarInfo const * tbinfo = guiApp->toolbars().info(tbitem_.name_);
811                 if (!tbinfo) {
812                         LYXERR0("Unknown toolbar " << tbitem_.name_);
813                         return;
814                 }
815                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
816                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
817                 for (; it != end; ++it)
818                         if (!getStatus(it->func_).unknown())
819                                 m->add(bar_->addItem(*it));
820                 setMenu(m);
821
822                 QToolButton::mousePressEvent(e);
823         }
824 };
825
826 }
827
828
829 void GuiToolbar::add(ToolbarItem const & item)
830 {
831         switch (item.type_) {
832         case ToolbarItem::SEPARATOR:
833                 addSeparator();
834                 break;
835         case ToolbarItem::LAYOUTS:
836                 layout_ = new GuiLayoutBox(this, owner_);
837                 addWidget(layout_);
838                 break;
839         case ToolbarItem::MINIBUFFER:
840                 command_buffer_ = new GuiCommandBuffer(&owner_);
841                 addWidget(command_buffer_);
842                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
843                 //setHorizontalStretchable(true);
844                 break;
845         case ToolbarItem::TABLEINSERT: {
846                 QToolButton * tb = new QToolButton;
847                 tb->setCheckable(true);
848                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
849                 QString const label = qt_(to_ascii(item.label_));
850                 tb->setToolTip(label);
851                 tb->setStatusTip(label);
852                 tb->setText(label);
853                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
854                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
855                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
856                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
857                 addWidget(tb);
858                 break;
859                 }
860         case ToolbarItem::ICONPALETTE:
861                 addWidget(new PaletteButton(this, item));
862                 break;
863
864         case ToolbarItem::POPUPMENU: {
865                 addWidget(new MenuButton(this, item));
866                 break;
867                 }
868         case ToolbarItem::COMMAND: {
869                 if (!getStatus(item.func_).unknown())
870                         addAction(addItem(item));
871                 break;
872                 }
873         default:
874                 break;
875         }
876 }
877
878
879 void GuiToolbar::update(bool in_math, bool in_table, bool in_review, 
880         bool in_mathmacrotemplate)
881 {
882         if (visibility_ & Toolbars::AUTO) {
883                 bool show_it = in_math && (visibility_ & Toolbars::MATH)
884                         || in_table && (visibility_ & Toolbars::TABLE)
885                         || in_review && (visibility_ & Toolbars::REVIEW)
886                         || in_mathmacrotemplate && (visibility_ & Toolbars::MATHMACROTEMPLATE);
887                 setVisible(show_it);
888         }
889
890         // update visible toolbars only
891         if (!isVisible())
892                 return;
893
894         // This is a speed bottleneck because this is called on every keypress
895         // and update calls getStatus, which copies the cursor at least two times
896         for (int i = 0; i < actions_.size(); ++i)
897                 actions_[i]->update();
898
899         if (layout_)
900                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
901
902         // emit signal
903         updated();
904 }
905
906
907 QString GuiToolbar::sessionKey() const
908 {
909         return "view-" + QString::number(owner_.id()) + "/" + objectName();
910 }
911
912
913 void GuiToolbar::saveSession() const
914 {
915         QSettings settings;
916         settings.setValue(sessionKey() + "/visibility", visibility_);
917 }
918
919
920 void GuiToolbar::restoreSession()
921 {
922         QSettings settings;
923         setVisibility(settings.value(sessionKey() + "/visibility").toInt());
924 }
925
926
927 void GuiToolbar::toggle()
928 {
929         docstring state;
930         if (allowauto_) {
931                 if (!(visibility_ & Toolbars::AUTO)) {
932                         visibility_ |= Toolbars::AUTO;
933                         hide();
934                         state = _("auto");
935                 } else {
936                         visibility_ &= ~Toolbars::AUTO;
937                         if (isVisible()) {
938                                 hide();
939                                 state = _("off");
940                         } else {
941                                 show();
942                                 state = _("on");
943                         }
944                 }
945         } else {
946                 if (isVisible()) {
947                         hide();
948                         state = _("off");
949                 } else {
950                         show();
951                         state = _("on");
952                 }
953         }
954
955         owner_.message(bformat(_("Toolbar \"%1$s\" state set to %2$s"),
956                 qstring_to_ucs4(windowTitle()), state));
957 }
958
959 } // namespace frontend
960 } // namespace lyx
961
962 #include "GuiToolbar_moc.cpp"