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.
6 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
10 * \author Stefan Schimanski
11 * \author Jürgen Spitzmüller
12 * \author Abdelrazak Younes
14 * Full author contact details are available in file CREDITS.
19 #include "CategorizedCombo.h"
21 #include "qt_helpers.h"
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"
29 #include <QAbstractTextDocumentLayout>
31 #include <QHeaderView>
32 #include <QItemDelegate>
34 #include <QSortFilterProxyModel>
35 #include <QStandardItemModel>
38 using namespace lyx::support;
44 class CCItemDelegate : public QItemDelegate {
47 explicit CCItemDelegate(CategorizedCombo * cc)
48 : QItemDelegate(cc), cc_(cc)
51 void paint(QPainter * painter, QStyleOptionViewItem const & option,
52 QModelIndex const & index) const override;
54 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
55 const QRect & /*rect*/, const QString & text ) const override;
57 QSize sizeHint(QStyleOptionViewItem const & opt,
58 QModelIndex const & index) const override;
62 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
63 QString const & category) const;
65 QString underlineFilter(QString const & s) const;
67 CategorizedCombo * cc_;
71 class CCFilterModel : public QSortFilterProxyModel {
74 CCFilterModel(QObject * parent = nullptr)
75 : QSortFilterProxyModel(parent)
80 /////////////////////////////////////////////////////////////////////
82 // CategorizedCombo::Private
84 /////////////////////////////////////////////////////////////////////
86 struct CategorizedCombo::Private
88 Private(CategorizedCombo * parent) : p(parent),
89 // set the model with four columns
90 // 1st: translated item names
93 // 4th: availability (bool)
94 model_(new QStandardItemModel(0, 4, p)),
95 filterModel_(new CCFilterModel(p)),
97 CCItemDelegate_(new CCItemDelegate(parent)),
98 visibleCategories_(0), inShowPopup_(false)
100 filterModel_->setSourceModel(model_);
103 void resetFilter() { setFilter(QString()); }
105 void setFilter(QString const & s);
107 void countCategories();
109 CategorizedCombo * p;
111 /** the layout model:
112 * 1st column: translated GUI name,
113 * 2nd column: raw item name,
114 * 3rd column: category,
115 * 4th column: availability
117 QStandardItemModel * model_;
118 /// the proxy model filtering \c model_
119 CCFilterModel * filterModel_;
120 /// the (model-) index of the last successful selection
122 /// the character filter
125 CCItemDelegate * CCItemDelegate_;
127 unsigned visibleCategories_;
133 static QString categoryCC(QAbstractItemModel const & model, int row)
135 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
139 static int headerHeightCC(QStyleOptionViewItem const & opt)
141 return opt.fontMetrics.height();
145 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
146 QModelIndex const & index) const
148 QStyleOptionViewItem opt = option;
150 // default background
151 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
153 QString cat = categoryCC(*index.model(), index.row());
155 // not the same as in the previous line?
156 if (cc_->d->visibleCategories_ > 0
157 && (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1))) {
160 // draw unselected background
161 QStyle::State state = opt.state;
162 opt.state = opt.state & ~QStyle::State_Selected;
163 drawBackground(painter, opt, index);
166 // draw category header
167 drawCategoryHeader(painter, opt,
168 categoryCC(*index.model(), index.row()));
170 // move rect down below header
171 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
176 QItemDelegate::paint(painter, opt, index);
180 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
181 const QRect & /*rect*/, const QString & text) const
183 QString utext = underlineFilter(text);
185 // Draw the rich text.
187 QColor col = opt.palette.text().color();
188 // grey out unavailable items
189 if (text.startsWith(qt_("Unavailable:")))
190 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
191 if (opt.state & QStyle::State_Selected)
192 col = opt.palette.highlightedText().color();
193 QAbstractTextDocumentLayout::PaintContext context;
194 context.palette.setColor(QPalette::Text, col);
197 doc.setDefaultFont(opt.font);
200 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
202 doc.rootFrame()->setFrameFormat(fmt);
204 painter->translate(opt.rect.x() + 5,
205 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
206 doc.documentLayout()->draw(painter, context);
211 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
212 QModelIndex const & index) const
214 QSize size = QItemDelegate::sizeHint(opt, index);
216 /// QComboBox uses the first row height to estimate the
217 /// complete popup height during QComboBox::showPopup().
218 /// To avoid scrolling we have to sneak in space for the headers.
219 /// So we tweak this value accordingly. It's not nice, but the
220 /// only possible way it seems.
221 // Add space for the category headers here
222 QString cat = categoryCC(*index.model(), index.row());
223 if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
224 size.setHeight(size.height() + headerHeightCC(opt));
231 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
232 QString const & category) const
234 // slightly blended color
235 QColor lcol = opt.palette.text().color();
237 painter->setPen(lcol);
239 // set 80% scaled, bold font
240 QFont font = opt.font;
242 font.setWeight(QFont::Black);
243 font.setPointSize(opt.font.pointSize() * 8 / 10);
244 painter->setFont(font);
246 // draw the centered text
247 QFontMetrics fm(font);
248 int w = fm.boundingRect(category).width();
249 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
250 int y = opt.rect.y() + 3 * fm.ascent() / 2;
253 painter->drawText(x, y, category);
255 // the vertical position of the line: middle of lower case chars
256 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
258 // draw the horizontal line
259 if (!category.isEmpty()) {
260 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
261 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
263 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
267 QString CCItemDelegate::underlineFilter(QString const & s) const
269 QString const & f = cc_->filter();
273 QRegExp pattern(charFilterRegExpC(f));
274 r.replace(pattern, "<u><b>\\1</b></u>");
279 void CategorizedCombo::Private::setFilter(QString const & s)
281 bool enabled = p->view()->updatesEnabled();
282 p->view()->setUpdatesEnabled(false);
284 // remember old selection
285 int sel = p->currentIndex();
287 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
290 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
293 // restore old selection
294 if (lastSel_ != -1) {
295 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
297 p->setCurrentIndex(i.row());
300 // Workaround to resize to content size
301 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
303 if (p->view()->isVisible()) {
304 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
305 // the hack in the item delegate to make space for the headers.
306 // We do not call our implementation of showPopup because that
307 // would reset the filter again. This is only needed if the user clicks
309 LASSERT(!inShowPopup_, /**/);
311 p->QComboBox::showPopup();
312 inShowPopup_ = false;
315 p->view()->setUpdatesEnabled(enabled);
319 CategorizedCombo::CategorizedCombo(QWidget * parent)
320 : QComboBox(parent), d(new Private(this))
322 setSizeAdjustPolicy(QComboBox::AdjustToContents);
323 setMinimumWidth(sizeHint().width());
324 setMaxVisibleItems(100);
326 setModel(d->filterModel_);
328 // for the filtering we have to intercept characters
329 view()->installEventFilter(this);
330 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
336 CategorizedCombo::~CategorizedCombo() {
341 void CategorizedCombo::Private::countCategories()
343 int n = filterModel_->rowCount();
344 visibleCategories_ = 0;
348 QString prevCat = model_->index(0, 2).data().toString();
351 for (int i = 1; i < n; ++i) {
352 QString cat = filterModel_->index(i, 2).data().toString();
354 ++visibleCategories_;
360 void CategorizedCombo::showPopup()
362 bool enabled = view()->updatesEnabled();
363 view()->setUpdatesEnabled(false);
367 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
368 // the hack in the item delegate to make space for the headers.
369 LASSERT(!d->inShowPopup_, /**/);
370 d->inShowPopup_ = true;
371 QComboBox::showPopup();
372 d->inShowPopup_ = false;
374 view()->setUpdatesEnabled(enabled);
378 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
380 if (e->type() != QEvent::KeyPress)
381 return QComboBox::eventFilter(o, e);
383 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
384 bool modified = (ke->modifiers() == Qt::ControlModifier)
385 || (ke->modifiers() == Qt::AltModifier)
386 || (ke->modifiers() == Qt::MetaModifier);
390 if (!modified && !d->filter_.isEmpty()) {
395 case Qt::Key_Backspace:
397 // cut off one character
398 d->setFilter(d->filter_.left(d->filter_.length() - 1));
402 if (modified || ke->text().isEmpty())
404 // find chars for the filter string
406 for (int i = 0; i < ke->text().length(); ++i) {
407 QChar c = ke->text()[i];
408 if (c.isLetterOrNumber()
411 || c.category() == QChar::Separator_Space) {
416 // append new chars to the filter string
417 d->setFilter(d->filter_ + s);
423 return QComboBox::eventFilter(o, e);
427 void CategorizedCombo::setIconSize(QSize size)
430 bool small = size.height() < 20;
431 setAttribute(Qt::WA_MacSmallSize, small);
432 setAttribute(Qt::WA_MacNormalSize, !small);
434 (void)size; // suppress warning
439 bool CategorizedCombo::set(QString const & item)
443 int const curItem = currentIndex();
444 QModelIndex const mindex =
445 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
446 QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
447 if (item == currentItem) {
448 LYXERR(Debug::GUI, "Already had " << item << " selected.");
452 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
454 LYXERR0("Trying to select non existent layout type " << item);
458 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
463 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
464 QString const & category, QString const & tooltip,
465 bool sorted, bool sortedByCat, bool sortCats,
468 QString titem = available ? guiname
469 : toqstr(bformat(_("Unavailable: %1$s"),
470 qstring_to_ucs4(guiname)));
471 bool const uncategorized = category.isEmpty();
472 QString qcat = uncategorized ? qt_("Uncategorized") : category;
474 QList<QStandardItem *> row;
475 QStandardItem * gui = new QStandardItem(titem);
476 if (!tooltip.isEmpty())
477 gui->setToolTip(tooltip);
479 row.append(new QStandardItem(item));
480 row.append(new QStandardItem(qcat));
481 row.append(new QStandardItem(available));
483 // the first entry is easy
484 int const end = d->model_->rowCount();
486 d->model_->appendRow(row);
493 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
494 while (i < end && d->model_->item(i, 2)->text() != qcat
496 || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
497 && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
498 || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
502 // the simple unsorted case
505 // jump to the end of the category group
506 while (i < end && d->model_->item(i, 2)->text() == qcat)
508 d->model_->insertRow(i, row);
510 d->model_->appendRow(row);
514 // find row to insert the item, after the separator if it exists
516 // find alphabetic position, unavailable at the end
518 && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
519 || ((!available && d->model_->item(i, 3))
520 || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
521 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
525 d->model_->insertRow(i, row);
529 QString CategorizedCombo::getData(int row) const
531 int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
532 return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
536 void CategorizedCombo::reset()
542 void CategorizedCombo::resetFilter()
548 void CategorizedCombo::updateCombo()
550 d->countCategories();
552 // needed to recalculate size hint
554 setMinimumWidth(sizeHint().width());
559 QString const & CategorizedCombo::filter() const
564 } // namespace frontend
568 #include "moc_CategorizedCombo.cpp"