]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
* draw the separator as a menu separator
[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
526         int i = 1; // skip the Standard layout
527         QString is = model_->item(i, 0)->text();
528         while (is.compare(titem) < 0) {
529                 // e.g. --Separator--
530                 if (is[0].category() != QChar::Letter_Uppercase)
531                         break;
532                 ++i;
533                 if (i == end)
534                         break;
535                 is = model_->item(i, 0)->text();
536         }
537
538         model_->insertRow(i, row);
539 }
540
541
542 void GuiLayoutBox::updateContents(bool reset)
543 {
544         resetFilter();
545         
546         Buffer const * buffer = owner_.buffer();
547         if (!buffer) {
548                 model_->clear();
549                 setEnabled(false);
550                 text_class_ = 0;
551                 inset_ = 0;
552                 return;
553         }
554
555         // we'll only update the layout list if the text class has changed
556         // or we've moved from one inset to another
557         DocumentClass const * text_class = &buffer->params().documentClass();
558         Inset const * inset = 
559         owner_.view()->cursor().innerParagraph().inInset();
560         if (!reset && text_class_ == text_class && inset_ == inset) {
561                 set(owner_.view()->cursor().innerParagraph().layout()->name());
562                 return;
563         }
564
565         inset_ = inset;
566         text_class_ = text_class;
567
568         model_->clear();
569         for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
570                 Layout const & lt = *text_class_->layout(i);
571                 docstring const & name = lt.name();
572                 // if this inset requires the empty layout, we skip the default
573                 // layout
574                 if (name == text_class_->defaultLayoutName() && inset &&
575                     (inset->forceEmptyLayout() || inset->useEmptyLayout()))
576                         continue;
577                 // if it doesn't require the empty layout, we skip it
578                 if (name == text_class_->emptyLayoutName() && inset &&
579                     !inset->forceEmptyLayout() && !inset->useEmptyLayout())
580                         continue;
581                 addItemSort(name, lyxrc.sort_layouts);
582         }
583
584         set(owner_.view()->cursor().innerParagraph().layout()->name());
585
586         // needed to recalculate size hint
587         hide();
588         setMinimumWidth(sizeHint().width());
589         setEnabled(!buffer->isReadonly());
590         show();
591 }
592
593
594 void GuiLayoutBox::selected(int index)
595 {
596         // get selection
597         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
598         docstring const name = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
599
600         owner_.setFocus();
601
602         if (!text_class_) {
603                 updateContents(false);
604                 resetFilter();
605                 return;
606         }
607
608         // find corresponding text class
609         for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
610                 docstring const & itname = text_class_->layout(i)->name();
611                 if (itname == name) {
612                         FuncRequest const func(LFUN_LAYOUT, itname,
613                                                FuncRequest::TOOLBAR);
614                         theLyXFunc().setLyXView(&owner_);
615                         lyx::dispatch(func);
616                         updateContents(false);
617                         resetFilter();
618                         return;
619                 }
620         }
621         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
622 }
623
624
625
626 /////////////////////////////////////////////////////////////////////
627 //
628 // GuiToolbar
629 //
630 /////////////////////////////////////////////////////////////////////
631
632
633 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
634         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
635           layout_(0), command_buffer_(0)
636 {
637         // give visual separation between adjacent toolbars
638         addSeparator();
639
640         // TODO: save toolbar position
641         setMovable(true);
642
643         ToolbarInfo::item_iterator it = tbinfo.items.begin();
644         ToolbarInfo::item_iterator end = tbinfo.items.end();
645         for (; it != end; ++it)
646                 add(*it);
647 }
648
649
650 Action * GuiToolbar::addItem(ToolbarItem const & item)
651 {
652         Action * act = new Action(owner_,
653                 getIcon(item.func_, false),
654           toqstr(item.label_), item.func_, toqstr(item.label_));
655         actions_.append(act);
656         return act;
657 }
658
659 namespace {
660
661 class PaletteButton : public QToolButton
662 {
663 private:
664         GuiToolbar * bar_;
665         ToolbarItem const & tbitem_;
666         bool initialized_;
667 public:
668         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
669                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
670         {
671                 QString const label = qt_(to_ascii(tbitem_.label_));
672                 setToolTip(label);
673                 setStatusTip(label);
674                 setText(label);
675                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
676                         this, SLOT(setIconSize(QSize)));
677                 setCheckable(true);
678                 ToolbarInfo const * tbinfo = 
679                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
680                 if (tbinfo)
681                         // use the icon of first action for the toolbar button
682                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
683         }
684
685         void mousePressEvent(QMouseEvent * e)
686         {
687                 if (initialized_) {
688                         QToolButton::mousePressEvent(e);
689                         return;
690                 }
691
692                 initialized_ = true;
693
694                 ToolbarInfo const * tbinfo = 
695                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
696                 if (!tbinfo) {
697                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
698                         return;
699                 }
700                 IconPalette * panel = new IconPalette(this);
701                 QString const label = qt_(to_ascii(tbitem_.label_));
702                 panel->setWindowTitle(label);
703                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
704                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
705                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
706                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
707                 for (; it != end; ++it)
708                         if (!getStatus(it->func_).unknown())
709                                 panel->addButton(bar_->addItem(*it));
710
711                 QToolButton::mousePressEvent(e);
712         }
713 };
714
715 class MenuButton : public QToolButton
716 {
717 private:
718         GuiToolbar * bar_;
719         ToolbarItem const & tbitem_;
720         bool initialized_;
721 public:
722         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
723                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
724         {
725                 setPopupMode(QToolButton::InstantPopup);
726                 QString const label = qt_(to_ascii(tbitem_.label_));
727                 setToolTip(label);
728                 setStatusTip(label);
729                 setText(label);
730                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
731                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
732                         this, SLOT(setIconSize(QSize)));
733         }
734
735         void mousePressEvent(QMouseEvent * e)
736         {
737                 if (initialized_) {
738                         QToolButton::mousePressEvent(e);
739                         return;
740                 }
741
742                 initialized_ = true;
743
744                 QString const label = qt_(to_ascii(tbitem_.label_));
745                 ButtonMenu * m = new ButtonMenu(label, this);
746                 m->setWindowTitle(label);
747                 m->setTearOffEnabled(true);
748                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
749                 ToolbarInfo const * tbinfo = 
750                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
751                 if (!tbinfo) {
752                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
753                         return;
754                 }
755                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
756                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
757                 for (; it != end; ++it)
758                         if (!getStatus(it->func_).unknown())
759                                 m->add(bar_->addItem(*it));
760                 setMenu(m);
761
762                 QToolButton::mousePressEvent(e);
763         }
764 };
765
766 }
767
768
769 void GuiToolbar::add(ToolbarItem const & item)
770 {
771         switch (item.type_) {
772         case ToolbarItem::SEPARATOR:
773                 addSeparator();
774                 break;
775         case ToolbarItem::LAYOUTS:
776                 layout_ = new GuiLayoutBox(owner_);
777                 addWidget(layout_);
778                 break;
779         case ToolbarItem::MINIBUFFER:
780                 command_buffer_ = new GuiCommandBuffer(&owner_);
781                 addWidget(command_buffer_);
782                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
783                 //setHorizontalStretchable(true);
784                 break;
785         case ToolbarItem::TABLEINSERT: {
786                 QToolButton * tb = new QToolButton;
787                 tb->setCheckable(true);
788                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
789                 QString const label = qt_(to_ascii(item.label_));
790                 tb->setToolTip(label);
791                 tb->setStatusTip(label);
792                 tb->setText(label);
793                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
794                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
795                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
796                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
797                 addWidget(tb);
798                 break;
799                 }
800         case ToolbarItem::ICONPALETTE:
801                 addWidget(new PaletteButton(this, item));
802                 break;
803
804         case ToolbarItem::POPUPMENU: {
805                 addWidget(new MenuButton(this, item));
806                 break;
807                 }
808         case ToolbarItem::COMMAND: {
809                 if (!getStatus(item.func_).unknown())
810                         addAction(addItem(item));
811                 break;
812                 }
813         default:
814                 break;
815         }
816 }
817
818
819 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
820 {
821         // if tbinfo.state == auto *do not* set on/off
822         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
823                 if (GuiToolbar::isVisible())
824                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
825                 else
826                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
827         }
828         //
829         // no need to save it here.
830         Qt::ToolBarArea loc = owner_.toolBarArea(this);
831
832         if (loc == Qt::TopToolBarArea)
833                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
834         else if (loc == Qt::BottomToolBarArea)
835                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
836         else if (loc == Qt::RightToolBarArea)
837                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
838         else if (loc == Qt::LeftToolBarArea)
839                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
840         else
841                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
842
843         // save toolbar position. They are not used to restore toolbar position
844         // now because move(x,y) does not work for toolbar.
845         tbinfo.posx = pos().x();
846         tbinfo.posy = pos().y();
847 }
848
849
850 void GuiToolbar::updateContents()
851 {
852         // update visible toolbars only
853         if (!isVisible())
854                 return;
855         // This is a speed bottleneck because this is called on every keypress
856         // and update calls getStatus, which copies the cursor at least two times
857         for (int i = 0; i < actions_.size(); ++i)
858                 actions_[i]->update();
859
860         if (layout_)
861                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
862
863         // emit signal
864         updated();
865 }
866
867
868 } // namespace frontend
869 } // namespace lyx
870
871 #include "GuiToolbar_moc.cpp"