2 * \file qt4/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.width(category);
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 // step through data item and put "(x)" for every matching character
275 for (int i = 0; i < f.length(); ++i) {
276 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
279 if (lastp == p - 1 && lastp != -1) {
280 // remove ")" and append "x)"
281 r = r.left(r.length() - 4) + s[p] + "</u>";
284 r += s.mid(lastp + 1, p - lastp - 1);
285 r += QString("<u>") + s[p] + "</u>";
289 r += s.mid(lastp + 1);
294 void CategorizedCombo::Private::setFilter(QString const & s)
296 bool enabled = p->view()->updatesEnabled();
297 p->view()->setUpdatesEnabled(false);
299 // remember old selection
300 int sel = p->currentIndex();
302 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
305 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
308 // restore old selection
309 if (lastSel_ != -1) {
310 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
312 p->setCurrentIndex(i.row());
315 // Workaround to resize to content size
316 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
318 if (p->view()->isVisible()) {
319 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
320 // the hack in the item delegate to make space for the headers.
321 // We do not call our implementation of showPopup because that
322 // would reset the filter again. This is only needed if the user clicks
324 LASSERT(!inShowPopup_, /**/);
326 p->QComboBox::showPopup();
327 inShowPopup_ = false;
330 p->view()->setUpdatesEnabled(enabled);
334 CategorizedCombo::CategorizedCombo(QWidget * parent)
335 : QComboBox(parent), d(new Private(this))
337 setSizeAdjustPolicy(QComboBox::AdjustToContents);
338 setMinimumWidth(sizeHint().width());
339 setMaxVisibleItems(100);
341 setModel(d->filterModel_);
343 // for the filtering we have to intercept characters
344 view()->installEventFilter(this);
345 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
351 CategorizedCombo::~CategorizedCombo() {
356 void CategorizedCombo::Private::countCategories()
358 int n = filterModel_->rowCount();
359 visibleCategories_ = 0;
363 QString prevCat = model_->index(0, 2).data().toString();
366 for (int i = 1; i < n; ++i) {
367 QString cat = filterModel_->index(i, 2).data().toString();
369 ++visibleCategories_;
375 void CategorizedCombo::showPopup()
377 bool enabled = view()->updatesEnabled();
378 view()->setUpdatesEnabled(false);
382 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
383 // the hack in the item delegate to make space for the headers.
384 LASSERT(!d->inShowPopup_, /**/);
385 d->inShowPopup_ = true;
386 QComboBox::showPopup();
387 d->inShowPopup_ = false;
389 view()->setUpdatesEnabled(enabled);
393 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
395 if (e->type() != QEvent::KeyPress)
396 return QComboBox::eventFilter(o, e);
398 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
399 bool modified = (ke->modifiers() == Qt::ControlModifier)
400 || (ke->modifiers() == Qt::AltModifier)
401 || (ke->modifiers() == Qt::MetaModifier);
405 if (!modified && !d->filter_.isEmpty()) {
410 case Qt::Key_Backspace:
412 // cut off one character
413 d->setFilter(d->filter_.left(d->filter_.length() - 1));
417 if (modified || ke->text().isEmpty())
419 // find chars for the filter string
421 for (int i = 0; i < ke->text().length(); ++i) {
422 QChar c = ke->text()[i];
423 if (c.isLetterOrNumber()
426 || c.category() == QChar::Separator_Space) {
431 // append new chars to the filter string
432 d->setFilter(d->filter_ + s);
438 return QComboBox::eventFilter(o, e);
442 void CategorizedCombo::setIconSize(QSize size)
445 bool small = size.height() < 20;
446 setAttribute(Qt::WA_MacSmallSize, small);
447 setAttribute(Qt::WA_MacNormalSize, !small);
449 (void)size; // suppress warning
454 bool CategorizedCombo::set(QString const & item)
458 int const curItem = currentIndex();
459 QModelIndex const mindex =
460 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
461 QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
462 if (item == currentItem) {
463 LYXERR(Debug::GUI, "Already had " << item << " selected.");
467 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
469 LYXERR0("Trying to select non existent layout type " << item);
473 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
478 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
479 QString const & category, QString const & tooltip,
480 bool sorted, bool sortedByCat, bool sortCats,
483 QString titem = available ? guiname
484 : toqstr(bformat(_("Unavailable: %1$s"),
485 qstring_to_ucs4(guiname)));
486 bool const uncategorized = category.isEmpty();
487 QString qcat = uncategorized ? qt_("Uncategorized") : category;
489 QList<QStandardItem *> row;
490 QStandardItem * gui = new QStandardItem(titem);
491 if (!tooltip.isEmpty())
492 gui->setToolTip(tooltip);
494 row.append(new QStandardItem(item));
495 row.append(new QStandardItem(qcat));
496 row.append(new QStandardItem(available));
498 // the first entry is easy
499 int const end = d->model_->rowCount();
501 d->model_->appendRow(row);
508 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
509 while (i < end && d->model_->item(i, 2)->text() != qcat
511 || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
512 && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
513 || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
517 // the simple unsorted case
520 // jump to the end of the category group
521 while (i < end && d->model_->item(i, 2)->text() == qcat)
523 d->model_->insertRow(i, row);
525 d->model_->appendRow(row);
529 // find row to insert the item, after the separator if it exists
531 // find alphabetic position, unavailable at the end
533 && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
534 || ((!available && d->model_->item(i, 3))
535 || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
536 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
540 d->model_->insertRow(i, row);
544 QString CategorizedCombo::getData(int row) const
546 int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
547 return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
551 void CategorizedCombo::reset()
558 void CategorizedCombo::updateCombo()
560 d->countCategories();
562 // needed to recalculate size hint
564 setMinimumWidth(sizeHint().width());
569 QString const & CategorizedCombo::filter() const
574 } // namespace frontend
578 #include "moc_CategorizedCombo.cpp"