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>
37 using namespace lyx::support;
43 class CCItemDelegate : public QItemDelegate {
46 explicit CCItemDelegate(CategorizedCombo * cc)
47 : QItemDelegate(cc), cc_(cc)
50 void paint(QPainter * painter, QStyleOptionViewItem const & option,
51 QModelIndex const & index) const;
53 void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
54 const QRect & /*rect*/, const QString & text ) const;
56 QSize sizeHint(QStyleOptionViewItem const & opt,
57 QModelIndex const & index) const;
61 void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
62 QString const & category) const;
64 QString underlineFilter(QString const & s) const;
66 CategorizedCombo * cc_;
70 class CCFilterModel : public QSortFilterProxyModel {
73 CCFilterModel(QObject * parent = 0)
74 : QSortFilterProxyModel(parent)
79 /////////////////////////////////////////////////////////////////////
81 // CategorizedCombo::Private
83 /////////////////////////////////////////////////////////////////////
85 struct CategorizedCombo::Private
87 Private(CategorizedCombo * parent) : p(parent),
88 // set the model with four columns
89 // 1st: translated item names
92 // 4th: availability (bool)
93 model_(new QStandardItemModel(0, 4, p)),
94 filterModel_(new CCFilterModel(p)),
96 CCItemDelegate_(new CCItemDelegate(parent)),
97 visibleCategories_(0), inShowPopup_(false)
99 filterModel_->setSourceModel(model_);
102 void resetFilter() { setFilter(QString()); }
104 void setFilter(QString const & s);
106 void countCategories();
108 CategorizedCombo * p;
110 /** the layout model:
111 * 1st column: translated GUI name,
112 * 2nd column: raw item name,
113 * 3rd column: category,
114 * 4th column: availability
116 QStandardItemModel * model_;
117 /// the proxy model filtering \c model_
118 CCFilterModel * filterModel_;
119 /// the (model-) index of the last successful selection
121 /// the character filter
124 CCItemDelegate * CCItemDelegate_;
126 unsigned visibleCategories_;
132 static QString categoryCC(QAbstractItemModel const & model, int row)
134 return model.data(model.index(row, 2), Qt::DisplayRole).toString();
138 static int headerHeightCC(QStyleOptionViewItem const & opt)
140 return opt.fontMetrics.height();
144 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
145 QModelIndex const & index) const
147 QStyleOptionViewItem opt = option;
149 // default background
150 painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
152 QString cat = categoryCC(*index.model(), index.row());
154 // not the same as in the previous line?
155 if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
158 // draw unselected background
159 QStyle::State state = opt.state;
160 opt.state = opt.state & ~QStyle::State_Selected;
161 drawBackground(painter, opt, index);
164 // draw category header
165 drawCategoryHeader(painter, opt,
166 categoryCC(*index.model(), index.row()));
168 // move rect down below header
169 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
174 QItemDelegate::paint(painter, opt, index);
178 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
179 const QRect & /*rect*/, const QString & text) const
181 QString utext = underlineFilter(text);
183 // Draw the rich text.
185 QColor col = opt.palette.text().color();
186 // grey out unavailable items
187 if (text.startsWith(qt_("Unavailable:")))
188 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
189 if (opt.state & QStyle::State_Selected)
190 col = opt.palette.highlightedText().color();
191 QAbstractTextDocumentLayout::PaintContext context;
192 context.palette.setColor(QPalette::Text, col);
195 doc.setDefaultFont(opt.font);
198 QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
200 doc.rootFrame()->setFrameFormat(fmt);
202 painter->translate(opt.rect.x() + 5,
203 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
204 doc.documentLayout()->draw(painter, context);
209 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
210 QModelIndex const & index) const
212 QSize size = QItemDelegate::sizeHint(opt, index);
214 /// QComboBox uses the first row height to estimate the
215 /// complete popup height during QComboBox::showPopup().
216 /// To avoid scrolling we have to sneak in space for the headers.
217 /// So we tweak this value accordingly. It's not nice, but the
218 /// only possible way it seems.
219 // Add space for the category headers here
220 QString cat = categoryCC(*index.model(), index.row());
221 if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
222 size.setHeight(size.height() + headerHeightCC(opt));
229 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
230 QString const & category) const
232 // slightly blended color
233 QColor lcol = opt.palette.text().color();
235 painter->setPen(lcol);
237 // set 80% scaled, bold font
238 QFont font = opt.font;
240 font.setWeight(QFont::Black);
241 font.setPointSize(opt.font.pointSize() * 8 / 10);
242 painter->setFont(font);
244 // draw the centered text
245 QFontMetrics fm(font);
246 int w = fm.width(category);
247 int x = opt.rect.x() + (opt.rect.width() - w) / 2;
248 int y = opt.rect.y() + 3 * fm.ascent() / 2;
251 painter->drawText(x, y, category);
253 // the vertical position of the line: middle of lower case chars
254 int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
256 // draw the horizontal line
257 if (!category.isEmpty()) {
258 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
259 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
261 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
265 QString CCItemDelegate::underlineFilter(QString const & s) const
267 QString const & f = cc_->filter();
271 // 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);
277 LASSERT(p != -1, /**/);
278 if (lastp == p - 1 && lastp != -1) {
279 // remove ")" and append "x)"
280 r = r.left(r.length() - 4) + s[p] + "</u>";
283 r += s.mid(lastp + 1, p - lastp - 1);
284 r += QString("<u>") + s[p] + "</u>";
288 r += s.mid(lastp + 1);
293 static QString charFilterRegExpCC(QString const & filter)
296 for (int i = 0; i < filter.length(); ++i) {
299 re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
301 re += ".*" + QRegExp::escape(c);
307 void CategorizedCombo::Private::setFilter(QString const & s)
309 bool enabled = p->view()->updatesEnabled();
310 p->view()->setUpdatesEnabled(false);
312 // remember old selection
313 int sel = p->currentIndex();
315 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
318 filterModel_->setFilterRegExp(charFilterRegExpCC(filter_));
321 // restore old selection
322 if (lastSel_ != -1) {
323 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
325 p->setCurrentIndex(i.row());
328 // Workaround to resize to content size
329 // FIXME: There must be a better way. The QComboBox::AdjustToContents)
331 if (p->view()->isVisible()) {
332 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
333 // the hack in the item delegate to make space for the headers.
334 // We do not call our implementation of showPopup because that
335 // would reset the filter again. This is only needed if the user clicks
337 LASSERT(!inShowPopup_, /**/);
339 p->QComboBox::showPopup();
340 inShowPopup_ = false;
343 p->view()->setUpdatesEnabled(enabled);
347 CategorizedCombo::CategorizedCombo(QWidget * parent)
348 : QComboBox(parent), d(new Private(this))
350 setSizeAdjustPolicy(QComboBox::AdjustToContents);
351 setFocusPolicy(Qt::ClickFocus);
352 setMinimumWidth(sizeHint().width());
353 setMaxVisibleItems(100);
355 setModel(d->filterModel_);
357 // for the filtering we have to intercept characters
358 view()->installEventFilter(this);
359 view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
365 CategorizedCombo::~CategorizedCombo() {
370 void CategorizedCombo::Private::countCategories()
372 int n = filterModel_->rowCount();
373 visibleCategories_ = 0;
377 QString prevCat = model_->index(0, 2).data().toString();
380 for (int i = 1; i < n; ++i) {
381 QString cat = filterModel_->index(i, 2).data().toString();
383 ++visibleCategories_;
389 void CategorizedCombo::showPopup()
391 bool enabled = view()->updatesEnabled();
392 view()->setUpdatesEnabled(false);
396 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
397 // the hack in the item delegate to make space for the headers.
398 LASSERT(!d->inShowPopup_, /**/);
399 d->inShowPopup_ = true;
400 QComboBox::showPopup();
401 d->inShowPopup_ = false;
403 view()->setUpdatesEnabled(enabled);
407 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
409 if (e->type() != QEvent::KeyPress)
410 return QComboBox::eventFilter(o, e);
412 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
413 bool modified = (ke->modifiers() == Qt::ControlModifier)
414 || (ke->modifiers() == Qt::AltModifier)
415 || (ke->modifiers() == Qt::MetaModifier);
419 if (!modified && !d->filter_.isEmpty()) {
424 case Qt::Key_Backspace:
426 // cut off one character
427 d->setFilter(d->filter_.left(d->filter_.length() - 1));
431 if (modified || ke->text().isEmpty())
433 // find chars for the filter string
435 for (int i = 0; i < ke->text().length(); ++i) {
436 QChar c = ke->text()[i];
437 if (c.isLetterOrNumber()
440 || c.category() == QChar::Separator_Space) {
445 // append new chars to the filter string
446 d->setFilter(d->filter_ + s);
452 return QComboBox::eventFilter(o, e);
456 void CategorizedCombo::setIconSize(QSize size)
459 bool small = size.height() < 20;
460 setAttribute(Qt::WA_MacSmallSize, small);
461 setAttribute(Qt::WA_MacNormalSize, !small);
463 (void)size; // suppress warning
468 bool CategorizedCombo::set(QString const & item)
472 int const curItem = currentIndex();
473 QModelIndex const mindex =
474 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
475 QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
476 if (item == currentItem) {
477 LYXERR(Debug::GUI, "Already had " << item << " selected.");
481 QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
483 LYXERR0("Trying to select non existent layout type " << item);
487 setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
492 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
493 QString const & category, QString const & tooltip,
494 bool sorted, bool sortedByCat, bool sortCats,
497 QString titem = available ? guiname
498 : toqstr(bformat(_("Unavailable: %1$s"),
499 qstring_to_ucs4(guiname)));
500 bool const uncategorized = category.isEmpty();
501 QString qcat = uncategorized ? qt_("Uncategorized") : category;
503 QList<QStandardItem *> row;
504 QStandardItem * gui = new QStandardItem(titem);
505 if (!tooltip.isEmpty())
506 gui->setToolTip(tooltip);
508 row.append(new QStandardItem(item));
509 row.append(new QStandardItem(qcat));
510 row.append(new QStandardItem(available));
512 // the first entry is easy
513 int const end = d->model_->rowCount();
515 d->model_->appendRow(row);
522 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
523 while (i < end && d->model_->item(i, 2)->text() != qcat
525 || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
526 && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
527 || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
531 // the simple unsorted case
534 // jump to the end of the category group
535 while (i < end && d->model_->item(i, 2)->text() == qcat)
537 d->model_->insertRow(i, row);
539 d->model_->appendRow(row);
543 // find row to insert the item, after the separator if it exists
545 // find alphabetic position, unavailable at the end
547 && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
548 || ((!available && d->model_->item(i, 3))
549 || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
550 && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
554 d->model_->insertRow(i, row);
558 QString CategorizedCombo::getData(int row) const
560 int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
561 return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
565 void CategorizedCombo::reset()
572 void CategorizedCombo::updateCombo()
574 d->countCategories();
576 // needed to recalculate size hint
578 setMinimumWidth(sizeHint().width());
583 QString const & CategorizedCombo::filter() const
588 } // namespace frontend
592 #include "moc_CategorizedCombo.cpp"