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;
54 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
55 const QRect & /*rect*/, const QString & text ) const;
57 QSize sizeHint(QStyleOptionViewItem const & opt,
58 QModelIndex const & index) const;
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 = 0)
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 (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
159 // draw unselected background
160 QStyle::State state = opt.state;
161 opt.state = opt.state & ~QStyle::State_Selected;
162 drawBackground(painter, opt, index);
165 // draw category header
166 drawCategoryHeader(painter, opt,
167 categoryCC(*index.model(), index.row()));
169 // move rect down below header
170 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
175 QItemDelegate::paint(painter, opt, index);
179 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
180 const QRect & /*rect*/, const QString & text) const
182 QString utext = underlineFilter(text);
184 // Draw the rich text.
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);
196 doc.setDefaultFont(opt.font);
199 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
201 doc.rootFrame()->setFrameFormat(fmt);
203 painter->translate(opt.rect.x() + 5,
204 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
205 doc.documentLayout()->draw(painter, context);
210 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
211 QModelIndex const & index) const
213 QSize size = QItemDelegate::sizeHint(opt, index);
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));
230 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
231 QString const & category) const
233 // slightly blended color
234 QColor lcol = opt.palette.text().color();
236 painter->setPen(lcol);
238 // set 80% scaled, bold font
239 QFont font = opt.font;
241 font.setWeight(QFont::Black);
242 font.setPointSize(opt.font.pointSize() * 8 / 10);
243 painter->setFont(font);
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;
252 painter->drawText(x, y, category);
254 // the vertical position of the line: middle of lower case chars
255 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
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);
262 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
266 QString CCItemDelegate::underlineFilter(QString const & s) const
268 QString const & f = cc_->filter();
272 QRegExp pattern(charFilterRegExpC(f));
273 r.replace(pattern, "<u><b>\\1</b></u>");
278 void CategorizedCombo::Private::setFilter(QString const & s)
280 bool enabled = p->view()->updatesEnabled();
281 p->view()->setUpdatesEnabled(false);
283 // remember old selection
284 int sel = p->currentIndex();
286 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
289 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
292 // restore old selection
293 if (lastSel_ != -1) {
294 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
296 p->setCurrentIndex(i.row());
299 // Workaround to resize to content size
300 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
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
308 LASSERT(!inShowPopup_, /**/);
310 p->QComboBox::showPopup();
311 inShowPopup_ = false;
314 p->view()->setUpdatesEnabled(enabled);
318 CategorizedCombo::CategorizedCombo(QWidget * parent)
319 : QComboBox(parent), d(new Private(this))
321 setSizeAdjustPolicy(QComboBox::AdjustToContents);
322 setMinimumWidth(sizeHint().width());
323 setMaxVisibleItems(100);
325 setModel(d->filterModel_);
327 // for the filtering we have to intercept characters
328 view()->installEventFilter(this);
329 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
335 CategorizedCombo::~CategorizedCombo() {
340 void CategorizedCombo::Private::countCategories()
342 int n = filterModel_->rowCount();
343 visibleCategories_ = 0;
347 QString prevCat = model_->index(0, 2).data().toString();
350 for (int i = 1; i < n; ++i) {
351 QString cat = filterModel_->index(i, 2).data().toString();
353 ++visibleCategories_;
359 void CategorizedCombo::showPopup()
361 bool enabled = view()->updatesEnabled();
362 view()->setUpdatesEnabled(false);
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;
373 view()->setUpdatesEnabled(enabled);
377 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
379 if (e->type() != QEvent::KeyPress)
380 return QComboBox::eventFilter(o, e);
382 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
383 bool modified = (ke->modifiers() == Qt::ControlModifier)
384 || (ke->modifiers() == Qt::AltModifier)
385 || (ke->modifiers() == Qt::MetaModifier);
389 if (!modified && !d->filter_.isEmpty()) {
394 case Qt::Key_Backspace:
396 // cut off one character
397 d->setFilter(d->filter_.left(d->filter_.length() - 1));
401 if (modified || ke->text().isEmpty())
403 // find chars for the filter string
405 for (int i = 0; i < ke->text().length(); ++i) {
406 QChar c = ke->text()[i];
407 if (c.isLetterOrNumber()
410 || c.category() == QChar::Separator_Space) {
415 // append new chars to the filter string
416 d->setFilter(d->filter_ + s);
422 return QComboBox::eventFilter(o, e);
426 void CategorizedCombo::setIconSize(QSize size)
429 bool small = size.height() < 20;
430 setAttribute(Qt::WA_MacSmallSize, small);
431 setAttribute(Qt::WA_MacNormalSize, !small);
433 (void)size; // suppress warning
438 bool CategorizedCombo::set(QString const & item)
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.");
451 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
453 LYXERR0("Trying to select non existent layout type " << item);
457 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
462 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
463 QString const & category, QString const & tooltip,
464 bool sorted, bool sortedByCat, bool sortCats,
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;
473 QList<QStandardItem *> row;
474 QStandardItem * gui = new QStandardItem(titem);
475 if (!tooltip.isEmpty())
476 gui->setToolTip(tooltip);
478 row.append(new QStandardItem(item));
479 row.append(new QStandardItem(qcat));
480 row.append(new QStandardItem(available));
482 // the first entry is easy
483 int const end = d->model_->rowCount();
485 d->model_->appendRow(row);
492 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
493 while (i < end && d->model_->item(i, 2)->text() != qcat
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"))))
501 // the simple unsorted case
504 // jump to the end of the category group
505 while (i < end && d->model_->item(i, 2)->text() == qcat)
507 d->model_->insertRow(i, row);
509 d->model_->appendRow(row);
513 // find row to insert the item, after the separator if it exists
515 // find alphabetic position, unavailable at the 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))
524 d->model_->insertRow(i, row);
528 QString CategorizedCombo::getData(int row) const
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();
535 void CategorizedCombo::reset()
542 void CategorizedCombo::updateCombo()
544 d->countCategories();
546 // needed to recalculate size hint
548 setMinimumWidth(sizeHint().width());
553 QString const & CategorizedCombo::filter() const
558 } // namespace frontend
562 #include "moc_CategorizedCombo.cpp"