]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/CategorizedCombo.cpp
Refactor
[lyx.git] / src / frontends / qt4 / CategorizedCombo.cpp
1 /**
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.
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;
53         ///
54         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
55                 const QRect & /*rect*/, const QString & text ) const;
56         ///
57         QSize sizeHint(QStyleOptionViewItem const & opt,
58                 QModelIndex const & index) const;
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 = 0)
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 (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
157                 painter->save();
158
159                 // draw unselected background
160                 QStyle::State state = opt.state;
161                 opt.state = opt.state & ~QStyle::State_Selected;
162                 drawBackground(painter, opt, index);
163                 opt.state = state;
164
165                 // draw category header
166                 drawCategoryHeader(painter, opt,
167                         categoryCC(*index.model(), index.row()));
168
169                 // move rect down below header
170                 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
171
172                 painter->restore();
173         }
174
175         QItemDelegate::paint(painter, opt, index);
176 }
177
178
179 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
180                                  const QRect & /*rect*/, const QString & text) const
181 {
182         QString utext = underlineFilter(text);
183
184         // Draw the rich text.
185         painter->save();
186         QColor col = opt.palette.text().color();
187         // grey out unavailable items
188         if (text.startsWith(qt_("Unavailable:")))
189                 col = opt.palette.color(QPalette::Disabled, QPalette::Text);
190         if (opt.state & QStyle::State_Selected)
191                 col = opt.palette.highlightedText().color();
192         QAbstractTextDocumentLayout::PaintContext context;
193         context.palette.setColor(QPalette::Text, col);
194
195         QTextDocument doc;
196         doc.setDefaultFont(opt.font);
197         doc.setHtml(utext);
198
199         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
200         fmt.setMargin(0);
201         doc.rootFrame()->setFrameFormat(fmt);
202
203         painter->translate(opt.rect.x() + 5,
204                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
205         doc.documentLayout()->draw(painter, context);
206         painter->restore();
207 }
208
209
210 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
211                                QModelIndex const & index) const
212 {
213         QSize size = QItemDelegate::sizeHint(opt, index);
214
215         /// QComboBox uses the first row height to estimate the
216         /// complete popup height during QComboBox::showPopup().
217         /// To avoid scrolling we have to sneak in space for the headers.
218         /// So we tweak this value accordingly. It's not nice, but the
219         /// only possible way it seems.
220         // Add space for the category headers here
221         QString cat = categoryCC(*index.model(), index.row());
222         if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
223                 size.setHeight(size.height() + headerHeightCC(opt));
224         }
225
226         return size;
227 }
228
229
230 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
231                                         QString const & category) const
232 {
233         // slightly blended color
234         QColor lcol = opt.palette.text().color();
235         lcol.setAlpha(127);
236         painter->setPen(lcol);
237
238         // set 80% scaled, bold font
239         QFont font = opt.font;
240         font.setBold(true);
241         font.setWeight(QFont::Black);
242         font.setPointSize(opt.font.pointSize() * 8 / 10);
243         painter->setFont(font);
244
245         // draw the centered text
246         QFontMetrics fm(font);
247         int w = fm.width(category);
248         int x = opt.rect.x() + (opt.rect.width() - w) / 2;
249         int y = opt.rect.y() + 3 * fm.ascent() / 2;
250         int left = x;
251         int right = x + w;
252         painter->drawText(x, y, category);
253
254         // the vertical position of the line: middle of lower case chars
255         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
256
257         // draw the horizontal line
258         if (!category.isEmpty()) {
259                 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
260                 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
261         } else
262                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
263 }
264
265
266 QString CCItemDelegate::underlineFilter(QString const & s) const
267 {
268         QString const & f = cc_->filter();
269         if (f.isEmpty())
270                 return s;
271
272         // step through data item and put "(x)" for every matching character
273         QString r;
274         int lastp = -1;
275         for (int i = 0; i < f.length(); ++i) {
276                 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
277                 if (p < 0)
278                         continue;
279                 if (lastp == p - 1 && lastp != -1) {
280                         // remove ")" and append "x)"
281                         r = r.left(r.length() - 4) + s[p] + "</u>";
282                 } else {
283                         // append "(x)"
284                         r += s.mid(lastp + 1, p - lastp - 1);
285                         r += QString("<u>") + s[p] + "</u>";
286                 }
287                 lastp = p;
288         }
289         r += s.mid(lastp + 1);
290         return r;
291 }
292
293
294 void CategorizedCombo::Private::setFilter(QString const & s)
295 {
296         bool enabled = p->view()->updatesEnabled();
297         p->view()->setUpdatesEnabled(false);
298
299         // remember old selection
300         int sel = p->currentIndex();
301         if (sel != -1)
302                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
303
304         filter_ = s;
305     filterModel_->setFilterRegExp(charFilterRegExp(filter_));
306         countCategories();
307
308         // restore old selection
309         if (lastSel_ != -1) {
310                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
311                 if (i.isValid())
312                         p->setCurrentIndex(i.row());
313         }
314
315         // Workaround to resize to content size
316         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
317         //        does not help.
318         if (p->view()->isVisible()) {
319                 // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
320                 // the hack in the item delegate to make space for the headers.
321                 // We do not call our implementation of showPopup because that
322                 // would reset the filter again. This is only needed if the user clicks
323                 // on the QComboBox.
324                 LASSERT(!inShowPopup_, /**/);
325                 inShowPopup_ = true;
326                 p->QComboBox::showPopup();
327                 inShowPopup_ = false;
328         }
329
330         p->view()->setUpdatesEnabled(enabled);
331 }
332
333
334 CategorizedCombo::CategorizedCombo(QWidget * parent)
335         : QComboBox(parent), d(new Private(this))
336 {
337         setSizeAdjustPolicy(QComboBox::AdjustToContents);
338         setMinimumWidth(sizeHint().width());
339         setMaxVisibleItems(100);
340
341         setModel(d->filterModel_);
342
343         // for the filtering we have to intercept characters
344         view()->installEventFilter(this);
345         view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
346
347         updateCombo();
348 }
349
350
351 CategorizedCombo::~CategorizedCombo() {
352         delete d;
353 }
354
355
356 void CategorizedCombo::Private::countCategories()
357 {
358         int n = filterModel_->rowCount();
359         visibleCategories_ = 0;
360         if (n == 0)
361                 return;
362
363         QString prevCat = model_->index(0, 2).data().toString();
364
365         // count categories
366         for (int i = 1; i < n; ++i) {
367                 QString cat = filterModel_->index(i, 2).data().toString();
368                 if (cat != prevCat)
369                         ++visibleCategories_;
370                 prevCat = cat;
371         }
372 }
373
374
375 void CategorizedCombo::showPopup()
376 {
377         bool enabled = view()->updatesEnabled();
378         view()->setUpdatesEnabled(false);
379
380         d->resetFilter();
381
382         // call QComboBox::showPopup. But set the inShowPopup_ flag to switch on
383         // the hack in the item delegate to make space for the headers.
384         LASSERT(!d->inShowPopup_, /**/);
385         d->inShowPopup_ = true;
386         QComboBox::showPopup();
387         d->inShowPopup_ = false;
388
389         view()->setUpdatesEnabled(enabled);
390 }
391
392
393 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
394 {
395         if (e->type() != QEvent::KeyPress)
396                 return QComboBox::eventFilter(o, e);
397
398         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
399         bool modified = (ke->modifiers() == Qt::ControlModifier)
400                 || (ke->modifiers() == Qt::AltModifier)
401                 || (ke->modifiers() == Qt::MetaModifier);
402
403         switch (ke->key()) {
404         case Qt::Key_Escape:
405                 if (!modified && !d->filter_.isEmpty()) {
406                         d->resetFilter();
407                         return true;
408                 }
409                 break;
410         case Qt::Key_Backspace:
411                 if (!modified) {
412                         // cut off one character
413                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
414                 }
415                 break;
416         default:
417                 if (modified || ke->text().isEmpty())
418                         break;
419                 // find chars for the filter string
420                 QString s;
421                 for (int i = 0; i < ke->text().length(); ++i) {
422                         QChar c = ke->text()[i];
423                         if (c.isLetterOrNumber()
424                             || c.isSymbol()
425                             || c.isPunct()
426                             || c.category() == QChar::Separator_Space) {
427                                 s += c;
428                         }
429                 }
430                 if (!s.isEmpty()) {
431                         // append new chars to the filter string
432                         d->setFilter(d->filter_ + s);
433                         return true;
434                 }
435                 break;
436         }
437
438         return QComboBox::eventFilter(o, e);
439 }
440
441
442 void CategorizedCombo::setIconSize(QSize size)
443 {
444 #ifdef Q_OS_MAC
445         bool small = size.height() < 20;
446         setAttribute(Qt::WA_MacSmallSize, small);
447         setAttribute(Qt::WA_MacNormalSize, !small);
448 #else
449         (void)size; // suppress warning
450 #endif
451 }
452
453
454 bool CategorizedCombo::set(QString const & item)
455 {
456         d->resetFilter();
457
458         int const curItem = currentIndex();
459         QModelIndex const mindex =
460                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
461         QString const & currentItem = d->model_->itemFromIndex(mindex)->text();
462         if (item == currentItem) {
463                 LYXERR(Debug::GUI, "Already had " << item << " selected.");
464                 return true;
465         }
466
467         QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
468         if (r.empty()) {
469                 LYXERR0("Trying to select non existent layout type " << item);
470                 return false;
471         }
472
473         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
474         return true;
475 }
476
477
478 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
479                                    QString const & category, QString const & tooltip,
480                                    bool sorted, bool sortedByCat, bool sortCats,
481                                    bool available)
482 {
483         QString titem = available ? guiname
484                                   : toqstr(bformat(_("Unavailable: %1$s"),
485                                                    qstring_to_ucs4(guiname)));
486         bool const uncategorized = category.isEmpty();
487         QString qcat = uncategorized ? qt_("Uncategorized") : category;
488
489         QList<QStandardItem *> row;
490         QStandardItem * gui = new QStandardItem(titem);
491         if (!tooltip.isEmpty())
492                 gui->setToolTip(tooltip);
493         row.append(gui);
494         row.append(new QStandardItem(item));
495         row.append(new QStandardItem(qcat));
496         row.append(new QStandardItem(available));
497
498         // the first entry is easy
499         int const end = d->model_->rowCount();
500         if (end == 0) {
501                 d->model_->appendRow(row);
502                 return;
503         }
504
505         // find category
506         int i = 0;
507         if (sortedByCat) {
508                 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
509                 while (i < end && d->model_->item(i, 2)->text() != qcat
510                        && (!sortCats
511                            || (!uncategorized && d->model_->item(i, 2)->text().localeAwareCompare(qcat) < 0
512                                && d->model_->item(i, 2)->text() != qt_("Uncategorized"))
513                            || (uncategorized && d->model_->item(i, 2)->text() != qt_("Uncategorized"))))
514                         ++i;
515         }
516
517         // the simple unsorted case
518         if (!sorted) {
519                 if (sortedByCat) {
520                         // jump to the end of the category group
521                         while (i < end && d->model_->item(i, 2)->text() == qcat)
522                                 ++i;
523                         d->model_->insertRow(i, row);
524                 } else
525                         d->model_->appendRow(row);
526                 return;
527         }
528
529         // find row to insert the item, after the separator if it exists
530         if (i < end) {
531                 // find alphabetic position, unavailable at the end
532                 while (i != end
533                        && ((available && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0)
534                            || ((!available && d->model_->item(i, 3))
535                                || d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0))
536                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
537                         ++i;
538         }
539
540         d->model_->insertRow(i, row);
541 }
542
543
544 QString CategorizedCombo::getData(int row) const
545 {
546         int srow = d->filterModel_->mapToSource(d->filterModel_->index(row, 1)).row();
547         return d->model_->data(d->model_->index(srow, 1), Qt::DisplayRole).toString();
548 }
549
550
551 void CategorizedCombo::reset()
552 {
553         d->resetFilter();
554         d->model_->clear();
555 }
556
557
558 void CategorizedCombo::updateCombo()
559 {
560         d->countCategories();
561
562         // needed to recalculate size hint
563         hide();
564         setMinimumWidth(sizeHint().width());
565         show();
566 }
567
568
569 QString const & CategorizedCombo::filter() const
570 {
571         return d->filter_;
572 }
573
574 } // namespace frontend
575 } // namespace lyx
576
577
578 #include "moc_CategorizedCombo.cpp"