]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
Change the interface to a paragraph's layout. We still store a LayoutPtr, but now...
[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 Abdelrazak Younes
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "GuiView.h"
18 #include "GuiCommandBuffer.h"
19 #include "GuiToolbar.h"
20 #include "LyXAction.h"
21 #include "Action.h"
22 #include "qt_helpers.h"
23 #include "InsertTableWidget.h"
24
25 #include "Buffer.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Cursor.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
31 #include "IconPalette.h"
32 #include "Layout.h"
33 #include "LyXFunc.h"
34 #include "LyXRC.h"
35 #include "Paragraph.h"
36 #include "TextClass.h"
37 #include "ToolbarBackend.h"
38
39 #include "support/debug.h"
40 #include "support/filetools.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/lyxalgo.h" // sorted
44
45 #include <QAbstractItemDelegate>
46 #include <QAbstractTextDocumentLayout>
47 #include <QApplication>
48 #include <QComboBox>
49 #include <QHeaderView>
50 #include <QKeyEvent>
51 #include <QList>
52 #include <QPainter>
53 #include <QPixmap>
54 #include <QSortFilterProxyModel>
55 #include <QStandardItem>
56 #include <QStandardItemModel>
57 #include <QTextDocument>
58 #include <QToolBar>
59 #include <QToolButton>
60 #include <QVariant>
61
62 #include <boost/assert.hpp>
63
64 using namespace std;
65 using namespace lyx::support;
66
67 static void initializeResources()
68 {
69         static bool initialized = false;
70         if (!initialized) {
71                 Q_INIT_RESOURCE(Resources); 
72                 initialized = true;
73         }
74 }
75
76
77 namespace lyx {
78 namespace frontend {
79
80 namespace {
81
82 struct PngMap {
83         char const * key;
84         char const * value;
85 };
86
87
88 bool operator<(PngMap const & lhs, PngMap const & rhs)
89 {
90                 return strcmp(lhs.key, rhs.key) < 0;
91 }
92
93
94 class CompareKey {
95 public:
96         CompareKey(string const & name) : name_(name) {}
97         bool operator()(PngMap const & other) const { return other.key == name_; }
98 private:
99         string const name_;
100 };
101
102
103 PngMap sorted_png_map[] = {
104         { "Bumpeq", "bumpeq2" },
105         { "Cap", "cap2" },
106         { "Cup", "cup2" },
107         { "Delta", "delta2" },
108         { "Downarrow", "downarrow2" },
109         { "Gamma", "gamma2" },
110         { "Lambda", "lambda2" },
111         { "Leftarrow", "leftarrow2" },
112         { "Leftrightarrow", "leftrightarrow2" },
113         { "Longleftarrow", "longleftarrow2" },
114         { "Longleftrightarrow", "longleftrightarrow2" },
115         { "Longrightarrow", "longrightarrow2" },
116         { "Omega", "omega2" },
117         { "Phi", "phi2" },
118         { "Pi", "pi2" },
119         { "Psi", "psi2" },
120         { "Rightarrow", "rightarrow2" },
121         { "Sigma", "sigma2" },
122         { "Subset", "subset2" },
123         { "Supset", "supset2" },
124         { "Theta", "theta2" },
125         { "Uparrow", "uparrow2" },
126         { "Updownarrow", "updownarrow2" },
127         { "Upsilon", "upsilon2" },
128         { "Vdash", "vdash3" },
129         { "Xi", "xi2" },
130         { "nLeftarrow", "nleftarrow2" },
131         { "nLeftrightarrow", "nleftrightarrow2" },
132         { "nRightarrow", "nrightarrow2" },
133         { "nVDash", "nvdash3" },
134         { "nvDash", "nvdash2" },
135         { "textrm \\AA", "textrm_AA"},
136         { "textrm \\O", "textrm_O"},
137         { "vDash", "vdash2" }
138 };
139
140 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
141
142
143 string const find_png(string const & name)
144 {
145         PngMap const * const begin = sorted_png_map;
146         PngMap const * const end = begin + nr_sorted_png_map;
147         BOOST_ASSERT(sorted(begin, end));
148
149         PngMap const * const it = find_if(begin, end, CompareKey(name));
150
151         string png_name;
152         if (it != end)
153                 png_name = it->value;
154         else {
155                 png_name = subst(name, "_", "underscore");
156                 png_name = subst(png_name, ' ', '_');
157
158                 // This way we can have "math-delim { }" on the toolbar.
159                 png_name = subst(png_name, "(", "lparen");
160                 png_name = subst(png_name, ")", "rparen");
161                 png_name = subst(png_name, "[", "lbracket");
162                 png_name = subst(png_name, "]", "rbracket");
163                 png_name = subst(png_name, "{", "lbrace");
164                 png_name = subst(png_name, "}", "rbrace");
165                 png_name = subst(png_name, "|", "bars");
166                 png_name = subst(png_name, ",", "thinspace");
167                 png_name = subst(png_name, ":", "mediumspace");
168                 png_name = subst(png_name, ";", "thickspace");
169                 png_name = subst(png_name, "!", "negthinspace");
170         }
171
172         LYXERR(Debug::GUI, "find_png(" << name << ")\n"
173                 << "Looking for math PNG called \"" << png_name << '"');
174         return png_name;
175 }
176
177 } // namespace anon
178
179
180 /// return a icon for the given action
181 static QIcon getIcon(FuncRequest const & f, bool unknown)
182 {
183         initializeResources();
184         QPixmap pm;
185         string name1;
186         string name2;
187         string path;
188         string fullname;
189
190         switch (f.action) {
191         case LFUN_MATH_INSERT:
192                 if (!f.argument().empty()) {
193                         path = "math/";
194                         name1 = find_png(to_utf8(f.argument()).substr(1));
195                 }
196                 break;
197         case LFUN_MATH_DELIM:
198         case LFUN_MATH_BIGDELIM:
199                 path = "math/";
200                 name1 = find_png(to_utf8(f.argument()));
201                 break;
202         case LFUN_CALL:
203                 path = "commands/";
204                 name1 = to_utf8(f.argument());
205                 break;
206         default:
207                 name2 = lyxaction.getActionName(f.action);
208                 name1 = name2;
209
210                 if (!f.argument().empty())
211                         name1 = subst(name2 + ' ' + to_utf8(f.argument()), ' ', '_');
212         }
213
214         fullname = libFileSearch("images/" + path, name1, "png").absFilename();
215         if (pm.load(toqstr(fullname)))
216                 return pm;
217
218         fullname = libFileSearch("images/" + path, name2, "png").absFilename();
219         if (pm.load(toqstr(fullname)))
220                 return pm;
221
222         if (pm.load(":/images/" + toqstr(path + name1) + ".png"))
223                 return pm;
224
225         if (pm.load(":/images/" + toqstr(path + name2) + ".png"))
226                 return pm;
227
228         LYXERR(Debug::GUI, "Cannot find icon for command \""
229                            << lyxaction.getActionName(f.action)
230                            << '(' << to_utf8(f.argument()) << ")\"");
231         if (unknown)
232                 pm.load(":/images/unknown.png");
233
234         return pm;
235 }
236
237
238 /////////////////////////////////////////////////////////////////////
239 //
240 // GuiLayoutBox
241 //
242 /////////////////////////////////////////////////////////////////////
243
244 class FilterItemDelegate : public QAbstractItemDelegate {
245 public:
246         ///
247         explicit FilterItemDelegate(QObject * parent = 0)
248                 : QAbstractItemDelegate(parent) {}
249         
250         ///
251         void paint(QPainter * painter, QStyleOptionViewItem const & option,
252                 QModelIndex const & index) const {
253                 QComboBox * combo = static_cast<QComboBox *>(parent());
254                 QStyleOptionMenuItem opt = getStyleOption(option, index);
255                 
256                 // draw line with small text string for separator
257                 if (opt.text.left(2) == "--") {
258                         painter->save();
259
260                         // set options for the separator, the first 8/18 of the vertical space
261                         QStyleOptionMenuItem sopt = opt;
262                         sopt.state = QStyle::State_Active | QStyle::State_Enabled;
263                         sopt.checked = false;
264                         sopt.text = QString();
265                         sopt.rect.setHeight(sopt.rect.height() * 8 / 18);
266                         sopt.menuRect.setHeight(sopt.menuRect.height() * 8 / 18);
267
268                         // use the style with an empty text to paint the background
269                         painter->eraseRect(sopt.rect);
270                         combo->style()->drawControl(QStyle::CE_MenuItem, &sopt, painter, combo->view());
271
272                         // draw the centered text, small and bold
273                         QPen pen;
274                         pen.setWidth(1);
275                         pen.setColor(sopt.palette.text().color());
276                         painter->setPen(pen);
277                         QFont font = sopt.font;
278                         font.setBold(true);
279                         font.setWeight(QFont::Black);
280                         font.setPointSize(sopt.font.pointSize() * 8 / 10);
281                         painter->setFont(font);
282                         QRect brect;
283                         painter->drawText(sopt.rect, Qt::AlignCenter, "Modules", &brect);
284                         
285                         // draw the horizontal line
286                         QColor lcol = sopt.palette.text().color();
287                         lcol.setAlpha(127);
288                         painter->setPen(lcol);
289                         painter->drawLine(sopt.rect.x(), sopt.rect.y() + sopt.rect.height() / 2 ,
290                                           brect.left() - 1, sopt.rect.y() + sopt.rect.height() / 2);
291                         painter->drawLine(brect.right() + 1, sopt.rect.y() + sopt.rect.height() / 2,
292                                           sopt.rect.right(), sopt.rect.y() + sopt.rect.height() / 2);
293                         
294                         painter->restore();
295                         
296                         // move rect down 8/20 of the original height
297                         opt.rect.setTop(sopt.rect.y() + sopt.rect.height());
298                         opt.menuRect = opt.rect;
299                 }
300
301                 // Draw using the menu item style (this is how QComboBox does it).
302                 // But for the rich text drawing below we will call it with an
303                 // empty string, and later then draw over it the real string.
304                 painter->save();
305                 QString text = underlineFilter(opt.text);
306                 opt.text = QString();
307                 painter->eraseRect(opt.rect);
308                 combo->style()->drawControl(QStyle::CE_MenuItem, &opt, painter, combo->view());
309                 painter->restore();
310                 
311                 // Draw the rich text.
312                 painter->save();
313                 QColor col = opt.palette.text().color();
314                 if (opt.state & QStyle::State_Selected)
315                         col = opt.palette.highlightedText().color();
316                 QAbstractTextDocumentLayout::PaintContext context;
317                 context.palette.setColor(QPalette::Text, col);
318                 
319                 QTextDocument doc;
320                 doc.setDefaultFont(opt.font);
321                 doc.setHtml(text);
322                 painter->translate(opt.rect.x() + 20, opt.rect.y());
323                 doc.documentLayout()->draw(painter, context);
324                 painter->restore();
325         }
326         
327         ///
328         QSize sizeHint(QStyleOptionViewItem const & option,
329                 QModelIndex const & index) const {
330                 QComboBox * combo = static_cast<QComboBox *>(parent());
331
332                 QStyleOptionMenuItem opt = getStyleOption(option, index);
333                 QSize size = combo->style()->sizeFromContents(
334                          QStyle::CT_MenuItem, &opt, option.rect.size(), combo);
335                 if (opt.text.left(2) == "--")
336                         size.setHeight(size.height() * 18 / 10);
337                 return size;
338         }
339         
340 private:
341         ///
342         QString underlineFilter(QString const & s) const
343         {
344                 // get filter
345                 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
346                 QString const & f = p->filter();
347                 if (f.isEmpty())
348                         return s;
349                 
350                 // step through data item and put "(x)" for every matching character
351                 QString r;
352                 int lastp = -1;
353                 p->filter();
354                 for (int i = 0; i < f.length(); ++i) {
355                         int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
356                         BOOST_ASSERT(p != -1);
357                         if (lastp == p - 1 && lastp != -1) {
358                                 // remove ")" and append "x)"
359                                 r = r.left(r.length() - 4) + s[p] + "</u>";
360                         } else {
361                                 // append "(x)"
362                                 r += s.mid(lastp + 1, p - lastp - 1);
363                                 r += QString("<u>") + s[p] + "</u>";
364                         }
365                         lastp = p;
366                 }
367                 r += s.mid(lastp + 1);
368                 return r;
369         }
370
371         ///
372         QStyleOptionMenuItem getStyleOption(QStyleOptionViewItem const & option,
373                 QModelIndex const & index) const
374         {
375                 QComboBox * combo = static_cast<QComboBox *>(parent());
376                 
377                 // create the options for a menu item
378                 QStyleOptionMenuItem menuOption;
379                 menuOption.palette = QApplication::palette("QMenu");
380                 menuOption.checkType = QStyleOptionMenuItem::NonExclusive;
381                 menuOption.state = QStyle::State_Active | QStyle::State_Enabled;
382                 menuOption.menuRect = option.rect;
383                 menuOption.rect = option.rect;
384                 menuOption.font = combo->font();
385                 menuOption.fontMetrics = QFontMetrics(menuOption.font);
386                 menuOption.tabWidth = 0;
387                 menuOption.text = index.model()->data(index, Qt::DisplayRole).toString()
388                         .replace(QLatin1Char('&'), QLatin1String("&&"));
389                 menuOption.menuItemType = QStyleOptionMenuItem::Normal;
390                 if (option.state & QStyle::State_Selected)
391                         menuOption.state |= QStyle::State_Selected;
392                 menuOption.checked = combo->currentIndex() == index.row();
393                 
394                 return menuOption;
395         }
396 };
397
398
399 class GuiFilterProxyModel : public QSortFilterProxyModel
400 {
401 public:
402         ///
403         GuiFilterProxyModel(QObject * parent)
404                 : QSortFilterProxyModel(parent) {}
405
406         ///
407         void setCharFilter(QString const & f)
408         {
409                 setFilterRegExp(charFilterRegExp(f));
410                 dataChanged(index(0, 0), index(rowCount() - 1, 1));
411         }
412
413 private:
414         ///
415         QString charFilterRegExp(QString const & filter)
416         {
417                 QString re;
418                 for (int i = 0; i < filter.length(); ++i)
419                         re += ".*" + QRegExp::escape(filter[i]);
420                 return re;
421         }
422 };
423
424
425 GuiLayoutBox::GuiLayoutBox(GuiView & owner)
426         : owner_(owner), filterItemDelegate_(new FilterItemDelegate(this))
427 {
428         setSizeAdjustPolicy(QComboBox::AdjustToContents);
429         setFocusPolicy(Qt::ClickFocus);
430         setMinimumWidth(sizeHint().width());
431         setMaxVisibleItems(100);
432
433         // set the layout model with two columns
434         // 1st: translated layout names
435         // 2nd: raw layout names
436         model_ = new QStandardItemModel(0, 2, this);
437         filterModel_ = new GuiFilterProxyModel(this);
438         filterModel_->setSourceModel(model_);
439         filterModel_->setDynamicSortFilter(true);
440         filterModel_->setFilterCaseSensitivity(Qt::CaseInsensitive);
441         setModel(filterModel_);
442
443         // for the filtering we have to intercept characters
444         view()->installEventFilter(this);
445         view()->setItemDelegateForColumn(0, filterItemDelegate_);
446         
447         QObject::connect(this, SIGNAL(activated(int)),
448                          this, SLOT(selected(int)));
449         owner_.setLayoutDialog(this);
450         updateContents(true);
451 }
452
453
454 void GuiLayoutBox::setFilter(QString const & s)
455 {
456         // remember old selection
457         int sel = currentIndex();
458         if (sel != -1)
459                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
460
461         filter_ = s;
462         filterModel_->setCharFilter(s);
463         
464         // restore old selection
465         if (lastSel_ != -1) {
466                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
467                 if (i.isValid())
468                         setCurrentIndex(i.row());
469         }
470         
471         // Workaround to resize to content size
472         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
473         //        does not help.
474         if (view()->isVisible())
475                 QComboBox::showPopup();
476 }
477
478
479 void GuiLayoutBox::resetFilter()
480 {
481         setFilter(QString());
482 }
483
484
485 void GuiLayoutBox::showPopup()
486 {
487         resetFilter();
488         owner_.message(_("Enter characters to filter the layout list."));
489         QComboBox::showPopup();
490 }
491
492
493 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
494 {
495         if (e->type() != QEvent::KeyPress)
496                 return QComboBox::eventFilter(o, e);
497
498         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
499         bool modified = (ke->modifiers() == Qt::ControlModifier)
500                 || (ke->modifiers() == Qt::AltModifier)
501                 || (ke->modifiers() == Qt::MetaModifier);
502         
503         switch (ke->key()) {
504         case Qt::Key_Escape:
505                 if (!modified && !filter_.isEmpty()) {
506                         resetFilter();
507                         return true;
508                 }
509                 break;
510         case Qt::Key_Backspace:
511                 if (!modified) {
512                         // cut off one character
513                         setFilter(filter_.left(filter_.length() - 1));
514                 }
515                 break;
516         default:
517                 if (modified || ke->text().isEmpty())
518                         break;
519                 // find chars for the filter string
520                 QString s;
521                 for (int i = 0; i < ke->text().length(); ++i) {
522                         QChar c = ke->text()[i];
523                         if (c.isLetterOrNumber()
524                             || c.isSymbol()
525                             || c.isPunct()
526                             || c.category() == QChar::Separator_Space) {
527                                 s += c;
528                         }
529                 }
530                 if (!s.isEmpty()) {
531                         // append new chars to the filter string
532                         setFilter(filter_ + s);
533                         return true;
534                 }
535                 break;
536         }
537
538         return QComboBox::eventFilter(o, e);
539 }
540
541
542 void GuiLayoutBox::set(docstring const & layout)
543 {
544         resetFilter();
545         
546         if (!text_class_)
547                 return;
548
549         QString const & name = toqstr((*text_class_)[layout].name());
550         if (name == currentText())
551                 return;
552
553         QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
554         if (r.empty()) {
555                 lyxerr << "Trying to select non existent layout type "
556                         << fromqstr(name) << endl;
557                 return;
558         }
559
560         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
561 }
562
563
564 void GuiLayoutBox::addItemSort(docstring const & item, bool sorted)
565 {
566         QString qitem = toqstr(item);
567         QString titem = toqstr(translateIfPossible(item));
568
569         QList<QStandardItem *> row;
570         row.append(new QStandardItem(titem));
571         row.append(new QStandardItem(qitem));
572
573         // the simple unsorted case
574         int const end = model_->rowCount();
575         if (!sorted || end < 2 || qitem[0].category() != QChar::Letter_Uppercase) {
576                 model_->appendRow(row);
577                 return;
578         }
579
580         // find row to insert the item, after the separator if it exists
581         int i = 1; // skip the Standard layout
582         
583         QList<QStandardItem *> sep = model_->findItems("--", Qt::MatchStartsWith);
584         if (!sep.isEmpty())
585                 i = sep.first()->index().row() + 1;
586         if (i < model_->rowCount()) {
587                 // find alphabetic position
588                 QString is = model_->item(i, 0)->text();
589                 while (is.compare(titem) < 0) {
590                         // e.g. --Separator--
591                         if (is.at(0).category() != QChar::Letter_Uppercase)
592                                 break;
593                         ++i;
594                         if (i == end)
595                                 break;
596                         is = model_->item(i, 0)->text();
597                 }
598         }
599
600         model_->insertRow(i, row);
601 }
602
603
604 void GuiLayoutBox::updateContents(bool reset)
605 {
606         resetFilter();
607         
608         Buffer const * buffer = owner_.buffer();
609         if (!buffer) {
610                 model_->clear();
611                 setEnabled(false);
612                 text_class_ = 0;
613                 inset_ = 0;
614                 return;
615         }
616
617         // we'll only update the layout list if the text class has changed
618         // or we've moved from one inset to another
619         DocumentClass const * text_class = &buffer->params().documentClass();
620         Inset const * inset = 
621         owner_.view()->cursor().innerParagraph().inInset();
622         if (!reset && text_class_ == text_class && inset_ == inset) {
623                 set(owner_.view()->cursor().innerParagraph().layout().name());
624                 return;
625         }
626
627         inset_ = inset;
628         text_class_ = text_class;
629
630         model_->clear();
631         DocumentClass::const_iterator lit = text_class_->begin();
632         DocumentClass::const_iterator len = text_class_->end();
633         for (; lit != len; ++lit) {
634                 docstring const & name = lit->name();
635                 // if this inset requires the empty layout, we skip the default
636                 // layout
637                 if (name == text_class_->defaultLayoutName() && inset &&
638                     (inset->forceEmptyLayout() || inset->useEmptyLayout()))
639                         continue;
640                 // if it doesn't require the empty layout, we skip it
641                 if (name == text_class_->emptyLayoutName() && inset &&
642                     !inset->forceEmptyLayout() && !inset->useEmptyLayout())
643                         continue;
644                 addItemSort(name, lyxrc.sort_layouts);
645         }
646
647         set(owner_.view()->cursor().innerParagraph().layout().name());
648
649         // needed to recalculate size hint
650         hide();
651         setMinimumWidth(sizeHint().width());
652         setEnabled(!buffer->isReadonly());
653         show();
654 }
655
656
657 void GuiLayoutBox::selected(int index)
658 {
659         // get selection
660         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
661         docstring const layoutName = 
662                 qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
663
664         owner_.setFocus();
665
666         if (!text_class_) {
667                 updateContents(false);
668                 resetFilter();
669                 return;
670         }
671
672         // find corresponding text class
673         if (text_class_->hasLayout(layoutName)) {
674                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
675                 theLyXFunc().setLyXView(&owner_);
676                 lyx::dispatch(func);
677                 updateContents(false);
678                 resetFilter();
679                 return;
680         }
681         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
682 }
683
684
685
686 /////////////////////////////////////////////////////////////////////
687 //
688 // GuiToolbar
689 //
690 /////////////////////////////////////////////////////////////////////
691
692
693 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
694         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
695           layout_(0), command_buffer_(0)
696 {
697         // give visual separation between adjacent toolbars
698         addSeparator();
699
700         // TODO: save toolbar position
701         setMovable(true);
702
703         ToolbarInfo::item_iterator it = tbinfo.items.begin();
704         ToolbarInfo::item_iterator end = tbinfo.items.end();
705         for (; it != end; ++it)
706                 add(*it);
707 }
708
709
710 Action * GuiToolbar::addItem(ToolbarItem const & item)
711 {
712         Action * act = new Action(owner_,
713                 getIcon(item.func_, false),
714           toqstr(item.label_), item.func_, toqstr(item.label_));
715         actions_.append(act);
716         return act;
717 }
718
719 namespace {
720
721 class PaletteButton : public QToolButton
722 {
723 private:
724         GuiToolbar * bar_;
725         ToolbarItem const & tbitem_;
726         bool initialized_;
727 public:
728         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
729                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
730         {
731                 QString const label = qt_(to_ascii(tbitem_.label_));
732                 setToolTip(label);
733                 setStatusTip(label);
734                 setText(label);
735                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
736                         this, SLOT(setIconSize(QSize)));
737                 setCheckable(true);
738                 ToolbarInfo const * tbinfo = 
739                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
740                 if (tbinfo)
741                         // use the icon of first action for the toolbar button
742                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
743         }
744
745         void mousePressEvent(QMouseEvent * e)
746         {
747                 if (initialized_) {
748                         QToolButton::mousePressEvent(e);
749                         return;
750                 }
751
752                 initialized_ = true;
753
754                 ToolbarInfo const * tbinfo = 
755                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
756                 if (!tbinfo) {
757                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
758                         return;
759                 }
760                 IconPalette * panel = new IconPalette(this);
761                 QString const label = qt_(to_ascii(tbitem_.label_));
762                 panel->setWindowTitle(label);
763                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
764                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
765                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
766                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
767                 for (; it != end; ++it)
768                         if (!getStatus(it->func_).unknown())
769                                 panel->addButton(bar_->addItem(*it));
770
771                 QToolButton::mousePressEvent(e);
772         }
773 };
774
775 class MenuButton : public QToolButton
776 {
777 private:
778         GuiToolbar * bar_;
779         ToolbarItem const & tbitem_;
780         bool initialized_;
781 public:
782         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
783                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
784         {
785                 setPopupMode(QToolButton::InstantPopup);
786                 QString const label = qt_(to_ascii(tbitem_.label_));
787                 setToolTip(label);
788                 setStatusTip(label);
789                 setText(label);
790                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
791                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
792                         this, SLOT(setIconSize(QSize)));
793         }
794
795         void mousePressEvent(QMouseEvent * e)
796         {
797                 if (initialized_) {
798                         QToolButton::mousePressEvent(e);
799                         return;
800                 }
801
802                 initialized_ = true;
803
804                 QString const label = qt_(to_ascii(tbitem_.label_));
805                 ButtonMenu * m = new ButtonMenu(label, this);
806                 m->setWindowTitle(label);
807                 m->setTearOffEnabled(true);
808                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
809                 ToolbarInfo const * tbinfo = 
810                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
811                 if (!tbinfo) {
812                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
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(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::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
880 {
881         // if tbinfo.state == auto *do not* set on/off
882         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
883                 if (GuiToolbar::isVisible())
884                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
885                 else
886                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
887         }
888         //
889         // no need to save it here.
890         Qt::ToolBarArea loc = owner_.toolBarArea(this);
891
892         if (loc == Qt::TopToolBarArea)
893                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
894         else if (loc == Qt::BottomToolBarArea)
895                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
896         else if (loc == Qt::RightToolBarArea)
897                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
898         else if (loc == Qt::LeftToolBarArea)
899                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
900         else
901                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
902
903         // save toolbar position. They are not used to restore toolbar position
904         // now because move(x,y) does not work for toolbar.
905         tbinfo.posx = pos().x();
906         tbinfo.posy = pos().y();
907 }
908
909
910 void GuiToolbar::updateContents()
911 {
912         // update visible toolbars only
913         if (!isVisible())
914                 return;
915         // This is a speed bottleneck because this is called on every keypress
916         // and update calls getStatus, which copies the cursor at least two times
917         for (int i = 0; i < actions_.size(); ++i)
918                 actions_[i]->update();
919
920         if (layout_)
921                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
922
923         // emit signal
924         updated();
925 }
926
927
928 } // namespace frontend
929 } // namespace lyx
930
931 #include "GuiToolbar_moc.cpp"