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