]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/CategorizedCombo.cpp
#9245 replace Q_WS_MACX with Q_OS_MAC - the Q_OS_MAC macro is usable with Qt4 and...
[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
28 #include <QAbstractTextDocumentLayout>
29 #include <QComboBox>
30 #include <QHeaderView>
31 #include <QItemDelegate>
32 #include <QPainter>
33 #include <QSortFilterProxyModel>
34 #include <QStandardItemModel>
35 #include <QTextFrame>
36
37 using namespace lyx::support;
38
39 namespace lyx {
40 namespace frontend {
41
42
43 class CCItemDelegate : public QItemDelegate {
44 public:
45         ///
46         explicit CCItemDelegate(CategorizedCombo * cc)
47                 : QItemDelegate(cc), cc_(cc)
48         {}
49         ///
50         void paint(QPainter * painter, QStyleOptionViewItem const & option,
51                 QModelIndex const & index) const;
52         ///
53         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
54                 const QRect & /*rect*/, const QString & text ) const;
55         ///
56         QSize sizeHint(QStyleOptionViewItem const & opt,
57                 QModelIndex const & index) const;
58         
59 private:
60         ///
61         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
62                 QString const & category) const;        
63         ///
64         QString underlineFilter(QString const & s) const;
65         ///
66         CategorizedCombo * cc_;
67 };
68
69
70 class CCFilterModel : public QSortFilterProxyModel {
71 public:
72         ///
73         CCFilterModel(QObject * parent = 0)
74                 : QSortFilterProxyModel(parent)
75         {}
76 };
77
78
79 /////////////////////////////////////////////////////////////////////
80 //
81 // CategorizedCombo::Private
82 //
83 /////////////////////////////////////////////////////////////////////
84
85 struct CategorizedCombo::Private
86 {
87         Private(CategorizedCombo * parent) : p(parent),
88                 // set the model with four columns
89                 // 1st: translated item names
90                 // 2nd: raw names
91                 // 3rd: category
92                 // 4th: availability (bool)
93                 model_(new QStandardItemModel(0, 4, p)),
94                 filterModel_(new CCFilterModel(p)),
95                 lastSel_(-1),
96                 CCItemDelegate_(new CCItemDelegate(parent)),
97                 visibleCategories_(0), inShowPopup_(false)
98         {
99                 filterModel_->setSourceModel(model_);
100         }
101
102         void resetFilter() { setFilter(QString()); }
103         ///
104         void setFilter(QString const & s);
105         ///
106         void countCategories();
107         ///
108         CategorizedCombo * p;
109         
110         /** the layout model: 
111          * 1st column: translated GUI name,
112          * 2nd column: raw item name,
113          * 3rd column: category,
114          * 4th column: availability
115         **/
116         QStandardItemModel * model_;
117         /// the proxy model filtering \c model_
118         CCFilterModel * filterModel_;
119         /// the (model-) index of the last successful selection
120         int lastSel_;
121         /// the character filter
122         QString filter_;
123         ///
124         CCItemDelegate * CCItemDelegate_;
125         ///
126         unsigned visibleCategories_;
127         ///
128         bool inShowPopup_;
129 };
130
131
132 static QString categoryCC(QAbstractItemModel const & model, int row)
133 {
134         return model.data(model.index(row, 2), Qt::DisplayRole).toString();
135 }
136
137
138 static int headerHeightCC(QStyleOptionViewItem const & opt)
139 {
140         return opt.fontMetrics.height();
141 }
142
143
144 void CCItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
145                            QModelIndex const & index) const
146 {
147         QStyleOptionViewItem opt = option;
148
149         // default background
150         painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
151
152         QString cat = categoryCC(*index.model(), index.row());
153
154         // not the same as in the previous line?
155         if (index.row() == 0 || cat != categoryCC(*index.model(), index.row() - 1)) {
156                 painter->save();
157
158                 // draw unselected background
159                 QStyle::State state = opt.state;
160                 opt.state = opt.state & ~QStyle::State_Selected;
161                 drawBackground(painter, opt, index);
162                 opt.state = state;
163
164                 // draw category header
165                 drawCategoryHeader(painter, opt, 
166                         categoryCC(*index.model(), index.row()));
167
168                 // move rect down below header
169                 opt.rect.setTop(opt.rect.top() + headerHeightCC(opt));
170
171                 painter->restore();
172         }
173
174         QItemDelegate::paint(painter, opt, index);
175 }
176
177
178 void CCItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
179                                  const QRect & /*rect*/, const QString & text) const
180 {
181         QString utext = underlineFilter(text);
182
183         // Draw the rich text.
184         painter->save();
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);
193
194         QTextDocument doc;
195         doc.setDefaultFont(opt.font);
196         doc.setHtml(utext);
197
198         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
199         fmt.setMargin(0);
200         doc.rootFrame()->setFrameFormat(fmt);
201
202         painter->translate(opt.rect.x() + 5,
203                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
204         doc.documentLayout()->draw(painter, context);
205         painter->restore();
206 }
207
208
209 QSize CCItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
210                                QModelIndex const & index) const
211 {
212         QSize size = QItemDelegate::sizeHint(opt, index);
213
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));
223         }
224
225         return size;
226 }
227
228
229 void CCItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
230                                         QString const & category) const
231 {
232         // slightly blended color
233         QColor lcol = opt.palette.text().color();
234         lcol.setAlpha(127);
235         painter->setPen(lcol);
236
237         // set 80% scaled, bold font
238         QFont font = opt.font;
239         font.setBold(true);
240         font.setWeight(QFont::Black);
241         font.setPointSize(opt.font.pointSize() * 8 / 10);
242         painter->setFont(font);
243
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() + 1.5 * fm.ascent();
249         int left = x;
250         int right = x + w;
251         painter->drawText(x, y, category);
252
253         // the vertical position of the line: middle of lower case chars
254         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
255
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);
260         } else
261                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
262 }
263
264
265 QString CCItemDelegate::underlineFilter(QString const & s) const
266 {
267         QString const & f = cc_->filter();
268         if (f.isEmpty())
269                 return s;
270
271         // step through data item and put "(x)" for every matching character
272         QString r;
273         int lastp = -1;
274         cc_->filter();
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>";
281                 } else {
282                         // append "(x)"
283                         r += s.mid(lastp + 1, p - lastp - 1);
284                         r += QString("<u>") + s[p] + "</u>";
285                 }
286                 lastp = p;
287         }
288         r += s.mid(lastp + 1);
289         return r;
290 }
291
292
293 static QString charFilterRegExpCC(QString const & filter)
294 {
295         QString re;
296         for (int i = 0; i < filter.length(); ++i) {
297                 QChar c = filter[i];
298                 if (c.isLower())
299                         re += ".*[" + QRegExp::escape(c) + QRegExp::escape(c.toUpper()) + "]";
300                 else
301                         re += ".*" + QRegExp::escape(c);
302         }
303         return re;
304 }
305
306
307 void CategorizedCombo::Private::setFilter(QString const & s)
308 {
309         bool enabled = p->view()->updatesEnabled();
310         p->view()->setUpdatesEnabled(false);
311
312         // remember old selection
313         int sel = p->currentIndex();
314         if (sel != -1)
315                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
316
317         filter_ = s;
318         filterModel_->setFilterRegExp(charFilterRegExpCC(filter_));
319         countCategories();
320         
321         // restore old selection
322         if (lastSel_ != -1) {
323                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
324                 if (i.isValid())
325                         p->setCurrentIndex(i.row());
326         }
327         
328         // Workaround to resize to content size
329         // FIXME: There must be a better way. The QComboBox::AdjustToContents)
330         //        does not help.
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
336                 // on the QComboBox.
337                 LASSERT(!inShowPopup_, /**/);
338                 inShowPopup_ = true;
339                 p->QComboBox::showPopup();
340                 inShowPopup_ = false;
341         }
342         
343         p->view()->setUpdatesEnabled(enabled);
344 }
345
346
347 CategorizedCombo::CategorizedCombo(QWidget * parent)
348         : QComboBox(parent), d(new Private(this))
349 {
350         setSizeAdjustPolicy(QComboBox::AdjustToContents);
351         setFocusPolicy(Qt::ClickFocus);
352         setMinimumWidth(sizeHint().width());
353         setMaxVisibleItems(100);
354
355         setModel(d->filterModel_);
356
357         // for the filtering we have to intercept characters
358         view()->installEventFilter(this);
359         view()->setItemDelegateForColumn(0, d->CCItemDelegate_);
360         
361         updateCombo();
362 }
363
364
365 CategorizedCombo::~CategorizedCombo() {
366         delete d;
367 }
368
369
370 void CategorizedCombo::Private::countCategories()
371 {
372         int n = filterModel_->rowCount();
373         visibleCategories_ = 0;
374         if (n == 0)
375                 return;
376
377         QString prevCat = model_->index(0, 2).data().toString(); 
378
379         // count categories
380         for (int i = 1; i < n; ++i) {
381                 QString cat = filterModel_->index(i, 2).data().toString();
382                 if (cat != prevCat)
383                         ++visibleCategories_;
384                 prevCat = cat;
385         }
386 }
387
388
389 void CategorizedCombo::showPopup()
390 {
391         bool enabled = view()->updatesEnabled();
392         view()->setUpdatesEnabled(false);
393
394         d->resetFilter();
395
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;
402
403         view()->setUpdatesEnabled(enabled);
404 }
405
406
407 bool CategorizedCombo::eventFilter(QObject * o, QEvent * e)
408 {
409         if (e->type() != QEvent::KeyPress)
410                 return QComboBox::eventFilter(o, e);
411
412         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
413         bool modified = (ke->modifiers() == Qt::ControlModifier)
414                 || (ke->modifiers() == Qt::AltModifier)
415                 || (ke->modifiers() == Qt::MetaModifier);
416         
417         switch (ke->key()) {
418         case Qt::Key_Escape:
419                 if (!modified && !d->filter_.isEmpty()) {
420                         d->resetFilter();
421                         return true;
422                 }
423                 break;
424         case Qt::Key_Backspace:
425                 if (!modified) {
426                         // cut off one character
427                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
428                 }
429                 break;
430         default:
431                 if (modified || ke->text().isEmpty())
432                         break;
433                 // find chars for the filter string
434                 QString s;
435                 for (int i = 0; i < ke->text().length(); ++i) {
436                         QChar c = ke->text()[i];
437                         if (c.isLetterOrNumber()
438                             || c.isSymbol()
439                             || c.isPunct()
440                             || c.category() == QChar::Separator_Space) {
441                                 s += c;
442                         }
443                 }
444                 if (!s.isEmpty()) {
445                         // append new chars to the filter string
446                         d->setFilter(d->filter_ + s);
447                         return true;
448                 }
449                 break;
450         }
451
452         return QComboBox::eventFilter(o, e);
453 }
454
455
456 void CategorizedCombo::setIconSize(QSize size)
457 {
458 #ifdef Q_OS_MAC
459         bool small = size.height() < 20;
460         setAttribute(Qt::WA_MacSmallSize, small);
461         setAttribute(Qt::WA_MacNormalSize, !small);
462 #else
463         (void)size; // suppress warning
464 #endif
465 }
466
467
468 bool CategorizedCombo::set(QString const & item)
469 {
470         d->resetFilter();
471
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.");
478                 return true;
479         }
480
481         QList<QStandardItem *> r = d->model_->findItems(item, Qt::MatchExactly, 1);
482         if (r.empty()) {
483                 LYXERR0("Trying to select non existent layout type " << item);
484                 return false;
485         }
486
487         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
488         return true;
489 }
490
491
492 void CategorizedCombo::addItemSort(QString const & item, QString const & guiname,
493                                    QString const & category, QString const & tooltip,
494                                    bool sorted, bool sortedByCat, bool sortCats,
495                                    bool available)
496 {
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;
502
503         QList<QStandardItem *> row;
504         QStandardItem * gui = new QStandardItem(titem);
505         if (!tooltip.isEmpty())
506                 gui->setToolTip(tooltip);
507         row.append(gui);
508         row.append(new QStandardItem(item));
509         row.append(new QStandardItem(qcat));
510         row.append(new QStandardItem(available));
511
512         // the first entry is easy
513         int const end = d->model_->rowCount();
514         if (end == 0) {
515                 d->model_->appendRow(row);
516                 return;
517         }
518
519         // find category
520         int i = 0;
521         if (sortedByCat) {
522                 // If sortCats == true, sort categories alphabetically, uncategorized at the end.
523                 while (i < end && d->model_->item(i, 2)->text() != qcat
524                        && (!sortCats 
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"))))
528                         ++i;
529         }
530
531         // the simple unsorted case
532         if (!sorted) {
533                 if (sortedByCat) {
534                         // jump to the end of the category group
535                         while (i < end && d->model_->item(i, 2)->text() == qcat)
536                                 ++i;
537                         d->model_->insertRow(i, row);
538                 } else
539                         d->model_->appendRow(row);
540                 return;
541         }
542
543         // find row to insert the item, after the separator if it exists
544         if (i < end) {
545                 // find alphabetic position, unavailable at the end
546                 while (i != 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))
551                         ++i;
552         }
553
554         d->model_->insertRow(i, row);
555 }
556
557
558 QString CategorizedCombo::getData(int row) const
559 {
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();
562 }
563
564
565 void CategorizedCombo::reset()
566 {
567         d->resetFilter();
568         d->model_->clear();
569 }
570
571
572 void CategorizedCombo::updateCombo()
573 {
574         d->countCategories();
575         
576         // needed to recalculate size hint
577         hide();
578         setMinimumWidth(sizeHint().width());
579         show();
580 }
581
582
583 QString const & CategorizedCombo::filter() const
584 {
585         return d->filter_;
586 }
587
588 }  // namespace frontend
589 }  // namespace lyx
590
591
592 #include "moc_CategorizedCombo.cpp"