]> git.lyx.org Git - features.git/blob - src/frontends/qt/CategorizedCombo.cpp
4aebcf6a917e85ed0c2bfc371cc52ae31c785ee3
[features.git] / src / frontends / qt / CategorizedCombo.cpp
1 /**
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.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Stefan Schimanski
11  * \author Jürgen Spitzmüller
12  * \author Abdelrazak Younes
13  *
14  * Full author contact details are available in file CREDITS.
15  */
16
17 #include <config.h>
18
19 #include "CategorizedCombo.h"
20
21 #include "qt_helpers.h"
22
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"
28
29 #include <QAbstractTextDocumentLayout>
30 #include <QComboBox>
31 #include <QHeaderView>
32 #include <QItemDelegate>
33 #include <QPainter>
34 #include <QSortFilterProxyModel>
35 #include <QStandardItemModel>
36 #include <QTextFrame>
37
38 using namespace lyx::support;
39
40 namespace lyx {
41 namespace frontend {
42
43
44 class CCItemDelegate : public QItemDelegate {
45 public:
46         ///
47         explicit CCItemDelegate(CategorizedCombo * cc)
48                 : QItemDelegate(cc), cc_(cc)
49         {}
50         ///
51         void paint(QPainter * painter, QStyleOptionViewItem const & option,
52                 QModelIndex const & index) const override;
53         ///
54         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
55                 const QRect & /*rect*/, const QString & text ) const override;
56         ///
57         QSize sizeHint(QStyleOptionViewItem const & opt,
58                 QModelIndex const & index) const override;
59
60 private:
61         ///
62         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
63                 QString const & category) const;
64         ///
65         QString underlineFilter(QString const & s) const;
66         ///
67         CategorizedCombo * cc_;
68 };
69
70
71 class CCFilterModel : public QSortFilterProxyModel {
72 public:
73         ///
74         CCFilterModel(QObject * parent = nullptr)
75                 : QSortFilterProxyModel(parent)
76         {}
77 };
78
79
80 /////////////////////////////////////////////////////////////////////
81 //
82 // CategorizedCombo::Private
83 //
84 /////////////////////////////////////////////////////////////////////
85
86 struct CategorizedCombo::Private
87 {
88         Private(CategorizedCombo * parent) : p(parent),
89                 // set the model with four columns
90                 // 1st: translated item names
91                 // 2nd: raw names
92                 // 3rd: category
93                 // 4th: availability (bool)
94                 model_(new QStandardItemModel(0, 4, p)),
95                 filterModel_(new CCFilterModel(p)),
96                 lastSel_(-1),
97                 CCItemDelegate_(new CCItemDelegate(parent)),
98                 visibleCategories_(0), inShowPopup_(false)
99         {
100                 filterModel_->setSourceModel(model_);
101         }
102
103         void resetFilter() { setFilter(QString()); }
104         ///
105         void setFilter(QString const & s);
106         ///
107         void countCategories();
108         ///
109         CategorizedCombo * p;
110
111         /** the layout model:
112          * 1st column: translated GUI name,
113          * 2nd column: raw item name,
114          * 3rd column: category,
115          * 4th column: availability
116         **/
117         QStandardItemModel * model_;
118         /// the proxy model filtering \c model_
119         CCFilterModel * filterModel_;
120         /// the (model-) index of the last successful selection
121         int lastSel_;
122         /// the character filter
123         QString filter_;
124         ///
125         CCItemDelegate * CCItemDelegate_;
126         ///
127         unsigned visibleCategories_;
128         ///
129         bool inShowPopup_;
130 };
131
132
133 static QString categoryCC(QAbstractItemModel const & model, int row)
134 {
135         return model.data(model.index(row, 2), Qt::DisplayRole).toString();
136 }
137
138
139 static int headerHeightCC(QStyleOptionViewItem const & opt)
140 {
141         return opt.fontMetrics.height();
142 }
143
144
145 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
146                            QModelIndex const & index) const
147 {
148         QStyleOptionViewItem opt = option;
149
150         // default background
151         painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
152
153         QString cat = categoryCC(*index.model(), index.row());
154
155         // not the same as in the previous line?
156         if (cc_->d->visibleCategories_ > 0
157             && (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1))) {
158                 painter->save();
159
160                 // draw unselected background
161                 QStyle::State state = opt.state;
162                 opt.state = opt.state & ~QStyle::State_Selected;
163                 drawBackground(painter, opt, index);
164                 opt.state = state;
165
166                 // draw category header
167                 drawCategoryHeader(painter, opt,
168                         categoryCC(*index.model(), index.row()));
169
170                 // move rect down below header
171                 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
172
173                 painter->restore();
174         }
175
176         QItemDelegate::paint(painter, opt, index);
177 }
178
179
180 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
181                                  const QRect & /*rect*/, const QString & text) const
182 {
183         QString utext = underlineFilter(text);
184
185         // Draw the rich text.
186         painter->save();
187         QColor col = opt.palette.text().color();
188         // grey out unavailable items
189         if (text.startsWith(qt_("Unavailable:")))
190                 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
191         if (opt.state & QStyle::State_Selected)
192                 col = opt.palette.highlightedText().color();
193         QAbstractTextDocumentLayout::PaintContext context;
194         context.palette.setColor(QPalette::Text, col);
195
196         QTextDocument doc;
197         doc.setDefaultFont(opt.font);
198         doc.setHtml(utext);
199
200         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
201         fmt.setMargin(0);
202         doc.rootFrame()->setFrameFormat(fmt);
203
204         painter->translate(opt.rect.x() + 5,
205                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
206         doc.documentLayout()->draw(painter, context);
207         painter->restore();
208 }
209
210
211 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
212                                QModelIndex const & index) const
213 {
214         QSize size = QItemDelegate::sizeHint(opt, index);
215
216         /// QComboBox uses the first row height to estimate the
217         /// complete popup height during QComboBox::showPopup().
218         /// To avoid scrolling we have to sneak in space for the headers.
219         /// So we tweak this value accordingly. It's not nice, but the
220         /// only possible way it seems.
221         // Add space for the category headers here
222         QString cat = categoryCC(*index.model(), index.row());
223         if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
224                 size.setHeight(size.height() + headerHeightCC(opt));
225         }
226
227         return size;
228 }
229
230
231 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
232                                         QString const & category) const
233 {
234         // slightly blended color
235         QColor lcol = opt.palette.text().color();
236         lcol.setAlpha(127);
237         painter->setPen(lcol);
238
239         // set 80% scaled, bold font
240         QFont font = opt.font;
241         font.setBold(true);
242         font.setWeight(QFont::Black);
243         font.setPointSize(opt.font.pointSize() * 8 / 10);
244         painter->setFont(font);
245
246         // draw the centered text
247         QFontMetrics fm(font);
248         int w = fm.boundingRect(category).width();
249         int x = opt.rect.x() + (opt.rect.width() - w) / 2;
250         int y = opt.rect.y() + 3 * fm.ascent() / 2;
251         int left = x;
252         int right = x + w;
253         painter->drawText(x, y, category);
254
255         // the vertical position of the line: middle of lower case chars
256         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
257
258         // draw the horizontal line
259         if (!category.isEmpty()) {
260                 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
261                 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
262         } else
263                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
264 }
265
266
267 QString CCItemDelegate::underlineFilter(QString const & s) const
268 {
269         QString const & f = cc_->filter();
270         if (f.isEmpty())
271                 return s;
272         QString r(s);
273         QRegExp pattern(charFilterRegExpC(f));
274         r.replace(pattern, "<u><b>\\1</b></u>");
275         return r;
276 }
277
278
279 void CategorizedCombo::Private::setFilter(QString const & s)
280 {
281         bool enabled = p->view()->updatesEnabled();
282         p->view()->setUpdatesEnabled(false);
283
284         // remember old selection
285         int sel = p->currentIndex();
286         if (sel != -1)
287                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
288
289         filter_ = s;
290         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
291         countCategories();
292
293         // restore old selection
294         if (lastSel_ != -1) {
295                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
296                 if (i.isValid())
297                         p->setCurrentIndex(i.row());
298         }
299
300         // Workaround to resize to content size
301         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
302         //        does not help.
303         if (p->view()->isVisible()) {
304                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
305                 // the hack in the item delegate to make space for the headers.
306                 // We do not call our implementation of showPopup because that
307                 // would reset the filter again. This is only needed if the user clicks
308                 // on the QComboBox.
309                 LASSERT(!inShowPopup_, /**/);
310                 inShowPopup_ = true;
311                 p->QComboBox::showPopup();
312                 inShowPopup_ = false;
313         }
314
315         p->view()->setUpdatesEnabled(enabled);
316 }
317
318
319 CategorizedCombo::CategorizedCombo(QWidget * parent)
320         : QComboBox(parent), d(new Private(this))
321 {
322         setSizeAdjustPolicy(QComboBox::AdjustToContents);
323         setMinimumWidth(sizeHint().width());
324         setMaxVisibleItems(100);
325
326         setModel(d->filterModel_);
327
328         // for the filtering we have to intercept characters
329         view()->installEventFilter(this);
330         view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
331
332         updateCombo();
333 }
334
335
336 CategorizedCombo::~CategorizedCombo() {
337         delete d;
338 }
339
340
341 void CategorizedCombo::Private::countCategories()
342 {
343         int n = filterModel_->rowCount();
344         visibleCategories_ = 0;
345         if (n == 0)
346                 return;
347
348         QString prevCat = model_->index(0, 2).data().toString();
349
350         // count categories
351         for (int i = 1; i < n; ++i) {
352                 QString cat = filterModel_->index(i, 2).data().toString();
353                 if (cat != prevCat)
354                         ++visibleCategories_;
355                 prevCat = cat;
356         }
357 }
358
359
360 void CategorizedCombo::showPopup()
361 {
362         bool enabled = view()->updatesEnabled();
363         view()->setUpdatesEnabled(false);
364
365         d->resetFilter();
366
367         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
368         // the hack in the item delegate to make space for the headers.
369         LASSERT(!d->inShowPopup_, /**/);
370         d->inShowPopup_ = true;
371         QComboBox::showPopup();
372         d->inShowPopup_ = false;
373
374         view()->setUpdatesEnabled(enabled);
375 }
376
377
378 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
379 {
380         if (e->type() != QEvent::KeyPress)
381                 return QComboBox::eventFilter(o, e);
382
383         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
384         bool modified = (ke->modifiers() == Qt::ControlModifier)
385                 || (ke->modifiers() == Qt::AltModifier)
386                 || (ke->modifiers() == Qt::MetaModifier);
387
388         switch (ke->key()) {
389         case Qt::Key_Escape:
390                 if (!modified && !d->filter_.isEmpty()) {
391                         d->resetFilter();
392                         return true;
393                 }
394                 break;
395         case Qt::Key_Backspace:
396                 if (!modified) {
397                         // cut off one character
398                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
399                 }
400                 break;
401         default:
402                 if (modified || ke->text().isEmpty())
403                         break;
404                 // find chars for the filter string
405                 QString s;
406                 for (int i = 0; i < ke->text().length(); ++i) {
407                         QChar c = ke->text()[i];
408                         if (c.isLetterOrNumber()
409                             || c.isSymbol()
410                             || c.isPunct()
411                             || c.category() == QChar::Separator_Space) {
412                                 s += c;
413                         }
414                 }
415                 if (!s.isEmpty()) {
416                         // append new chars to the filter string
417                         d->setFilter(d->filter_ + s);
418                         return true;
419                 }
420                 break;
421         }
422
423         return QComboBox::eventFilter(o, e);
424 }
425
426
427 void CategorizedCombo::setIconSize(QSize size)
428 {
429 #ifdef Q_OS_MAC
430         bool small = size.height() < 20;
431         setAttribute(Qt::WA_MacSmallSize, small);
432         setAttribute(Qt::WA_MacNormalSize, !small);
433 #else
434         (void)size; // suppress warning
435 #endif
436 }
437
438
439 bool CategorizedCombo::set(QString const & item)
440 {
441         d->resetFilter();
442
443         int const curItem = currentIndex();
444         QModelIndex const mindex =
445                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
446         QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
447         if (item == currentItem) {
448                 LYXERR(Debug::GUI, "Already had " << item << " selected.");
449                 return true;
450         }
451
452         QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
453         if (r.empty()) {
454                 LYXERR0("Trying to select non existent layout type " << item);
455                 return false;
456         }
457
458         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
459         return true;
460 }
461
462
463 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
464                                    QString const & category, QString const & tooltip,
465                                    bool sorted, bool sortedByCat, bool sortCats,
466                                    bool available)
467 {
468         QString titem = available ? guiname
469                                   : toqstr(bformat(_("Unavailable: %1$s"),
470                                                    qstring_to_ucs4(guiname)));
471         bool const uncategorized = category.isEmpty();
472         QString qcat = uncategorized ? qt_("Uncategorized") : category;
473
474         QList<QStandardItem *> row;
475         QStandardItem * gui = new QStandardItem(titem);
476         if (!tooltip.isEmpty())
477                 gui->setToolTip(tooltip);
478         row.append(gui);
479         row.append(new QStandardItem(item));
480         row.append(new QStandardItem(qcat));
481         row.append(new QStandardItem(available));
482
483         // the first entry is easy
484         int const end = d->model_->rowCount();
485         if (end == 0) {
486                 d->model_->appendRow(row);
487                 return;
488         }
489
490         // find category
491         int i = 0;
492         if (sortedByCat) {
493                 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
494                 while (i < end && d->model_->item(i, 2)->text() != qcat
495                        && (!sortCats
496                            || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
497                                && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
498                            || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
499                         ++i;
500         }
501
502         // the simple unsorted case
503         if (!sorted) {
504                 if (sortedByCat) {
505                         // jump to the end of the category group
506                         while (i < end && d->model_->item(i, 2)->text() == qcat)
507                                 ++i;
508                         d->model_->insertRow(i, row);
509                 } else
510                         d->model_->appendRow(row);
511                 return;
512         }
513
514         // find row to insert the item, after the separator if it exists
515         if (i < end) {
516                 // find alphabetic position, unavailable at the end
517                 while (i != end
518                        && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
519                            || ((!available && d->model_->item(i, 3))
520                                || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
521                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
522                         ++i;
523         }
524
525         d->model_->insertRow(i, row);
526 }
527
528
529 QString CategorizedCombo::getData(int row) const
530 {
531         int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
532         return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
533 }
534
535
536 void CategorizedCombo::reset()
537 {
538         d->resetFilter();
539         d->model_->clear();
540 }
541
542 void CategorizedCombo::resetFilter()
543 {
544         d->resetFilter();
545 }
546
547
548 void CategorizedCombo::updateCombo()
549 {
550         d->countCategories();
551
552         // needed to recalculate size hint
553         hide();
554         setMinimumWidth(sizeHint().width());
555         show();
556 }
557
558
559 QString const & CategorizedCombo::filter() const
560 {
561         return d->filter_;
562 }
563
564 } // namespace frontend
565 } // namespace lyx
566
567
568 #include "moc_CategorizedCombo.cpp"