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