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"
28 #include <QAbstractTextDocumentLayout>
30 #include <QHeaderView>
31 #include <QItemDelegate>
33 #include <QSortFilterProxyModel>
34 #include <QStandardItemModel>
39 using namespace lyx::support;
42 class CCItemDelegate : public QItemDelegate {
45 explicit CCItemDelegate(CategorizedCombo * cc)
46 : QItemDelegate(cc), cc_(cc)
49 void paint(QPainter * painter, QStyleOptionViewItem const & option,
50 QModelIndex const & index) const;
52 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
53 const QRect & /*rect*/, const QString & text ) const;
55 QSize sizeHint(QStyleOptionViewItem const & opt,
56 QModelIndex const & index) const;
60 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
61 QString const & category) const;
63 QString underlineFilter(QString const & s) const;
65 CategorizedCombo * cc_;
69 class CCFilterModel : public QSortFilterProxyModel {
72 CCFilterModel(QObject * parent = 0)
73 : QSortFilterProxyModel(parent)
78 /////////////////////////////////////////////////////////////////////
80 // CategorizedCombo::Private
82 /////////////////////////////////////////////////////////////////////
84 struct CategorizedCombo::Private
86 Private(CategorizedCombo * parent) : p(parent),
87 // set the model with four columns
88 // 1st: translated item names
91 // 4th: availability (bool)
92 model_(new QStandardItemModel(0, 4, p)),
93 filterModel_(new CCFilterModel(p)),
95 CCItemDelegate_(new CCItemDelegate(parent)),
96 visibleCategories_(0), inShowPopup_(false)
98 filterModel_->setSourceModel(model_);
101 void resetFilter() { setFilter(QString()); }
103 void setFilter(QString const & s);
105 void countCategories();
107 CategorizedCombo * p;
109 /** the layout model:
110 * 1st column: translated GUI name,
111 * 2nd column: raw item name,
112 * 3rd column: category,
113 * 4th column: availability
115 QStandardItemModel * model_;
116 /// the proxy model filtering \c model_
117 CCFilterModel * filterModel_;
118 /// the (model-) index of the last successful selection
120 /// the character filter
123 CCItemDelegate * CCItemDelegate_;
125 unsigned visibleCategories_;
131 static QString category(QAbstractItemModel const & model, int row)
133 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
137 static int headerHeight(QStyleOptionViewItem const & opt)
139 return opt.fontMetrics.height();
143 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
144 QModelIndex const & index) const
146 QStyleOptionViewItem opt = option;
148 // default background
149 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
151 QString cat = category(*index.model(), index.row());
153 // not the same as in the previous line?
154 if (index.row() == 0 || cat != category(*index.model(), index.row() - 1)) {
157 // draw unselected background
158 QStyle::State state = opt.state;
159 opt.state = opt.state & ~QStyle::State_Selected;
160 drawBackground(painter, opt, index);
163 // draw category header
164 drawCategoryHeader(painter, opt,
165 category(*index.model(), index.row()));
167 // move rect down below header
168 opt.rect.setTop(opt.rect.top() + headerHeight(opt));
173 QItemDelegate::paint(painter, opt, index);
177 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
178 const QRect & /*rect*/, const QString & text) const
180 QString utext = underlineFilter(text);
182 // Draw the rich text.
184 QColor col = opt.palette.text().color();
185 // grey out unavailable items
186 if (text.startsWith(qt_("Unavailable:")))
187 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
188 if (opt.state & QStyle::State_Selected)
189 col = opt.palette.highlightedText().color();
190 QAbstractTextDocumentLayout::PaintContext context;
191 context.palette.setColor(QPalette::Text, col);
194 doc.setDefaultFont(opt.font);
197 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
199 doc.rootFrame()->setFrameFormat(fmt);
201 painter->translate(opt.rect.x() + 5,
202 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
203 doc.documentLayout()->draw(painter, context);
208 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
209 QModelIndex const & index) const
211 QSize size = QItemDelegate::sizeHint(opt, index);
213 /// QComboBox uses the first row height to estimate the
214 /// complete popup height during QComboBox::showPopup().
215 /// To avoid scrolling we have to sneak in space for the headers.
216 /// So we tweak this value accordingly. It's not nice, but the
217 /// only possible way it seems.
218 // Add space for the category headers here
219 QString cat = category(*index.model(), index.row());
220 if (index.row() == 0 || cat != category(*index.model(), index.row() - 1)) {
221 size.setHeight(size.height() + headerHeight(opt));
228 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
229 QString const & category) const
231 // slightly blended color
232 QColor lcol = opt.palette.text().color();
234 painter->setPen(lcol);
236 // set 80% scaled, bold font
237 QFont font = opt.font;
239 font.setWeight(QFont::Black);
240 font.setPointSize(opt.font.pointSize() * 8 / 10);
241 painter->setFont(font);
243 // draw the centered text
244 QFontMetrics fm(font);
245 int w = fm.width(category);
246 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
247 int y = opt.rect.y() + 1.5 * fm.ascent();
250 painter->drawText(x, y, category);
252 // the vertical position of the line: middle of lower case chars
253 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
255 // draw the horizontal line
256 if (!category.isEmpty()) {
257 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
258 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
260 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
264 QString CCItemDelegate::underlineFilter(QString const & s) const
266 QString const & f = cc_->filter();
270 // step through data item and put "(x)" for every matching character
274 for (int i = 0; i < f.length(); ++i) {
275 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
276 LASSERT(p != -1, /**/);
277 if (lastp == p - 1 && lastp != -1) {
278 // remove ")" and append "x)"
279 r = r.left(r.length() - 4) + s[p] + "</u>";
282 r += s.mid(lastp + 1, p - lastp - 1);
283 r += QString("<u>") + s[p] + "</u>";
287 r += s.mid(lastp + 1);
292 static QString charFilterRegExp(QString const & filter)
295 for (int i = 0; i < filter.length(); ++i) {
298 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
300 re += ".*" + QRegExp::escape(c);
306 void CategorizedCombo::Private::setFilter(QString const & s)
308 bool enabled = p->view()->updatesEnabled();
309 p->view()->setUpdatesEnabled(false);
311 // remember old selection
312 int sel = p->currentIndex();
314 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
317 filterModel_->setFilterRegExp(charFilterRegExp(filter_));
320 // restore old selection
321 if (lastSel_ != -1) {
322 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
324 p->setCurrentIndex(i.row());
327 // Workaround to resize to content size
328 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
330 if (p->view()->isVisible()) {
331 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
332 // the hack in the item delegate to make space for the headers.
333 // We do not call our implementation of showPopup because that
334 // would reset the filter again. This is only needed if the user clicks
336 LASSERT(!inShowPopup_, /**/);
338 p->QComboBox::showPopup();
339 inShowPopup_ = false;
342 p->view()->setUpdatesEnabled(enabled);
346 CategorizedCombo::CategorizedCombo(QWidget * parent)
347 : QComboBox(parent), d(new Private(this))
349 setSizeAdjustPolicy(QComboBox::AdjustToContents);
350 setFocusPolicy(Qt::ClickFocus);
351 setMinimumWidth(sizeHint().width());
352 setMaxVisibleItems(100);
354 setModel(d->filterModel_);
356 // for the filtering we have to intercept characters
357 view()->installEventFilter(this);
358 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
364 CategorizedCombo::~CategorizedCombo() {
369 void CategorizedCombo::Private::countCategories()
371 int n = filterModel_->rowCount();
372 visibleCategories_ = 0;
376 QString prevCat = model_->index(0, 2).data().toString();
379 for (int i = 1; i < n; ++i) {
380 QString cat = filterModel_->index(i, 2).data().toString();
382 ++visibleCategories_;
388 void CategorizedCombo::showPopup()
390 bool enabled = view()->updatesEnabled();
391 view()->setUpdatesEnabled(false);
395 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
396 // the hack in the item delegate to make space for the headers.
397 LASSERT(!d->inShowPopup_, /**/);
398 d->inShowPopup_ = true;
399 QComboBox::showPopup();
400 d->inShowPopup_ = false;
402 view()->setUpdatesEnabled(enabled);
406 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
408 if (e->type() != QEvent::KeyPress)
409 return QComboBox::eventFilter(o, e);
411 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
412 bool modified = (ke->modifiers() == Qt::ControlModifier)
413 || (ke->modifiers() == Qt::AltModifier)
414 || (ke->modifiers() == Qt::MetaModifier);
418 if (!modified && !d->filter_.isEmpty()) {
423 case Qt::Key_Backspace:
425 // cut off one character
426 d->setFilter(d->filter_.left(d->filter_.length() - 1));
430 if (modified || ke->text().isEmpty())
432 // find chars for the filter string
434 for (int i = 0; i < ke->text().length(); ++i) {
435 QChar c = ke->text()[i];
436 if (c.isLetterOrNumber()
439 || c.category() == QChar::Separator_Space) {
444 // append new chars to the filter string
445 d->setFilter(d->filter_ + s);
451 return QComboBox::eventFilter(o, e);
455 void CategorizedCombo::setIconSize(QSize size)
458 bool small = size.height() < 20;
459 setAttribute(Qt::WA_MacSmallSize, small);
460 setAttribute(Qt::WA_MacNormalSize, !small);
462 (void)size; // suppress warning
467 bool CategorizedCombo::set(QString const & item)
471 int const curItem = currentIndex();
472 QModelIndex const mindex =
473 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
474 QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
475 if (item == currentItem) {
476 LYXERR(Debug::GUI, "Already had " << item << " selected.");
480 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
482 LYXERR0("Trying to select non existent layout type " << item);
486 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
491 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
492 QString const & category, QString const & tooltip,
493 bool sorted, bool sortedByCat, bool sortCats,
496 QString titem = available ? guiname : qt_("Unavailable: %1").arg(guiname);
497 bool const uncategorized = category.isEmpty();
498 QString qcat = uncategorized ? qt_("Uncategorized") : category;
500 QList<QStandardItem *> row;
501 QStandardItem * gui = new QStandardItem(titem);
502 if (!tooltip.isEmpty())
503 gui->setToolTip(tooltip);
505 row.append(new QStandardItem(item));
506 row.append(new QStandardItem(qcat));
507 row.append(new QStandardItem(available));
509 // the first entry is easy
510 int const end = d->model_->rowCount();
512 d->model_->appendRow(row);
519 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
520 while (i < end && d->model_->item(i, 2)->text() != qcat
522 || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
523 && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
524 || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
528 // the simple unsorted case
531 // jump to the end of the category group
532 while (i < end && d->model_->item(i, 2)->text() == qcat)
534 d->model_->insertRow(i, row);
536 d->model_->appendRow(row);
540 // find row to insert the item, after the separator if it exists
542 // find alphabetic position, unavailable at the end
544 && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
545 || ((!available && d->model_->item(i, 3))
546 || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
547 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
551 d->model_->insertRow(i, row);
555 QString CategorizedCombo::getData(int row) const
557 return d->model_->data(d->model_->index(row, 1), Qt::DisplayRole).toString();
561 void CategorizedCombo::reset()
568 void CategorizedCombo::updateCombo()
570 d->countCategories();
572 // needed to recalculate size hint
574 setMinimumWidth(sizeHint().width());
579 QString const & CategorizedCombo::filter() const
585 #include "moc_CategorizedCombo.cpp"