]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/CategorizedCombo.cpp
Remove two remaining snippets from the QRegExp era.
[lyx.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         QRegularExpression 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_->setFilterRegularExpression(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         lastCurrentIndex_ = currentIndex();
363         bool enabled = view()->updatesEnabled();
364         view()->setUpdatesEnabled(false);
365
366         d->resetFilter();
367
368         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
369         // the hack in the item delegate to make space for the headers.
370         LASSERT(!d->inShowPopup_, /**/);
371         d->inShowPopup_ = true;
372         QComboBox::showPopup();
373         d->inShowPopup_ = false;
374
375         view()->setUpdatesEnabled(enabled);
376 }
377
378
379 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
380 {
381         if (e->type() != QEvent::KeyPress)
382                 return QComboBox::eventFilter(o, e);
383
384         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
385         bool modified = (ke->modifiers() == Qt::ControlModifier)
386                 || (ke->modifiers() == Qt::AltModifier)
387                 || (ke->modifiers() == Qt::MetaModifier);
388
389         switch (ke->key()) {
390         case Qt::Key_Escape:
391                 if (!modified && !d->filter_.isEmpty()) {
392                         d->resetFilter();
393                         setCurrentIndex(lastCurrentIndex_);
394                         return true;
395                 }
396                 break;
397         case Qt::Key_Backspace:
398                 if (!modified) {
399                         // cut off one character
400                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
401                 }
402                 break;
403         default:
404                 if (modified || ke->text().isEmpty())
405                         break;
406                 // find chars for the filter string
407                 QString s;
408                 for (int i = 0; i < ke->text().length(); ++i) {
409                         QChar c = ke->text()[i];
410                         if (c.isLetterOrNumber()
411                             || c.isSymbol()
412                             || c.isPunct()
413                             || c.category() == QChar::Separator_Space) {
414                                 s += c;
415                         }
416                 }
417                 if (!s.isEmpty()) {
418                         // append new chars to the filter string
419                         d->setFilter(d->filter_ + s);
420                         return true;
421                 }
422                 break;
423         }
424
425         return QComboBox::eventFilter(o, e);
426 }
427
428
429 void CategorizedCombo::setIconSize(QSize size)
430 {
431 #ifdef Q_OS_MAC
432         bool small = size.height() < 20;
433         setAttribute(Qt::WA_MacSmallSize, small);
434         setAttribute(Qt::WA_MacNormalSize, !small);
435 #else
436         (void)size; // suppress warning
437 #endif
438 }
439
440
441 bool CategorizedCombo::set(QString const & item, bool const report_missing)
442 {
443         d->resetFilter();
444
445         int const curItem = currentIndex();
446         QModelIndex const mindex =
447                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
448         QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
449         if (item == currentItem) {
450                 LYXERR(Debug::GUI, "Already had " << item << " selected.");
451                 return true;
452         }
453
454         QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
455         if (r.empty()) {
456                 if (report_missing)
457                         LYXERR0("Trying to select non existent layout type " << item);
458                 return false;
459         }
460
461         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
462         return true;
463 }
464
465
466 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
467                                    QString const & category, QString const & tooltip,
468                                    bool sorted, bool sortedByCat, bool sortCats,
469                                    bool available, bool nocategories)
470 {
471         QString titem = available ? guiname
472                                   : toqstr(bformat(_("Unavailable: %1$s"),
473                                                    qstring_to_ucs4(guiname)));
474         bool const uncategorized = category.isEmpty();
475         QString qcat = (uncategorized && !nocategories) ? qt_("Uncategorized") : category;
476
477         QList<QStandardItem *> row;
478         QStandardItem * gui = new QStandardItem(titem);
479         if (!tooltip.isEmpty())
480                 gui->setToolTip(tooltip);
481         row.append(gui);
482         row.append(new QStandardItem(item));
483         row.append(new QStandardItem(qcat));
484         row.append(new QStandardItem(available));
485
486         // the first entry is easy
487         int const end = d->model_->rowCount();
488         if (end == 0) {
489                 d->model_->appendRow(row);
490                 return;
491         }
492
493         // find category
494         int i = 0;
495         if (sortedByCat) {
496                 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
497                 while (i < end && d->model_->item(i, 2)->text() != qcat
498                        && (!sortCats
499                            || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
500                                && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
501                            || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
502                         ++i;
503         }
504
505         // the simple unsorted case
506         if (!sorted) {
507                 if (sortedByCat) {
508                         // jump to the end of the category group
509                         while (i < end && d->model_->item(i, 2)->text() == qcat)
510                                 ++i;
511                         d->model_->insertRow(i, row);
512                 } else
513                         d->model_->appendRow(row);
514                 return;
515         }
516
517         // find row to insert the item, after the separator if it exists
518         if (i < end) {
519                 // find alphabetic position, unavailable at the end
520                 while (i != end
521                        && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
522                            || ((!available && d->model_->item(i, 3))
523                                || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
524                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
525                         ++i;
526         }
527
528         d->model_->insertRow(i, row);
529 }
530
531
532 QString CategorizedCombo::getData(int row) const
533 {
534         int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
535         return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
536 }
537
538
539 void CategorizedCombo::reset()
540 {
541         d->resetFilter();
542         d->model_->clear();
543 }
544
545 void CategorizedCombo::resetFilter()
546 {
547         d->resetFilter();
548 }
549
550
551 void CategorizedCombo::updateCombo()
552 {
553         d->countCategories();
554
555         // needed to recalculate size hint
556         hide();
557         setMinimumWidth(sizeHint().width());
558         show();
559 }
560
561
562 QString const & CategorizedCombo::filter() const
563 {
564         return d->filter_;
565 }
566
567 } // namespace frontend
568 } // namespace lyx
569
570
571 #include "moc_CategorizedCombo.cpp"