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