]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/CategorizedCombo.cpp
Change a couple instances of QFontMetrics::width()
[lyx.git] / src / frontends / qt / CategorizedCombo.cpp
1 /**
2  * \file qt/CategorizedCombo.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 Jürgen Spitzmüller
12  * \author Abdelrazak Younes
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "CategorizedCombo.h"
20
21 #include "qt_helpers.h"
22
23 #include "support/debug.h"
24 #include "support/gettext.h"
25 #include "support/lassert.h"
26 #include "support/lstrings.h"
27 #include "support/qstring_helpers.h"
28
29 #include <QAbstractTextDocumentLayout>
30 #include <QComboBox>
31 #include <QHeaderView>
32 #include <QItemDelegate>
33 #include <QPainter>
34 #include <QSortFilterProxyModel>
35 #include <QStandardItemModel>
36 #include <QTextFrame>
37
38 using namespace lyx::support;
39
40 namespace lyx {
41 namespace frontend {
42
43
44 class CCItemDelegate : public QItemDelegate {
45 public:
46         ///
47         explicit CCItemDelegate(CategorizedCombo * cc)
48                 : QItemDelegate(cc), cc_(cc)
49         {}
50         ///
51         void paint(QPainter * painter, QStyleOptionViewItem const & option,
52                 QModelIndex const & index) const;
53         ///
54         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
55                 const QRect & /*rect*/, const QString & text ) const;
56         ///
57         QSize sizeHint(QStyleOptionViewItem const & opt,
58                 QModelIndex const & index) const;
59
60 private:
61         ///
62         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
63                 QString const & category) const;
64         ///
65         QString underlineFilter(QString const & s) const;
66         ///
67         CategorizedCombo * cc_;
68 };
69
70
71 class CCFilterModel : public QSortFilterProxyModel {
72 public:
73         ///
74         CCFilterModel(QObject * parent = 0)
75                 : QSortFilterProxyModel(parent)
76         {}
77 };
78
79
80 /////////////////////////////////////////////////////////////////////
81 //
82 // CategorizedCombo::Private
83 //
84 /////////////////////////////////////////////////////////////////////
85
86 struct CategorizedCombo::Private
87 {
88         Private(CategorizedCombo * parent) : p(parent),
89                 // set the model with four columns
90                 // 1st: translated item names
91                 // 2nd: raw names
92                 // 3rd: category
93                 // 4th: availability (bool)
94                 model_(new QStandardItemModel(0, 4, p)),
95                 filterModel_(new CCFilterModel(p)),
96                 lastSel_(-1),
97                 CCItemDelegate_(new CCItemDelegate(parent)),
98                 visibleCategories_(0), inShowPopup_(false)
99         {
100                 filterModel_->setSourceModel(model_);
101         }
102
103         void resetFilter() { setFilter(QString()); }
104         ///
105         void setFilter(QString const & s);
106         ///
107         void countCategories();
108         ///
109         CategorizedCombo * p;
110
111         /** the layout model:
112          * 1st column: translated GUI name,
113          * 2nd column: raw item name,
114          * 3rd column: category,
115          * 4th column: availability
116         **/
117         QStandardItemModel * model_;
118         /// the proxy model filtering \c model_
119         CCFilterModel * filterModel_;
120         /// the (model-) index of the last successful selection
121         int lastSel_;
122         /// the character filter
123         QString filter_;
124         ///
125         CCItemDelegate * CCItemDelegate_;
126         ///
127         unsigned visibleCategories_;
128         ///
129         bool inShowPopup_;
130 };
131
132
133 static QString categoryCC(QAbstractItemModel const & model, int row)
134 {
135         return model.data(model.index(row, 2), Qt::DisplayRole).toString();
136 }
137
138
139 static int headerHeightCC(QStyleOptionViewItem const & opt)
140 {
141         return opt.fontMetrics.height();
142 }
143
144
145 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
146                            QModelIndex const & index) const
147 {
148         QStyleOptionViewItem opt = option;
149
150         // default background
151         painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
152
153         QString cat = categoryCC(*index.model(), index.row());
154
155         // not the same as in the previous line?
156         if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
157                 painter->save();
158
159                 // draw unselected background
160                 QStyle::State state = opt.state;
161                 opt.state = opt.state & ~QStyle::State_Selected;
162                 drawBackground(painter, opt, index);
163                 opt.state = state;
164
165                 // draw category header
166                 drawCategoryHeader(painter, opt,
167                         categoryCC(*index.model(), index.row()));
168
169                 // move rect down below header
170                 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
171
172                 painter->restore();
173         }
174
175         QItemDelegate::paint(painter, opt, index);
176 }
177
178
179 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
180                                  const QRect & /*rect*/, const QString & text) const
181 {
182         QString utext = underlineFilter(text);
183
184         // Draw the rich text.
185         painter->save();
186         QColor col = opt.palette.text().color();
187         // grey out unavailable items
188         if (text.startsWith(qt_("Unavailable:")))
189                 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
190         if (opt.state & QStyle::State_Selected)
191                 col = opt.palette.highlightedText().color();
192         QAbstractTextDocumentLayout::PaintContext context;
193         context.palette.setColor(QPalette::Text, col);
194
195         QTextDocument doc;
196         doc.setDefaultFont(opt.font);
197         doc.setHtml(utext);
198
199         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
200         fmt.setMargin(0);
201         doc.rootFrame()->setFrameFormat(fmt);
202
203         painter->translate(opt.rect.x() + 5,
204                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
205         doc.documentLayout()->draw(painter, context);
206         painter->restore();
207 }
208
209
210 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
211                                QModelIndex const & index) const
212 {
213         QSize size = QItemDelegate::sizeHint(opt, index);
214
215         /// QComboBox uses the first row height to estimate the
216         /// complete popup height during QComboBox::showPopup().
217         /// To avoid scrolling we have to sneak in space for the headers.
218         /// So we tweak this value accordingly. It's not nice, but the
219         /// only possible way it seems.
220         // Add space for the category headers here
221         QString cat = categoryCC(*index.model(), index.row());
222         if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
223                 size.setHeight(size.height() + headerHeightCC(opt));
224         }
225
226         return size;
227 }
228
229
230 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
231                                         QString const & category) const
232 {
233         // slightly blended color
234         QColor lcol = opt.palette.text().color();
235         lcol.setAlpha(127);
236         painter->setPen(lcol);
237
238         // set 80% scaled, bold font
239         QFont font = opt.font;
240         font.setBold(true);
241         font.setWeight(QFont::Black);
242         font.setPointSize(opt.font.pointSize() * 8 / 10);
243         painter->setFont(font);
244
245         // draw the centered text
246         QFontMetrics fm(font);
247         int w = fm.boundingRect(category).width();
248         int x = opt.rect.x() + (opt.rect.width() - w) / 2;
249         int y = opt.rect.y() + 3 * fm.ascent() / 2;
250         int left = x;
251         int right = x + w;
252         painter->drawText(x, y, category);
253
254         // the vertical position of the line: middle of lower case chars
255         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
256
257         // draw the horizontal line
258         if (!category.isEmpty()) {
259                 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
260                 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
261         } else
262                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
263 }
264
265
266 QString CCItemDelegate::underlineFilter(QString const & s) const
267 {
268         QString const & f = cc_->filter();
269         if (f.isEmpty())
270                 return s;
271         QString r(s);
272         QRegExp pattern(charFilterRegExpC(f));
273         r.replace(pattern, "<u><b>\\1</b></u>");
274         return r;
275 }
276
277
278 void CategorizedCombo::Private::setFilter(QString const & s)
279 {
280         bool enabled = p->view()->updatesEnabled();
281         p->view()->setUpdatesEnabled(false);
282
283         // remember old selection
284         int sel = p->currentIndex();
285         if (sel != -1)
286                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
287
288         filter_ = s;
289     filterModel_->setFilterRegExp(charFilterRegExp(filter_));
290         countCategories();
291
292         // restore old selection
293         if (lastSel_ != -1) {
294                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
295                 if (i.isValid())
296                         p->setCurrentIndex(i.row());
297         }
298
299         // Workaround to resize to content size
300         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
301         //        does not help.
302         if (p->view()->isVisible()) {
303                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
304                 // the hack in the item delegate to make space for the headers.
305                 // We do not call our implementation of showPopup because that
306                 // would reset the filter again. This is only needed if the user clicks
307                 // on the QComboBox.
308                 LASSERT(!inShowPopup_, /**/);
309                 inShowPopup_ = true;
310                 p->QComboBox::showPopup();
311                 inShowPopup_ = false;
312         }
313
314         p->view()->setUpdatesEnabled(enabled);
315 }
316
317
318 CategorizedCombo::CategorizedCombo(QWidget * parent)
319         : QComboBox(parent), d(new Private(this))
320 {
321         setSizeAdjustPolicy(QComboBox::AdjustToContents);
322         setMinimumWidth(sizeHint().width());
323         setMaxVisibleItems(100);
324
325         setModel(d->filterModel_);
326
327         // for the filtering we have to intercept characters
328         view()->installEventFilter(this);
329         view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
330
331         updateCombo();
332 }
333
334
335 CategorizedCombo::~CategorizedCombo() {
336         delete d;
337 }
338
339
340 void CategorizedCombo::Private::countCategories()
341 {
342         int n = filterModel_->rowCount();
343         visibleCategories_ = 0;
344         if (n == 0)
345                 return;
346
347         QString prevCat = model_->index(0, 2).data().toString();
348
349         // count categories
350         for (int i = 1; i < n; ++i) {
351                 QString cat = filterModel_->index(i, 2).data().toString();
352                 if (cat != prevCat)
353                         ++visibleCategories_;
354                 prevCat = cat;
355         }
356 }
357
358
359 void CategorizedCombo::showPopup()
360 {
361         bool enabled = view()->updatesEnabled();
362         view()->setUpdatesEnabled(false);
363
364         d->resetFilter();
365
366         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
367         // the hack in the item delegate to make space for the headers.
368         LASSERT(!d->inShowPopup_, /**/);
369         d->inShowPopup_ = true;
370         QComboBox::showPopup();
371         d->inShowPopup_ = false;
372
373         view()->setUpdatesEnabled(enabled);
374 }
375
376
377 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
378 {
379         if (e->type() != QEvent::KeyPress)
380                 return QComboBox::eventFilter(o, e);
381
382         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
383         bool modified = (ke->modifiers() == Qt::ControlModifier)
384                 || (ke->modifiers() == Qt::AltModifier)
385                 || (ke->modifiers() == Qt::MetaModifier);
386
387         switch (ke->key()) {
388         case Qt::Key_Escape:
389                 if (!modified && !d->filter_.isEmpty()) {
390                         d->resetFilter();
391                         return true;
392                 }
393                 break;
394         case Qt::Key_Backspace:
395                 if (!modified) {
396                         // cut off one character
397                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
398                 }
399                 break;
400         default:
401                 if (modified || ke->text().isEmpty())
402                         break;
403                 // find chars for the filter string
404                 QString s;
405                 for (int i = 0; i < ke->text().length(); ++i) {
406                         QChar c = ke->text()[i];
407                         if (c.isLetterOrNumber()
408                             || c.isSymbol()
409                             || c.isPunct()
410                             || c.category() == QChar::Separator_Space) {
411                                 s += c;
412                         }
413                 }
414                 if (!s.isEmpty()) {
415                         // append new chars to the filter string
416                         d->setFilter(d->filter_ + s);
417                         return true;
418                 }
419                 break;
420         }
421
422         return QComboBox::eventFilter(o, e);
423 }
424
425
426 void CategorizedCombo::setIconSize(QSize size)
427 {
428 #ifdef Q_OS_MAC
429         bool small = size.height() < 20;
430         setAttribute(Qt::WA_MacSmallSize, small);
431         setAttribute(Qt::WA_MacNormalSize, !small);
432 #else
433         (void)size; // suppress warning
434 #endif
435 }
436
437
438 bool CategorizedCombo::set(QString const & item)
439 {
440         d->resetFilter();
441
442         int const curItem = currentIndex();
443         QModelIndex const mindex =
444                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
445         QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
446         if (item == currentItem) {
447                 LYXERR(Debug::GUI, "Already had " << item << " selected.");
448                 return true;
449         }
450
451         QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
452         if (r.empty()) {
453                 LYXERR0("Trying to select non existent layout type " << item);
454                 return false;
455         }
456
457         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
458         return true;
459 }
460
461
462 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
463                                    QString const & category, QString const & tooltip,
464                                    bool sorted, bool sortedByCat, bool sortCats,
465                                    bool available)
466 {
467         QString titem = available ? guiname
468                                   : toqstr(bformat(_("Unavailable: %1$s"),
469                                                    qstring_to_ucs4(guiname)));
470         bool const uncategorized = category.isEmpty();
471         QString qcat = uncategorized ? qt_("Uncategorized") : category;
472
473         QList<QStandardItem *> row;
474         QStandardItem * gui = new QStandardItem(titem);
475         if (!tooltip.isEmpty())
476                 gui->setToolTip(tooltip);
477         row.append(gui);
478         row.append(new QStandardItem(item));
479         row.append(new QStandardItem(qcat));
480         row.append(new QStandardItem(available));
481
482         // the first entry is easy
483         int const end = d->model_->rowCount();
484         if (end == 0) {
485                 d->model_->appendRow(row);
486                 return;
487         }
488
489         // find category
490         int i = 0;
491         if (sortedByCat) {
492                 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
493                 while (i < end && d->model_->item(i, 2)->text() != qcat
494                        && (!sortCats
495                            || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
496                                && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
497                            || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
498                         ++i;
499         }
500
501         // the simple unsorted case
502         if (!sorted) {
503                 if (sortedByCat) {
504                         // jump to the end of the category group
505                         while (i < end && d->model_->item(i, 2)->text() == qcat)
506                                 ++i;
507                         d->model_->insertRow(i, row);
508                 } else
509                         d->model_->appendRow(row);
510                 return;
511         }
512
513         // find row to insert the item, after the separator if it exists
514         if (i < end) {
515                 // find alphabetic position, unavailable at the end
516                 while (i != end
517                        && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
518                            || ((!available && d->model_->item(i, 3))
519                                || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
520                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
521                         ++i;
522         }
523
524         d->model_->insertRow(i, row);
525 }
526
527
528 QString CategorizedCombo::getData(int row) const
529 {
530         int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
531         return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
532 }
533
534
535 void CategorizedCombo::reset()
536 {
537         d->resetFilter();
538         d->model_->clear();
539 }
540
541
542 void CategorizedCombo::updateCombo()
543 {
544         d->countCategories();
545
546         // needed to recalculate size hint
547         hide();
548         setMinimumWidth(sizeHint().width());
549         show();
550 }
551
552
553 QString const & CategorizedCombo::filter() const
554 {
555         return d->filter_;
556 }
557
558 } // namespace frontend
559 } // namespace lyx
560
561
562 #include "moc_CategorizedCombo.cpp"