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