]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiToolbar.cpp
Minor cleanup.
[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 Stefan Schimanski
11  * \author Abdelrazak Younes
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "GuiView.h"
19 #include "GuiCommandBuffer.h"
20 #include "GuiToolbar.h"
21 #include "LyXAction.h"
22 #include "Action.h"
23 #include "qt_helpers.h"
24 #include "InsertTableWidget.h"
25
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "Cursor.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
32 #include "IconPalette.h"
33 #include "Layout.h"
34 #include "LyXFunc.h"
35 #include "LyXRC.h"
36 #include "Paragraph.h"
37 #include "TextClass.h"
38 #include "ToolbarBackend.h"
39
40 #include "support/debug.h"
41 #include "support/filetools.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/lyxalgo.h" // sorted
45
46 #include <QAbstractItemDelegate>
47 #include <QAbstractTextDocumentLayout>
48 #include <QApplication>
49 #include <QComboBox>
50 #include <QFontMetrics>
51 #include <QHeaderView>
52 #include <QItemDelegate>
53 #include <QKeyEvent>
54 #include <QList>
55 #include <QListView>
56 #include <QPainter>
57 #include <QPixmap>
58 #include <QSortFilterProxyModel>
59 #include <QStandardItem>
60 #include <QStandardItemModel>
61 #include <QTextDocument>
62 #include <QTextFrame>
63 #include <QToolBar>
64 #include <QToolButton>
65 #include <QVariant>
66
67 #include <boost/assert.hpp>
68
69 #include <map>
70 #include <vector>
71
72 using namespace std;
73 using namespace lyx::support;
74
75 static void initializeResources()
76 {
77         static bool initialized = false;
78         if (!initialized) {
79                 Q_INIT_RESOURCE(Resources); 
80                 initialized = true;
81         }
82 }
83
84
85 namespace lyx {
86 namespace frontend {
87
88 namespace {
89
90 struct PngMap {
91         QString key;
92         QString value;
93 };
94
95
96 bool operator<(PngMap const & lhs, PngMap const & rhs)
97 {
98                 return lhs.key < rhs.key;
99 }
100
101
102 class CompareKey {
103 public:
104         CompareKey(QString const & name) : name_(name) {}
105         bool operator()(PngMap const & other) const { return other.key == name_; }
106 private:
107         QString const name_;
108 };
109
110
111 PngMap sorted_png_map[] = {
112         { "Bumpeq", "bumpeq2" },
113         { "Cap", "cap2" },
114         { "Cup", "cup2" },
115         { "Delta", "delta2" },
116         { "Downarrow", "downarrow2" },
117         { "Gamma", "gamma2" },
118         { "Lambda", "lambda2" },
119         { "Leftarrow", "leftarrow2" },
120         { "Leftrightarrow", "leftrightarrow2" },
121         { "Longleftarrow", "longleftarrow2" },
122         { "Longleftrightarrow", "longleftrightarrow2" },
123         { "Longrightarrow", "longrightarrow2" },
124         { "Omega", "omega2" },
125         { "Phi", "phi2" },
126         { "Pi", "pi2" },
127         { "Psi", "psi2" },
128         { "Rightarrow", "rightarrow2" },
129         { "Sigma", "sigma2" },
130         { "Subset", "subset2" },
131         { "Supset", "supset2" },
132         { "Theta", "theta2" },
133         { "Uparrow", "uparrow2" },
134         { "Updownarrow", "updownarrow2" },
135         { "Upsilon", "upsilon2" },
136         { "Vdash", "vdash3" },
137         { "Xi", "xi2" },
138         { "nLeftarrow", "nleftarrow2" },
139         { "nLeftrightarrow", "nleftrightarrow2" },
140         { "nRightarrow", "nrightarrow2" },
141         { "nVDash", "nvdash3" },
142         { "nvDash", "nvdash2" },
143         { "textrm \\AA", "textrm_AA"},
144         { "textrm \\O", "textrm_O"},
145         { "vDash", "vdash2" }
146 };
147
148 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
149
150
151 QString findPng(QString const & name)
152 {
153         PngMap const * const begin = sorted_png_map;
154         PngMap const * const end = begin + nr_sorted_png_map;
155         BOOST_ASSERT(sorted(begin, end));
156
157         PngMap const * const it = find_if(begin, end, CompareKey(name));
158
159         QString png_name;
160         if (it != end) {
161                 png_name = it->value;
162         } else {
163                 png_name = name;
164                 png_name.replace('_', "underscore");
165                 png_name.replace(' ', '_');
166
167                 // This way we can have "math-delim { }" on the toolbar.
168                 png_name.replace('(', "lparen");
169                 png_name.replace(')', "rparen");
170                 png_name.replace('[', "lbracket");
171                 png_name.replace(']', "rbracket");
172                 png_name.replace('{', "lbrace");
173                 png_name.replace('}', "rbrace");
174                 png_name.replace('|', "bars");
175                 png_name.replace(',', "thinspace");
176                 png_name.replace(':', "mediumspace");
177                 png_name.replace(';', "thickspace");
178                 png_name.replace('!', "negthinspace");
179         }
180
181         LYXERR(Debug::GUI, "findPng(" << fromqstr(name) << ")\n"
182                 << "Looking for math PNG called \"" << fromqstr(png_name) << '"');
183         return png_name;
184 }
185
186 } // namespace anon
187
188
189 /// return a icon for the given action
190 static QIcon getIcon(FuncRequest const & f, bool unknown)
191 {
192         initializeResources();
193         QPixmap pm;
194         QString name1;
195         QString name2;
196         QString path;
197         switch (f.action) {
198         case LFUN_MATH_INSERT:
199                 if (!f.argument().empty()) {
200                         path = "math/";
201                         name1 = findPng(toqstr(f.argument()).mid(1));
202                 }
203                 break;
204         case LFUN_MATH_DELIM:
205         case LFUN_MATH_BIGDELIM:
206                 path = "math/";
207                 name1 = findPng(toqstr(f.argument()));
208                 break;
209         case LFUN_CALL:
210                 path = "commands/";
211                 name1 = toqstr(f.argument());
212                 break;
213         default:
214                 name2 = toqstr(lyxaction.getActionName(f.action));
215                 name1 = name2;
216
217                 if (!f.argument().empty()) {
218                         name1 = name2 + ' ' + toqstr(f.argument());
219                         name1.replace(' ', '_');
220                 }
221         }
222
223         string fullname = libFileSearch("images/" + path, name1, "png").absFilename();
224         if (pm.load(toqstr(fullname)))
225                 return pm;
226
227         fullname = libFileSearch("images/" + path, name2, "png").absFilename();
228         if (pm.load(toqstr(fullname)))
229                 return pm;
230
231         if (pm.load(":/images/" + path + name1 + ".png"))
232                 return pm;
233
234         if (pm.load(":/images/" + path + name2 + ".png"))
235                 return pm;
236
237         LYXERR(Debug::GUI, "Cannot find icon for command \""
238                            << lyxaction.getActionName(f.action)
239                            << '(' << to_utf8(f.argument()) << ")\"");
240         if (unknown)
241                 pm.load(":/images/unknown.png");
242
243         return pm;
244 }
245
246
247 /////////////////////////////////////////////////////////////////////
248 //
249 // GuiLayoutBox
250 //
251 /////////////////////////////////////////////////////////////////////
252
253 class LayoutItemDelegate : public QItemDelegate {
254 public:
255         ///
256         explicit LayoutItemDelegate(QObject * parent = 0)
257                 : QItemDelegate(parent)
258         {}
259         
260         ///
261         void paint(QPainter * painter, QStyleOptionViewItem const & option,
262                 QModelIndex const & index) const
263         {
264                 QStyleOptionViewItem opt = option;
265                 
266                 // default background
267                 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
268                 
269                 // category header?
270                 if (lyxrc.group_layouts) {
271                         QSortFilterProxyModel const * model
272                         = static_cast<QSortFilterProxyModel const *>(index.model());
273                         
274                         QString stdCat = category(*model->sourceModel(), 0);
275                         QString cat = category(*index.model(), index.row());
276                         
277                         // not the standard layout and not the same as in the previous line?
278                         if (stdCat != cat
279                             && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
280                                 painter->save();
281                                 
282                                 // draw unselected background
283                                 QStyle::State state = opt.state;
284                                 opt.state = opt.state & ~QStyle::State_Selected;
285                                 drawBackground(painter, opt, index);
286                                 opt.state = state;
287                                 
288                                 // draw category header
289                                 drawCategoryHeader(painter, opt, 
290                                         category(*index.model(), index.row()));
291
292                                 // move rect down below header
293                                 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
294                                 
295                                 painter->restore();
296                         }
297                 }
298
299                 QItemDelegate::paint(painter, opt, index);
300         }
301         
302         ///
303         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
304                          const QRect & /*rect*/, const QString & text ) const
305         {
306                 QString utext = underlineFilter(text);
307
308                 // Draw the rich text.
309                 painter->save();
310                 QColor col = opt.palette.text().color();
311                 if (opt.state & QStyle::State_Selected)
312                         col = opt.palette.highlightedText().color();
313                 QAbstractTextDocumentLayout::PaintContext context;
314                 context.palette.setColor(QPalette::Text, col);
315                 
316                 QTextDocument doc;
317                 doc.setDefaultFont(opt.font);
318                 doc.setHtml(utext);
319                 
320                 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
321                 fmt.setMargin(0);
322                 doc.rootFrame()->setFrameFormat(fmt);
323                 
324                 painter->translate(opt.rect.x() + 5,
325                         opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
326                 doc.documentLayout()->draw(painter, context);
327                 painter->restore();
328         }
329         
330         ///
331         QSize sizeHint(QStyleOptionViewItem const & opt,
332                 QModelIndex const & index) const
333         {
334                 GuiLayoutBox * combo = static_cast<GuiLayoutBox *>(parent());
335                 QSortFilterProxyModel const * model
336                 = static_cast<QSortFilterProxyModel const *>(index.model());    
337                 QSize size = QItemDelegate::sizeHint(opt, index);
338                 
339                 /// QComboBox uses the first row height to estimate the
340                 /// complete popup height during QComboBox::showPopup().
341                 /// To avoid scrolling we have to sneak in space for the headers.
342                 /// So we tweak this value accordingly. It's not nice, but the
343                 /// only possible way it seems.
344                 if (lyxrc.group_layouts && index.row() == 0 && combo->inShowPopup_) {
345                         int itemHeight = size.height();
346                         
347                         // we have to show \c cats many headers:
348                         unsigned cats = combo->visibleCategories_;
349                         
350                         // and we have \c n items to distribute the needed space over
351                         unsigned n = combo->model()->rowCount();
352                         
353                         // so the needed average height (rounded upwards) is:
354                         size.setHeight((headerHeight(opt) * cats + itemHeight * n + n - 1) / n); 
355                         return size;
356                 }
357
358                 // Add space for the category headers here?
359                 // Not for the standard layout though.
360                 QString stdCat = category(*model->sourceModel(), 0);
361                 QString cat = category(*index.model(), index.row());
362                 if (lyxrc.group_layouts && stdCat != cat
363                     && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
364                         size.setHeight(size.height() + headerHeight(opt));
365                 }
366
367                 return size;
368         }
369         
370 private:
371         ///
372         QString category(QAbstractItemModel const & model, int row) const
373         {
374                 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
375         }
376                 
377         ///
378         int headerHeight(QStyleOptionViewItem const & opt) const
379         {
380                 return opt.fontMetrics.height() * 8 / 10;
381         }
382         ///
383         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
384                 QString const & category) const
385         {
386                 // slightly blended color
387                 QColor lcol = opt.palette.text().color();
388                 lcol.setAlpha(127);
389                 painter->setPen(lcol);
390                 
391                 // set 80% scaled, bold font
392                 QFont font = opt.font;
393                 font.setBold(true);
394                 font.setWeight(QFont::Black);
395                 font.setPointSize(opt.font.pointSize() * 8 / 10);
396                 painter->setFont(font);
397                 
398                 // draw the centered text
399                 QFontMetrics fm(font);
400                 int w = fm.width(category);
401                 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
402                 int y = opt.rect.y() + fm.ascent();
403                 int left = x;
404                 int right = x + w;
405                 painter->drawText(x, y, category);
406                 
407                 // the vertical position of the line: middle of lower case chars
408                 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
409                 
410                 // draw the horizontal line
411                 if (!category.isEmpty()) {
412                         painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
413                         painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
414                 } else
415                         painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
416         }
417
418         
419         ///
420         QString underlineFilter(QString const & s) const
421         {
422                 // get filter
423                 GuiLayoutBox * p = static_cast<GuiLayoutBox *>(parent());
424                 QString const & f = p->filter();
425                 if (f.isEmpty())
426                         return s;
427                 
428                 // step through data item and put "(x)" for every matching character
429                 QString r;
430                 int lastp = -1;
431                 p->filter();
432                 for (int i = 0; i < f.length(); ++i) {
433                         int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
434                         BOOST_ASSERT(p != -1);
435                         if (lastp == p - 1 && lastp != -1) {
436                                 // remove ")" and append "x)"
437                                 r = r.left(r.length() - 4) + s[p] + "</u>";
438                         } else {
439                                 // append "(x)"
440                                 r += s.mid(lastp + 1, p - lastp - 1);
441                                 r += QString("<u>") + s[p] + "</u>";
442                         }
443                         lastp = p;
444                 }
445                 r += s.mid(lastp + 1);
446                 return r;
447         }
448 };
449
450
451 class GuiLayoutFilterModel : public QSortFilterProxyModel {
452 public:
453         ///
454         GuiLayoutFilterModel(QObject * parent = 0)
455                 : QSortFilterProxyModel(parent)
456         {}
457         
458         ///
459         void triggerLayoutChange()
460         {
461                 layoutAboutToBeChanged();
462                 layoutChanged();
463         }
464 };
465
466
467 GuiLayoutBox::GuiLayoutBox(GuiToolbar * bar, GuiView & owner)
468         : owner_(owner), bar_(bar), lastSel_(-1),
469           layoutItemDelegate_(new LayoutItemDelegate(this)),
470           visibleCategories_(0), inShowPopup_(false)
471 {
472         setSizeAdjustPolicy(QComboBox::AdjustToContents);
473         setFocusPolicy(Qt::ClickFocus);
474         setMinimumWidth(sizeHint().width());
475         setMaxVisibleItems(100);
476
477         // set the layout model with two columns
478         // 1st: translated layout names
479         // 2nd: raw layout names
480         model_ = new QStandardItemModel(0, 2, this);
481         filterModel_ = new GuiLayoutFilterModel(this);
482         filterModel_->setSourceModel(model_);
483         setModel(filterModel_);
484
485         // for the filtering we have to intercept characters
486         view()->installEventFilter(this);
487         view()->setItemDelegateForColumn(0, layoutItemDelegate_);
488         
489         QObject::connect(this, SIGNAL(activated(int)),
490                 this, SLOT(selected(int)));
491         QObject::connect(bar_, SIGNAL(iconSizeChanged(QSize)),
492                 this, SLOT(setIconSize(QSize)));
493
494         owner_.setLayoutDialog(this);
495         updateContents(true);
496 }
497
498
499 void GuiLayoutBox::setFilter(QString const & s)
500 {
501         bool enabled = view()->updatesEnabled();
502         view()->setUpdatesEnabled(false);
503
504         // remember old selection
505         int sel = currentIndex();
506         if (sel != -1)
507                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
508
509         filter_ = s;
510         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
511         countCategories();
512         
513         // restore old selection
514         if (lastSel_ != -1) {
515                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
516                 if (i.isValid())
517                         setCurrentIndex(i.row());
518         }
519         
520         // Workaround to resize to content size
521         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
522         //        does not help.
523         if (view()->isVisible()) {
524                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
525                 // the hack in the item delegate to make space for the headers.
526                 // We do not call our implementation of showPopup because that
527                 // would reset the filter again. This is only needed if the user clicks
528                 // on the QComboBox.
529                 BOOST_ASSERT(!inShowPopup_);
530                 inShowPopup_ = true;
531                 QComboBox::showPopup();
532                 inShowPopup_ = false;
533
534                 // The item delegate hack is off again. So trigger a relayout of the popup.
535                 filterModel_->triggerLayoutChange();
536                 
537                 if (!s.isEmpty())
538                         owner_.message(_("Filtering layouts with \"" + fromqstr(s) + "\". "
539                                          "Press ESC to remove filter."));
540                 else
541                         owner_.message(_("Enter characters to filter the layout list."));
542         }
543         
544         view()->setUpdatesEnabled(enabled);
545 }
546
547
548 void GuiLayoutBox::countCategories()
549 {
550         int n = filterModel_->rowCount();
551         visibleCategories_ = 0;
552         if (n == 0 || !lyxrc.group_layouts)
553                 return;
554
555         // skip the "Standard" category
556         QString prevCat = model_->index(0, 2).data().toString(); 
557
558         // count categories
559         for (int i = 0; i < n; ++i) {
560                 QString cat = filterModel_->index(i, 2).data().toString();
561                 if (cat != prevCat)
562                         ++visibleCategories_;
563                 prevCat = cat;
564         }
565 }
566
567
568 QString GuiLayoutBox::charFilterRegExp(QString const & filter)
569 {
570         QString re;
571         for (int i = 0; i < filter.length(); ++i) {
572                 QChar c = filter[i];
573                 if (c.isLower())
574                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
575                 else
576                         re += ".*" + QRegExp::escape(c);
577         }
578         return re;
579 }
580
581
582 void GuiLayoutBox::resetFilter()
583 {
584         setFilter(QString());
585 }
586
587
588 void GuiLayoutBox::showPopup()
589 {
590         owner_.message(_("Enter characters to filter the layout list."));
591
592         bool enabled = view()->updatesEnabled();
593         view()->setUpdatesEnabled(false);
594
595         resetFilter();
596
597         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
598         // the hack in the item delegate to make space for the headers.
599         BOOST_ASSERT(!inShowPopup_);
600         inShowPopup_ = true;
601         QComboBox::showPopup();
602         inShowPopup_ = false;
603         
604         // The item delegate hack is off again. So trigger a relayout of the popup.
605         filterModel_->triggerLayoutChange();
606         
607         view()->setUpdatesEnabled(enabled);
608 }
609
610
611 bool GuiLayoutBox::eventFilter(QObject * o, QEvent * e)
612 {
613         if (e->type() != QEvent::KeyPress)
614                 return QComboBox::eventFilter(o, e);
615
616         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
617         bool modified = (ke->modifiers() == Qt::ControlModifier)
618                 || (ke->modifiers() == Qt::AltModifier)
619                 || (ke->modifiers() == Qt::MetaModifier);
620         
621         switch (ke->key()) {
622         case Qt::Key_Escape:
623                 if (!modified && !filter_.isEmpty()) {
624                         resetFilter();
625                         return true;
626                 }
627                 break;
628         case Qt::Key_Backspace:
629                 if (!modified) {
630                         // cut off one character
631                         setFilter(filter_.left(filter_.length() - 1));
632                 }
633                 break;
634         default:
635                 if (modified || ke->text().isEmpty())
636                         break;
637                 // find chars for the filter string
638                 QString s;
639                 for (int i = 0; i < ke->text().length(); ++i) {
640                         QChar c = ke->text()[i];
641                         if (c.isLetterOrNumber()
642                             || c.isSymbol()
643                             || c.isPunct()
644                             || c.category() == QChar::Separator_Space) {
645                                 s += c;
646                         }
647                 }
648                 if (!s.isEmpty()) {
649                         // append new chars to the filter string
650                         setFilter(filter_ + s);
651                         return true;
652                 }
653                 break;
654         }
655
656         return QComboBox::eventFilter(o, e);
657 }
658
659         
660 void GuiLayoutBox::setIconSize(QSize size)
661 {
662 #ifdef Q_WS_MACX
663         bool small = size.height() < 20;
664         setAttribute(Qt::WA_MacSmallSize, small);
665         setAttribute(Qt::WA_MacNormalSize, !small);
666 #endif
667 }
668
669
670 void GuiLayoutBox::set(docstring const & layout)
671 {
672         resetFilter();
673         
674         if (!text_class_)
675                 return;
676
677         QString const & name = toqstr((*text_class_)[layout].name());
678         if (name == currentText())
679                 return;
680
681         QList<QStandardItem *> r = model_->findItems(name, Qt::MatchExactly, 1);
682         if (r.empty()) {
683                 lyxerr << "Trying to select non existent layout type "
684                         << fromqstr(name) << endl;
685                 return;
686         }
687
688         setCurrentIndex(filterModel_->mapFromSource(r.first()->index()).row());
689 }
690
691
692 void GuiLayoutBox::addItemSort(docstring const & item, docstring const & category,
693         bool sorted, bool sortedByCat)
694 {
695         QString qitem = toqstr(item);
696         QString titem = toqstr(translateIfPossible(item));
697         QString qcat = toqstr(translateIfPossible(category));
698
699         QList<QStandardItem *> row;
700         row.append(new QStandardItem(titem));
701         row.append(new QStandardItem(qitem));
702         row.append(new QStandardItem(qcat));
703
704         // the first entry is easy
705         int const end = model_->rowCount();
706         if (end == 0) {
707                 model_->appendRow(row);
708                 return;
709         }
710
711         // find category
712         int i = 0;
713         if (sortedByCat) {
714                 while (i < end && model_->item(i, 2)->text() != qcat)
715                         ++i;
716         }
717
718         // skip the Standard layout
719         if (i == 0)
720                 ++i;
721         
722         // the simple unsorted case
723         if (!sorted) {
724                 if (sortedByCat) {
725                         // jump to the end of the category group
726                         while (i < end && model_->item(i, 2)->text() == qcat)
727                                 ++i;
728                         model_->insertRow(i, row);
729                 } else
730                         model_->appendRow(row);
731                 return;
732         }
733
734         // find row to insert the item, after the separator if it exists
735         if (i < end) {
736                 // find alphabetic position
737                 while (i != end
738                        && model_->item(i, 0)->text().compare(titem) < 0 
739                        && (!sortedByCat || model_->item(i, 2)->text() == qcat))
740                         ++i;
741         }
742
743         model_->insertRow(i, row);
744 }
745
746
747 void GuiLayoutBox::updateContents(bool reset)
748 {
749         resetFilter();
750         
751         Buffer const * buffer = owner_.buffer();
752         if (!buffer) {
753                 model_->clear();
754                 setEnabled(false);
755                 text_class_ = 0;
756                 inset_ = 0;
757                 return;
758         }
759
760         // we'll only update the layout list if the text class has changed
761         // or we've moved from one inset to another
762         DocumentClass const * text_class = &buffer->params().documentClass();
763         Inset const * inset = 
764                 owner_.view()->cursor().innerParagraph().inInset();
765         if (!reset && text_class_ == text_class && inset_ == inset) {
766                 set(owner_.view()->cursor().innerParagraph().layout().name());
767                 return;
768         }
769
770         inset_ = inset;
771         text_class_ = text_class;
772
773         model_->clear();
774         DocumentClass::const_iterator lit = text_class_->begin();
775         DocumentClass::const_iterator len = text_class_->end();
776
777         for (; lit != len; ++lit) {
778                 docstring const & name = lit->name();
779                 bool const useEmpty = inset_->forceEmptyLayout() || inset_->useEmptyLayout();
780                 // if this inset requires the empty layout, we skip the default
781                 // layout
782                 if (name == text_class_->defaultLayoutName() && inset_ && useEmpty)
783                         continue;
784                 // if it doesn't require the empty layout, we skip it
785                 if (name == text_class_->emptyLayoutName() && inset_ && !useEmpty)
786                         continue;
787                 addItemSort(name, lit->category(), lyxrc.sort_layouts, lyxrc.group_layouts);
788         }
789
790         set(owner_.view()->cursor().innerParagraph().layout().name());
791         countCategories();
792         
793         // needed to recalculate size hint
794         hide();
795         setMinimumWidth(sizeHint().width());
796         setEnabled(!buffer->isReadonly());
797         show();
798 }
799
800
801 void GuiLayoutBox::selected(int index)
802 {
803         // get selection
804         QModelIndex mindex = filterModel_->mapToSource(filterModel_->index(index, 1));
805         docstring const layoutName = 
806                 qstring_to_ucs4(model_->itemFromIndex(mindex)->text());
807
808         owner_.setFocus();
809
810         if (!text_class_) {
811                 updateContents(false);
812                 resetFilter();
813                 return;
814         }
815
816         // find corresponding text class
817         if (text_class_->hasLayout(layoutName)) {
818                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
819                 theLyXFunc().setLyXView(&owner_);
820                 lyx::dispatch(func);
821                 updateContents(false);
822                 resetFilter();
823                 return;
824         }
825         lyxerr << "ERROR (layoutSelected): layout not found!" << endl;
826 }
827
828
829
830 /////////////////////////////////////////////////////////////////////
831 //
832 // GuiToolbar
833 //
834 /////////////////////////////////////////////////////////////////////
835
836
837 GuiToolbar::GuiToolbar(ToolbarInfo const & tbinfo, GuiView & owner)
838         : QToolBar(qt_(tbinfo.gui_name), &owner), owner_(owner),
839           layout_(0), command_buffer_(0)
840 {
841         // give visual separation between adjacent toolbars
842         addSeparator();
843
844         // TODO: save toolbar position
845         setMovable(true);
846
847         ToolbarInfo::item_iterator it = tbinfo.items.begin();
848         ToolbarInfo::item_iterator end = tbinfo.items.end();
849         for (; it != end; ++it)
850                 add(*it);
851 }
852
853
854 Action * GuiToolbar::addItem(ToolbarItem const & item)
855 {
856         Action * act = new Action(&owner_, getIcon(item.func_, false),
857                 toqstr(item.label_), item.func_, toqstr(item.label_), this);
858         actions_.append(act);
859         return act;
860 }
861
862 namespace {
863
864 class PaletteButton : public QToolButton
865 {
866 private:
867         GuiToolbar * bar_;
868         ToolbarItem const & tbitem_;
869         bool initialized_;
870 public:
871         PaletteButton(GuiToolbar * bar, ToolbarItem const & item)
872                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
873         {
874                 QString const label = qt_(to_ascii(tbitem_.label_));
875                 setToolTip(label);
876                 setStatusTip(label);
877                 setText(label);
878                 connect(bar_, SIGNAL(iconSizeChanged(QSize)),
879                         this, SLOT(setIconSize(QSize)));
880                 setCheckable(true);
881                 ToolbarInfo const * tbinfo = 
882                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
883                 if (tbinfo)
884                         // use the icon of first action for the toolbar button
885                         setIcon(getIcon(tbinfo->items.begin()->func_, true));
886         }
887
888         void mousePressEvent(QMouseEvent * e)
889         {
890                 if (initialized_) {
891                         QToolButton::mousePressEvent(e);
892                         return;
893                 }
894
895                 initialized_ = true;
896
897                 ToolbarInfo const * tbinfo = 
898                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
899                 if (!tbinfo) {
900                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
901                         return;
902                 }
903                 IconPalette * panel = new IconPalette(this);
904                 QString const label = qt_(to_ascii(tbitem_.label_));
905                 panel->setWindowTitle(label);
906                 connect(this, SIGNAL(clicked(bool)), panel, SLOT(setVisible(bool)));
907                 connect(panel, SIGNAL(visible(bool)), this, SLOT(setChecked(bool)));
908                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
909                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
910                 for (; it != end; ++it)
911                         if (!getStatus(it->func_).unknown())
912                                 panel->addButton(bar_->addItem(*it));
913
914                 QToolButton::mousePressEvent(e);
915         }
916 };
917
918 class MenuButton : public QToolButton
919 {
920 private:
921         GuiToolbar * bar_;
922         ToolbarItem const & tbitem_;
923         bool initialized_;
924 public:
925         MenuButton(GuiToolbar * bar, ToolbarItem const & item)
926                 : QToolButton(bar), bar_(bar), tbitem_(item), initialized_(false)
927         {
928                 setPopupMode(QToolButton::InstantPopup);
929                 QString const label = qt_(to_ascii(tbitem_.label_));
930                 setToolTip(label);
931                 setStatusTip(label);
932                 setText(label);
933                 setIcon(QPixmap(":images/math/" + toqstr(tbitem_.name_) + ".png"));
934                 connect(bar, SIGNAL(iconSizeChanged(QSize)),
935                         this, SLOT(setIconSize(QSize)));
936         }
937
938         void mousePressEvent(QMouseEvent * e)
939         {
940                 if (initialized_) {
941                         QToolButton::mousePressEvent(e);
942                         return;
943                 }
944
945                 initialized_ = true;
946
947                 QString const label = qt_(to_ascii(tbitem_.label_));
948                 ButtonMenu * m = new ButtonMenu(label, this);
949                 m->setWindowTitle(label);
950                 m->setTearOffEnabled(true);
951                 connect(bar_, SIGNAL(updated()), m, SLOT(updateParent()));
952                 ToolbarInfo const * tbinfo = 
953                         toolbarbackend.getDefinedToolbarInfo(tbitem_.name_);
954                 if (!tbinfo) {
955                         lyxerr << "Unknown toolbar " << tbitem_.name_ << endl;
956                         return;
957                 }
958                 ToolbarInfo::item_iterator it = tbinfo->items.begin();
959                 ToolbarInfo::item_iterator const end = tbinfo->items.end();
960                 for (; it != end; ++it)
961                         if (!getStatus(it->func_).unknown())
962                                 m->add(bar_->addItem(*it));
963                 setMenu(m);
964
965                 QToolButton::mousePressEvent(e);
966         }
967 };
968
969 }
970
971
972 void GuiToolbar::add(ToolbarItem const & item)
973 {
974         switch (item.type_) {
975         case ToolbarItem::SEPARATOR:
976                 addSeparator();
977                 break;
978         case ToolbarItem::LAYOUTS:
979                 layout_ = new GuiLayoutBox(this, owner_);
980                 addWidget(layout_);
981                 break;
982         case ToolbarItem::MINIBUFFER:
983                 command_buffer_ = new GuiCommandBuffer(&owner_);
984                 addWidget(command_buffer_);
985                 /// \todo find a Qt4 equivalent to setHorizontalStretchable(true);
986                 //setHorizontalStretchable(true);
987                 break;
988         case ToolbarItem::TABLEINSERT: {
989                 QToolButton * tb = new QToolButton;
990                 tb->setCheckable(true);
991                 tb->setIcon(getIcon(FuncRequest(LFUN_TABULAR_INSERT), true));
992                 QString const label = qt_(to_ascii(item.label_));
993                 tb->setToolTip(label);
994                 tb->setStatusTip(label);
995                 tb->setText(label);
996                 InsertTableWidget * iv = new InsertTableWidget(owner_, tb);
997                 connect(tb, SIGNAL(clicked(bool)), iv, SLOT(show(bool)));
998                 connect(iv, SIGNAL(visible(bool)), tb, SLOT(setChecked(bool)));
999                 connect(this, SIGNAL(updated()), iv, SLOT(updateParent()));
1000                 addWidget(tb);
1001                 break;
1002                 }
1003         case ToolbarItem::ICONPALETTE:
1004                 addWidget(new PaletteButton(this, item));
1005                 break;
1006
1007         case ToolbarItem::POPUPMENU: {
1008                 addWidget(new MenuButton(this, item));
1009                 break;
1010                 }
1011         case ToolbarItem::COMMAND: {
1012                 if (!getStatus(item.func_).unknown())
1013                         addAction(addItem(item));
1014                 break;
1015                 }
1016         default:
1017                 break;
1018         }
1019 }
1020
1021
1022 void GuiToolbar::saveInfo(ToolbarSection::ToolbarInfo & tbinfo)
1023 {
1024         // if tbinfo.state == auto *do not* set on/off
1025         if (tbinfo.state != ToolbarSection::ToolbarInfo::AUTO) {
1026                 if (GuiToolbar::isVisible())
1027                         tbinfo.state = ToolbarSection::ToolbarInfo::ON;
1028                 else
1029                         tbinfo.state = ToolbarSection::ToolbarInfo::OFF;
1030         }
1031         //
1032         // no need to save it here.
1033         Qt::ToolBarArea loc = owner_.toolBarArea(this);
1034
1035         if (loc == Qt::TopToolBarArea)
1036                 tbinfo.location = ToolbarSection::ToolbarInfo::TOP;
1037         else if (loc == Qt::BottomToolBarArea)
1038                 tbinfo.location = ToolbarSection::ToolbarInfo::BOTTOM;
1039         else if (loc == Qt::RightToolBarArea)
1040                 tbinfo.location = ToolbarSection::ToolbarInfo::RIGHT;
1041         else if (loc == Qt::LeftToolBarArea)
1042                 tbinfo.location = ToolbarSection::ToolbarInfo::LEFT;
1043         else
1044                 tbinfo.location = ToolbarSection::ToolbarInfo::NOTSET;
1045
1046         // save toolbar position. They are not used to restore toolbar position
1047         // now because move(x,y) does not work for toolbar.
1048         tbinfo.posx = pos().x();
1049         tbinfo.posy = pos().y();
1050 }
1051
1052
1053 void GuiToolbar::updateContents()
1054 {
1055         // update visible toolbars only
1056         if (!isVisible())
1057                 return;
1058         // This is a speed bottleneck because this is called on every keypress
1059         // and update calls getStatus, which copies the cursor at least two times
1060         for (int i = 0; i < actions_.size(); ++i)
1061                 actions_[i]->update();
1062
1063         if (layout_)
1064                 layout_->setEnabled(lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
1065
1066         // emit signal
1067         updated();
1068 }
1069
1070
1071 } // namespace frontend
1072 } // namespace lyx
1073
1074 #include "GuiToolbar_moc.cpp"