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
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 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
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2010-10-27
 * Description : Model to an ItemHistoryGraph
 *
 * SPDX-FileCopyrightText: 2010-2011 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "itemhistorygraphmodel.h"

// Qt includes

#include <QTreeWidgetItem>
#include <QIcon>

// KDE includes

#include <klocalizedstring.h>

// Local includes

#include "dcategorizedsortfilterproxymodel.h"
#include "dimgfiltermanager.h"
#include "itemlistmodel.h"
#include "itemhistorygraphdata.h"

// clazy:excludeall=missing-typeinfo

namespace Digikam
{

class Q_DECL_HIDDEN HistoryTreeItem
{
public:

    enum HistoryTreeItemType
    {
        UnspecifiedType,
        VertexItemType,
        FilterActionItemType,
        HeaderItemType,
        CategoryItemType,
        SeparatorItemType
    };

public:

    HistoryTreeItem();
    virtual ~HistoryTreeItem();

    virtual HistoryTreeItemType type()  const
    {
        return UnspecifiedType;
    }

    bool isType(HistoryTreeItemType t)  const
    {
        return (type() == t);
    }

    void addItem(HistoryTreeItem* child);

    int childCount() const
    {
        return children.size();
    }

    HistoryTreeItem* child(int index)   const
    {
        return children.at(index);
    }

public:

    HistoryTreeItem*        parent = nullptr;
    QList<HistoryTreeItem*> children;

private:

    Q_DISABLE_COPY(HistoryTreeItem)
};

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

class Q_DECL_HIDDEN VertexItem : public HistoryTreeItem
{
public:

    VertexItem() = default;

    explicit VertexItem(const HistoryGraph::Vertex& v)
        : vertex  (v),
          category(HistoryImageId::InvalidType)
    {
    }

    HistoryTreeItemType type() const override
    {
        return VertexItemType;
    }

public:

    HistoryGraph::Vertex  vertex;
    QModelIndex           index;
    HistoryImageId::Types category;

private:

    Q_DISABLE_COPY(VertexItem)
};

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

class Q_DECL_HIDDEN FilterActionItem : public HistoryTreeItem
{
public:

    FilterActionItem() = default;

    explicit FilterActionItem(const FilterAction& action)
        : action(action)
    {
    }

    HistoryTreeItemType type() const override
    {
        return FilterActionItemType;
    }

public:

    FilterAction action;

private:

    Q_DISABLE_COPY(FilterActionItem)
};

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

class Q_DECL_HIDDEN HeaderItem : public HistoryTreeItem
{
public:

    explicit HeaderItem(const QString& tt)
        : title(tt)
    {
    }

    HistoryTreeItemType type() const override
    {
        return HeaderItemType;
    }

public:

    QString title;

private:

    Q_DISABLE_COPY(HeaderItem)
};

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

class Q_DECL_HIDDEN CategoryItem : public HistoryTreeItem
{
public:

    explicit CategoryItem(const QString& tt)
        : title(tt)
    {
    }

    HistoryTreeItemType type() const override
    {
        return CategoryItemType;
    }

public:

    QString title;

private:

    Q_DISABLE_COPY(CategoryItem)
};

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

class Q_DECL_HIDDEN SeparatorItem : public HistoryTreeItem
{
public:

    SeparatorItem() = default;

    HistoryTreeItemType type() const override
    {
        return SeparatorItemType;
    }

private:

    Q_DISABLE_COPY(SeparatorItem)
};

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

#define if_isItem(class, name, pointer)                                                             \
    if (pointer && static_cast<HistoryTreeItem*>(pointer)->type() == HistoryTreeItem:: class##Type) \
        for (class* name = static_cast<class*>(pointer) ; name ; name = nullptr)

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

HistoryTreeItem::HistoryTreeItem()
    : parent(nullptr)
{
}

HistoryTreeItem::~HistoryTreeItem()
{
    qDeleteAll(children);
}

void HistoryTreeItem::addItem(HistoryTreeItem* child)
{
    children << child;
    child->parent = this;
}

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

static bool oldestInfoFirst(const ItemInfo&a, const ItemInfo& b)
{
    return (a.modDateTime() < b.modDateTime());
}

static bool newestInfoFirst(const ItemInfo&a, const ItemInfo& b)
{
    return (a.modDateTime() > b.modDateTime());
}

template <typename ItemInfoLessThan>

class Q_DECL_HIDDEN LessThanOnVertexItemInfo
{
public:

    LessThanOnVertexItemInfo(const HistoryGraph& gg, ItemInfoLessThan imageInfoLessThan)
        : graph            (gg),
          imageInfoLessThan(imageInfoLessThan)
    {
    }

    bool operator()(const HistoryGraph::Vertex& a, const HistoryGraph::Vertex& b) const
    {
        const HistoryVertexProperties& propsA = graph.properties(a);
        const HistoryVertexProperties& propsB = graph.properties(b);

        if      (propsA.infos.isEmpty())
        {
            return false;
        }
        else if (propsB.infos.isEmpty())
        {
            return true;
        }

        return imageInfoLessThan(propsA.infos.first(), propsB.infos.first());
    }

public:

    const HistoryGraph& graph;
    ItemInfoLessThan    imageInfoLessThan;
};

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

class Q_DECL_HIDDEN ItemHistoryGraphModel::Private
{
public:

    Private() = default;

public:

    ItemHistoryGraphModel::Mode                        mode         = ItemHistoryGraphModel::CombinedTreeMode;

    ItemHistoryGraph                                   historyGraph;
    ItemInfo                                           info;

    HistoryTreeItem*                                   rootItem     = nullptr;
    QList<VertexItem*>                                 vertexItems;
    ItemListModel*                                     imageModel   = nullptr;
    QList<HistoryGraph::Vertex>                        path;
    QHash<HistoryGraph::Vertex, HistoryImageId::Types> categories;

public:

    inline const ItemHistoryGraphData& graph() const
    {
        return historyGraph.data();
    }

    inline HistoryTreeItem* historyItem(const QModelIndex& index) const
    {
        return (index.isValid() ? static_cast<HistoryTreeItem*>(index.internalPointer())
                                : rootItem);
    }

    void build();
    void buildImagesList();
    void buildImagesTree();
    void buildCombinedTree(const HistoryGraph::Vertex& ref);
    void addCombinedItemCategory(HistoryTreeItem* parentItem, QList<HistoryGraph::Vertex>& vertices,
                                 const QString& title, const HistoryGraph::Vertex& showActionsFrom,
                                 QList<HistoryGraph::Vertex>& added);
    void addItemSubgroup(VertexItem* parent, const QList<HistoryGraph::Vertex>& vertices, const QString& title, bool flat = false);
    void addIdenticalItems(HistoryTreeItem* parentItem, const HistoryGraph::Vertex& vertex,
                           const QList<ItemInfo>& infos, const QString& title);

    VertexItem* createVertexItem(const HistoryGraph::Vertex& v, const ItemInfo& info = ItemInfo());
    FilterActionItem* createFilterActionItem(const FilterAction& action);

    template <typename ItemInfoLessThan> LessThanOnVertexItemInfo<ItemInfoLessThan>

    sortBy(ItemInfoLessThan imageInfoLessThan)
    {
        return LessThanOnVertexItemInfo<ItemInfoLessThan>(graph(), imageInfoLessThan);
    }
};

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

VertexItem* ItemHistoryGraphModel::Private::createVertexItem(const HistoryGraph::Vertex& v,
                                                             const ItemInfo& givenInfo)
{
    const HistoryVertexProperties& props = graph().properties(v);
    ItemInfo info                        = givenInfo.isNull() ? props.firstItemInfo() : givenInfo;
    QModelIndex index                    = imageModel->indexForItemInfo(info);
/*
    qCDebug(DIGIKAM_DATABASE_LOG) << "Added" << info.id() << index;
*/
    VertexItem* item                     = new VertexItem(v);
    item->index                          = index;
    item->category                       = categories.value(v);
    vertexItems << item;
/*
    qCDebug(DIGIKAM_DATABASE_LOG) << "Adding vertex item" << graph().properties(v).firstItemInfo().id() << index;
*/
    return item;
}

FilterActionItem* ItemHistoryGraphModel::Private::createFilterActionItem(const FilterAction& action)
{
/*
    qCDebug(DIGIKAM_DATABASE_LOG) << "Adding vertex item for" << action.displayableName();
*/
    return new FilterActionItem(action);
}

void ItemHistoryGraphModel::Private::build()
{
    delete rootItem;
    vertexItems.clear();
    rootItem = new HistoryTreeItem;
/*
    qCDebug(DIGIKAM_DATABASE_LOG) << historyGraph;
*/
    HistoryGraph::Vertex ref = graph().findVertexByProperties(info);
    path                     = graph().longestPathTouching(ref, sortBy(newestInfoFirst));
    categories               = graph().categorize();

    if (path.isEmpty())
    {
        return;
    }

    if      (mode == ItemHistoryGraphModel::ImagesListMode)
    {
        buildImagesList();
    }
    else if (mode == ItemHistoryGraphModel::ImagesTreeMode)
    {
        buildImagesTree();
    }
    else if (mode == CombinedTreeMode)
    {
        buildCombinedTree(ref);
    }
}

void ItemHistoryGraphModel::Private::buildImagesList()
{
    QList<HistoryGraph::Vertex> verticesOrdered = graph().verticesDepthFirstSorted(path.first(),
                                                                                   sortBy(oldestInfoFirst));  // clazy:exclude=missing-typeinfo

    for (const HistoryGraph::Vertex& v : std::as_const(verticesOrdered))
    {
        rootItem->addItem(createVertexItem(v));
    }
}

void ItemHistoryGraphModel::Private::buildImagesTree()
{
    QList<HistoryGraph::Vertex> verticesOrdered = graph().verticesDepthFirstSorted(path.first(),
                                                                                   sortBy(oldestInfoFirst));  // clazy:exclude=missing-typeinfo

    QMap<HistoryGraph::Vertex, int> distances   = graph().shortestDistancesFrom(path.first());                // clazy:exclude=missing-typeinfo


    QList<HistoryGraph::Vertex> sources;                            // clazy:exclude=missing-typeinfo
    int previousLevel                           = 0;
    HistoryTreeItem* parent                     = rootItem;
    VertexItem* item                            = nullptr;
    VertexItem* previousItem                    = nullptr;

    for (const HistoryGraph::Vertex& v : std::as_const(verticesOrdered))
    {
        int currentLevel = distances.value(v);

        if (currentLevel == -1)
        {
            // Unreachable from first root.

            if (graph().isRoot(v) && (parent == rootItem))
            {
                // Other first-level root?

                parent->addItem(createVertexItem(v));
            }
            else
            {
                // Add later as sources.

                sources << v;
            }

            continue;
        }

        item = createVertexItem(v);

        if (!sources.isEmpty())
        {
            addItemSubgroup(item, sources, i18nc("@title", "Source Images"));
        }

        if      (currentLevel == previousLevel)
        {
            parent->addItem(item);
        }
        else if (currentLevel > previousLevel && previousItem) // Check pointer, prevent crash is distances are faulty.
        {
            previousItem->addItem(item);
            parent = previousItem;
        }
        else if (currentLevel < previousLevel)
        {
            for (int level = currentLevel ; level < previousLevel ; ++level)
            {
                parent = parent->parent;
            }
            parent->addItem(item);
        }

        previousItem  = item;
        previousLevel = currentLevel;
    }
}

void ItemHistoryGraphModel::Private::buildCombinedTree(const HistoryGraph::Vertex& ref)
{
    VertexItem* item                            = nullptr;
    CategoryItem *categoryItem                  = new CategoryItem(i18nc("@title", "Image History"));
    rootItem->addItem(categoryItem);

    QList<HistoryGraph::Vertex> added;                                                          // clazy:exclude=missing-typeinfo
    QList<HistoryGraph::Vertex> currentVersions = categories.keys(HistoryImageId::Current);     // clazy:exclude=missing-typeinfo
    QList<HistoryGraph::Vertex> leavesFromRef   = graph().leavesFrom(ref);                      // clazy:exclude=missing-typeinfo

    bool onePath = (leavesFromRef.size() <= 1);

    for (int i = 0 ; i < path.size() ; ++i)
    {
        const HistoryGraph::Vertex& v       = path.at(i);
        HistoryGraph::Vertex previous       = i ? path.at(i-1) : HistoryGraph::Vertex();
/*
        HistoryGraph::Vertex next           = i < path.size() - 1 ? path[i+1] : HistoryGraph::Vertex();
*/
/*
        qCDebug(DIGIKAM_DATABASE_LOG) << "Vertex on path" << path[i];
*/
        // Create new item.

        item                                = createVertexItem(v);

        // Any extra sources?

        QList<HistoryGraph::Vertex> sources = graph().adjacentVertices(item->vertex, HistoryGraph::EdgesToRoot);    // clazy:exclude=missing-typeinfo

        for (const HistoryGraph::Vertex& source : std::as_const(sources))
        {
            if (source != previous)
            {
                rootItem->addItem(createVertexItem(source));
            }
        }

/*
        // Any other egdes off the main path?

        QList<HistoryGraph::Vertex> branches = graph().adjacentVertices(v, HistoryGraph::EdgesToLeaf);
        QList<HistoryGraph::Vertex> subgraph;

        for (const HistoryGraph::Vertex& branch : std::as_const(branches))
        {
            if (branch != next)
            {
                subgraph << graph().verticesDominatedByDepthFirstSorted(branch, v, sortBy(oldestInfoFirst));
            }
        }

        addItemSubgroup(item, subgraph, i18nc("@title", "More Derived Images"));
*/

        // Add filter actions above item.

        HistoryEdgeProperties props = graph().properties(v, previous);

        for (const FilterAction& action : std::as_const(props.actions))
        {
            rootItem->addItem(createFilterActionItem(action));
        }

        // now, add item.

        rootItem->addItem(item);
        added << v;

        // If there are multiple derived images, we display them in the next section.

        if ((v == ref) && !onePath)
        {
            break;
        }
    }

    for (const HistoryGraph::Vertex& v : std::as_const(added))
    {
        leavesFromRef.removeOne(v);
    }

    if (!leavesFromRef.isEmpty())
    {
        addCombinedItemCategory(rootItem, leavesFromRef, i18nc("@title", "Derived Images"), ref, added);
    }

    for (const HistoryGraph::Vertex& v : std::as_const(added))
    {
        currentVersions.removeOne(v);
    }

    if (!currentVersions.isEmpty())
    {
        addCombinedItemCategory(rootItem, currentVersions, i18nc("@title", "Related Images"), path.first(), added);
    }

    QList<ItemInfo> allInfos = graph().properties(ref).infos;

    if (allInfos.size() > 1)
    {
        addIdenticalItems(rootItem, ref, allInfos, i18nc("@title", "Identical Images"));
    }
}

void ItemHistoryGraphModel::Private::addCombinedItemCategory(HistoryTreeItem* parentItem,
                                                             QList<HistoryGraph::Vertex>& vertices,
                                                             const QString& title,
                                                             const HistoryGraph::Vertex& showActionsFrom,
                                                             QList<HistoryGraph::Vertex>& added)
{
    parentItem->addItem(new CategoryItem(title));

    std::sort(vertices.begin(), vertices.end(), sortBy(oldestInfoFirst));
    bool isFirst     = true;
    VertexItem* item = nullptr;

    for (const HistoryGraph::Vertex& v : std::as_const(vertices))
    {
        if (isFirst)
        {
            isFirst = false;
        }
        else
        {
            parentItem->addItem(new SeparatorItem);
        }

        item                                     = createVertexItem(v);

        QList<HistoryGraph::Vertex> shortestPath = graph().shortestPath(showActionsFrom, v);     // clazy:exclude=missing-typeinfo

        // add all filter actions showActionsFrom -> v above item

        for (int i = 1 ; i < shortestPath.size() ; ++i)
        {
            HistoryEdgeProperties props = graph().properties(shortestPath.at(i), shortestPath.at(i-1));

            for (const FilterAction& action : std::as_const(props.actions))
            {
                parentItem->addItem(createFilterActionItem(action));
            }
        }

        parentItem->addItem(item);
        added << v;

        // Provide access to intermediates.

        shortestPath.removeOne(showActionsFrom);
        shortestPath.removeOne(v);

        for (const HistoryGraph::Vertex& addedVertex : std::as_const(added))
        {
            shortestPath.removeOne(addedVertex);
        }

        addItemSubgroup(item, shortestPath, i18nc("@title", "Intermediate Steps:"), true);
    }
}

void ItemHistoryGraphModel::Private::addItemSubgroup(VertexItem* parent,
                                                     const QList<HistoryGraph::Vertex>& vertices,
                                                     const QString& title,
                                                     bool flat)
{
    if (vertices.isEmpty())
    {
        return;
    }

    HeaderItem* const header         = new HeaderItem(title);
    parent->addItem(header);
    HistoryTreeItem* const addToItem = flat ? static_cast<HistoryTreeItem*>(parent) : static_cast<HistoryTreeItem*>(header);

    for (const HistoryGraph::Vertex& v : std::as_const(vertices))
    {
        addToItem->addItem(createVertexItem(v));
    }
}

void ItemHistoryGraphModel::Private::addIdenticalItems(HistoryTreeItem* parentItem,
                                                       const HistoryGraph::Vertex& vertex,
                                                       const QList<ItemInfo>& infos,
                                                       const QString& title)
{
    parentItem->addItem(new CategoryItem(title));

    // The properties image info list is already sorted by proximity to subject.

    VertexItem* item = nullptr;
    bool isFirst     = true;

    for (int i = 1 ; i < infos.size() ; ++i)
    {
        if (isFirst)
        {
            isFirst = false;
        }
        else
        {
            parentItem->addItem(new SeparatorItem);
        }

        item = createVertexItem(vertex, infos.at(i));
        parentItem->addItem(item);
    }
}

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

ItemHistoryGraphModel::ItemHistoryGraphModel(QWidget* const parent)
    : QAbstractItemModel(parent),
      d                 (new Private)
{
    d->rootItem   = new HistoryTreeItem;
    d->imageModel = new ItemListModel(parent);
}

ItemHistoryGraphModel::~ItemHistoryGraphModel()
{
    delete d->rootItem;
    delete d;
}

void ItemHistoryGraphModel::setMode(Mode mode)
{
    if (d->mode == mode)
    {
        return;
    }

    d->mode = mode;
    setHistory(d->info, d->historyGraph);
}

ItemHistoryGraphModel::Mode ItemHistoryGraphModel::mode() const
{
    return d->mode;
}

void ItemHistoryGraphModel::setHistory(const ItemInfo& subject, const ItemHistoryGraph& graph)
{
    beginResetModel();

    d->info = subject;

    if (graph.isNull())
    {
        d->historyGraph = ItemHistoryGraph::fromInfo(subject);
    }
    else
    {
        d->historyGraph = graph;
        d->historyGraph.prepareForDisplay(subject);
    }

    // Fill helper model.

    d->imageModel->clearItemInfos();
    d->imageModel->addItemInfos(d->historyGraph.allImages());

    d->build();

    endResetModel();
}

ItemInfo ItemHistoryGraphModel::subject() const
{
    return d->info;
}

bool ItemHistoryGraphModel::isImage(const QModelIndex& index) const
{
    HistoryTreeItem* const item = d->historyItem(index);

    return (item && item->isType(HistoryTreeItem::VertexItemType));
}

bool ItemHistoryGraphModel::isFilterAction(const QModelIndex& index) const
{
    HistoryTreeItem* const item = d->historyItem(index);

    return (item && item->isType(HistoryTreeItem::FilterActionItemType));
}

FilterAction ItemHistoryGraphModel::filterAction(const QModelIndex& index) const
{
    HistoryTreeItem* const item = d->historyItem(index);

    if_isItem(FilterActionItem, filterActionItem, item)
    {
        return filterActionItem->action;
    }

    return FilterAction();
}

bool ItemHistoryGraphModel::hasImage(const ItemInfo& info)
{
    return d->imageModel->hasImage(info);
}

ItemInfo ItemHistoryGraphModel::imageInfo(const QModelIndex& index) const
{
    QModelIndex imageIndex = imageModelIndex(index);

    return ItemModel::retrieveItemInfo(imageIndex);
}

QModelIndex ItemHistoryGraphModel::indexForInfo(const ItemInfo& info) const
{
    if (info.isNull())
    {
        return QModelIndex();
    }

    // Try with primary info.

    for (VertexItem* const item : std::as_const(d->vertexItems))
    {
        if (ItemModel::retrieveItemInfo(item->index) == info)
        {    // cppcheck-suppress useStlAlgorithm
            return createIndex(item->parent->children.indexOf(item), 0, item);
        }
    }

    // Try all associated infos.

    for (VertexItem* const item : std::as_const(d->vertexItems))
    {
        if (d->graph().properties(item->vertex).infos.contains(info))
        {
            return createIndex(item->parent->children.indexOf(item), 0, item);
        }
    }

    return QModelIndex();
}

QVariant ItemHistoryGraphModel::data(const QModelIndex& index, int role) const
{
    if (!index.isValid())
    {
        return QVariant();
    }

    HistoryTreeItem* const item = d->historyItem(index);

    if_isItem(VertexItem, vertexItem, item)
    {
        if (vertexItem->index.isValid())
        {
            QVariant data = vertexItem->index.data(role);<--- Shadow variable

            switch (role)
            {
                case IsImageItemRole:
                {
                    return true;
                }

                case IsSubjectImageRole:
                {
                    return (bool)d->graph().properties(vertexItem->vertex).infos.contains(d->info);
                }

                case Qt::DisplayRole:
                {
                    if (vertexItem->category & HistoryImageId::Original)
                    {
                        return i18nc("@item filename", "%1\n(Original Image)", data.toString());
                    }

                    if (vertexItem->category & HistoryImageId::Source)
                    {
                        return i18nc("@item filename", "%1\n(Source Image)", data.toString());
                    }

                    break;
                }
            }

            return data;
        }

        // Else, read HistoryImageId from d->graph().properties(vertexItem->vertex)?
    }
    else if_isItem(FilterActionItem, filterActionItem, item)
    {
        switch (role)
        {
            case IsFilterActionItemRole:
            {
                return true;
            }

            case Qt::DisplayRole:
            {
                return DImgFilterManager::instance()->i18nDisplayableName(filterActionItem->action);
            }

            case Qt::DecorationRole:
            {
                QString iconName = DImgFilterManager::instance()->filterIcon(filterActionItem->action);
                return QIcon::fromTheme(iconName);
            }

            case FilterActionRole:
            {
                return QVariant::fromValue(filterActionItem->action);
            }

            default:
            {
                break;
            }
        }
    }
    else if_isItem(HeaderItem, headerItem, item)
    {
        switch (role)
        {
            case IsHeaderItemRole:
            {
                return true;
            }

            case Qt::DisplayRole:
/*
            case Qt::ToolTipRole:
*/
            {
                return headerItem->title;
            }
        }
    }
    else if_isItem(CategoryItem, categoryItem, item)
    {
        switch (role)
        {
            case IsCategoryItemRole:
            {
                return true;
            }

            case Qt::DisplayRole:
            case DCategorizedSortFilterProxyModel::CategoryDisplayRole:
/*
            case Qt::ToolTipRole:
*/
            {
                return categoryItem->title;
            }
        }
    }
    else if_isItem(SeparatorItem, separatorItem, item)
    {
        switch (role)
        {
            case IsSeparatorItemRole:
            {
                return true;
            }
        }
    }

    switch (role)
    {
        case IsImageItemRole:
        case IsFilterActionItemRole:
        case IsHeaderItemRole:
        case IsCategoryItemRole:
        case IsSubjectImageRole:
        {
            return false;
        }

        default:
        {
            return QVariant();
        }
    }
}

bool ItemHistoryGraphModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
    HistoryTreeItem* const item = d->historyItem(index);

    if_isItem(VertexItem, vertexItem, item)
    {
        if (vertexItem->index.isValid())
        {
            return d->imageModel->setData(vertexItem->index, value, role);
        }
    }

    return false;
}

ItemListModel* ItemHistoryGraphModel::imageModel() const
{
    return d->imageModel;
}

QModelIndex ItemHistoryGraphModel::imageModelIndex(const QModelIndex& index) const
{
    HistoryTreeItem* const item = d->historyItem(index);

    if_isItem(VertexItem, vertexItem, item)
    {
        return vertexItem->index;
    }

    return QModelIndex();
}

QVariant ItemHistoryGraphModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_UNUSED(section)
    Q_UNUSED(orientation)
    Q_UNUSED(role)

    return QVariant();
}

int ItemHistoryGraphModel::rowCount(const QModelIndex& parent) const
{
    return d->historyItem(parent)->childCount();
}

int ItemHistoryGraphModel::columnCount(const QModelIndex&) const
{
    return 1;
}

Qt::ItemFlags ItemHistoryGraphModel::flags(const QModelIndex& index) const
{
    if (!index.isValid())
    {
        return Qt::NoItemFlags;
    }

    HistoryTreeItem* const item = d->historyItem(index);

    if_isItem(VertexItem, vertexItem, item)
    {
        return d->imageModel->flags(vertexItem->index);
    }

    if (item)
    {
        switch (item->type())
        {
            case HistoryTreeItem::FilterActionItemType:
            {
                return (Qt::ItemIsEnabled | Qt::ItemIsSelectable);
            }

            case HistoryTreeItem::HeaderItemType:
            case HistoryTreeItem::CategoryItemType:
            case HistoryTreeItem::SeparatorItemType:
            default:
            {
                return Qt::ItemIsEnabled;
            }
        }
    }

    return Qt::ItemIsEnabled;
}

QModelIndex ItemHistoryGraphModel::index(int row, int column, const QModelIndex& parent) const
{
    if ((column != 0) || (row < 0))
    {
        return QModelIndex();
    }

    HistoryTreeItem* const item = d->historyItem(parent);

    if (row >= item->childCount())
    {
        return QModelIndex();
    }

    return createIndex(row, 0, item->child(row));
}

bool ItemHistoryGraphModel::hasChildren(const QModelIndex& parent) const
{
    return d->historyItem(parent)->childCount();
}

QModelIndex ItemHistoryGraphModel::parent(const QModelIndex& index) const
{
    HistoryTreeItem* const item   = d->historyItem(index);
    HistoryTreeItem* const parent = item->parent;

    if (!parent)
    {
        return QModelIndex();    // Index was an invalid index.
    }

    HistoryTreeItem* const grandparent = parent->parent;

    if (!grandparent)
    {
        return QModelIndex();    // Index was a top-level index, was the invisible rootItem as parent.
    }

    return createIndex(grandparent->children.indexOf(parent), 0, parent);
}

} // namespace Digikam

#include "moc_itemhistorygraphmodel.cpp"