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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
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
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2009-04-22
 * Description : Qt model-view for items
 *
 * SPDX-FileCopyrightText: 2009-2012 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 * SPDX-FileCopyrightText: 2017      by Simon Frei <freisim93 at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "itemcategorizedview.h"

// Qt includes

#include <QApplication>
#include <QTimer>

// Local includes

#include "digikam_debug.h"
#include "album.h"
#include "albummanager.h"
#include "coredbfields.h"
#include "iccsettings.h"
#include "itemalbummodel.h"
#include "itemalbumfiltermodel.h"
#include "itemcategorydrawer.h"
#include "itemdelegate.h"
#include "itemdelegateoverlay.h"
#include "itemthumbnailmodel.h"
#include "itemselectionoverlay.h"
#include "itemviewtooltip.h"
#include "loadingcacheinterface.h"
#include "thumbnailloadthread.h"
#include "tooltipfiller.h"
#include "itemfacedelegate.h"

namespace Digikam
{

class Q_DECL_HIDDEN ItemCategorizedViewToolTip : public ItemViewToolTip
{
    Q_OBJECT

public:

    explicit ItemCategorizedViewToolTip(ItemCategorizedView* const view)
        : ItemViewToolTip(view)
    {
    }

    ItemCategorizedView* view() const override
    {
        return static_cast<ItemCategorizedView*>(ItemViewToolTip::view());
    }

protected:

    QString tipContents() override
    {
        ItemInfo info = ItemModel::retrieveItemInfo(currentIndex());

        return ToolTipFiller::imageInfoTipContents(info);
    }
};

// -------------------------------------------------------------------------------

class Q_DECL_HIDDEN ItemCategorizedView::Private
{
public:

    Private() = default;

public:

    ItemModel*            model             = nullptr;
    ImageSortFilterModel* filterModel       = nullptr;

    ItemDelegate*         delegate          = nullptr;
    bool                  showToolTip       = false;

    qlonglong             scrollToItemId    = 0;

    QUrl                  unknownCurrentUrl;

    QTimer*               delayedEnterTimer = nullptr;
};

// -------------------------------------------------------------------------------

ItemCategorizedView::ItemCategorizedView(QWidget* const parent)
    : ItemViewCategorized(parent),
      d                  (new Private)
{
    setToolTip(new ItemCategorizedViewToolTip(this));

    LoadingCacheInterface::connectToSignalFileChanged(this,
            SLOT(slotFileChanged(QString)));

    connect(IccSettings::instance(), SIGNAL(signalICCSettingsChanged(ICCSettingsContainer,ICCSettingsContainer)),
            this, SLOT(slotIccSettingsChanged(ICCSettingsContainer,ICCSettingsContainer)));

    d->delayedEnterTimer = new QTimer(this);
    d->delayedEnterTimer->setInterval(10);
    d->delayedEnterTimer->setSingleShot(true);

    connect(d->delayedEnterTimer, SIGNAL(timeout()),
            this, SLOT(slotDelayedEnter()));
}

ItemCategorizedView::~ItemCategorizedView()
{
    d->delegate->removeAllOverlays();

    delete d;
}

void ItemCategorizedView::installDefaultModels()
{
    ItemAlbumModel* model             = new ItemAlbumModel(this);
    ItemAlbumFilterModel* filterModel = new ItemAlbumFilterModel(this);<--- Shadow variable

    filterModel->setSourceItemModel(model);

    filterModel->setSortRole(ItemSortSettings::SortByFileName);
    filterModel->setCategorizationMode(ItemSortSettings::CategoryByAlbum);
    filterModel->sort(0); // an initial sorting is necessary

    // set flags that we want to get dataChanged() signals for

    model->setWatchFlags(filterModel->suggestedWatchFlags());

    setModels(model, filterModel);
}

void ItemCategorizedView::setModels(ItemModel* model, ImageSortFilterModel* filterModel)
{
    if (d->delegate)
    {
        d->delegate->setAllOverlaysActive(false);
    }

    if (d->filterModel)
    {
        disconnect(d->filterModel, SIGNAL(layoutAboutToBeChanged()),
                   this, SLOT(layoutAboutToBeChanged()));

        disconnect(d->filterModel, SIGNAL(layoutChanged()),
                   this, SLOT(layoutWasChanged()));
    }

    if (d->model)
    {
        disconnect(d->model, SIGNAL(imageInfosAdded(QList<ItemInfo>)),
                   this, SLOT(slotItemInfosAdded()));
    }

    d->model       = model;
    d->filterModel = filterModel;

    setModel(d->filterModel);

    connect(d->filterModel, SIGNAL(layoutAboutToBeChanged()),
            this, SLOT(layoutAboutToBeChanged()));

    connect(d->filterModel, SIGNAL(layoutChanged()),
            this, SLOT(layoutWasChanged()),
            Qt::QueuedConnection);

    connect(d->model, SIGNAL(imageInfosAdded(QList<ItemInfo>)),
            this, SLOT(slotItemInfosAdded()));

    Q_EMIT modelChanged();

    if (d->delegate)
    {
        d->delegate->setAllOverlaysActive(true);
    }
}

ItemModel* ItemCategorizedView::itemModel() const
{
    return d->model;
}

ImageSortFilterModel* ItemCategorizedView::itemSortFilterModel() const
{
    return d->filterModel;
}

ItemFilterModel* ItemCategorizedView::itemFilterModel() const
{
    return d->filterModel->imageFilterModel();
}

ItemThumbnailModel* ItemCategorizedView::itemThumbnailModel() const
{
    return qobject_cast<ItemThumbnailModel*>(d->model);
}

ItemAlbumModel* ItemCategorizedView::itemAlbumModel() const
{
    return qobject_cast<ItemAlbumModel*>(d->model);
}

ItemAlbumFilterModel* ItemCategorizedView::itemAlbumFilterModel() const
{
    return qobject_cast<ItemAlbumFilterModel*>(d->filterModel->imageFilterModel());
}

QSortFilterProxyModel* ItemCategorizedView::filterModel() const
{
    return d->filterModel;
}

ItemDelegate* ItemCategorizedView::itemDelegate() const
{
    return d->delegate;
}

void ItemCategorizedView::setItemDelegate(ItemDelegate* delegate)
{
    ThumbnailSize oldSize     = thumbnailSize();
    ItemDelegate* oldDelegate = d->delegate;<--- Variable 'oldDelegate' can be declared as pointer to const

    if (oldDelegate)
    {
        hideIndexNotification();
        d->delegate->setAllOverlaysActive(false);
        d->delegate->setViewOnAllOverlays(nullptr);

        // Note: Be precise, no wildcard disconnect!

        disconnect(d->delegate, SIGNAL(requestNotification(QModelIndex,QString)),
                   this, SLOT(showIndexNotification(QModelIndex,QString)));

        disconnect(d->delegate, SIGNAL(hideNotification()),
                   this, SLOT(hideIndexNotification()));
    }

    d->delegate = delegate;
    d->delegate->setThumbnailSize(oldSize);

    if (oldDelegate)
    {
        d->delegate->setSpacing(oldDelegate->spacing());
    }

    ItemViewCategorized::setItemDelegate(d->delegate);
    setCategoryDrawer(d->delegate->categoryDrawer());
    updateDelegateSizes();

    d->delegate->setViewOnAllOverlays(this);
    d->delegate->setAllOverlaysActive(true);

    connect(d->delegate, SIGNAL(requestNotification(QModelIndex,QString)),
            this, SLOT(showIndexNotification(QModelIndex,QString)));

    connect(d->delegate, SIGNAL(hideNotification()),
            this, SLOT(hideIndexNotification()));
}

Album* ItemCategorizedView::currentAlbum() const
{
    ItemAlbumModel* const albumModel = itemAlbumModel();<--- Variable 'albumModel' can be declared as pointer to const

    // TODO: Change to QList return type

    if (albumModel && !(albumModel->currentAlbums().isEmpty()))
    {
        return albumModel->currentAlbums().constFirst();
    }

    return nullptr;
}

ItemInfo ItemCategorizedView::currentInfo() const
{
    return imageInfo(currentIndex());
}

QUrl ItemCategorizedView::currentUrl() const
{
    return currentInfo().fileUrl();
}

ItemInfo ItemCategorizedView::imageInfo(const QModelIndex& index) const
{
    return d->filterModel->imageInfo(index);
}

ItemInfoList ItemCategorizedView::imageInfos(const QList<QModelIndex>& indexes) const
{
    return ItemInfoList(d->filterModel->imageInfos(indexes));
}

ItemInfoList ItemCategorizedView::allItemInfos() const
{
    return ItemInfoList(d->filterModel->imageInfosSorted());
}

QList<QUrl> ItemCategorizedView::allUrls() const
{
    return allItemInfos().toImageUrlList();
}

ItemInfoList ItemCategorizedView::selectedItemInfos() const
{
    return imageInfos(selectedIndexes());
}

ItemInfoList ItemCategorizedView::selectedItemInfosCurrentFirst() const
{
    QModelIndexList indexes   = selectedIndexes();
    const QModelIndex current = currentIndex();

    if (!indexes.isEmpty())
    {
        if (indexes.first() != current)
        {
            if (indexes.removeOne(current))
            {
                indexes.prepend(current);
            }
        }
    }

    return imageInfos(indexes);
}

void ItemCategorizedView::toIndex(const QUrl& url)
{
    ItemViewCategorized::toIndex(d->filterModel->indexForPath(url.toLocalFile()));
}

QModelIndex ItemCategorizedView::indexForInfo(const ItemInfo& info) const
{
    return d->filterModel->indexForItemInfo(info);
}

ItemInfo ItemCategorizedView::nextInOrder(const ItemInfo& startingPoint, int nth)
{
    QModelIndex index = d->filterModel->indexForItemInfo(startingPoint);

    if (!index.isValid())
    {
        return ItemInfo();
    }

    return imageInfo(d->filterModel->index(index.row() + nth, 0, QModelIndex()));
}

QModelIndex ItemCategorizedView::nextIndexHint(const QModelIndex& anchor, const QItemSelectionRange& removed) const
{
    QModelIndex hint = ItemViewCategorized::nextIndexHint(anchor, removed);
    ItemInfo info    = imageInfo(anchor);
/*
    qCDebug(DIGIKAM_GENERAL_LOG) << "Having initial hint" << hint << "for" << anchor << d->model->numberOfIndexesForItemInfo(info);
*/
    // Fixes a special case of multiple (face) entries for the same image.
    // If one is removed, any entry of the same image shall be preferred.

    if (d->model->numberOfIndexesForItemInfo(info) > 1)
    {
        // The hint is for a different info, but we may have a hint for the same info

        if (info != imageInfo(hint))
        {
            int minDiff                           = d->filterModel->rowCount();
            QList<QModelIndex> indexesForItemInfo = d->filterModel->mapListFromSource(d->model->indexesForItemInfo(info));

            for (const QModelIndex& index : std::as_const(indexesForItemInfo))
            {
                if ((index == anchor) || !index.isValid() || removed.contains(index))
                {
                    continue;
                }

                int distance = qAbs(index.row() - anchor.row());

                if (distance < minDiff)
                {
                    minDiff = distance;
                    hint    = index;
/*
                    qCDebug(DIGIKAM_GENERAL_LOG) << "Chose index" << hint << "at distance" << minDiff << "to" << anchor;
*/
                }
            }
        }
    }

    return hint;
}

void ItemCategorizedView::openAlbum(const QList<Album*>& albums)
{
    ItemAlbumModel* const albumModel = itemAlbumModel();

    if (albumModel)
    {
        albumModel->openAlbum(albums);
    }
}

ThumbnailSize ItemCategorizedView::thumbnailSize() const
{
/*
    ItemThumbnailModel* const thumbModel = imageThumbnailModel();

    if (thumbModel)
    {
        return thumbModel->thumbnailSize();
    }
*/
    if (d->delegate)
    {
        return d->delegate->thumbnailSize();
    }

    return ThumbnailSize();
}

void ItemCategorizedView::setThumbnailSize(int size)
{
    setThumbnailSize(ThumbnailSize(size));
}

void ItemCategorizedView::setThumbnailSize(const ThumbnailSize& s)
{
    // we abuse this pair of method calls to restore scroll position

    layoutAboutToBeChanged();
    d->delegate->setThumbnailSize(s);
    layoutWasChanged();
}

void ItemCategorizedView::setCurrentWhenAvailable(qlonglong imageId)
{
    d->scrollToItemId = imageId;
}

void ItemCategorizedView::setCurrentUrlWhenAvailable(const QUrl& url)
{
    if (url.isEmpty())
    {
        clearSelection();
        setCurrentIndex(QModelIndex());

        return;
    }

    QString path      = url.toLocalFile();
    QModelIndex index = d->filterModel->indexForPath(path);

    if (!index.isValid())
    {
        d->unknownCurrentUrl = url;

        return;
    }

    clearSelection();
    setCurrentIndex(index);
    d->unknownCurrentUrl.clear();
}

void ItemCategorizedView::setCurrentUrl(const QUrl& url)
{
    if (url.isEmpty())
    {
        clearSelection();
        setCurrentIndex(QModelIndex());

        return;
    }

    QString path      = url.toLocalFile();
    QModelIndex index = d->filterModel->indexForPath(path);

    if (!index.isValid())
    {
        return;
    }

    clearSelection();
    setCurrentIndex(index);
}

void ItemCategorizedView::setCurrentInfo(const ItemInfo& info)
{
    QModelIndex index = d->filterModel->indexForItemInfo(info);
    clearSelection();
    setCurrentIndex(index);
}

void ItemCategorizedView::setSelectedUrls(const QList<QUrl>& urlList)
{
    QItemSelection mySelection;

    for (QList<QUrl>::const_iterator it = urlList.constBegin() ; it!=urlList.constEnd() ; ++it)
    {
        const QString path      = it->toLocalFile();
        const QModelIndex index = d->filterModel->indexForPath(path);

        if (!index.isValid())
        {
            qCWarning(DIGIKAM_GENERAL_LOG) << "no QModelIndex found for" << *it;
        }
        else
        {
            // TODO: is there a better way?

            mySelection.select(index, index);
        }
    }

    clearSelection();
    selectionModel()->select(mySelection, QItemSelectionModel::Select);
}

void ItemCategorizedView::setSelectedItemInfos(const QList<ItemInfo>& infos)
{
    QItemSelection mySelection;

    for (const ItemInfo& info : std::as_const(infos))
    {
        QModelIndex index = d->filterModel->indexForItemInfo(info);
        mySelection.select(index, index);
    }

    selectionModel()->select(mySelection, QItemSelectionModel::ClearAndSelect);
}

void ItemCategorizedView::hintAt(const ItemInfo& info)
{
    if (info.isNull())
    {
        return;
    }

    QModelIndex index = d->filterModel->indexForItemInfo(info);

    if (!index.isValid())
    {
        return;
    }

    selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
    scrollTo(index);
}

void ItemCategorizedView::addOverlay(ItemDelegateOverlay* overlay, ItemDelegate* delegate)
{
    if (!delegate)
    {
        delegate = d->delegate;
    }

    delegate->installOverlay(overlay);

    if (delegate == d->delegate)
    {
        overlay->setView(this);
        overlay->setActive(true);
    }
}

void ItemCategorizedView::removeOverlay(ItemDelegateOverlay* overlay)
{
    ItemDelegate* const delegate = dynamic_cast<ItemDelegate*>(overlay->delegate());

    if (delegate)
    {
        delegate->removeOverlay(overlay);
    }

    overlay->setView(nullptr);
}

void ItemCategorizedView::updateGeometries()
{
    ItemViewCategorized::updateGeometries();
    d->delayedEnterTimer->start();
}

void ItemCategorizedView::slotDelayedEnter()
{
    // re-emit entered() for index under mouse (after layout).

    QModelIndex mouseIndex = indexAt(mapFromGlobal(QCursor::pos()));

    if (mouseIndex.isValid())
    {
        Q_EMIT DCategorizedView::entered(mouseIndex);
    }
}

void ItemCategorizedView::addSelectionOverlay(ItemDelegate* delegate)
{
    addOverlay(new ItemSelectionOverlay(this), delegate);
}

void ItemCategorizedView::scrollToStoredItem()
{
    if (d->scrollToItemId)
    {
        if (d->model->hasImage(d->scrollToItemId))
        {
            QModelIndex index = d->filterModel->indexForImageId(d->scrollToItemId);
            setCurrentIndex(index);
            scrollToRelaxed(index, QAbstractItemView::PositionAtCenter);
            d->scrollToItemId = 0;
        }
    }
}

void ItemCategorizedView::slotItemInfosAdded()
{
    if      (d->scrollToItemId)
    {
        scrollToStoredItem();
    }
    else if (!d->unknownCurrentUrl.isEmpty())
    {
        QTimer::singleShot(100, this, SLOT(slotCurrentUrlTimer()));
    }
}

void ItemCategorizedView::slotCurrentUrlTimer()
{
    setCurrentUrl(d->unknownCurrentUrl);
    d->unknownCurrentUrl.clear();
}

void ItemCategorizedView::slotFileChanged(const QString& filePath)
{
    QModelIndex index = d->filterModel->indexForPath(filePath);

    if (index.isValid())
    {
        update(index);
    }
}

void ItemCategorizedView::indexActivated(const QModelIndex& index, Qt::KeyboardModifiers modifiers)
{
    ItemInfo info = imageInfo(index);

    if (!info.isNull())
    {
        activated(info, modifiers);

        Q_EMIT imageActivated(info);
    }
}

void ItemCategorizedView::currentChanged(const QModelIndex& index, const QModelIndex& previous)
{
    ItemViewCategorized::currentChanged(index, previous);

    Q_EMIT currentChanged(imageInfo(index));
}

void ItemCategorizedView::selectionChanged(const QItemSelection& selectedItems, const QItemSelection& deselectedItems)
{
    ItemViewCategorized::selectionChanged(selectedItems, deselectedItems);

    if (!selectedItems.isEmpty())
    {
        Q_EMIT selected(imageInfos(selectedItems.indexes()));
    }

    if (!deselectedItems.isEmpty())
    {
        Q_EMIT deselected(imageInfos(deselectedItems.indexes()));
    }
}

Album* ItemCategorizedView::albumAt(const QPoint& pos) const
{
    if (itemFilterModel()->imageSortSettings().categorizationMode == ItemSortSettings::CategoryByAlbum)
    {
        QModelIndex categoryIndex = indexForCategoryAt(pos);

        if (categoryIndex.isValid())
        {
            int albumId = categoryIndex.data(ItemFilterModel::CategoryAlbumIdRole).toInt();

            return AlbumManager::instance()->findPAlbum(albumId);
        }
    }

    return currentAlbum();
}

void ItemCategorizedView::activated(const ItemInfo&, Qt::KeyboardModifiers)
{
    // implemented in subclass
}

void ItemCategorizedView::showContextMenuOnIndex(QContextMenuEvent* event, const QModelIndex& index)
{
    showContextMenuOnInfo(event, imageInfo(index));
}

void ItemCategorizedView::showContextMenuOnInfo(QContextMenuEvent*, const ItemInfo&)
{
    // implemented in subclass
}

QItemSelectionModel* ItemCategorizedView::getSelectionModel() const
{
    return selectionModel();
}

AbstractItemDragDropHandler* ItemCategorizedView::dragDropHandler() const
{
    return d->model->dragDropHandler();
}

void ItemCategorizedView::slotIccSettingsChanged(const ICCSettingsContainer&, const ICCSettingsContainer&)
{
    viewport()->update();
}

} // namespace Digikam

#include "itemcategorizedview.moc"

#include "moc_itemcategorizedview.cpp"