]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/CategorizedCombo.cpp
BiblioInfo: provide macro for ellipses
[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 #if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
291         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
292 #else
293         filterModel_->setFilterRegularExpression(charFilterRegExp(filter_));
294 #endif
295         countCategories();
296
297         // restore old selection
298         if (lastSel_ != -1) {
299                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
300                 if (i.isValid())
301                         p->setCurrentIndex(i.row());
302         }
303
304         // Workaround to resize to content size
305         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
306         //        does not help.
307         if (p->view()->isVisible()) {
308                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
309                 // the hack in the item delegate to make space for the headers.
310                 // We do not call our implementation of showPopup because that
311                 // would reset the filter again. This is only needed if the user clicks
312                 // on the QComboBox.
313                 LASSERT(!inShowPopup_, /**/);
314                 inShowPopup_ = true;
315                 p->QComboBox::showPopup();
316                 inShowPopup_ = false;
317         }
318
319         p->view()->setUpdatesEnabled(enabled);
320 }
321
322
323 CategorizedCombo::CategorizedCombo(QWidget * parent)
324         : QComboBox(parent), d(new Private(this))
325 {
326         setSizeAdjustPolicy(QComboBox::AdjustToContents);
327         setMinimumWidth(sizeHint().width());
328         setMaxVisibleItems(100);
329
330         setModel(d->filterModel_);
331
332         // for the filtering we have to intercept characters
333         view()->installEventFilter(this);
334         view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
335
336         updateCombo();
337 }
338
339
340 CategorizedCombo::~CategorizedCombo() {
341         delete d;
342 }
343
344
345 void CategorizedCombo::Private::countCategories()
346 {
347         int n = filterModel_->rowCount();
348         visibleCategories_ = 0;
349         if (n == 0)
350                 return;
351
352         QString prevCat = model_->index(0, 2).data().toString();
353
354         // count categories
355         for (int i = 1; i < n; ++i) {
356                 QString cat = filterModel_->index(i, 2).data().toString();
357                 if (cat != prevCat)
358                         ++visibleCategories_;
359                 prevCat = cat;
360         }
361 }
362
363
364 void CategorizedCombo::showPopup()
365 {
366         lastCurrentIndex_ = currentIndex();
367         bool enabled = view()->updatesEnabled();
368         view()->setUpdatesEnabled(false);
369
370         d->resetFilter();
371
372         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
373         // the hack in the item delegate to make space for the headers.
374         LASSERT(!d->inShowPopup_, /**/);
375         d->inShowPopup_ = true;
376         QComboBox::showPopup();
377         d->inShowPopup_ = false;
378
379         view()->setUpdatesEnabled(enabled);
380 }
381
382
383 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
384 {
385         if (e->type() != QEvent::KeyPress)
386                 return QComboBox::eventFilter(o, e);
387
388         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
389         bool modified = (ke->modifiers() == Qt::ControlModifier)
390                 || (ke->modifiers() == Qt::AltModifier)
391                 || (ke->modifiers() == Qt::MetaModifier);
392
393         switch (ke->key()) {
394         case Qt::Key_Escape:
395                 if (!modified && !d->filter_.isEmpty()) {
396                         d->resetFilter();
397                         setCurrentIndex(lastCurrentIndex_);
398                         return true;
399                 }
400                 break;
401         case Qt::Key_Backspace:
402                 if (!modified) {
403                         // cut off one character
404                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
405                 }
406                 break;
407         default:
408                 if (modified || ke->text().isEmpty())
409                         break;
410                 // find chars for the filter string
411                 QString s;
412                 for (int i = 0; i < ke->text().length(); ++i) {
413                         QChar c = ke->text()[i];
414                         if (c.isLetterOrNumber()
415                             || c.isSymbol()
416                             || c.isPunct()
417                             || c.category() == QChar::Separator_Space) {
418                                 s += c;
419                         }
420                 }
421                 if (!s.isEmpty()) {
422                         // append new chars to the filter string
423                         d->setFilter(d->filter_ + s);
424                         return true;
425                 }
426                 break;
427         }
428
429         return QComboBox::eventFilter(o, e);
430 }
431
432
433 void CategorizedCombo::setIconSize(QSize size)
434 {
435 #ifdef Q_OS_MAC
436         bool small = size.height() < 20;
437         setAttribute(Qt::WA_MacSmallSize, small);
438         setAttribute(Qt::WA_MacNormalSize, !small);
439 #else
440         (void)size; // suppress warning
441 #endif
442 }
443
444
445 bool CategorizedCombo::set(QString const & item, bool const report_missing)
446 {
447         d->resetFilter();
448
449         int const curItem = currentIndex();
450         QModelIndex const mindex =
451                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
452         QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
453         if (item == currentItem) {
454                 LYXERR(Debug::GUI, "Already had " << item << " selected.");
455                 return true;
456         }
457
458         QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
459         if (r.empty()) {
460                 if (report_missing)
461                         LYXERR0("Trying to select non existent layout type " << item);
462                 return false;
463         }
464
465         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
466         return true;
467 }
468
469
470 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
471                                    QString const & category, QString const & tooltip,
472                                    bool sorted, bool sortedByCat, bool sortCats,
473                                    bool available, bool nocategories)
474 {
475         QString titem = available ? guiname
476                                   : toqstr(bformat(_("Unavailable: %1$s"),
477                                                    qstring_to_ucs4(guiname)));
478         bool const uncategorized = category.isEmpty();
479         QString qcat = (uncategorized && !nocategories) ? qt_("Uncategorized") : category;
480
481         QList<QStandardItem *> row;
482         QStandardItem * gui = new QStandardItem(titem);
483         if (!tooltip.isEmpty())
484                 gui->setToolTip(tooltip);
485         row.append(gui);
486         row.append(new QStandardItem(item));
487         row.append(new QStandardItem(qcat));
488         row.append(new QStandardItem(available));
489
490         // the first entry is easy
491         int const end = d->model_->rowCount();
492         if (end == 0) {
493                 d->model_->appendRow(row);
494                 return;
495         }
496
497         // find category
498         int i = 0;
499         if (sortedByCat) {
500                 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
501                 while (i < end && d->model_->item(i, 2)->text() != qcat
502                        && (!sortCats
503                            || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
504                                && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
505                            || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
506                         ++i;
507         }
508
509         // the simple unsorted case
510         if (!sorted) {
511                 if (sortedByCat) {
512                         // jump to the end of the category group
513                         while (i < end && d->model_->item(i, 2)->text() == qcat)
514                                 ++i;
515                         d->model_->insertRow(i, row);
516                 } else
517                         d->model_->appendRow(row);
518                 return;
519         }
520
521         // find row to insert the item, after the separator if it exists
522         if (i < end) {
523                 // find alphabetic position, unavailable at the end
524                 while (i != end
525                        && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
526                            || ((!available && d->model_->item(i, 3))
527                                || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
528                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
529                         ++i;
530         }
531
532         d->model_->insertRow(i, row);
533 }
534
535
536 QString CategorizedCombo::getData(int row) const
537 {
538         int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
539         return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
540 }
541
542
543 void CategorizedCombo::reset()
544 {
545         d->resetFilter();
546         d->model_->clear();
547 }
548
549 void CategorizedCombo::resetFilter()
550 {
551         d->resetFilter();
552 }
553
554
555 void CategorizedCombo::updateCombo()
556 {
557         d->countCategories();
558
559         // needed to recalculate size hint
560         hide();
561         setMinimumWidth(sizeHint().width());
562         show();
563 }
564
565
566 QString const & CategorizedCombo::filter() const
567 {
568         return d->filter_;
569 }
570
571 } // namespace frontend
572 } // namespace lyx
573
574
575 #include "moc_CategorizedCombo.cpp"