kitemlistview.cpp 93.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/***************************************************************************
 *   Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com>             *
 *                                                                         *
 *   Based on the Itemviews NG project from Trolltech Labs:                *
 *   http://qt.gitorious.org/qt-labs/itemviews-ng                          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "kitemlistview.h"

25
#include "dolphindebug.h"
26
#include "kitemlistcontainer.h"
27
#include "kitemlistcontroller.h"
28
#include "kitemlistheader.h"
29
#include "kitemlistselectionmanager.h"
Roman Inflianskas's avatar
Roman Inflianskas committed
30
#include "kitemlistviewaccessible.h"
31
#include "kstandarditemlistwidget.h"
32

33
34
35
36
37
#include "private/kitemlistheaderwidget.h"
#include "private/kitemlistrubberband.h"
#include "private/kitemlistsizehintresolver.h"
#include "private/kitemlistviewlayouter.h"

Roman Inflianskas's avatar
Roman Inflianskas committed
38
#include <QElapsedTimer>
39
#include <QGraphicsSceneMouseEvent>
40
#include <QGraphicsView>
41
#include <QStyleOptionRubberBand>
42
43
#include <QTimer>

44

Peter Penz's avatar
Peter Penz committed
45
46
47
48
49
50
51
52
53
namespace {
    // Time in ms until reaching the autoscroll margin triggers
    // an initial autoscrolling
    const int InitialAutoScrollDelay = 700;

    // Delay in ms for triggering the next autoscroll
    const int RepeatingAutoScrollDelay = 1000 / 60;
}

54
#ifndef QT_NO_ACCESSIBILITY
Frederik Gladhorn's avatar
Frederik Gladhorn committed
55
QAccessibleInterface* accessibleInterfaceFactory(const QString& key, QObject* object)
56
57
{
    Q_UNUSED(key)
58
59
60
61

    if (KItemListContainer* container = qobject_cast<KItemListContainer*>(object)) {
        return new KItemListContainerAccessible(container);
    } else if (KItemListView* view = qobject_cast<KItemListView*>(object)) {
62
        return new KItemListViewAccessible(view);
63
    }
64

Kevin Funk's avatar
Kevin Funk committed
65
    return nullptr;
66
}
67
#endif
68

69
70
KItemListView::KItemListView(QGraphicsWidget* parent) :
    QGraphicsWidget(parent),
Peter Penz's avatar
Peter Penz committed
71
    m_enabledSelectionToggles(false),
72
    m_grouped(false),
73
    m_supportsItemExpanding(false),
74
    m_editingRole(false),
75
    m_activeTransactions(0),
Peter Penz's avatar
Peter Penz committed
76
    m_endTransactionAnimationHint(Animation),
77
    m_itemSize(),
Kevin Funk's avatar
Kevin Funk committed
78
79
    m_controller(nullptr),
    m_model(nullptr),
80
    m_visibleRoles(),
Kevin Funk's avatar
Kevin Funk committed
81
82
    m_widgetCreator(nullptr),
    m_groupHeaderCreator(nullptr),
83
84
85
    m_styleOption(),
    m_visibleItems(),
    m_visibleGroups(),
86
    m_visibleCells(),
Kevin Funk's avatar
Kevin Funk committed
87
88
89
90
    m_sizeHintResolver(nullptr),
    m_layouter(nullptr),
    m_animation(nullptr),
    m_layoutTimer(nullptr),
Peter Penz's avatar
Peter Penz committed
91
92
93
94
    m_oldScrollOffset(0),
    m_oldMaximumScrollOffset(0),
    m_oldItemOffset(0),
    m_oldMaximumItemOffset(0),
95
    m_skipAutoScrollForRubberBand(false),
Kevin Funk's avatar
Kevin Funk committed
96
    m_rubberBand(nullptr),
97
    m_mousePos(),
Peter Penz's avatar
Peter Penz committed
98
    m_autoScrollIncrement(0),
Kevin Funk's avatar
Kevin Funk committed
99
100
101
    m_autoScrollTimer(nullptr),
    m_header(nullptr),
    m_headerWidget(nullptr),
Peter Penz's avatar
Peter Penz committed
102
    m_dropIndicator()
103
104
105
106
107
{
    setAcceptHoverEvents(true);

    m_sizeHintResolver = new KItemListSizeHintResolver(this);

108
    m_layouter = new KItemListViewLayouter(m_sizeHintResolver, this);
109
110

    m_animation = new KItemListViewAnimation(this);
111
112
    connect(m_animation, &KItemListViewAnimation::finished,
            this, &KItemListView::slotAnimationFinished);
113
114
115
116

    m_layoutTimer = new QTimer(this);
    m_layoutTimer->setInterval(300);
    m_layoutTimer->setSingleShot(true);
117
    connect(m_layoutTimer, &QTimer::timeout, this, &KItemListView::slotLayoutTimerFinished);
118
119

    m_rubberBand = new KItemListRubberBand(this);
120
    connect(m_rubberBand, &KItemListRubberBand::activationChanged, this, &KItemListView::slotRubberBandActivationChanged);
121
122
123
124
125

    m_headerWidget = new KItemListHeaderWidget(this);
    m_headerWidget->setVisible(false);

    m_header = new KItemListHeader(this);
126

127
#ifndef QT_NO_ACCESSIBILITY
Amandeep Singh's avatar
Amandeep Singh committed
128
    QAccessible::installFactory(accessibleInterfaceFactory);
129
#endif
130

131
132
133
134
}

KItemListView::~KItemListView()
{
135
136
137
138
    // The group headers are children of the widgets created by
    // widgetCreator(). So it is mandatory to delete the group headers
    // first.
    delete m_groupHeaderCreator;
Kevin Funk's avatar
Kevin Funk committed
139
    m_groupHeaderCreator = nullptr;
140

141
    delete m_widgetCreator;
Kevin Funk's avatar
Kevin Funk committed
142
    m_widgetCreator = nullptr;
143

144
    delete m_sizeHintResolver;
Kevin Funk's avatar
Kevin Funk committed
145
    m_sizeHintResolver = nullptr;
146
147
}

Peter Penz's avatar
Peter Penz committed
148
void KItemListView::setScrollOffset(qreal offset)
149
150
151
152
153
{
    if (offset < 0) {
        offset = 0;
    }

Peter Penz's avatar
Peter Penz committed
154
    const qreal previousOffset = m_layouter->scrollOffset();
155
156
157
158
    if (offset == previousOffset) {
        return;
    }

Peter Penz's avatar
Peter Penz committed
159
160
    m_layouter->setScrollOffset(offset);
    m_animation->setScrollOffset(offset);
161
162
163
164
165

    // Don't check whether the m_layoutTimer is active: Changing the
    // scroll offset must always trigger a synchronous layout, otherwise
    // the smooth-scrolling might get jerky.
    doLayout(NoAnimation);
Peter Penz's avatar
Peter Penz committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    onScrollOffsetChanged(offset, previousOffset);
}

qreal KItemListView::scrollOffset() const
{
    return m_layouter->scrollOffset();
}

qreal KItemListView::maximumScrollOffset() const
{
    return m_layouter->maximumScrollOffset();
}

void KItemListView::setItemOffset(qreal offset)
{
Peter Penz's avatar
Peter Penz committed
181
182
183
184
    if (m_layouter->itemOffset() == offset) {
        return;
    }

Peter Penz's avatar
Peter Penz committed
185
    m_layouter->setItemOffset(offset);
186
    if (m_headerWidget->isVisible()) {
187
        m_headerWidget->setOffset(offset);
188
    }
Peter Penz's avatar
Peter Penz committed
189
190
191
192
193

    // Don't check whether the m_layoutTimer is active: Changing the
    // item offset must always trigger a synchronous layout, otherwise
    // the smooth-scrolling might get jerky.
    doLayout(NoAnimation);
194
195
}

Peter Penz's avatar
Peter Penz committed
196
qreal KItemListView::itemOffset() const
197
{
Peter Penz's avatar
Peter Penz committed
198
    return m_layouter->itemOffset();
199
200
}

Peter Penz's avatar
Peter Penz committed
201
qreal KItemListView::maximumItemOffset() const
202
{
Peter Penz's avatar
Peter Penz committed
203
    return m_layouter->maximumItemOffset();
204
205
}

206
207
208
209
210
int KItemListView::maximumVisibleItems() const
{
    return m_layouter->maximumVisibleItems();
}

211
void KItemListView::setVisibleRoles(const QList<QByteArray>& roles)
212
{
213
    const QList<QByteArray> previousRoles = m_visibleRoles;
214
    m_visibleRoles = roles;
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    onVisibleRolesChanged(roles, previousRoles);

    m_sizeHintResolver->clearCache();
    m_layouter->markAsDirty();

    if (m_itemSize.isEmpty()) {
        m_headerWidget->setColumns(roles);
        updatePreferredColumnWidths();
        if (!m_headerWidget->automaticColumnResizing()) {
            // The column-width of new roles are still 0. Apply the preferred
            // column-width as default with.
            foreach (const QByteArray& role, m_visibleRoles) {
                if (m_headerWidget->columnWidth(role) == 0) {
                    const qreal width = m_headerWidget->preferredColumnWidth(role);
                    m_headerWidget->setColumnWidth(role, width);
                }
            }

            applyColumnWidthsFromHeader();
        }
    }
236

Peter Penz's avatar
Peter Penz committed
237
238
239
    const bool alternateBackgroundsChanged = m_itemSize.isEmpty() &&
                                             ((roles.count() > 1 && previousRoles.count() <= 1) ||
                                              (roles.count() <= 1 && previousRoles.count() > 1));
240

241
242
243
244
245
    QHashIterator<int, KItemListWidget*> it(m_visibleItems);
    while (it.hasNext()) {
        it.next();
        KItemListWidget* widget = it.value();
        widget->setVisibleRoles(roles);
Peter Penz's avatar
Peter Penz committed
246
        if (alternateBackgroundsChanged) {
247
248
            updateAlternateBackgroundForWidget(widget);
        }
249
250
    }

251
    doLayout(NoAnimation);
252
253
}

254
QList<QByteArray> KItemListView::visibleRoles() const
255
256
257
258
{
    return m_visibleRoles;
}

259
260
261
262
void KItemListView::setAutoScroll(bool enabled)
{
    if (enabled && !m_autoScrollTimer) {
        m_autoScrollTimer = new QTimer(this);
263
        m_autoScrollTimer->setSingleShot(true);
264
        connect(m_autoScrollTimer, &QTimer::timeout, this, &KItemListView::triggerAutoScrolling);
Peter Penz's avatar
Peter Penz committed
265
        m_autoScrollTimer->start(InitialAutoScrollDelay);
266
267
    } else if (!enabled && m_autoScrollTimer) {
        delete m_autoScrollTimer;
Kevin Funk's avatar
Kevin Funk committed
268
        m_autoScrollTimer = nullptr;
269
270
271
272
273
    }
}

bool KItemListView::autoScroll() const
{
Kevin Funk's avatar
Kevin Funk committed
274
    return m_autoScrollTimer != nullptr;
275
276
}

Peter Penz's avatar
Peter Penz committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
void KItemListView::setEnabledSelectionToggles(bool enabled)
{
    if (m_enabledSelectionToggles != enabled) {
        m_enabledSelectionToggles = enabled;

        QHashIterator<int, KItemListWidget*> it(m_visibleItems);
        while (it.hasNext()) {
            it.next();
            it.value()->setEnabledSelectionToggle(enabled);
        }
    }
}

bool KItemListView::enabledSelectionToggles() const
{
    return m_enabledSelectionToggles;
}

295
296
297
298
299
300
301
302
303
304
305
306
KItemListController* KItemListView::controller() const
{
    return m_controller;
}

KItemModelBase* KItemListView::model() const
{
    return m_model;
}

void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator)
{
307
    delete m_widgetCreator;
308
309
310
311
312
    m_widgetCreator = widgetCreator;
}

KItemListWidgetCreatorBase* KItemListView::widgetCreator() const
{
313
314
315
    if (!m_widgetCreator) {
        m_widgetCreator = defaultWidgetCreator();
    }
316
317
318
319
320
    return m_widgetCreator;
}

void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator)
{
321
    delete m_groupHeaderCreator;
322
323
324
325
326
    m_groupHeaderCreator = groupHeaderCreator;
}

KItemListGroupHeaderCreatorBase* KItemListView::groupHeaderCreator() const
{
327
328
329
    if (!m_groupHeaderCreator) {
        m_groupHeaderCreator = defaultGroupHeaderCreator();
    }
330
331
332
    return m_groupHeaderCreator;
}

333
QSizeF KItemListView::itemSize() const
334
{
335
    return m_itemSize;
336
337
338
339
340
341
342
343
344
345
}

const KItemListStyleOption& KItemListView::styleOption() const
{
    return m_styleOption;
}

void KItemListView::setGeometry(const QRectF& rect)
{
    QGraphicsWidget::setGeometry(rect);
346

347
348
349
350
    if (!m_model) {
        return;
    }

351
352
    const QSizeF newSize = rect.size();
    if (m_itemSize.isEmpty()) {
353
        m_headerWidget->resize(rect.width(), m_headerWidget->size().height());
354
        if (m_headerWidget->automaticColumnResizing()) {
355
            applyAutomaticColumnWidths();
356
357
358
359
        } else {
            const qreal requiredWidth = columnWidthsSum();
            const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth),
                                         m_itemSize.height());
360
361
            m_layouter->setItemSize(dynamicItemSize);
        }
362

363
364
365
        // Triggering a synchronous layout is fine from a performance point of view,
        // as with dynamic item sizes no moving animation must be done.
        m_layouter->setSize(newSize);
366
        doLayout(NoAnimation);
367
    } else {
Peter Penz's avatar
Peter Penz committed
368
369
        const bool animate = !changesItemGridLayout(newSize,
                                                    m_layouter->itemSize(),
370
                                                    m_layouter->itemMargin());
Peter Penz's avatar
Peter Penz committed
371
        m_layouter->setSize(newSize);
372

373
374
375
376
377
378
379
380
381
382
        if (animate) {
            // Trigger an asynchronous relayout with m_layoutTimer to prevent
            // performance bottlenecks. If the timer is exceeded, an animated layout
            // will be triggered.
            if (!m_layoutTimer->isActive()) {
                m_layoutTimer->start();
            }
        } else {
            m_layoutTimer->stop();
            doLayout(NoAnimation);
383
        }
384
    }
385
386
}

387
388
389
390
391
392
393
394
395
qreal KItemListView::verticalPageStep() const
{
    qreal headerHeight = 0;
    if (m_headerWidget->isVisible()) {
        headerHeight = m_headerWidget->size().height();
    }
    return size().height() - headerHeight;
}

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
int KItemListView::itemAt(const QPointF& pos) const
{
    QHashIterator<int, KItemListWidget*> it(m_visibleItems);
    while (it.hasNext()) {
        it.next();

        const KItemListWidget* widget = it.value();
        const QPointF mappedPos = widget->mapFromItem(this, pos);
        if (widget->contains(mappedPos)) {
            return it.key();
        }
    }

    return -1;
}

bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const
{
414
415
416
417
    if (!m_enabledSelectionToggles) {
        return false;
    }

Peter Penz's avatar
Peter Penz committed
418
419
420
421
422
423
424
425
    const KItemListWidget* widget = m_visibleItems.value(index);
    if (widget) {
        const QRectF selectionToggleRect = widget->selectionToggleRect();
        if (!selectionToggleRect.isEmpty()) {
            const QPointF mappedPos = widget->mapFromItem(this, pos);
            return selectionToggleRect.contains(mappedPos);
        }
    }
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    return false;
}

bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const
{
    const KItemListWidget* widget = m_visibleItems.value(index);
    if (widget) {
        const QRectF expansionToggleRect = widget->expansionToggleRect();
        if (!expansionToggleRect.isEmpty()) {
            const QPointF mappedPos = widget->mapFromItem(this, pos);
            return expansionToggleRect.contains(mappedPos);
        }
    }
    return false;
}

442
443
444
445
446
447
448
449
450
451
452
453
454
bool KItemListView::isAboveText(int index, const QPointF &pos) const
{
    const KItemListWidget* widget = m_visibleItems.value(index);
    if (widget) {
        const QRectF &textRect = widget->textRect();
        if (!textRect.isEmpty()) {
            const QPointF mappedPos = widget->mapFromItem(this, pos);
            return textRect.contains(mappedPos);
        }
    }
    return false;
}

455
456
457
458
459
460
461
462
463
464
int KItemListView::firstVisibleIndex() const
{
    return m_layouter->firstVisibleIndex();
}

int KItemListView::lastVisibleIndex() const
{
    return m_layouter->lastVisibleIndex();
}

465
void KItemListView::calculateItemSizeHints(QVector<qreal>& logicalHeightHints, qreal& logicalWidthHint) const
466
{
467
    widgetCreator()->calculateItemSizeHints(logicalHeightHints, logicalWidthHint, this);
468
469
}

470
471
472
473
474
475
476
477
478
void KItemListView::setSupportsItemExpanding(bool supportsExpanding)
{
    if (m_supportsItemExpanding != supportsExpanding) {
        m_supportsItemExpanding = supportsExpanding;
        updateSiblingsInformation();
        onSupportsItemExpandingChanged(supportsExpanding);
    }
}

Peter Penz's avatar
Peter Penz committed
479
480
bool KItemListView::supportsItemExpanding() const
{
481
    return m_supportsItemExpanding;
Peter Penz's avatar
Peter Penz committed
482
483
}

Peter Penz's avatar
Peter Penz committed
484
QRectF KItemListView::itemRect(int index) const
485
{
Peter Penz's avatar
Peter Penz committed
486
    return m_layouter->itemRect(index);
487
488
}

Peter Penz's avatar
Peter Penz committed
489
490
491
492
493
494
495
496
497
498
499
500
501
QRectF KItemListView::itemContextRect(int index) const
{
    QRectF contextRect;

    const KItemListWidget* widget = m_visibleItems.value(index);
    if (widget) {
        contextRect = widget->iconRect() | widget->textRect();
        contextRect.translate(itemRect(index).topLeft());
    }

    return contextRect;
}

Peter Penz's avatar
Peter Penz committed
502
503
void KItemListView::scrollToItem(int index)
{
Peter Penz's avatar
Peter Penz committed
504
    QRectF viewGeometry = geometry();
505
506
    if (m_headerWidget->isVisible()) {
        const qreal headerHeight = m_headerWidget->size().height();
Peter Penz's avatar
Peter Penz committed
507
508
        viewGeometry.adjust(0, headerHeight, 0, 0);
    }
509
510
511
512
513
    QRectF currentRect = itemRect(index);

    // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
    currentRect.adjust(-m_styleOption.horizontalMargin, -m_styleOption.verticalMargin,
                        m_styleOption.horizontalMargin,  m_styleOption.verticalMargin);
Peter Penz's avatar
Peter Penz committed
514
515
516

    if (!viewGeometry.contains(currentRect)) {
        qreal newOffset = scrollOffset();
517
518
519
520
521
        if (scrollOrientation() == Qt::Vertical) {
            if (currentRect.top() < viewGeometry.top()) {
                newOffset += currentRect.top() - viewGeometry.top();
            } else if (currentRect.bottom() > viewGeometry.bottom()) {
                newOffset += currentRect.bottom() - viewGeometry.bottom();
Peter Penz's avatar
Peter Penz committed
522
            }
523
524
525
526
        } else {
            if (currentRect.left() < viewGeometry.left()) {
                newOffset += currentRect.left() - viewGeometry.left();
            } else if (currentRect.right() > viewGeometry.right()) {
Peter Penz's avatar
Peter Penz committed
527
528
529
530
531
532
533
534
535
536
                newOffset += currentRect.right() - viewGeometry.right();
            }
        }

        if (newOffset != scrollOffset()) {
            emit scrollTo(newOffset);
        }
    }
}

537
538
539
540
541
542
543
544
545
546
547
548
549
void KItemListView::beginTransaction()
{
    ++m_activeTransactions;
    if (m_activeTransactions == 1) {
        onTransactionBegin();
    }
}

void KItemListView::endTransaction()
{
    --m_activeTransactions;
    if (m_activeTransactions < 0) {
        m_activeTransactions = 0;
550
        qCWarning(DolphinDebug) << "Mismatch between beginTransaction()/endTransaction()";
551
552
553
554
    }

    if (m_activeTransactions == 0) {
        onTransactionEnd();
Peter Penz's avatar
Peter Penz committed
555
556
        doLayout(m_endTransactionAnimationHint);
        m_endTransactionAnimationHint = Animation;
557
558
559
560
561
562
563
564
    }
}

bool KItemListView::isTransactionActive() const
{
    return m_activeTransactions > 0;
}

565
void KItemListView::setHeaderVisible(bool visible)
Peter Penz's avatar
Peter Penz committed
566
{
567
    if (visible && !m_headerWidget->isVisible()) {
568
569
570
571
        QStyleOptionHeader option;
        const QSize headerSize = style()->sizeFromContents(QStyle::CT_HeaderSection,
                                                           &option, QSize());

Peter Penz's avatar
Peter Penz committed
572
        m_headerWidget->setPos(0, 0);
573
        m_headerWidget->resize(size().width(), headerSize.height());
574
575
576
        m_headerWidget->setModel(m_model);
        m_headerWidget->setColumns(m_visibleRoles);
        m_headerWidget->setZValue(1);
Peter Penz's avatar
Peter Penz committed
577

578
579
580
581
582
583
584
585
        connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged,
                this, &KItemListView::slotHeaderColumnWidthChanged);
        connect(m_headerWidget, &KItemListHeaderWidget::columnMoved,
                this, &KItemListView::slotHeaderColumnMoved);
        connect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged,
                this, &KItemListView::sortOrderChanged);
        connect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged,
                this, &KItemListView::sortRoleChanged);
Peter Penz's avatar
Peter Penz committed
586

587
        m_layouter->setHeaderHeight(headerSize.height());
588
589
        m_headerWidget->setVisible(true);
    } else if (!visible && m_headerWidget->isVisible()) {
590
591
592
593
594
595
596
597
        disconnect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged,
                   this, &KItemListView::slotHeaderColumnWidthChanged);
        disconnect(m_headerWidget, &KItemListHeaderWidget::columnMoved,
                   this, &KItemListView::slotHeaderColumnMoved);
        disconnect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged,
                   this, &KItemListView::sortOrderChanged);
        disconnect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged,
                   this, &KItemListView::sortRoleChanged);
Peter Penz's avatar
Peter Penz committed
598
599

        m_layouter->setHeaderHeight(0);
600
        m_headerWidget->setVisible(false);
Peter Penz's avatar
Peter Penz committed
601
602
603
    }
}

604
bool KItemListView::isHeaderVisible() const
Peter Penz's avatar
Peter Penz committed
605
{
606
607
608
609
610
611
    return m_headerWidget->isVisible();
}

KItemListHeader* KItemListView::header() const
{
    return m_header;
Peter Penz's avatar
Peter Penz committed
612
613
}

614
QPixmap KItemListView::createDragPixmap(const KItemSet& indexes) const
615
{
616
617
618
    QPixmap pixmap;

    if (indexes.count() == 1) {
619
        KItemListWidget* item = m_visibleItems.value(indexes.first());
620
621
        QGraphicsView* graphicsView = scene()->views()[0];
        if (item && graphicsView) {
Kevin Funk's avatar
Kevin Funk committed
622
            pixmap = item->createDragPixmap(nullptr, graphicsView);
623
624
625
626
627
628
629
630
        }
    } else {
        // TODO: Not implemented yet. Probably extend the interface
        // from KItemListWidget::createDragPixmap() to return a pixmap
        // that can be used for multiple indexes.
    }

    return pixmap;
631
632
}

633
634
void KItemListView::editRole(int index, const QByteArray& role)
{
635
    KStandardItemListWidget* widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
636
    if (!widget || m_editingRole) {
637
638
639
640
641
642
        return;
    }

    m_editingRole = true;
    widget->setEditedRole(role);

643
644
645
646
    connect(widget, &KItemListWidget::roleEditingCanceled,
            this, &KItemListView::slotRoleEditingCanceled);
    connect(widget, &KItemListWidget::roleEditingFinished,
            this, &KItemListView::slotRoleEditingFinished);
647
648
649

    connect(this, &KItemListView::scrollOffsetChanged,
            widget, &KStandardItemListWidget::finishRoleEditing);
650
651
}

652
653
654
655
656
657
658
659
660
661
void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    QGraphicsWidget::paint(painter, option, widget);

    if (m_rubberBand->isActive()) {
        QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
                                       m_rubberBand->endPosition()).normalized();

        const QPointF topLeft = rubberBandRect.topLeft();
        if (scrollOrientation() == Qt::Vertical) {
Peter Penz's avatar
Peter Penz committed
662
            rubberBandRect.moveTo(topLeft.x(), topLeft.y() - scrollOffset());
663
        } else {
Peter Penz's avatar
Peter Penz committed
664
            rubberBandRect.moveTo(topLeft.x() - scrollOffset(), topLeft.y());
665
666
667
        }

        QStyleOptionRubberBand opt;
668
        initStyleOption(&opt);
669
670
671
672
673
        opt.shape = QRubberBand::Rectangle;
        opt.opaque = false;
        opt.rect = rubberBandRect.toRect();
        style()->drawControl(QStyle::CE_RubberBand, &opt, painter);
    }
Peter Penz's avatar
Peter Penz committed
674
675
676
677

    if (!m_dropIndicator.isEmpty()) {
        const QRectF r = m_dropIndicator.toRect();

George Vogiatzis's avatar
George Vogiatzis committed
678
        QColor color = palette().brush(QPalette::Normal, QPalette::Text).color();
Peter Penz's avatar
Peter Penz committed
679
680
681
682
683
684
685
686
687
688
689
        painter->setPen(color);

        // TODO: The following implementation works only for a vertical scroll-orientation
        // and assumes a height of the m_draggingInsertIndicator of 1.
        Q_ASSERT(r.height() == 1);
        painter->drawLine(r.left() + 1, r.top(), r.right() - 1, r.top());

        color.setAlpha(128);
        painter->setPen(color);
        painter->drawRect(r.left(), r.top() - 1, r.width() - 1, 2);
    }
690
691
}

692
693
694
695
696
697
698
699
700
701
QVariant KItemListView::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSceneHasChanged && scene()) {
        if (!scene()->views().isEmpty()) {
            m_styleOption.palette = scene()->views().at(0)->palette();
        }
    }
    return QGraphicsItem::itemChange(change, value);
}

702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
void KItemListView::setItemSize(const QSizeF& size)
{
    const QSizeF previousSize = m_itemSize;
    if (size == previousSize) {
        return;
    }

    // Skip animations when the number of rows or columns
    // are changed in the grid layout. Although the animation
    // engine can handle this usecase, it looks obtrusive.
    const bool animate = !changesItemGridLayout(m_layouter->size(),
                                                size,
                                                m_layouter->itemMargin());

    const bool alternateBackgroundsChanged = (m_visibleRoles.count() > 1) &&
                                             (( m_itemSize.isEmpty() && !size.isEmpty()) ||
                                              (!m_itemSize.isEmpty() && size.isEmpty()));

    m_itemSize = size;

    if (alternateBackgroundsChanged) {
        // For an empty item size alternate backgrounds are drawn if more than
        // one role is shown. Assure that the backgrounds for visible items are
        // updated when changing the size in this context.
        updateAlternateBackgrounds();
    }

    if (size.isEmpty()) {
        if (m_headerWidget->automaticColumnResizing()) {
            updatePreferredColumnWidths();
        } else {
            // Only apply the changed height and respect the header widths
            // set by the user
            const qreal currentWidth = m_layouter->itemSize().width();
            const QSizeF newSize(currentWidth, size.height());
            m_layouter->setItemSize(newSize);
        }
    } else {
        m_layouter->setItemSize(size);
    }

    m_sizeHintResolver->clearCache();
    doLayout(animate ? Animation : NoAnimation);
    onItemSizeChanged(size, previousSize);
}

void KItemListView::setStyleOption(const KItemListStyleOption& option)
{
750
751
752
753
    if (m_styleOption == option) {
        return;
    }

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    const KItemListStyleOption previousOption = m_styleOption;
    m_styleOption = option;

    bool animate = true;
    const QSizeF margin(option.horizontalMargin, option.verticalMargin);
    if (margin != m_layouter->itemMargin()) {
        // Skip animations when the number of rows or columns
        // are changed in the grid layout. Although the animation
        // engine can handle this usecase, it looks obtrusive.
        animate = !changesItemGridLayout(m_layouter->size(),
                                         m_layouter->itemSize(),
                                         margin);
        m_layouter->setItemMargin(margin);
    }

    if (m_grouped) {
        updateGroupHeaderHeight();
    }

773
774
    if (animate &&
        (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) {
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
        // Animating a change of the maximum text size just results in expensive
        // temporary eliding and clipping operations and does not look good visually.
        animate = false;
    }

    QHashIterator<int, KItemListWidget*> it(m_visibleItems);
    while (it.hasNext()) {
        it.next();
        it.value()->setStyleOption(option);
    }

    m_sizeHintResolver->clearCache();
    m_layouter->markAsDirty();
    doLayout(animate ? Animation : NoAnimation);

790
791
792
793
    if (m_itemSize.isEmpty()) {
        updatePreferredColumnWidths();
    }

794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
    onStyleOptionChanged(option, previousOption);
}

void KItemListView::setScrollOrientation(Qt::Orientation orientation)
{
    const Qt::Orientation previousOrientation = m_layouter->scrollOrientation();
    if (orientation == previousOrientation) {
        return;
    }

    m_layouter->setScrollOrientation(orientation);
    m_animation->setScrollOrientation(orientation);
    m_sizeHintResolver->clearCache();

    if (m_grouped) {
        QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
        while (it.hasNext()) {
            it.next();
            it.value()->setScrollOrientation(orientation);
        }
        updateGroupHeaderHeight();

    }

    doLayout(NoAnimation);

    onScrollOrientationChanged(orientation, previousOrientation);
    emit scrollOrientationChanged(orientation, previousOrientation);
}

Qt::Orientation KItemListView::scrollOrientation() const
{
    return m_layouter->scrollOrientation();
}

KItemListWidgetCreatorBase* KItemListView::defaultWidgetCreator() const
{
Kevin Funk's avatar
Kevin Funk committed
831
    return nullptr;
832
833
834
835
}

KItemListGroupHeaderCreatorBase* KItemListView::defaultGroupHeaderCreator() const
{
Kevin Funk's avatar
Kevin Funk committed
836
    return nullptr;
837
838
}

839
840
void KItemListView::initializeItemListWidget(KItemListWidget* item)
{
841
    Q_UNUSED(item)
842
843
}

844
845
bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
{
846
    Q_UNUSED(changedRoles)
847
848
849
    return true;
}

850
851
void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
{
852
853
    Q_UNUSED(current)
    Q_UNUSED(previous)
854
855
856
857
}

void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
{
858
859
    Q_UNUSED(current)
    Q_UNUSED(previous)
860
861
862
863
}

void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous)
{
864
865
    Q_UNUSED(current)
    Q_UNUSED(previous)
866
867
868
869
}

void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
{
870
871
    Q_UNUSED(current)
    Q_UNUSED(previous)
872
873
}

Peter Penz's avatar
Peter Penz committed
874
void KItemListView::onScrollOffsetChanged(qreal current, qreal previous)
875
{
876
877
    Q_UNUSED(current)
    Q_UNUSED(previous)
878
879
}

880
void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
881
{
882
883
    Q_UNUSED(current)
    Q_UNUSED(previous)
884
885
886
887
}

void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
{
888
889
    Q_UNUSED(current)
    Q_UNUSED(previous)
890
891
}

892
893
void KItemListView::onSupportsItemExpandingChanged(bool supportsExpanding)
{
894
    Q_UNUSED(supportsExpanding)
895
896
}

897
898
899
900
901
902
903
904
905
906
void KItemListView::onTransactionBegin()
{
}

void KItemListView::onTransactionEnd()
{
}

bool KItemListView::event(QEvent* event)
{
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
    switch (event->type()) {
    case QEvent::PaletteChange:
        updatePalette();
        break;

    case QEvent::FontChange:
        updateFont();
        break;

    default:
        // Forward all other events to the controller and handle them there
        if (!m_editingRole && m_controller && m_controller->processEvent(event, transform())) {
            event->accept();
            return true;
        }
922
    }
923

924
925
926
927
928
    return QGraphicsWidget::event(event);
}

void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
929
    m_mousePos = transform().map(event->pos());
930
931
932
    event->accept();
}

933
934
935
void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    QGraphicsWidget::mouseMoveEvent(event);
936

Peter Penz's avatar
Peter Penz committed
937
    m_mousePos = transform().map(event->pos());
938
    if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
Peter Penz's avatar
Peter Penz committed
939
        m_autoScrollTimer->start(InitialAutoScrollDelay);
940
    }
941
942
}

943
944
945
void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
{
    event->setAccepted(true);
Peter Penz's avatar
Peter Penz committed
946
947
948
    setAutoScroll(true);
}

Frederik Gladhorn's avatar
Frederik Gladhorn committed
949
void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent* event)
Peter Penz's avatar
Peter Penz committed
950
951
952
953
954
955
956
957
958
{
    QGraphicsWidget::dragMoveEvent(event);

    m_mousePos = transform().map(event->pos());
    if (m_autoScrollTimer && !m_autoScrollTimer->isActive()) {
        m_autoScrollTimer->start(InitialAutoScrollDelay);
    }
}

Frederik Gladhorn's avatar
Frederik Gladhorn committed
959
void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent* event)
Peter Penz's avatar
Peter Penz committed
960
961
962
963
964
965
966
967
968
{
    QGraphicsWidget::dragLeaveEvent(event);
    setAutoScroll(false);
}

void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
{
    QGraphicsWidget::dropEvent(event);
    setAutoScroll(false);
969
970
}

971
972
973
974
975
QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
{
    return m_visibleItems.values();
}

976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
void KItemListView::updateFont()
{
    if (scene() && !scene()->views().isEmpty()) {
        KItemListStyleOption option = styleOption();
        option.font = scene()->views().first()->font();
        option.fontMetrics = QFontMetrics(option.font);

        setStyleOption(option);
    }
}

void KItemListView::updatePalette()
{
    if (scene() && !scene()->views().isEmpty()) {
        KItemListStyleOption option = styleOption();
        option.palette = scene()->views().first()->palette();

        setStyleOption(option);
    }
}

997
998
void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
{
999
1000
1001
    if (m_itemSize.isEmpty()) {
        updatePreferredColumnWidths(itemRanges);
    }
1002
1003
1004
1005
1006
1007

    const bool hasMultipleRanges = (itemRanges.count() > 1);
    if (hasMultipleRanges) {
        beginTransaction();
    }

1008
1009
    m_layouter->markAsDirty();

1010
1011
    m_sizeHintResolver->itemsInserted(itemRanges);

1012
    int previouslyInsertedCount = 0;
1013
    foreach (const KItemRange& range, itemRanges) {
1014
1015
        // range.index is related to the model before anything has been inserted.
        // As in each loop the current item-range gets inserted the index must
1016
        // be increased by the already previously inserted items.
1017
        const int index = range.index + previouslyInsertedCount;
1018
1019
        const int count = range.count;
        if (index < 0 || count <= 0) {
1020
            qCWarning(DolphinDebug) << "Invalid item range (index:" << index << ", count:" << count << ")";
1021
1022
            continue;
        }
1023
        previouslyInsertedCount += count;
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038

        // Determine which visible items must be moved
        QList<int> itemsToMove;
        QHashIterator<int, KItemListWidget*> it(m_visibleItems);
        while (it.hasNext()) {
            it.next();
            const int visibleItemIndex = it.key();
            if (visibleItemIndex >= index) {
                itemsToMove.append(visibleItemIndex);
            }
        }

        // Update the indexes of all KItemListWidget instances that are located
        // after the inserted items. It is important to adjust the indexes in the order
        // from the highest index to the lowest index to prevent overlaps when setting the new index.
Laurent Montel's avatar
Laurent Montel committed
1039
        std::sort(itemsToMove.begin(), itemsToMove.end());
1040
1041
1042
        for (int i = itemsToMove.count() - 1; i >= 0; --i) {
            KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
            Q_ASSERT(widget);
1043
            const int newIndex = widget->index() + count;
1044
            if (hasMultipleRanges) {
1045
                setWidgetIndex(widget, newIndex);
1046
1047
            } else {
                // Try to animate the moving of the item
1048
                moveWidgetToIndex(widget, newIndex);
1049
            }
1050
1051
        }

1052
1053
1054
1055
1056
1057
1058
1059
1060
        if (m_model->count() == count && m_activeTransactions == 0) {
            // Check whether a scrollbar is required to show the inserted items. In this case
            // the size of the layouter will be decreased before calling doLayout(): This prevents
            // an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
            const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical);
            const bool decreaseLayouterSize = ( verticalScrollOrientation && maximumScrollOffset() > size().height()) ||
                                              (!verticalScrollOrientation && maximumScrollOffset() > size().width());
            if (decreaseLayouterSize) {
                const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
1061
1062
1063
1064
1065
1066

                int scrollbarSpacing = 0;
                if (style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) {
                    scrollbarSpacing = style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing);
                }

1067
1068
                QSizeF layouterSize = m_layouter->size();
                if (verticalScrollOrientation) {
1069
                    layouterSize.rwidth() -= scrollBarExtent + scrollbarSpacing;
1070
                } else {
1071
                    layouterSize.rheight() -= scrollBarExtent + scrollbarSpacing;
1072
1073
                }
                m_layouter->setSize(layouterSize);
1074
1075
1076
1077
            }
        }

        if (!hasMultipleRanges) {
1078
            doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, count);
1079
            updateSiblingsInformation();
1080
        }
1081
    }
1082

1083
1084
    if (m_controller) {
        m_controller->selectionManager()->itemsInserted(itemRanges);
1085
1086
1087
    }

    if (hasMultipleRanges) {
1088
        m_endTransactionAnimationHint = NoAnimation;
1089
        endTransaction();
1090

1091
        updateSiblingsInformation();
1092
    }
Peter Penz's avatar
Peter Penz committed
1093

1094
1095
1096
1097
1098
1099
1100
    if (m_grouped && (hasMultipleRanges || itemRanges.first().count < m_model->count())) {
        // In case if items of the same group have been inserted before an item that
        // currently represents the first item of the group, the group header of
        // this item must be removed.
        updateVisibleGroupHeaders();
    }

Peter Penz's avatar
Peter Penz committed
1101
1102
1103
    if (useAlternateBackgrounds()) {
        updateAlternateBackgrounds();
    }
1104
1105
1106
1107
}

void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
{
1108
    if (m_itemSize.isEmpty()) {
1109
1110
        // Don't pass the item-range: The preferred column-widths of
        // all items must be adjusted when removing items.
1111
1112
        updatePreferredColumnWidths();
    }
1113
1114
1115
1116
1117
1118

    const bool hasMultipleRanges = (itemRanges.count() > 1);
    if (hasMultipleRanges) {
        beginTransaction();
    }

1119
1120
    m_layouter->markAsDirty();

1121
1122
    m_sizeHintResolver->itemsRemoved(itemRanges);

1123
    for (int i = itemRanges.count() - 1; i >= 0; --i) {
Peter Penz's avatar
Peter Penz committed
1124
        const KItemRange& range = itemRanges[i];
1125
1126
1127
        const int index = range.index;
        const int count = range.count;
        if (index < 0 || count <= 0) {
1128
            qCWarning(DolphinDebug) << "Invalid item range (index:" << index << ", count:" << count << ")";
1129
1130
1131
1132
1133
            continue;
        }

        const int firstRemovedIndex = index;
        const int lastRemovedIndex = index + count - 1;
1134

Yuri Chornoivan's avatar
Yuri Chornoivan committed
1135
        // Remember which items have to be moved because they are behind the removed range.
1136
        QVector<int> itemsToMove;
1137
1138

        // Remove all KItemListWidget instances that got deleted
1139
1140
1141
1142
1143
1144
        foreach (KItemListWidget* widget, m_visibleItems) {
            const int i = widget->index();
            if (i < firstRemovedIndex) {
                continue;
            } else if (i > lastRemovedIndex) {
                itemsToMove.append(i);
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
                continue;
            }

            m_animation->stop(widget);
            // Stopping the animation might lead to recycling the widget if
            // it is invisible (see slotAnimationFinished()).
            // Check again whether it is still visible:
            if (!m_visibleItems.contains(i)) {
                continue;
            }

1156
1157
            if (m_model->count() == 0 || hasMultipleRanges || !animateChangedItemCount(count)) {
                // Remove the widget without animation
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
                recycleWidget(widget);
            } else {
                // Animate the removing of the items. Special case: When removing an item there
                // is no valid model index available anymore. For the
                // remove-animation the item gets removed from m_visibleItems but the widget
                // will stay alive until the animation has been finished and will
                // be recycled (deleted) in KItemListView::slotAnimationFinished().
                m_visibleItems.remove(i);
                widget->setIndex(-1);
                m_animation->start(widget, KItemListViewAnimation::DeleteAnimation);
            }
        }

        // Update the indexes of all KItemListWidget instances that are located
1172
1173
1174
1175
        // after the deleted items. It is important to update them in ascending
        // order to prevent overlaps when setting the new index.
        std::sort(itemsToMove.begin(), itemsToMove.end());
        foreach (int i, itemsToMove) {
1176
            KItemListWidget* widget = m_visibleItems.value(i);
1177
1178
1179
1180
1181
1182
1183
            Q_ASSERT(widget);
            const int newIndex = i - count;
            if (hasMultipleRanges) {
                setWidgetIndex(widget, newIndex);
            } else {
                // Try to animate the moving of the item
                moveWidgetToIndex(widget, newIndex);
1184
1185
1186
1187
            }
        }

        if (!hasMultipleRanges) {
1188
1189
1190
1191
1192
1193
            // The decrease-layout-size optimization in KItemListView::slotItemsInserted()
            // assumes an updated geometry. If items are removed during an active transaction,
            // the transaction will be temporary deactivated so that doLayout() triggers a
            // geometry update if necessary.
            const int activeTransactions = m_activeTransactions;
            m_activeTransactions = 0;
Peter Penz's avatar
Peter Penz committed
1194
            doLayout(animateChangedItemCount(count) ? Animation : NoAnimation, index, -count);
1195
            m_activeTransactions = activeTransactions;
1196
            updateSiblingsInformation();
1197
        }
1198
    }
1199

1200
1201
    if (m_controller) {
        m_controller->selectionManager()->itemsRemoved(itemRanges);
1202
1203
1204
    }

    if (hasMultipleRanges) {
1205
        m_endTransactionAnimationHint = NoAnimation;
1206
        endTransaction();
1207
        updateSiblingsInformation();
1208
    }
Peter Penz's avatar
Peter Penz committed
1209