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>
37 #if QT_VERSION >= 0x060000
38 #include <QtCore5Compat/QRegExp>
41 using namespace lyx::support;
47 class CCItemDelegate : public QItemDelegate {
50 explicit CCItemDelegate(CategorizedCombo * cc)
51 : QItemDelegate(cc), cc_(cc)
54 void paint(QPainter * painter, QStyleOptionViewItem const & option,
55 QModelIndex const & index) const override;
57 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
58 const QRect & /*rect*/, const QString & text ) const override;
60 QSize sizeHint(QStyleOptionViewItem const & opt,
61 QModelIndex const & index) const override;
65 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
66 QString const & category) const;
68 QString underlineFilter(QString const & s) const;
70 CategorizedCombo * cc_;
74 class CCFilterModel : public QSortFilterProxyModel {
77 CCFilterModel(QObject * parent = nullptr)
78 : QSortFilterProxyModel(parent)
83 /////////////////////////////////////////////////////////////////////
85 // CategorizedCombo::Private
87 /////////////////////////////////////////////////////////////////////
89 struct CategorizedCombo::Private
91 Private(CategorizedCombo * parent) : p(parent),
92 // set the model with four columns
93 // 1st: translated item names
96 // 4th: availability (bool)
97 model_(new QStandardItemModel(0, 4, p)),
98 filterModel_(new CCFilterModel(p)),
100 CCItemDelegate_(new CCItemDelegate(parent)),
101 visibleCategories_(0), inShowPopup_(false)
103 filterModel_->setSourceModel(model_);
106 void resetFilter() { setFilter(QString()); }
108 void setFilter(QString const & s);
110 void countCategories();
112 CategorizedCombo * p;
114 /** the layout model:
115 * 1st column: translated GUI name,
116 * 2nd column: raw item name,
117 * 3rd column: category,
118 * 4th column: availability
120 QStandardItemModel * model_;
121 /// the proxy model filtering \c model_
122 CCFilterModel * filterModel_;
123 /// the (model-) index of the last successful selection
125 /// the character filter
128 CCItemDelegate * CCItemDelegate_;
130 unsigned visibleCategories_;
136 static QString categoryCC(QAbstractItemModel const & model, int row)
138 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
142 static int headerHeightCC(QStyleOptionViewItem const & opt)
144 return opt.fontMetrics.height();
148 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
149 QModelIndex const & index) const
151 QStyleOptionViewItem opt = option;
153 // default background
154 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
156 QString cat = categoryCC(*index.model(), index.row());
158 // not the same as in the previous line?
159 if (cc_->d->visibleCategories_ > 0
160 && (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1))) {
163 // draw unselected background
164 QStyle::State state = opt.state;
165 opt.state = opt.state & ~QStyle::State_Selected;
166 drawBackground(painter, opt, index);
169 // draw category header
170 drawCategoryHeader(painter, opt,
171 categoryCC(*index.model(), index.row()));
173 // move rect down below header
174 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
179 QItemDelegate::paint(painter, opt, index);
183 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
184 const QRect & /*rect*/, const QString & text) const
186 QString utext = underlineFilter(text);
188 // Draw the rich text.
190 QColor col = opt.palette.text().color();
191 // grey out unavailable items
192 if (text.startsWith(qt_("Unavailable:")))
193 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
194 if (opt.state & QStyle::State_Selected)
195 col = opt.palette.highlightedText().color();
196 QAbstractTextDocumentLayout::PaintContext context;
197 context.palette.setColor(QPalette::Text, col);
200 doc.setDefaultFont(opt.font);
203 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
205 doc.rootFrame()->setFrameFormat(fmt);
207 painter->translate(opt.rect.x() + 5,
208 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
209 doc.documentLayout()->draw(painter, context);
214 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
215 QModelIndex const & index) const
217 QSize size = QItemDelegate::sizeHint(opt, index);
219 /// QComboBox uses the first row height to estimate the
220 /// complete popup height during QComboBox::showPopup().
221 /// To avoid scrolling we have to sneak in space for the headers.
222 /// So we tweak this value accordingly. It's not nice, but the
223 /// only possible way it seems.
224 // Add space for the category headers here
225 QString cat = categoryCC(*index.model(), index.row());
226 if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
227 size.setHeight(size.height() + headerHeightCC(opt));
234 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
235 QString const & category) const
237 // slightly blended color
238 QColor lcol = opt.palette.text().color();
240 painter->setPen(lcol);
242 // set 80% scaled, bold font
243 QFont font = opt.font;
245 font.setWeight(QFont::Black);
246 font.setPointSize(opt.font.pointSize() * 8 / 10);
247 painter->setFont(font);
249 // draw the centered text
250 QFontMetrics fm(font);
251 int w = fm.boundingRect(category).width();
252 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
253 int y = opt.rect.y() + 3 * fm.ascent() / 2;
256 painter->drawText(x, y, category);
258 // the vertical position of the line: middle of lower case chars
259 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
261 // draw the horizontal line
262 if (!category.isEmpty()) {
263 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
264 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
266 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
270 QString CCItemDelegate::underlineFilter(QString const & s) const
272 QString const & f = cc_->filter();
276 #if QT_VERSION < 0x060000
277 QRegExp pattern(charFilterRegExpC(f));
279 QRegularExpression pattern(charFilterRegExpC(f));
281 r.replace(pattern, "<u><b>\\1</b></u>");
286 void CategorizedCombo::Private::setFilter(QString const & s)
288 bool enabled = p->view()->updatesEnabled();
289 p->view()->setUpdatesEnabled(false);
291 // remember old selection
292 int sel = p->currentIndex();
294 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
297 #if QT_VERSION < 0x060000
298 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
300 filterModel_->setFilterRegularExpression(charFilterRegExp(filter_));
304 // restore old selection
305 if (lastSel_ != -1) {
306 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
308 p->setCurrentIndex(i.row());
311 // Workaround to resize to content size
312 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
314 if (p->view()->isVisible()) {
315 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
316 // the hack in the item delegate to make space for the headers.
317 // We do not call our implementation of showPopup because that
318 // would reset the filter again. This is only needed if the user clicks
320 LASSERT(!inShowPopup_, /**/);
322 p->QComboBox::showPopup();
323 inShowPopup_ = false;
326 p->view()->setUpdatesEnabled(enabled);
330 CategorizedCombo::CategorizedCombo(QWidget * parent)
331 : QComboBox(parent), d(new Private(this))
333 setSizeAdjustPolicy(QComboBox::AdjustToContents);
334 setMinimumWidth(sizeHint().width());
335 setMaxVisibleItems(100);
337 setModel(d->filterModel_);
339 // for the filtering we have to intercept characters
340 view()->installEventFilter(this);
341 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
347 CategorizedCombo::~CategorizedCombo() {
352 void CategorizedCombo::Private::countCategories()
354 int n = filterModel_->rowCount();
355 visibleCategories_ = 0;
359 QString prevCat = model_->index(0, 2).data().toString();
362 for (int i = 1; i < n; ++i) {
363 QString cat = filterModel_->index(i, 2).data().toString();
365 ++visibleCategories_;
371 void CategorizedCombo::showPopup()
373 bool enabled = view()->updatesEnabled();
374 view()->setUpdatesEnabled(false);
378 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
379 // the hack in the item delegate to make space for the headers.
380 LASSERT(!d->inShowPopup_, /**/);
381 d->inShowPopup_ = true;
382 QComboBox::showPopup();
383 d->inShowPopup_ = false;
385 view()->setUpdatesEnabled(enabled);
389 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
391 if (e->type() != QEvent::KeyPress)
392 return QComboBox::eventFilter(o, e);
394 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
395 bool modified = (ke->modifiers() == Qt::ControlModifier)
396 || (ke->modifiers() == Qt::AltModifier)
397 || (ke->modifiers() == Qt::MetaModifier);
401 if (!modified && !d->filter_.isEmpty()) {
406 case Qt::Key_Backspace:
408 // cut off one character
409 d->setFilter(d->filter_.left(d->filter_.length() - 1));
413 if (modified || ke->text().isEmpty())
415 // find chars for the filter string
417 for (int i = 0; i < ke->text().length(); ++i) {
418 QChar c = ke->text()[i];
419 if (c.isLetterOrNumber()
422 || c.category() == QChar::Separator_Space) {
427 // append new chars to the filter string
428 d->setFilter(d->filter_ + s);
434 return QComboBox::eventFilter(o, e);
438 void CategorizedCombo::setIconSize(QSize size)
441 bool small = size.height() < 20;
442 setAttribute(Qt::WA_MacSmallSize, small);
443 setAttribute(Qt::WA_MacNormalSize, !small);
445 (void)size; // suppress warning
450 bool CategorizedCombo::set(QString const & item)
454 int const curItem = currentIndex();
455 QModelIndex const mindex =
456 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
457 QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
458 if (item == currentItem) {
459 LYXERR(Debug::GUI, "Already had " << item << " selected.");
463 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
465 LYXERR0("Trying to select non existent layout type " << item);
469 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
474 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
475 QString const & category, QString const & tooltip,
476 bool sorted, bool sortedByCat, bool sortCats,
479 QString titem = available ? guiname
480 : toqstr(bformat(_("Unavailable: %1$s"),
481 qstring_to_ucs4(guiname)));
482 bool const uncategorized = category.isEmpty();
483 QString qcat = uncategorized ? qt_("Uncategorized") : category;
485 QList<QStandardItem *> row;
486 QStandardItem * gui = new QStandardItem(titem);
487 if (!tooltip.isEmpty())
488 gui->setToolTip(tooltip);
490 row.append(new QStandardItem(item));
491 row.append(new QStandardItem(qcat));
492 row.append(new QStandardItem(available));
494 // the first entry is easy
495 int const end = d->model_->rowCount();
497 d->model_->appendRow(row);
504 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
505 while (i < end && d->model_->item(i, 2)->text() != qcat
507 || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
508 && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
509 || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
513 // the simple unsorted case
516 // jump to the end of the category group
517 while (i < end && d->model_->item(i, 2)->text() == qcat)
519 d->model_->insertRow(i, row);
521 d->model_->appendRow(row);
525 // find row to insert the item, after the separator if it exists
527 // find alphabetic position, unavailable at the end
529 && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
530 || ((!available && d->model_->item(i, 3))
531 || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
532 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
536 d->model_->insertRow(i, row);
540 QString CategorizedCombo::getData(int row) const
542 int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
543 return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
547 void CategorizedCombo::reset()
553 void CategorizedCombo::resetFilter()
559 void CategorizedCombo::updateCombo()
561 d->countCategories();
563 // needed to recalculate size hint
565 setMinimumWidth(sizeHint().width());
570 QString const & CategorizedCombo::filter() const
575 } // namespace frontend
579 #include "moc_CategorizedCombo.cpp"