]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
* cosmetic
[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 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(QStyleOptionViewItem const & option,
288                 QModelIndex const & 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(QStyleOptionViewItem const & option,
329                 QModelIndex const & 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         // Workaround to resize to content size
431         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
432         //        does not help.
433         if (view()->isVisible())
434                 showPopup();
435 }
436
437
438 void GuiLayoutBox::resetFilter()
439 {
440         setFilter(QString());
441 }
442
443
444 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
445 {
446         if (e->type() != QEvent::KeyPress)
447                 return QComboBox::eventFilter(o, e);
448
449         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
450         bool modified = (ke->modifiers() == Qt::ControlModifier)
451                 || (ke->modifiers() == Qt::AltModifier)
452                 || (ke->modifiers() == Qt::MetaModifier);
453         
454         switch (ke->key()) {
455         case Qt::Key_Escape:
456                 if (!modified && !filter_.isEmpty()) {
457                         resetFilter();
458                         return true;
459                 }
460                 break;
461         case Qt::Key_Backspace:
462                 if (!modified) {
463                         // cut off one character
464                         setFilter(filter_.left(filter_.length() - 1));
465                 }
466                 break;
467         default:
468                 if (modified || ke->text().isEmpty())
469                         break;
470                 // find chars for the filter string
471                 QString s;
472                 for (int i = 0; i < ke->text().length(); ++i) {
473                         QChar c = ke->text()[i];
474                         if (c.isLetterOrNumber()
475                             || c.isSymbol()
476                             || c.isPunct()
477                             || c.category() == QChar::Separator_Space) {
478                                 s += c;
479                         }
480                 }
481                 if (!s.isEmpty()) {
482                         // append new chars to the filter string
483                         setFilter(filter_ + s);
484                         return true;
485                 }
486                 break;
487         }
488
489         return QComboBox::eventFilter(o, e);
490 }
491
492
493 void GuiLayoutBox::set(docstring const & layout)
494 {
495         resetFilter();
496         
497         if (!text_class_)
498                 return;
499
500         QString const & name = toqstr((*text_class_)[layout]->name());
501         if (name == currentText())
502                 return;
503
504         QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
505         if (r.empty()) {
506                 lyxerr << "Trying to select non existent layout type "
507                         << fromqstr(name) << endl;
508                 return;
509         }
510
511         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
512 }
513
514
515 void GuiLayoutBox::addItemSort(docstring const & item, bool sorted)
516 {
517         QString qitem = toqstr(item);
518         QString titem = toqstr(translateIfPossible(item));
519
520         QList<QStandardItem *> row;
521         row.append(new QStandardItem(titem));
522         row.append(new QStandardItem(qitem));
523
524         // the simple unsorted case
525         int const end = model_->rowCount();
526         if (!sorted || end < 2 || qitem[0].category() != QChar::Letter_Uppercase) {
527                 model_->appendRow(row);
528                 return;
529         }
530
531         // find row to insert the item, after the separator if it exists
532         int i = 1; // skip the Standard layout
533         
534         QList<QStandardItem *> sep = model_->findItems("--", Qt::MatchStartsWith);
535         if (!sep.isEmpty())
536                 i = sep.first()->index().row() + 1;
537         if (i < model_->rowCount()) {
538                 // find alphabetic position
539                 QString is = model_->item(i, 0)->text();
540                 while (is.compare(titem) < 0) {
541                         // e.g. --Separator--
542                         if (is[0].category() != QChar::Letter_Uppercase)
543                                 break;
544                         ++i;
545                         if (i == end)
546                                 break;
547                         is = model_->item(i, 0)->text();
548                 }
549         }
550
551         model_->insertRow(i, row);
552 }
553
554
555 void GuiLayoutBox::updateContents(bool reset)
556 {
557         resetFilter();
558         
559         Buffer const * buffer = owner_.buffer();
560         if (!buffer) {
561                 model_->clear();
562                 setEnabled(false);
563                 text_class_ = 0;
564                 inset_ = 0;
565                 return;
566         }
567
568         // we'll only update the layout list if the text class has changed
569         // or we've moved from one inset to another
570         DocumentClass const * text_class = &buffer->params().documentClass();
571         Inset const * inset = 
572         owner_.view()->cursor().innerParagraph().inInset();
573         if (!reset && text_class_ == text_class && inset_ == inset) {
574                 set(owner_.view()->cursor().innerParagraph().layout()->name());
575                 return;
576         }
577
578         inset_ = inset;
579         text_class_ = text_class;
580
581         model_->clear();
582         for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
583                 Layout const & lt = *text_class_->layout(i);
584                 docstring const & name = lt.name();
585                 // if this inset requires the empty layout, we skip the default
586                 // layout
587                 if (name == text_class_->defaultLayoutName() && inset &&
588                     (inset->forceEmptyLayout() || inset->useEmptyLayout()))
589                         continue;
590                 // if it doesn't require the empty layout, we skip it
591                 if (name == text_class_->emptyLayoutName() && inset &&
592                     !inset->forceEmptyLayout() && !inset->useEmptyLayout())
593                         continue;
594                 addItemSort(name, lyxrc.sort_layouts);
595         }
596
597         set(owner_.view()->cursor().innerParagraph().layout()->name());
598
599         // needed to recalculate size hint
600         hide();
601         setMinimumWidth(sizeHint().width());
602         setEnabled(!buffer->isReadonly());
603         show();
604 }
605
606
607 void GuiLayoutBox::selected(int index)
608 {
609         // get selection
610         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
611         docstring const name = qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
612
613         owner_.setFocus();
614
615         if (!text_class_) {
616                 updateContents(false);
617                 resetFilter();
618                 return;
619         }
620
621         // find corresponding text class
622         for (size_t i = 0; i != text_class_->layoutCount(); ++i) {
623                 docstring const & itname = text_class_->layout(i)->name();
624                 if (itname == name) {
625                         FuncRequest const func(LFUN_LAYOUT, itname,
626                                                FuncRequest::TOOLBAR);
627                         theLyXFunc().setLyXView(&owner_);
628                         lyx::dispatch(func);
629                         updateContents(false);
630                         resetFilter();
631                         return;
632                 }
633         }
634         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
635 }
636
637
638
639 /////////////////////////////////////////////////////////////////////
640 //
641 // GuiToolbar
642 //
643 /////////////////////////////////////////////////////////////////////
644
645
646 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
647         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
648           layout_(0), command_buffer_(0)
649 {
650         // give visual separation between adjacent toolbars
651         addSeparator();
652
653         // TODO: save toolbar position
654         setMovable(true);
655
656         ToolbarInfo::item_iterator it = tbinfo.items.begin();
657         ToolbarInfo::item_iterator end = tbinfo.items.end();
658         for (; it != end; ++it)
659                 add(*it);
660 }
661
662
663 Action * GuiToolbar::addItem(ToolbarItem const & item)
664 {
665         Action * act = new Action(owner_,
666                 getIcon(item.func_, false),
667           toqstr(item.label_), item.func_, toqstr(item.label_));
668         actions_.append(act);
669         return act;
670 }
671
672 namespace {
673
674 class PaletteButton : public QToolButton
675 {
676 private:
677         GuiToolbar * bar_;
678         ToolbarItem const & tbitem_;
679         bool initialized_;
680 public:
681         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
682                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
683         {
684                 QString const label = qt_(to_ascii(tbitem_.label_));
685                 setToolTip(label);
686                 setStatusTip(label);
687                 setText(label);
688                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
689                         this, SLOT(setIconSize(QSize)));
690                 setCheckable(true);
691                 ToolbarInfo const * tbinfo = 
692                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
693                 if (tbinfo)
694                         // use the icon of first action for the toolbar button
695                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
696         }
697
698         void mousePressEvent(QMouseEvent * e)
699         {
700                 if (initialized_) {
701                         QToolButton::mousePressEvent(e);
702                         return;
703                 }
704
705                 initialized_ = true;
706
707                 ToolbarInfo const * tbinfo = 
708                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
709                 if (!tbinfo) {
710                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
711                         return;
712                 }
713                 IconPalette * panel = new IconPalette(this);
714                 QString const label = qt_(to_ascii(tbitem_.label_));
715                 panel->setWindowTitle(label);
716                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
717                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
718                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
719                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
720                 for (; it != end; ++it)
721                         if (!getStatus(it->func_).unknown())
722                                 panel->addButton(bar_->addItem(*it));
723
724                 QToolButton::mousePressEvent(e);
725         }
726 };
727
728 class MenuButton : public QToolButton
729 {
730 private:
731         GuiToolbar * bar_;
732         ToolbarItem const & tbitem_;
733         bool initialized_;
734 public:
735         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
736                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
737         {
738                 setPopupMode(QToolButton::InstantPopup);
739                 QString const label = qt_(to_ascii(tbitem_.label_));
740                 setToolTip(label);
741                 setStatusTip(label);
742                 setText(label);
743                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
744                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
745                         this, SLOT(setIconSize(QSize)));
746         }
747
748         void mousePressEvent(QMouseEvent * e)
749         {
750                 if (initialized_) {
751                         QToolButton::mousePressEvent(e);
752                         return;
753                 }
754
755                 initialized_ = true;
756
757                 QString const label = qt_(to_ascii(tbitem_.label_));
758                 ButtonMenu * m = new ButtonMenu(label, this);
759                 m->setWindowTitle(label);
760                 m->setTearOffEnabled(true);
761                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
762                 ToolbarInfo const * tbinfo = 
763                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
764                 if (!tbinfo) {
765                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
766                         return;
767                 }
768                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
769                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
770                 for (; it != end; ++it)
771                         if (!getStatus(it->func_).unknown())
772                                 m->add(bar_->addItem(*it));
773                 setMenu(m);
774
775                 QToolButton::mousePressEvent(e);
776         }
777 };
778
779 }
780
781
782 void GuiToolbar::add(ToolbarItem const & item)
783 {
784         switch (item.type_) {
785         case ToolbarItem::SEPARATOR:
786                 addSeparator();
787                 break;
788         case ToolbarItem::LAYOUTS:
789                 layout_ = new GuiLayoutBox(owner_);
790                 addWidget(layout_);
791                 break;
792         case ToolbarItem::MINIBUFFER:
793                 command_buffer_ = new GuiCommandBuffer(&owner_);
794                 addWidget(command_buffer_);
795                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
796                 //setHorizontalStretchable(true);
797                 break;
798         case ToolbarItem::TABLEINSERT: {
799                 QToolButton * tb = new QToolButton;
800                 tb->setCheckable(true);
801                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
802                 QString const label = qt_(to_ascii(item.label_));
803                 tb->setToolTip(label);
804                 tb->setStatusTip(label);
805                 tb->setText(label);
806                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
807                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
808                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
809                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
810                 addWidget(tb);
811                 break;
812                 }
813         case ToolbarItem::ICONPALETTE:
814                 addWidget(new PaletteButton(this, item));
815                 break;
816
817         case ToolbarItem::POPUPMENU: {
818                 addWidget(new MenuButton(this, item));
819                 break;
820                 }
821         case ToolbarItem::COMMAND: {
822                 if (!getStatus(item.func_).unknown())
823                         addAction(addItem(item));
824                 break;
825                 }
826         default:
827                 break;
828         }
829 }
830
831
832 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
833 {
834         // if tbinfo.state == auto *do not* set on/off
835         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
836                 if (GuiToolbar::isVisible())
837                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
838                 else
839                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
840         }
841         //
842         // no need to save it here.
843         Qt::ToolBarArea loc = owner_.toolBarArea(this);
844
845         if (loc == Qt::TopToolBarArea)
846                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
847         else if (loc == Qt::BottomToolBarArea)
848                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
849         else if (loc == Qt::RightToolBarArea)
850                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
851         else if (loc == Qt::LeftToolBarArea)
852                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
853         else
854                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
855
856         // save toolbar position. They are not used to restore toolbar position
857         // now because move(x,y) does not work for toolbar.
858         tbinfo.posx = pos().x();
859         tbinfo.posy = pos().y();
860 }
861
862
863 void GuiToolbar::updateContents()
864 {
865         // update visible toolbars only
866         if (!isVisible())
867                 return;
868         // This is a speed bottleneck because this is called on every keypress
869         // and update calls getStatus, which copies the cursor at least two times
870         for (int i = 0; i < actions_.size(); ++i)
871                 actions_[i]->update();
872
873         if (layout_)
874                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
875
876         // emit signal
877         updated();
878 }
879
880
881 } // namespace frontend
882 } // namespace lyx
883
884 #include "GuiToolbar_moc.cpp"