]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
* even when sorted alphabetically keep the separation of standard and module layouts
[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, const QStyleOptionViewItem & option,
252                 const QModelIndex &index) const {
253                 QComboBox * combo = static_cast<QComboBox const *>(parent());
254                 
255                 // Draw using the menu item style (this is how QComboBox does it).
256                 // But for the rich text drawing below we will call it with an
257                 // empty string, and later then draw over it the real string.
258                 painter->save();
259                 QStyleOptionMenuItem opt = getStyleOption(option, index);
260                 QString text = underlineFilter(opt.text);
261                 opt.text = QString();
262                 painter->eraseRect(option.rect);
263                 combo->style()->drawControl(QStyle::CE_MenuItem, &opt, painter, combo->view());
264                 painter->restore();
265                 
266                 // don't draw string for separator
267                 if (opt.menuItemType == QStyleOptionMenuItem::Separator)
268                         return;
269                 
270                 // Draw the rich text.
271                 painter->save();
272                 QColor col = opt.palette.text().color();
273                 if (opt.state & QStyle::State_Selected)
274                         col = opt.palette.highlightedText().color();
275                 QAbstractTextDocumentLayout::PaintContext context;
276                 context.palette.setColor(QPalette::Text, col);
277                 
278                 QTextDocument doc;
279                 doc.setDefaultFont(opt.font);
280                 doc.setHtml(text);
281                 painter->translate(opt.rect.x() + 20, opt.rect.y());
282                 doc.documentLayout()->draw(painter, context);
283                 painter->restore();
284         }
285         
286         ///
287         QSize sizeHint(const QStyleOptionViewItem &option,
288                 const QModelIndex &index) const {
289                 QComboBox * combo = static_cast<QComboBox const *>(parent());
290
291                 QStyleOptionMenuItem opt = getStyleOption(option, index);
292                 return combo->style()->sizeFromContents(
293                          QStyle::CT_MenuItem, &opt, option.rect.size(), combo);
294         }
295         
296 private:
297         ///
298         QString underlineFilter(QString const & s) const
299         {
300                 // get filter
301                 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
302                 QString const & f = p->filter();
303                 if (f.isEmpty())
304                         return s;
305                 
306                 // step through data item and put "(x)" for every matching character
307                 QString r;
308                 int lastp = -1;
309                 p->filter();
310                 for (int i = 0; i < f.length(); ++i) {
311                         int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
312                         BOOST_ASSERT(p != -1);
313                         if (lastp == p - 1 && lastp != -1) {
314                                 // remove ")" and append "x)"
315                                 r = r.left(r.length() - 4) + s[p] + "</u>";
316                         } else {
317                                 // append "(x)"
318                                 r += s.mid(lastp + 1, p - lastp - 1);
319                                 r += QString("<u>") + s[p] + "</u>";
320                         }
321                         lastp = p;
322                 }
323                 r += s.mid(lastp + 1);
324                 return r;
325         }
326
327         ///
328         QStyleOptionMenuItem getStyleOption(const QStyleOptionViewItem &option,
329                 const QModelIndex &index) const
330         {
331                 QComboBox * combo = static_cast<QComboBox const *>(parent());
332
333                 // create the options for a menu item
334                 QStyleOptionMenuItem menuOption;
335                 menuOption.palette = QApplication::palette("QMenu");
336                 menuOption.state = QStyle::State_Active | QStyle::State_Enabled;
337                 if (option.state & QStyle::State_Selected)
338                         menuOption.state |= QStyle::State_Selected;
339                 menuOption.checkType = QStyleOptionMenuItem::NonExclusive;
340                 menuOption.checked = combo->currentIndex() == index.row();
341                 menuOption.text = index.model()->data(index, Qt::DisplayRole).toString()
342                         .replace(QLatin1Char('&'), QLatin1String("&&"));
343                 if (menuOption.text.left(2) == "--")
344                         menuOption.menuItemType = QStyleOptionMenuItem::Separator;
345                 else
346                         menuOption.menuItemType = QStyleOptionMenuItem::Normal;
347                 menuOption.tabWidth = 0;
348                 menuOption.menuRect = option.rect;
349                 menuOption.rect = option.rect;
350                 menuOption.font = combo->font();
351                 menuOption.fontMetrics = QFontMetrics(menuOption.font);
352                 
353                 return menuOption;
354         }
355 };
356
357
358 class GuiFilterProxyModel : public QSortFilterProxyModel
359 {
360 public:
361         ///
362         GuiFilterProxyModel(QObject * parent)
363         : QSortFilterProxyModel(parent) {}
364
365         ///
366         void setCharFilter(QString const & f)
367         {
368                 setFilterRegExp(charFilterRegExp(f));
369                 dataChanged(index(0, 0), index(rowCount() - 1, 1));
370         }
371
372 private:
373         ///
374         QString charFilterRegExp(QString const & filter)
375         {
376                 QString re;
377                 for (int i = 0; i < filter.length(); ++i)
378                         re += ".*" + QRegExp::escape(filter[i]);
379                 return re;
380         }
381 };
382
383
384 GuiLayoutBox::GuiLayoutBox(GuiView & owner)
385         : owner_(owner), filterItemDelegate_(new FilterItemDelegate(this))
386 {
387         setSizeAdjustPolicy(QComboBox::AdjustToContents);
388         setFocusPolicy(Qt::ClickFocus);
389         setMinimumWidth(sizeHint().width());
390         setMaxVisibleItems(100);
391
392         // set the layout model with two columns
393         // 1st: translated layout names
394         // 2nd: raw layout names
395         model_ = new QStandardItemModel(0, 2, this);
396         filterModel_ = new GuiFilterProxyModel(this);
397         filterModel_->setSourceModel(model_);
398         filterModel_->setDynamicSortFilter(true);
399         filterModel_->setFilterCaseSensitivity(Qt::CaseInsensitive);
400         setModel(filterModel_);
401
402         // for the filtering we have to intercept characters
403         view()->installEventFilter(this);
404         view()->setItemDelegateForColumn(0, filterItemDelegate_);
405         
406         QObject::connect(this, SIGNAL(activated(int)),
407                          this, SLOT(selected(int)));
408         owner_.setLayoutDialog(this);
409         updateContents(true);
410 }
411
412
413 void GuiLayoutBox::setFilter(QString const & s)
414 {
415         // remember old selection
416         int sel = currentIndex();
417         if (sel != -1)
418                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
419
420         filter_ = s;
421         filterModel_->setCharFilter(s);
422         
423         // restore old selection
424         if (lastSel_ != -1) {
425                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
426                 if (i.isValid())
427                         setCurrentIndex(i.row());
428         }
429 }
430
431
432 void GuiLayoutBox::resetFilter()
433 {
434         setFilter(QString());
435 }
436
437
438 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
439 {
440         if (e->type() != QEvent::KeyPress)
441                 return QComboBox::eventFilter(o, e);
442
443         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
444         bool modified = (ke->modifiers() == Qt::ControlModifier)
445                 || (ke->modifiers() == Qt::AltModifier)
446                 || (ke->modifiers() == Qt::MetaModifier);
447         
448         switch (ke->key()) {
449         case Qt::Key_Escape:
450                 if (!modified && !filter_.isEmpty()) {
451                         resetFilter();
452                         return true;
453                 }
454                 break;
455         case Qt::Key_Backspace:
456                 if (!modified) {
457                         // cut off one character
458                         setFilter(filter_.left(filter_.length() - 1));
459                 }
460                 break;
461         default:
462                 if (modified || ke->text().isEmpty())
463                         break;
464                 // find chars for the filter string
465                 QString s;
466                 for (int i = 0; i < ke->text().length(); ++i) {
467                         QChar c = ke->text()[i];
468                         if (c.isLetterOrNumber()
469                             || c.isSymbol()
470                             || c.isPunct()
471                             || c.category() == QChar::Separator_Space) {
472                                 s += c;
473                         }
474                 }
475                 if (!s.isEmpty()) {
476                         // append new chars to the filter string
477                         setFilter(filter_ + s);
478                         return true;
479                 }
480                 break;
481         }
482
483         return QComboBox::eventFilter(o, e);
484 }
485
486
487 void GuiLayoutBox::set(docstring const & layout)
488 {
489         resetFilter();
490         
491         if (!text_class_)
492                 return;
493
494         QString const & name = toqstr((*text_class_)[layout]->name());
495         if (name == currentText())
496                 return;
497
498         QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
499         if (r.empty()) {
500                 lyxerr << "Trying to select non existent layout type "
501                         << fromqstr(name) << endl;
502                 return;
503         }
504
505         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
506 }
507
508
509 void GuiLayoutBox::addItemSort(docstring const & item, bool sorted)
510 {
511         QString qitem = toqstr(item);
512         QString titem = toqstr(translateIfPossible(item));
513
514         QList<QStandardItem *> row;
515         row.append(new QStandardItem(titem));
516         row.append(new QStandardItem(qitem));
517
518         // the simple unsorted case
519         int const end = model_->rowCount();
520         if (!sorted || end < 2 || qitem[0].category() != QChar::Letter_Uppercase) {
521                 model_->appendRow(row);
522                 return;
523         }
524
525         // find row to insert the item, after the separator if it exists
526         int i = 1; // skip the Standard layout
527         
528         QList<QStandardItem *> sep = model_->findItems("--", Qt::MatchStartsWith);
529         if (!sep.isEmpty())
530                 i = sep.first()->index().row() + 1;
531         if (i < model_->rowCount()) {
532                 // find alphabetic position
533                 QString is = model_->item(i, 0)->text();
534                 while (is.compare(titem) < 0) {
535                         // e.g. --Separator--
536                         if (is[0].category() != QChar::Letter_Uppercase)
537                                 break;
538                         ++i;
539                         if (i == end)
540                                 break;
541                         is = model_->item(i, 0)->text();
542                 }
543         }
544
545         model_->insertRow(i, row);
546 }
547
548
549 void GuiLayoutBox::updateContents(bool reset)
550 {
551         resetFilter();
552         
553         Buffer const * buffer = owner_.buffer();
554         if (!buffer) {
555                 model_->clear();
556                 setEnabled(false);
557                 text_class_ = 0;
558                 inset_ = 0;
559                 return;
560         }
561
562         // we'll only update the layout list if the text class has changed
563         // or we've moved from one inset to another
564         DocumentClass const * text_class = &buffer->params().documentClass();
565         Inset const * inset = 
566         owner_.view()->cursor().innerParagraph().inInset();
567         if (!reset && text_class_ == text_class && inset_ == inset) {
568                 set(owner_.view()->cursor().innerParagraph().layout()->name());
569                 return;
570         }
571
572         inset_ = inset;
573         text_class_ = text_class;
574
575         model_->clear();
576         for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
577                 Layout const & lt = *text_class_->layout(i);
578                 docstring const & name = lt.name();
579                 // if this inset requires the empty layout, we skip the default
580                 // layout
581                 if (name == text_class_->defaultLayoutName() && inset &&
582                     (inset->forceEmptyLayout() || inset->useEmptyLayout()))
583                         continue;
584                 // if it doesn't require the empty layout, we skip it
585                 if (name == text_class_->emptyLayoutName() && inset &&
586                     !inset->forceEmptyLayout() && !inset->useEmptyLayout())
587                         continue;
588                 addItemSort(name, lyxrc.sort_layouts);
589         }
590
591         set(owner_.view()->cursor().innerParagraph().layout()->name());
592
593         // needed to recalculate size hint
594         hide();
595         setMinimumWidth(sizeHint().width());
596         setEnabled(!buffer->isReadonly());
597         show();
598 }
599
600
601 void GuiLayoutBox::selected(int index)
602 {
603         // get selection
604         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
605         docstring const name = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
606
607         owner_.setFocus();
608
609         if (!text_class_) {
610                 updateContents(false);
611                 resetFilter();
612                 return;
613         }
614
615         // find corresponding text class
616         for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
617                 docstring const & itname = text_class_->layout(i)->name();
618                 if (itname == name) {
619                         FuncRequest const func(LFUN_LAYOUT, itname,
620                                                FuncRequest::TOOLBAR);
621                         theLyXFunc().setLyXView(&owner_);
622                         lyx::dispatch(func);
623                         updateContents(false);
624                         resetFilter();
625                         return;
626                 }
627         }
628         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
629 }
630
631
632
633 /////////////////////////////////////////////////////////////////////
634 //
635 // GuiToolbar
636 //
637 /////////////////////////////////////////////////////////////////////
638
639
640 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
641         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
642           layout_(0), command_buffer_(0)
643 {
644         // give visual separation between adjacent toolbars
645         addSeparator();
646
647         // TODO: save toolbar position
648         setMovable(true);
649
650         ToolbarInfo::item_iterator it = tbinfo.items.begin();
651         ToolbarInfo::item_iterator end = tbinfo.items.end();
652         for (; it != end; ++it)
653                 add(*it);
654 }
655
656
657 Action * GuiToolbar::addItem(ToolbarItem const & item)
658 {
659         Action * act = new Action(owner_,
660                 getIcon(item.func_, false),
661           toqstr(item.label_), item.func_, toqstr(item.label_));
662         actions_.append(act);
663         return act;
664 }
665
666 namespace {
667
668 class PaletteButton : public QToolButton
669 {
670 private:
671         GuiToolbar * bar_;
672         ToolbarItem const & tbitem_;
673         bool initialized_;
674 public:
675         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
676                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
677         {
678                 QString const label = qt_(to_ascii(tbitem_.label_));
679                 setToolTip(label);
680                 setStatusTip(label);
681                 setText(label);
682                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
683                         this, SLOT(setIconSize(QSize)));
684                 setCheckable(true);
685                 ToolbarInfo const * tbinfo = 
686                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
687                 if (tbinfo)
688                         // use the icon of first action for the toolbar button
689                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
690         }
691
692         void mousePressEvent(QMouseEvent * e)
693         {
694                 if (initialized_) {
695                         QToolButton::mousePressEvent(e);
696                         return;
697                 }
698
699                 initialized_ = true;
700
701                 ToolbarInfo const * tbinfo = 
702                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
703                 if (!tbinfo) {
704                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
705                         return;
706                 }
707                 IconPalette * panel = new IconPalette(this);
708                 QString const label = qt_(to_ascii(tbitem_.label_));
709                 panel->setWindowTitle(label);
710                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
711                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
712                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
713                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
714                 for (; it != end; ++it)
715                         if (!getStatus(it->func_).unknown())
716                                 panel->addButton(bar_->addItem(*it));
717
718                 QToolButton::mousePressEvent(e);
719         }
720 };
721
722 class MenuButton : public QToolButton
723 {
724 private:
725         GuiToolbar * bar_;
726         ToolbarItem const & tbitem_;
727         bool initialized_;
728 public:
729         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
730                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
731         {
732                 setPopupMode(QToolButton::InstantPopup);
733                 QString const label = qt_(to_ascii(tbitem_.label_));
734                 setToolTip(label);
735                 setStatusTip(label);
736                 setText(label);
737                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
738                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
739                         this, SLOT(setIconSize(QSize)));
740         }
741
742         void mousePressEvent(QMouseEvent * e)
743         {
744                 if (initialized_) {
745                         QToolButton::mousePressEvent(e);
746                         return;
747                 }
748
749                 initialized_ = true;
750
751                 QString const label = qt_(to_ascii(tbitem_.label_));
752                 ButtonMenu * m = new ButtonMenu(label, this);
753                 m->setWindowTitle(label);
754                 m->setTearOffEnabled(true);
755                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
756                 ToolbarInfo const * tbinfo = 
757                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
758                 if (!tbinfo) {
759                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
760                         return;
761                 }
762                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
763                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
764                 for (; it != end; ++it)
765                         if (!getStatus(it->func_).unknown())
766                                 m->add(bar_->addItem(*it));
767                 setMenu(m);
768
769                 QToolButton::mousePressEvent(e);
770         }
771 };
772
773 }
774
775
776 void GuiToolbar::add(ToolbarItem const & item)
777 {
778         switch (item.type_) {
779         case ToolbarItem::SEPARATOR:
780                 addSeparator();
781                 break;
782         case ToolbarItem::LAYOUTS:
783                 layout_ = new GuiLayoutBox(owner_);
784                 addWidget(layout_);
785                 break;
786         case ToolbarItem::MINIBUFFER:
787                 command_buffer_ = new GuiCommandBuffer(&owner_);
788                 addWidget(command_buffer_);
789                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
790                 //setHorizontalStretchable(true);
791                 break;
792         case ToolbarItem::TABLEINSERT: {
793                 QToolButton * tb = new QToolButton;
794                 tb->setCheckable(true);
795                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
796                 QString const label = qt_(to_ascii(item.label_));
797                 tb->setToolTip(label);
798                 tb->setStatusTip(label);
799                 tb->setText(label);
800                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
801                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
802                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
803                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
804                 addWidget(tb);
805                 break;
806                 }
807         case ToolbarItem::ICONPALETTE:
808                 addWidget(new PaletteButton(this, item));
809                 break;
810
811         case ToolbarItem::POPUPMENU: {
812                 addWidget(new MenuButton(this, item));
813                 break;
814                 }
815         case ToolbarItem::COMMAND: {
816                 if (!getStatus(item.func_).unknown())
817                         addAction(addItem(item));
818                 break;
819                 }
820         default:
821                 break;
822         }
823 }
824
825
826 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
827 {
828         // if tbinfo.state == auto *do not* set on/off
829         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
830                 if (GuiToolbar::isVisible())
831                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
832                 else
833                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
834         }
835         //
836         // no need to save it here.
837         Qt::ToolBarArea loc = owner_.toolBarArea(this);
838
839         if (loc == Qt::TopToolBarArea)
840                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
841         else if (loc == Qt::BottomToolBarArea)
842                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
843         else if (loc == Qt::RightToolBarArea)
844                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
845         else if (loc == Qt::LeftToolBarArea)
846                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
847         else
848                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
849
850         // save toolbar position. They are not used to restore toolbar position
851         // now because move(x,y) does not work for toolbar.
852         tbinfo.posx = pos().x();
853         tbinfo.posy = pos().y();
854 }
855
856
857 void GuiToolbar::updateContents()
858 {
859         // update visible toolbars only
860         if (!isVisible())
861                 return;
862         // This is a speed bottleneck because this is called on every keypress
863         // and update calls getStatus, which copies the cursor at least two times
864         for (int i = 0; i < actions_.size(); ++i)
865                 actions_[i]->update();
866
867         if (layout_)
868                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
869
870         // emit signal
871         updated();
872 }
873
874
875 } // namespace frontend
876 } // namespace lyx
877
878 #include "GuiToolbar_moc.cpp"