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 QRegularExpression 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 #if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
291 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
293 filterModel_->setFilterRegularExpression(charFilterRegExp(filter_));
297 // restore old selection
298 if (lastSel_ != -1) {
299 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
301 p->setCurrentIndex(i.row());
304 // Workaround to resize to content size
305 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
307 if (p->view()->isVisible()) {
308 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
309 // the hack in the item delegate to make space for the headers.
310 // We do not call our implementation of showPopup because that
311 // would reset the filter again. This is only needed if the user clicks
313 LASSERT(!inShowPopup_, /**/);
315 p->QComboBox::showPopup();
316 inShowPopup_ = false;
319 p->view()->setUpdatesEnabled(enabled);
323 CategorizedCombo::CategorizedCombo(QWidget * parent)
324 : QComboBox(parent), d(new Private(this))
326 setSizeAdjustPolicy(QComboBox::AdjustToContents);
327 setMinimumWidth(sizeHint().width());
328 setMaxVisibleItems(100);
330 setModel(d->filterModel_);
332 // for the filtering we have to intercept characters
333 view()->installEventFilter(this);
334 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
340 CategorizedCombo::~CategorizedCombo() {
345 void CategorizedCombo::Private::countCategories()
347 int n = filterModel_->rowCount();
348 visibleCategories_ = 0;
352 QString prevCat = model_->index(0, 2).data().toString();
355 for (int i = 1; i < n; ++i) {
356 QString cat = filterModel_->index(i, 2).data().toString();
358 ++visibleCategories_;
364 void CategorizedCombo::showPopup()
366 lastCurrentIndex_ = currentIndex();
367 bool enabled = view()->updatesEnabled();
368 view()->setUpdatesEnabled(false);
372 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
373 // the hack in the item delegate to make space for the headers.
374 LASSERT(!d->inShowPopup_, /**/);
375 d->inShowPopup_ = true;
376 QComboBox::showPopup();
377 d->inShowPopup_ = false;
379 view()->setUpdatesEnabled(enabled);
383 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
385 if (e->type() != QEvent::KeyPress)
386 return QComboBox::eventFilter(o, e);
388 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
389 bool modified = (ke->modifiers() == Qt::ControlModifier)
390 || (ke->modifiers() == Qt::AltModifier)
391 || (ke->modifiers() == Qt::MetaModifier);
395 if (!modified && !d->filter_.isEmpty()) {
397 setCurrentIndex(lastCurrentIndex_);
401 case Qt::Key_Backspace:
403 // cut off one character
404 d->setFilter(d->filter_.left(d->filter_.length() - 1));
408 if (modified || ke->text().isEmpty())
410 // find chars for the filter string
412 for (int i = 0; i < ke->text().length(); ++i) {
413 QChar c = ke->text()[i];
414 if (c.isLetterOrNumber()
417 || c.category() == QChar::Separator_Space) {
422 // append new chars to the filter string
423 d->setFilter(d->filter_ + s);
429 return QComboBox::eventFilter(o, e);
433 void CategorizedCombo::setIconSize(QSize size)
436 bool small = size.height() < 20;
437 setAttribute(Qt::WA_MacSmallSize, small);
438 setAttribute(Qt::WA_MacNormalSize, !small);
440 (void)size; // suppress warning
445 bool CategorizedCombo::set(QString const & item, bool const report_missing)
449 int const curItem = currentIndex();
450 QModelIndex const mindex =
451 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
452 QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
453 if (item == currentItem) {
454 LYXERR(Debug::GUI, "Already had " << item << " selected.");
458 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
461 LYXERR0("Trying to select non existent layout type " << item);
465 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
470 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
471 QString const & category, QString const & tooltip,
472 bool sorted, bool sortedByCat, bool sortCats,
473 bool available, bool nocategories)
475 QString titem = available ? guiname
476 : toqstr(bformat(_("Unavailable: %1$s"),
477 qstring_to_ucs4(guiname)));
478 bool const uncategorized = category.isEmpty();
479 QString qcat = (uncategorized && !nocategories) ? qt_("Uncategorized") : category;
481 QList<QStandardItem *> row;
482 QStandardItem * gui = new QStandardItem(titem);
483 if (!tooltip.isEmpty())
484 gui->setToolTip(tooltip);
486 row.append(new QStandardItem(item));
487 row.append(new QStandardItem(qcat));
488 row.append(new QStandardItem(available));
490 // the first entry is easy
491 int const end = d->model_->rowCount();
493 d->model_->appendRow(row);
500 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
501 while (i < end && d->model_->item(i, 2)->text() != qcat
503 || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
504 && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
505 || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
509 // the simple unsorted case
512 // jump to the end of the category group
513 while (i < end && d->model_->item(i, 2)->text() == qcat)
515 d->model_->insertRow(i, row);
517 d->model_->appendRow(row);
521 // find row to insert the item, after the separator if it exists
523 // find alphabetic position, unavailable at the end
525 && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
526 || ((!available && d->model_->item(i, 3))
527 || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
528 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
532 d->model_->insertRow(i, row);
536 QString CategorizedCombo::getData(int row) const
538 int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
539 return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
543 void CategorizedCombo::reset()
549 void CategorizedCombo::resetFilter()
555 void CategorizedCombo::updateCombo()
557 d->countCategories();
559 // needed to recalculate size hint
561 setMinimumWidth(sizeHint().width());
566 QString const & CategorizedCombo::filter() const
571 } // namespace frontend
575 #include "moc_CategorizedCombo.cpp"