File: kextendableitemdelegate.cpp

package info (click to toggle)
kde4libs 4%3A4.14.2-5%2Bdeb8u2
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 82,428 kB
  • ctags: 99,415
  • sloc: cpp: 761,864; xml: 12,344; ansic: 6,295; java: 4,060; perl: 2,938; yacc: 2,507; python: 1,207; sh: 1,179; ruby: 337; lex: 278; makefile: 29
file content (451 lines) | stat: -rw-r--r-- 15,012 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* This file is part of the KDE libraries
    Copyright (C) 2006,2007 Andreas Hartmetz (ahartmetz@gmail.com)
    Copyright (C) 2008 Urs Wolfer (uwolfer @ kde.org)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "kextendableitemdelegate.h"

#include <QModelIndex>
#include <QScrollBar>
#include <QTreeView>
#include <QPainter>
#include <QApplication>


class KExtendableItemDelegate::Private {
public:
    Private(KExtendableItemDelegate *parent) :
        q(parent),
        stateTick(0),
        cachedStateTick(-1),
        cachedRow(-20), //Qt uses -1 for invalid indices
        extender(0),
        extenderHeight(0)

    {}

    void _k_extenderDestructionHandler(QObject *destroyed);
    void _k_verticalScroll();

    QSize maybeExtendedSize(const QStyleOptionViewItem &option, const QModelIndex &index) const;
    QModelIndex indexOfExtendedColumnInSameRow(const QModelIndex &index) const;
    void scheduleUpdateViewLayout();

    KExtendableItemDelegate *q;

    /**
     * Delete all active extenders
     */
    void deleteExtenders();

    //this will trigger a lot of auto-casting QModelIndex <-> QPersistentModelIndex
    QHash<QPersistentModelIndex, QWidget *> extenders;
    QHash<QWidget *, QPersistentModelIndex> extenderIndices;
    QHash<QWidget *, QPersistentModelIndex> deletionQueue;
    QPixmap extendPixmap;
    QPixmap contractPixmap;
    int stateTick;
    int cachedStateTick;
    int cachedRow;
    QModelIndex cachedParentIndex;
    QWidget *extender;
    int extenderHeight;
};


KExtendableItemDelegate::KExtendableItemDelegate(QAbstractItemView* parent)
 : QStyledItemDelegate(parent),
   d(new Private(this))
{
    connect(parent->verticalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(_k_verticalScroll()));
}


KExtendableItemDelegate::~KExtendableItemDelegate()
{
    delete d;
}


void KExtendableItemDelegate::extendItem(QWidget *ext, const QModelIndex &index)
{
    // kDebug() << "Creating extender at " << ext << " for item " << index.model()->data(index,Qt::DisplayRole).toString();

    if (!ext || !index.isValid()) {
        return;
    }
    //maintain the invariant "zero or one extender per row"
    d->stateTick++;
    contractItem(d->indexOfExtendedColumnInSameRow(index));
    d->stateTick++;
    //reparent, as promised in the docs
    QAbstractItemView *aiv = qobject_cast<QAbstractItemView *>(parent());
    if (!aiv) {
        return;
    }
    ext->setParent(aiv->viewport());
    d->extenders.insert(index, ext);
    d->extenderIndices.insert(ext, index);
    connect(ext, SIGNAL(destroyed(QObject*)), this, SLOT(_k_extenderDestructionHandler(QObject*)));
    emit extenderCreated(ext, index);
    d->scheduleUpdateViewLayout();
}


void KExtendableItemDelegate::contractItem(const QModelIndex& index)
{
    QWidget *extender = d->extenders.value(index);
    if (!extender) {
        return;
    }
    // kDebug() << "Collapse extender at " << extender << " for item " << index.model()->data(index,Qt::DisplayRole).toString();
    extender->hide();
    extender->deleteLater();

    QPersistentModelIndex persistentIndex = d->extenderIndices.take(extender);
    d->extenders.remove(persistentIndex);

    d->deletionQueue.insert(extender, persistentIndex);

    d->scheduleUpdateViewLayout();
}


void KExtendableItemDelegate::contractAll()
{
    d->deleteExtenders();
}


//slot
void KExtendableItemDelegate::Private::_k_extenderDestructionHandler(QObject *destroyed)
{
    // kDebug() << "Removing extender at " << destroyed;

    QWidget *extender = static_cast<QWidget *>(destroyed);
    stateTick++;

    QPersistentModelIndex persistentIndex = deletionQueue.take(extender);
    if (persistentIndex.isValid() &&
        q->receivers(SIGNAL(extenderDestroyed(QWidget*,QModelIndex)))) {

        QModelIndex index = persistentIndex;
        emit q->extenderDestroyed(extender, index);
    }

    scheduleUpdateViewLayout();
}


//slot
void KExtendableItemDelegate::Private::_k_verticalScroll()
{
    foreach (QWidget *extender, extenders) {
        // Fast scrolling can lead to artifacts where extenders stay in the viewport
        // of the parent's scroll area even though their items are scrolled out.
        // Therefore we hide all extenders when scrolling.
        // In paintEvent() show() will be called on actually visible extenders and
        // Qt's double buffering takes care of eliminating flicker.
        // ### This scales badly to many extenders. There are probably better ways to
        //     avoid the artifacts.
        extender->hide();
    }
}


bool KExtendableItemDelegate::isExtended(const QModelIndex &index) const
{
    return d->extenders.value(index);
}


QSize KExtendableItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSize ret;

    if (!d->extenders.isEmpty()) {
        ret = d->maybeExtendedSize(option, index);
    } else {
        ret = QStyledItemDelegate::sizeHint(option, index);
    }

    bool showExtensionIndicator = index.model() ?
        index.model()->data(index, ShowExtensionIndicatorRole).toBool() : false;
    if (showExtensionIndicator) {
        ret.rwidth() += d->extendPixmap.width();
    }

    return ret;
}


void KExtendableItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    int indicatorX = 0;
    int indicatorY = 0;

    QStyleOptionViewItemV4 indicatorOption(option);
    initStyleOption(&indicatorOption, index);
    if (index.column() == 0) {
        indicatorOption.viewItemPosition = QStyleOptionViewItemV4::Beginning;
    } else if (index.column() == index.model()->columnCount() - 1) {
        indicatorOption.viewItemPosition = QStyleOptionViewItemV4::End;
    } else {
        indicatorOption.viewItemPosition = QStyleOptionViewItemV4::Middle;
    }

    QStyleOptionViewItemV4 itemOption(option);
    initStyleOption(&itemOption, index);
    if (index.column() == 0) {
        itemOption.viewItemPosition = QStyleOptionViewItemV4::Beginning;
    } else if (index.column() == index.model()->columnCount() - 1) {
        itemOption.viewItemPosition = QStyleOptionViewItemV4::End;
    } else {
        itemOption.viewItemPosition = QStyleOptionViewItemV4::Middle;
    }

    const bool showExtensionIndicator = index.model()->data(index, ShowExtensionIndicatorRole).toBool();

    if (showExtensionIndicator) {
        if (QApplication::isRightToLeft()) {
            indicatorX = option.rect.right() - d->extendPixmap.width();
            itemOption.rect.setRight(option.rect.right() - d->extendPixmap.width());
            indicatorOption.rect.setLeft(option.rect.right() - d->extendPixmap.width());
        } else {
            indicatorX = option.rect.left();
            indicatorOption.rect.setRight(option.rect.left() + d->extendPixmap.width());
            itemOption.rect.setLeft(option.rect.left() + d->extendPixmap.width());
        }
        indicatorY = option.rect.top() + ((option.rect.height() - d->extendPixmap.height()) >> 1);
    }

    //fast path
    if (d->extenders.isEmpty()) {
        QStyledItemDelegate::paint(painter, itemOption, index);
        if (showExtensionIndicator) {
            painter->save();
            QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &indicatorOption,
                                                 painter);
            painter->restore();
            painter->drawPixmap(indicatorX, indicatorY, d->extendPixmap);
        }
        return;
    }

    int row = index.row();
    QModelIndex parentIndex = index.parent();

    //indexOfExtendedColumnInSameRow() is very expensive, try to avoid calling it.
    if (row != d->cachedRow || d->cachedStateTick != d->stateTick
        || d->cachedParentIndex != parentIndex) {
        d->extender = d->extenders.value(d->indexOfExtendedColumnInSameRow(index));
        d->cachedStateTick = d->stateTick;
        d->cachedRow = row;
        d->cachedParentIndex = parentIndex;
        if (d->extender) {
            d->extenderHeight = d->extender->sizeHint().height();
        }
    }

    if (!d->extender) {
        QStyledItemDelegate::paint(painter, itemOption, index);
        if (showExtensionIndicator) {
            painter->save();
            QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &indicatorOption,
                                                 painter);
            painter->restore();
            painter->drawPixmap(indicatorX, indicatorY, d->extendPixmap);
        }
        return;
    }

    //an extender is present - make two rectangles: one to paint the original item, one for the extender
    if (isExtended(index)) {
        QStyleOptionViewItemV4 extOption(option);
        initStyleOption(&extOption, index);
        extOption.rect = extenderRect(d->extender, option, index);
        updateExtenderGeometry(d->extender, extOption, index);
        //if we show it before, it will briefly flash in the wrong location.
        //the downside is, of course, that an api user effectively can't hide it.
        d->extender->show();
    }

    indicatorOption.rect.setHeight(option.rect.height() - d->extenderHeight);
    itemOption.rect.setHeight(option.rect.height() - d->extenderHeight);
    //tricky:make sure that the modified options' rect really has the
    //same height as the unchanged option.rect if no extender is present
    //(seems to work OK)
    QStyledItemDelegate::paint(painter, itemOption, index);

    if (showExtensionIndicator) {
        //indicatorOption's height changed, change this too
        indicatorY = indicatorOption.rect.top() + ((indicatorOption.rect.height() -
                                                   d->extendPixmap.height()) >> 1);
        painter->save();
        QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &indicatorOption,
                                             painter);
        painter->restore();

        if (d->extenders.contains(index)) {
            painter->drawPixmap(indicatorX, indicatorY, d->contractPixmap);
        } else {
            painter->drawPixmap(indicatorX, indicatorY, d->extendPixmap);
        }
    }
}


QRect KExtendableItemDelegate::extenderRect(QWidget *extender, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_ASSERT(extender);
    QRect rect(option.rect);
    rect.setTop(rect.bottom() + 1 - extender->sizeHint().height());

    int indentation = 0;
    if (QTreeView *tv = qobject_cast<QTreeView *>(parent())) {
        int indentSteps = 0;
        for (QModelIndex idx(index.parent()); idx.isValid(); idx = idx.parent()) {
            indentSteps++;
        }
        if (tv->rootIsDecorated()) {
            indentSteps++;
        }
        indentation = indentSteps * tv->indentation();
    }

    QAbstractScrollArea *container = qobject_cast<QAbstractScrollArea *>(parent());
    Q_ASSERT(container);
    if (qApp->isLeftToRight()) {
        rect.setLeft(indentation);
        rect.setRight(container->viewport()->width() - 1);
    } else {
        rect.setRight(container->viewport()->width() - 1 - indentation);
        rect.setLeft(0);
    }
    return rect;
}


QSize KExtendableItemDelegate::Private::maybeExtendedSize(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QWidget *extender = extenders.value(index);
    QSize size(q->QStyledItemDelegate::sizeHint(option, index));
    if (!extender) {
        return size;
    }
    //add extender height to maximum height of any column in our row
    int itemHeight = size.height();

    int row = index.row();
    int thisColumn = index.column();

    //this is quite slow, but Qt is smart about when to call sizeHint().
    for (int column = 0; index.model()->columnCount() < column; column++) {
        if (column == thisColumn) {
            continue;
        }
        QModelIndex neighborIndex(index.sibling(row, column));
        if (!neighborIndex.isValid()) {
            break;
        }
        itemHeight = qMax(itemHeight, q->QStyledItemDelegate::sizeHint(option, neighborIndex).height());
    }

    //we only want to reserve vertical space, the horizontal extender layout is our private business.
    size.rheight() = itemHeight + extender->sizeHint().height();
    return size;
}


QModelIndex KExtendableItemDelegate::Private::indexOfExtendedColumnInSameRow(const QModelIndex &index) const
{
    const QAbstractItemModel *const model = index.model();
    const QModelIndex parentIndex(index.parent());
    const int row = index.row();
    const int columnCount = model->columnCount();

    //slow, slow, slow
    for (int column = 0; column < columnCount; column++) {
        QModelIndex indexOfExt(model->index(row, column, parentIndex));
        if (extenders.value(indexOfExt)) {
            return indexOfExt;
        }
    }

    return QModelIndex();
}


void KExtendableItemDelegate::updateExtenderGeometry(QWidget *extender, const QStyleOptionViewItem &option,
                                                     const QModelIndex &index) const
{
    Q_UNUSED(index);
    extender->setGeometry(option.rect);
}


void KExtendableItemDelegate::Private::deleteExtenders()
{
    foreach (QWidget *ext, extenders) {
        ext->hide();
        ext->deleteLater();
    }
    deletionQueue.unite(extenderIndices);
    extenders.clear();
    extenderIndices.clear();
}


//make the view re-ask for sizeHint() and redisplay items with their new size
//### starting from Qt 4.4 we could emit sizeHintChanged() instead
void KExtendableItemDelegate::Private::scheduleUpdateViewLayout()
{
    QAbstractItemView *aiv = qobject_cast<QAbstractItemView *>(q->parent());
    //prevent crashes during destruction of the view
    if (aiv) {
        //dirty hack to call aiv's protected scheduleDelayedItemsLayout()
        aiv->setRootIndex(aiv->rootIndex());
    }
}


void KExtendableItemDelegate::setExtendPixmap(const QPixmap &pixmap)
{
    d->extendPixmap = pixmap;
}


void KExtendableItemDelegate::setContractPixmap(const QPixmap &pixmap)
{
    d->contractPixmap = pixmap;
}


QPixmap KExtendableItemDelegate::extendPixmap()
{
    return d->extendPixmap;
}


QPixmap KExtendableItemDelegate::contractPixmap()
{
    return d->contractPixmap;
}

#include "kextendableitemdelegate.moc"