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