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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2008-11-15
 * Description : collections setup tab model/view
 *
 * SPDX-FileCopyrightText: 2008-2012 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 * SPDX-FileCopyrightText: 2005-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * SPDX-FileCopyrightText:      2012 by Andi Clemens <andi dot clemens at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "setupcollectionview.h"

// Qt includes

#include <QGroupBox>
#include <QLabel>
#include <QDir>
#include <QGridLayout>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QStandardPaths>
#include <QComboBox>
#include <QUrlQuery>
#include <QUrl>
#include <QIcon>
#include <QDialog>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QApplication>

// KDE includes

#include <klocalizedstring.h>

// Local includes

#include "dmessagebox.h"
#include "dfiledialog.h"
#include "applicationsettings.h"
#include "collectionmanager.h"
#include "newitemsfinder.h"
#include "dtextedit.h"
#include "digikam_globals.h"

namespace Digikam
{

SetupCollectionDelegate::SetupCollectionDelegate(QAbstractItemView* const view, QObject* const parent)
    : DWItemDelegate(view, parent)
{
    // We keep a standard delegate that does all the normal drawing work for us
    // DWItemDelegate handles the widgets, for the rest of the work we act as a proxy to m_styledDelegate

    m_styledDelegate = new QStyledItemDelegate(parent);

    // forward all signals

    connect(m_styledDelegate, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)),
            this, SIGNAL(closeEditor(QWidget*,QAbstractItemDelegate::EndEditHint)));

    connect(m_styledDelegate, SIGNAL(commitData(QWidget*)),
            this, SIGNAL(commitData(QWidget*)));

    connect(m_styledDelegate, SIGNAL(sizeHintChanged(QModelIndex)),
            this, SIGNAL(sizeHintChanged(QModelIndex)));

    // For size hint. To get a valid size hint, the widgets seem to need a parent widget

    m_samplePushButton   = new QPushButton(view);
    m_samplePushButton->hide();
    m_sampleAppendButton = new QToolButton(view);
    m_sampleAppendButton->hide();
    m_sampleUpdateButton = new QToolButton(view);
    m_sampleUpdateButton->hide();
    m_sampleDeleteButton = new QToolButton(view);
    m_sampleDeleteButton->hide();
}

SetupCollectionDelegate::~SetupCollectionDelegate()
{
}

QList<QWidget*> SetupCollectionDelegate::createItemWidgets(const QModelIndex& /*index*/) const
{
    // We only need a push button for certain indexes and two tool button for others,
    // but we have no index here, but need to provide the widgets for each index

    QList<QWidget*> list;
    QPushButton* const pushButton   = new QPushButton();
    list << pushButton;

    connect(pushButton, &QPushButton::clicked,
            this, [this, pushButton]()
        {
            Q_EMIT categoryButtonPressed(pushButton->property("id").toInt());
        }
    );

    QToolButton* const appendButton = new QToolButton();
    appendButton->setToolTip(i18nc("@info:tooltip", "Append a path to the collection."));
    appendButton->setAutoRaise(true);
    list << appendButton;

    connect(appendButton, &QToolButton::clicked,
            this, [this, appendButton]()
        {
            Q_EMIT appendPressed(appendButton->property("id").toInt());
        }
    );

    QToolButton* const updateButton = new QToolButton();
    updateButton->setToolTip(i18nc("@info:tooltip", "Updates the path of the collection."));
    updateButton->setAutoRaise(true);
    list << updateButton;

    connect(updateButton, &QToolButton::clicked,
            this, [this, updateButton]()
        {
            Q_EMIT updatePressed(updateButton->property("id").toInt());
        }
    );

    QToolButton* const deleteButton = new QToolButton();
    deleteButton->setToolTip(i18nc("@info:tooltip", "Removes the collection from digiKam."));
    deleteButton->setAutoRaise(true);
    list << deleteButton;

    connect(deleteButton, &QToolButton::clicked,
            this, [this, deleteButton]()
        {
            Q_EMIT deletePressed(deleteButton->property("id").toInt());
        }
    );

    return list;
}

QSize SetupCollectionDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    // get default size hint

    QSize hint = m_styledDelegate->sizeHint(option, index);

    // We need to handle those two cases where we display widgets

    if      (index.data(SetupCollectionModel::IsCategoryRole).toBool())
    {
        // get the largest size hint for the icon/text of all category entries

        int maxStyledWidth = 0;
        const auto idx     = static_cast<const SetupCollectionModel*>(index.model())->categoryIndexes();

        for (const QModelIndex& catIndex : idx)
        {
            maxStyledWidth = qMax(maxStyledWidth, m_styledDelegate->sizeHint(option, catIndex).width());
        }

        const_cast<SetupCollectionDelegate*>(this)->m_categoryMaxStyledWidth = maxStyledWidth;

        // set real text on sample button to compute correct size hint

        m_samplePushButton->setText(index.data(SetupCollectionModel::CategoryButtonDisplayRole).toString());
        QSize widgetHint = m_samplePushButton->sizeHint();

        // add largest of the icon/text sizes (so that all buttons are aligned) and our button size hint

        hint.setWidth(m_categoryMaxStyledWidth + widgetHint.width());
        hint.setHeight(qMax(hint.height(), widgetHint.height()));
    }
    else if (index.data(SetupCollectionModel::IsAppendRole).toBool())
    {
        // set real pixmap on sample button to compute correct size hint

        m_sampleAppendButton->setIcon(index.data(SetupCollectionModel::AppendDecorationRole).value<QIcon>());
        QSize widgetHint = m_sampleAppendButton->sizeHint();

        // combine hints

        hint.setWidth(hint.width() + widgetHint.width());
        hint.setHeight(qMax(hint.height(), widgetHint.height()));
    }
    else if (index.data(SetupCollectionModel::IsUpdateRole).toBool())
    {
        // set real pixmap on sample button to compute correct size hint

        m_sampleUpdateButton->setIcon(index.data(SetupCollectionModel::UpdateDecorationRole).value<QIcon>());
        QSize widgetHint = m_sampleUpdateButton->sizeHint();

        // combine hints

        hint.setWidth(hint.width() + widgetHint.width());
        hint.setHeight(qMax(hint.height(), widgetHint.height()));
    }
    else if (index.data(SetupCollectionModel::IsDeleteRole).toBool())
    {
        // set real pixmap on sample button to compute correct size hint

        m_sampleDeleteButton->setIcon(index.data(SetupCollectionModel::DeleteDecorationRole).value<QIcon>());
        QSize widgetHint = m_sampleDeleteButton->sizeHint();

        // combine hints

        hint.setWidth(hint.width() + widgetHint.width());
        hint.setHeight(qMax(hint.height(), widgetHint.height()));
    }

    return hint;
}

void SetupCollectionDelegate::updateItemWidgets(const QList<QWidget*>& widgets,
                                                const QStyleOptionViewItem& option,
                                                const QPersistentModelIndex& index) const
{
    QPushButton* const pushButton   = static_cast<QPushButton*>(widgets.at(0));
    QToolButton* const appendButton = static_cast<QToolButton*>(widgets.at(1));
    QToolButton* const updateButton = static_cast<QToolButton*>(widgets.at(2));
    QToolButton* const deleteButton = static_cast<QToolButton*>(widgets.at(3));

    if      (index.data(SetupCollectionModel::IsCategoryRole).toBool())
    {
        // set text from model

        pushButton->setText(index.data(SetupCollectionModel::CategoryButtonDisplayRole).toString());

        // resize according to size hint

        pushButton->resize(pushButton->sizeHint());

        // move to position in line. We have cached the icon/text size hint from sizeHint()

        pushButton->move(m_categoryMaxStyledWidth, (option.rect.height() - pushButton->height()) / 2);
        pushButton->show();
        appendButton->hide();
        updateButton->hide();
        deleteButton->hide();

        pushButton->setEnabled(itemView()->isEnabled());
        pushButton->setProperty("id", index.data(SetupCollectionModel::CategoryButtonMapId));
    }
    else if (index.data(SetupCollectionModel::IsAppendRole).toBool())
    {
        appendButton->setIcon(index.data(SetupCollectionModel::AppendDecorationRole).value<QIcon>());
        appendButton->resize(appendButton->sizeHint());
        appendButton->move(0, (option.rect.height() - appendButton->height()) / 2);
        appendButton->show();
        pushButton->hide();

        appendButton->setEnabled(itemView()->isEnabled());
        appendButton->setProperty("id", index.data(SetupCollectionModel::AppendMapId));
    }
    else if (index.data(SetupCollectionModel::IsUpdateRole).toBool())
    {
        updateButton->setIcon(index.data(SetupCollectionModel::UpdateDecorationRole).value<QIcon>());
        updateButton->resize(updateButton->sizeHint());
        updateButton->move(0, (option.rect.height() - updateButton->height()) / 2);
        updateButton->show();
        pushButton->hide();

        updateButton->setEnabled(itemView()->isEnabled());
        updateButton->setProperty("id", index.data(SetupCollectionModel::UpdateMapId));
    }
    else if (index.data(SetupCollectionModel::IsDeleteRole).toBool())
    {
        deleteButton->setIcon(index.data(SetupCollectionModel::DeleteDecorationRole).value<QIcon>());
        deleteButton->resize(deleteButton->sizeHint());
        deleteButton->move(0, (option.rect.height() - deleteButton->height()) / 2);
        deleteButton->show();
        pushButton->hide();

        deleteButton->setEnabled(itemView()->isEnabled());
        deleteButton->setProperty("id", index.data(SetupCollectionModel::DeleteMapId));
    }
    else
    {
        pushButton->hide();
        appendButton->hide();
        updateButton->hide();
        deleteButton->hide();
    }
}

QWidget* SetupCollectionDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    return m_styledDelegate->createEditor(parent, option, index);
}

bool SetupCollectionDelegate::editorEvent(QEvent* event, QAbstractItemModel* model,
                                          const QStyleOptionViewItem& option, const QModelIndex& index)
{
    return static_cast<QAbstractItemDelegate*>(m_styledDelegate)->editorEvent(event, model, option, index);
}

void SetupCollectionDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    m_styledDelegate->paint(painter, option, index);
}

void SetupCollectionDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
    m_styledDelegate->setEditorData(editor, index);
}

void SetupCollectionDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    m_styledDelegate->setModelData(editor, model, index);
}

void SetupCollectionDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    m_styledDelegate->updateEditorGeometry(editor, option, index);
}

// ------------- View ----------------- //

SetupCollectionTreeView::SetupCollectionTreeView(QWidget* const parent)
    : QTreeView(parent)
{
    setHeaderHidden(true);
    setRootIsDecorated(false);
    setUniformRowHeights(true);
    setExpandsOnDoubleClick(false);

    // Set custom delegate

    setItemDelegate(new SetupCollectionDelegate(this, this));
}

void SetupCollectionTreeView::setModel(SetupCollectionModel* collectionModel)
{
    if (model())
    {
        disconnect(model(), nullptr, this, nullptr);
    }

    // we need to do some things after the model has loaded its data

    connect(collectionModel, SIGNAL(collectionsLoaded()),
            this, SLOT(modelLoadedCollections()));

    // connect button click signals from the delegate to the model

    connect(static_cast<SetupCollectionDelegate*>(itemDelegate()), SIGNAL(categoryButtonPressed(int)),
            collectionModel, SLOT(slotCategoryButtonPressed(int)));

    connect(static_cast<SetupCollectionDelegate*>(itemDelegate()), SIGNAL(appendPressed(int)),
            collectionModel, SLOT(slotAppendPressed(int)));

    connect(static_cast<SetupCollectionDelegate*>(itemDelegate()), SIGNAL(updatePressed(int)),
            collectionModel, SLOT(slotUpdatePressed(int)));

    connect(static_cast<SetupCollectionDelegate*>(itemDelegate()), SIGNAL(deletePressed(int)),
            collectionModel, SLOT(slotDeletePressed(int)));

    // give model a widget to use as parent for message boxes

    collectionModel->setParentWidgetForDialogs(this);

    QTreeView::setModel(collectionModel);
}

void SetupCollectionTreeView::modelLoadedCollections()
{
    // make category entries span the whole line

    for (int i = 0 ; i < model()->rowCount(QModelIndex()) ; ++i)
    {
        setFirstColumnSpanned(i, QModelIndex(), true);
    }

    // show all entries

    expandAll();

    // Resize name and path column

    header()->setSectionResizeMode(SetupCollectionModel::ColumnName, QHeaderView::Stretch);
    header()->setSectionResizeMode(SetupCollectionModel::ColumnPath, QHeaderView::Stretch);

    // Resize last column, so that delete button is always rightbound

    header()->setStretchLastSection(false); // defaults to true
    header()->setSectionResizeMode(SetupCollectionModel::ColumnAppendButton, QHeaderView::Fixed);
    resizeColumnToContents(SetupCollectionModel::ColumnAppendButton);
    header()->setSectionResizeMode(SetupCollectionModel::ColumnUpdateButton, QHeaderView::Fixed);
    resizeColumnToContents(SetupCollectionModel::ColumnUpdateButton);
    header()->setSectionResizeMode(SetupCollectionModel::ColumnDeleteButton, QHeaderView::Fixed);
    resizeColumnToContents(SetupCollectionModel::ColumnDeleteButton);

    // Resize first column
    // This is more difficult because we need to ignore the width of the category entries,
    // which are formally location in the first column (although spanning the whole line).
    // resizeColumnToContents fails therefore.

    SetupCollectionModel* const collectionModel = static_cast<SetupCollectionModel*>(model());
    QModelIndex categoryIndex = collectionModel->indexForCategory(SetupCollectionModel::CategoryLocal);
    QModelIndex firstChildOfFirstCategory       = collectionModel->index(0, SetupCollectionModel::ColumnStatus, categoryIndex);
    QSize hint                                  = sizeHintForIndex(firstChildOfFirstCategory);
    setColumnWidth(SetupCollectionModel::ColumnStatus, hint.width() + indentation());
}

// ------------- Model ----------------- //

SetupCollectionModel::Item::Item()
    : parentId(INTERNALID)
{
}

SetupCollectionModel::Item::Item(const CollectionLocation& location)
    : location(location)
{
    parentId = SetupCollectionModel::typeToCategory(location.type());
}

SetupCollectionModel::Item::Item(const QString& path, const QString& label, SetupCollectionModel::Category category)
    : label   (label),
      path    (path),
      parentId(category)
{
}

/**
 * Internal data structure:
 *
 * The category entries get a model index with INTERNALID and are identified by their row().
 * The item entries get the index in m_collections as INTERNALID.
 * No item is ever removed from m_collections, deleted entries are only marked as such.
 *
 * Items have a location, a parentId, and a name and label field.
 * parentId always contains the category, needed to implement parent().
 * The location is the location if it exists, or is null if the item was added.
 * Name and label are null if unchanged, then the values from location are used.
 * They are valid if edited (label) or the location was added (both valid, location null).
 */

SetupCollectionModel::SetupCollectionModel(QObject* const parent)
    : QAbstractItemModel(parent)
{
}

SetupCollectionModel::~SetupCollectionModel()
{
}

void SetupCollectionModel::loadCollections()
{
    beginResetModel();

    m_collections.clear();
    QList<CollectionLocation> locations = CollectionManager::instance()->allLocations();

    for (const CollectionLocation& location : std::as_const(locations))
    {
        m_collections << Item(location);
        int idx = m_collections.size() - 1;

        if (location.type() == CollectionLocation::Network)
        {
            QUrl url(location.identifier);

            if (url.scheme() == QLatin1String("networkshareid"))
            {
                QUrlQuery q(url);
                const auto pathes = q.allQueryItemValues(QLatin1String("mountpath"));

                for (const QString& path : pathes)
                {
                    if (location.albumRootPath() != path)
                    {
                        Item item(location);
                        item.orgIndex = idx;
                        item.appended = true;
                        item.path     = path;
                        m_collections << item;
                        m_collections[idx].childs << path;
                    }
                }
            }
        }
    }

    endResetModel();

    Q_EMIT collectionsLoaded();
}

void SetupCollectionModel::apply()
{
    QList<int> newItems, deletedItems, updatedItems, renamedItems;

    for (int i = 0 ; i < m_collections.count() ; ++i)
    {
        const Item& item = m_collections.at(i);

        if      (item.appended)
        {
            continue;
        }
        else if (item.deleted && !item.location.isNull())
        {
            // if item was deleted and had a valid location, i.e. exists in DB

            deletedItems << i;
        }
        else if (!item.deleted && item.location.isNull())
        {
            // if item has no valid location, i.e. does not yet exist in db

            newItems << i;
        }
        else if (!item.deleted && !item.location.isNull())
        {
            // if item has a valid location, is updated or has changed its label

            if      (item.updated)
            {
                updatedItems << i;
            }
            else if (!item.label.isNull() && item.label != item.location.label())
            {
                renamedItems << i;
            }
        }
    }

    // Delete deleted items

    for (int i : std::as_const(deletedItems))
    {
        Item& item    = m_collections[i];
        CollectionManager::instance()->removeLocation(item.location);
        item.location = CollectionLocation();
    }

    // Add added items

    QList<Item> failedItems;

    for (int i : std::as_const(newItems))
    {
        Item& item = m_collections[i];
        CollectionLocation location;

        if (item.parentId == CategoryRemote)
        {
            location = CollectionManager::instance()->addNetworkLocation(QUrl::fromLocalFile(item.path), item.label);
        }
        else
        {
            location = CollectionManager::instance()->addLocation(QUrl::fromLocalFile(item.path), item.label);
        }

        if (location.isNull())
        {
            failedItems << item;
        }
        else
        {
            item.location = location;
            item.path.clear();
            item.label.clear();
        }
    }

    // Update collections

    for (int i : std::as_const(updatedItems))
    {
        Item& item  = m_collections[i];
        CollectionLocation location;

        int newType = CollectionLocation::VolumeHardWired;

        if      (item.parentId == CategoryRemovable)
        {
            newType = CollectionLocation::VolumeRemovable;
        }
        else if (item.parentId == CategoryRemote)
        {
            newType = CollectionLocation::Network;
        }

        QStringList pathList;
        pathList << item.path << item.childs;
        location    = CollectionManager::instance()->refreshLocation(item.location, newType,
                                                                     pathList, item.label);

        if (location.isNull())
        {
            failedItems << item;
        }
        else
        {
            item.location = location;
            item.path.clear();
            item.label.clear();
        }
    }

    // Rename collections

    for (int i : std::as_const(renamedItems))
    {
        Item& item = m_collections[i];
        CollectionManager::instance()->setLabel(item.location, item.label);
        item.label.clear();
    }

    // Handle any errors

    if (!failedItems.isEmpty())
    {
        QStringList failedPaths;

        for (const Item& item : std::as_const(failedItems))
        {
            failedPaths << QDir::toNativeSeparators(item.path);
        }

        DMessageBox::showInformationList(QMessageBox::Critical,
                                         m_dialogParentWidget,
                                         qApp->applicationName(),
                                         i18n("It was not possible to add a collection for the following paths:"),
                                         failedPaths);
    }

    // Trigger collection scan

    if (!newItems.isEmpty() || !updatedItems.isEmpty() || !deletedItems.isEmpty())
    {
        NewItemsFinder* const tool = new NewItemsFinder();
        tool->start();
    }
}

void SetupCollectionModel::setParentWidgetForDialogs(QWidget* widget)
{
    m_dialogParentWidget = widget;
}

void SetupCollectionModel::slotCategoryButtonPressed(int mappedId)
{
    addCollection(mappedId);
}

void SetupCollectionModel::slotAppendPressed(int mappedId)
{
    QString picPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);

    QUrl curl       = DFileDialog::getExistingDirectoryUrl(m_dialogParentWidget,
                                                           i18nc("@title:window", "Choose the Folder Containing your Collection"),
                                                           QUrl::fromLocalFile(picPath));

    curl            = curl.adjusted(QUrl::StripTrailingSlash);

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

    bool foundPath = false;

    for (const Item& item : std::as_const(m_collections))
    {
        if (!item.deleted)
        {
            QStringList possiblePaths;

            possiblePaths << item.childs;

            if      (!item.path.isEmpty())
            {
                possiblePaths << item.path;
            }
            else if (!item.location.isNull())
            {
                possiblePaths << item.location.albumRootPath();
            }

            if (possiblePaths.contains(curl.toLocalFile()))
            {
                foundPath = true;
                break;
            }
        }
    }

    if (foundPath)
    {
        QMessageBox::warning(m_dialogParentWidget, i18nc("@title:window", "Problem Appending Collection"),
                                                   i18n("A collection with the path \"%1\" already exists.",
                                                        QDir::toNativeSeparators(curl.toLocalFile())));

        return;
    }

    QModelIndex index = indexForId(mappedId, (int)ColumnStatus);<--- Shadow variable

    if (!index.isValid() || (mappedId >= m_collections.count()))
    {
        return;
    }

    Item& orgItem   = m_collections[index.internalId()];

    Item item(curl.toLocalFile(), orgItem.label, (Category)orgItem.parentId);
    orgItem.path    = !orgItem.updated ? orgItem.location.albumRootPath()
                                       : orgItem.path;
    orgItem.label   = orgItem.location.label();
    orgItem.childs << curl.toLocalFile();
    orgItem.updated = true;

    item.orgIndex   = index.internalId();
    item.location   = orgItem.location;
    item.appended   = true;

    int row         = rowCount(index);

    beginInsertRows(index, row, row);
    m_collections << item;
    endInsertRows();

    // only workaround for bug 182753

    Q_EMIT layoutChanged();
}

void SetupCollectionModel::slotUpdatePressed(int mappedId)
{
    updateCollection(mappedId);
}

void SetupCollectionModel::slotDeletePressed(int mappedId)
{
    deleteCollection(mappedId);
}

void SetupCollectionModel::addCollection(int category)
{
    if ((category < 0) || (category >= NumberOfCategories))
    {
        return;
    }

    QString label;
    QString path = lastAddedCollectionPath;

    if (askForNewCollectionPath(true, category, &path, &label))
    {
        // Add new item to model. Adding to CollectionManager is done in apply()!

        QModelIndex parent = indexForCategory((Category)category);<--- Shadow variable
        int row            = rowCount(parent);

        beginInsertRows(parent, row, row);
        m_collections << Item(path, label, (Category)category);
        endInsertRows();

        // only workaround for bug 182753

        Q_EMIT layoutChanged();
    }
}

/*
// NOTE: This code works, but is currently not used. Was intended as a workaround for 219876.

void SetupCollectionModel::emitDataChangedForChildren(const QModelIndex& parent)
{
    int rows    = rowCount(parent);
    int columns = columnCount(parent);

    Q_EMIT dataChanged(index(0, 0, parent), index(rows, columns, parent));

    for (int r = 0 ; r < rows ; ++r)
    {
        for (int c = 0 ; c < columns ; ++c)
        {
            QModelIndex i = index(r, c, parent);

            if (i.isValid())
            {
                emitDataChangedForChildren(i);
            }
        }
    }
}
*/

void SetupCollectionModel::updateCollection(int internalId)
{
    QModelIndex index = indexForId(internalId, (int)ColumnStatus);<--- Shadow variable

    if (!index.isValid() || (internalId >= m_collections.count()))
    {
        return;
    }

    Item& item   = m_collections[index.internalId()];
    int parentId = item.parentId;

    if (askForNewCollectionCategory(&parentId))
    {
        QString path = item.path;
        QString label;

        if (!item.location.isNull())
        {
            path = item.location.albumRootPath();
        }

        // Mark item as deleted so that
        // the path can be used again.

        item.deleted = true;

        if (askForNewCollectionPath(false, parentId, &path, &label))
        {
            item.parentId = parentId;
            item.label    = label;
            item.path     = path;
            item.updated  = true;

            // only workaround for bug 182753

            Q_EMIT layoutChanged();
        }

        item.deleted = false;
    }
}

void SetupCollectionModel::deleteCollection(int internalId)
{
    QModelIndex index       = indexForId(internalId, (int)ColumnStatus);<--- Shadow variable
    QModelIndex parentIndex = parent(index);

    if (!index.isValid() || (internalId >= m_collections.count()))
    {
        return;
    }

    int result    = QMessageBox::No;
    Item& item    = m_collections[index.internalId()];
    QString label = data(indexForId(internalId, (int)ColumnName), Qt::DisplayRole).toString();

    Q_UNUSED(result);

    // Ask for confirmation

    if (item.appended)
    {
        result = QMessageBox::warning(m_dialogParentWidget,
                                      i18nc("@title:window", "Remove Path from the Collection?"),
                                      i18n("Do you want to remove the appended path \"%1\" from the collection \"%2\"?",
                                           item.path, label),
                                      QMessageBox::Yes | QMessageBox::No);
    }
    else
    {
        result = QMessageBox::warning(m_dialogParentWidget,
                                      i18nc("@title:window", "Remove Collection?"),
                                      i18n("Do you want to remove the collection \"%1\" from your list of collections?",
                                            label),
                                      QMessageBox::Yes | QMessageBox::No);
    }

    if (result == QMessageBox::Yes)
    {
        // Remove from model. Removing from CollectionManager is done in apply()!

        beginRemoveRows(parentIndex, index.row(), index.row());
        item.deleted = true;
        endRemoveRows();

        if      (item.appended)
        {
            Item& orgItem   = m_collections[item.orgIndex];

            orgItem.path    = orgItem.location.albumRootPath();
            orgItem.label   = orgItem.location.label();
            orgItem.childs.removeAll(item.path);
            orgItem.updated = true;
        }
        else if (!item.childs.isEmpty())
        {
            for (int i = 0 ; i < m_collections.count() ; ++i)
            {
                Item& remItem = m_collections[i];

                if (remItem.orgIndex == (int)index.internalId())
                {
                    QModelIndex remIndex       = indexForId(i, (int)ColumnStatus);
                    QModelIndex remParentIndex = parent(remIndex);

                    beginRemoveRows(remParentIndex, remIndex.row(), remIndex.row());
                    remItem.deleted = true;
                    endRemoveRows();
                }
            }
        }

        // only workaround for bug 182753

        Q_EMIT layoutChanged();
    }
}

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

    if (index.internalId() == INTERNALID)
    {
        if (index.column() == 0)
        {
            switch (role)
            {
                case Qt::DisplayRole:
                {
                    switch (index.row())
                    {
                        case CategoryLocal:
                        {
                            return i18n("Local Collections");
                        }

                        case CategoryRemovable:
                        {
                            return i18n("Collections on Removable Media");
                        }

                        case CategoryRemote:
                        {
                            return i18n("Collections on Network Shares");
                        }
                    }

                    break;
                }

                case Qt::DecorationRole:
                {
                    switch (index.row())
                    {
                        case CategoryLocal:
                        {
                            return QIcon::fromTheme(QLatin1String("drive-harddisk"));
                        }

                        case CategoryRemovable:
                        {
                            return QIcon::fromTheme(QLatin1String("drive-removable-media"));
                        }

                        case CategoryRemote:
                        {
                            return QIcon::fromTheme(QLatin1String("network-wired-activated"));
                        }
                    }

                    break;
                }

                case IsCategoryRole:
                {
                    return true;
                }

                case CategoryButtonDisplayRole:
                {
                    return i18n("Add Collection");
                }

                case CategoryButtonMapId:
                {
                    return categoryButtonMapId(index);
                }

                default:
                {
                    break;
                }
            }
        }
    }
    else
    {
        const Item& item = m_collections.at(index.internalId());

        if ((role == Qt::BackgroundRole) && item.appended)
        {
             return QPalette().alternateBase();
        }

        switch (index.column())
        {
            case ColumnName:
            {
                if ((role == Qt::DisplayRole) || (role == Qt::EditRole))
                {
                    if (item.appended)
                    {
                        const Item& orgItem = m_collections.at(item.orgIndex);

                        if (!orgItem.label.isNull())
                        {
                            return orgItem.label;
                        }
                    }

                    if (!item.label.isNull())
                    {
                        return item.label;
                    }

                    if (!item.location.label().isNull())
                    {
                        return item.location.label();
                    }

                    return i18n("Col. %1", index.row());
                }

                break;
            }

            case ColumnPath:
            {
                if ((role == Qt::DisplayRole) || (role == Qt::ToolTipRole))
                {
                    if (!item.path.isNull())
                    {
                        return QDir::toNativeSeparators(item.path);
                    }

                    // TODO: Path can be empty for items not available,
                    // query more info from CollectionManager

                    return QDir::toNativeSeparators(item.location.albumRootPath());
                }

                break;
            }

            case ColumnStatus:
            {
                if (role == Qt::DecorationRole)
                {
                    if (item.updated)
                    {
                        return QIcon::fromTheme(QLatin1String("view-refresh"));
                    }

                    if (item.deleted)
                    {
                        return QIcon::fromTheme(QLatin1String("edit-delete"));
                    }

                    if (item.location.isNull())
                    {
                        return QIcon::fromTheme(QLatin1String("folder-new"));
                    }

                    if (item.appended)
                    {
                        return QIcon::fromTheme(QLatin1String("mail-attachment"));
                    }

                    switch (item.location.status())
                    {
                        case CollectionLocation::LocationAvailable:
                        {
                            return QIcon::fromTheme(QLatin1String("dialog-ok-apply"));
                        }

                        case CollectionLocation::LocationHidden:
                        {
                            return QIcon::fromTheme(QLatin1String("object-locked"));
                        }

                        case CollectionLocation::LocationUnavailable:
                        {
                            switch (item.parentId)
                            {
                                case CategoryLocal:
                                {
                                    return QIcon::fromTheme(QLatin1String("drive-harddisk")).pixmap(16, QIcon::Disabled);
                                }

                                case CategoryRemovable:
                                {
                                    return QIcon::fromTheme(QLatin1String("drive-removable-media-usb")).pixmap(16, QIcon::Disabled);
                                }

                                case CategoryRemote:
                                {
                                    return QIcon::fromTheme(QLatin1String("network-wired-activated")).pixmap(16, QIcon::Disabled);
                                }
                            }

                            break;
                        }

                        case CollectionLocation::LocationNull:
                        case CollectionLocation::LocationDeleted:
                        {
                            return QIcon::fromTheme(QLatin1String("edit-delete"));
                        }
                    }
                }
                else if (role == Qt::ToolTipRole)
                {
                    switch (item.location.status())
                    {
                        case CollectionLocation::LocationUnavailable:
                        {
                            return i18n("This collection is currently not available.");
                        }

                        case CollectionLocation::LocationAvailable:
                        {
                            return i18n("No problems found, enjoy this collection.");
                        }

                        case CollectionLocation::LocationHidden:
                        {
                            return i18n("This collection is hidden.");
                        }

                        default:
                        {
                            break;
                        }
                    }
                }

                break;
            }

            case ColumnAppendButton:
            {
                switch (role)
                {
                    case Qt::ToolTipRole:
                    {
                        return i18n("Append network path");
                    }

                    case IsAppendRole:
                    {
                        return ((item.location.type() == CollectionLocation::Network) && !item.appended);
                    }

                    case AppendDecorationRole:
                    {
                        return QIcon::fromTheme(QLatin1String("list-add"));
                    }

                    case AppendMapId:
                    {
                        return buttonMapId(index);
                    }
                }

                break;
            }

            case ColumnUpdateButton:
            {
                switch (role)
                {
                    case Qt::ToolTipRole:
                    {
                        return i18n("Update collection");
                    }

                    case IsUpdateRole:
                    {
                        return (!item.appended);
                    }

                    case UpdateDecorationRole:
                    {
                        return QIcon::fromTheme(QLatin1String("view-refresh"));
                    }

                    case UpdateMapId:
                    {
                        return buttonMapId(index);
                    }
                }

                break;
            }

            case ColumnDeleteButton:
            {
                switch (role)
                {
                    case Qt::ToolTipRole:
                    {
                        return i18n("Remove collection");
                    }

                    case IsDeleteRole:
                    {
                        return true;
                    }

                    case DeleteDecorationRole:
                    {
                        return QIcon::fromTheme(QLatin1String("edit-delete"));
                    }

                    case DeleteMapId:
                    {
                        return buttonMapId(index);
                    }
                }

                break;
            }
        }
    }

    return QVariant();
}

QVariant SetupCollectionModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if ((role == Qt::DisplayRole) && (orientation == Qt::Horizontal) && (section < NumberOfColumns))
    {
        switch (section)
        {
            case ColumnName:
            {
                return i18nc("#title: collection name",       "Name");
            }

            case ColumnPath:
            {
                return i18nc("#title: collection mount path", "Path");
            }

            case ColumnStatus:
            {
                return i18nc("#title: collection status",     "Status");
            }

            case ColumnAppendButton:
            {
                break;
            }

            case ColumnUpdateButton:
            {
                break;
            }

            case ColumnDeleteButton:
            {
                break;
            }
        }
    }

    return QVariant();
}

int SetupCollectionModel::rowCount(const QModelIndex& parent) const
{
    if (!parent.isValid())
    {
        return NumberOfCategories;    // Level 0: the three top level items
    }

    if (parent.column() != 0)
    {
        return 0;
    }

    if (parent.internalId() != INTERNALID)
    {
        return 0;                     // Level 2: no children
    }

    // Level 1: item children count

    int parentId = parent.row();
    int rowCount = 0;

    for (const Item& item : std::as_const(m_collections))
    {
        if (!item.deleted && (item.parentId == parentId))
        {
            ++rowCount; // cppcheck-suppress useStlAlgorithm
        }
    }

    return rowCount;
}

int SetupCollectionModel::columnCount(const QModelIndex& /*parent*/) const
{
    return NumberOfColumns;
}

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

    if (index.internalId() == INTERNALID)
    {
        return Qt::ItemIsEnabled;
    }
    else
    {
        Qt::ItemFlags flags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);<--- Shadow variable

        switch (index.column())
        {
            case ColumnName:
            {
                const Item& item = m_collections.at(index.internalId());

                if (item.appended)
                {
                    return flags;
                }

                return (flags | Qt::ItemIsEditable);
            }

            default:
            {
                return flags;
            }
        }
    }
}

bool SetupCollectionModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
    // only editable in one case

    if (
        index.isValid()                    &&
        (index.internalId() != INTERNALID) &&
        (index.column() == ColumnName)     &&
        (role == Qt::EditRole)
       )
    {
        Item& item = m_collections[index.internalId()];
        item.label = value.toString();

        Q_EMIT dataChanged(index, index);
    }

    return false;
}

QModelIndex SetupCollectionModel::index(int row, int column, const QModelIndex& parent) const
{
    if      (!parent.isValid())
    {
        if ((row < NumberOfCategories) && (row >= 0) && (column == 0))
        {
            return createIndex(row, 0, INTERNALID);
        }
    }
    else if ((row >= 0) && (column < NumberOfColumns))
    {
        // m_collections is a flat list with all entries, of all categories and also deleted entries.
        // The model indices contain as internal id the index to this list.

        int parentId = parent.row();
        int rowCount = 0;<--- Shadow variable

        for (int i = 0 ; i < m_collections.count() ; ++i)
        {
            const Item& item = m_collections.at(i);

            if (!item.deleted && (item.parentId == parentId))
            {
                if (rowCount == row)
                {
                    return createIndex(row, column, i);
                }

                ++rowCount;
            }
        }
    }

    return QModelIndex();
}

QModelIndex SetupCollectionModel::parent(const QModelIndex& index) const
{
    if (!index.isValid())
    {
        return QModelIndex();
    }

    if (index.internalId() == INTERNALID)
    {
        return QModelIndex();    // one of the three toplevel items
    }

    const Item& item = m_collections.at(index.internalId());

    return createIndex(item.parentId, 0, INTERNALID);
}

QModelIndex SetupCollectionModel::indexForCategory(Category category) const
{
    return index(category, 0, QModelIndex());
}

QList<QModelIndex> SetupCollectionModel::categoryIndexes() const
{
    QList<QModelIndex> list;

    for (int cat = 0 ; cat < NumberOfCategories ; ++cat)
    {
        list << index(cat, 0, QModelIndex());
    }

    return list;
}

QModelIndex SetupCollectionModel::indexForId(int id, int column) const
{
    if (id >= m_collections.size())
    {
        return QModelIndex();
    }

    int   row             = 0;
    const Item& indexItem = m_collections.at(id);

    for (int i = 0 ; i < m_collections.count() ; ++i)
    {
        const Item& item = m_collections.at(i);

        if (!item.deleted && (item.parentId == indexItem.parentId))
        {
            if (i == id)
            {
                return createIndex(row, column, i);
            }

            ++row;
        }
    }

    return QModelIndex();
}

SetupCollectionModel::Category SetupCollectionModel::typeToCategory(CollectionLocation::Type type)
{
    switch (type)
    {
        default:
        case CollectionLocation::VolumeHardWired:
        {
            return CategoryLocal;
        }

        case CollectionLocation::VolumeRemovable:
        {
            return CategoryRemovable;
        }

        case CollectionLocation::Network:
        {
            return CategoryRemote;
        }
    }
}

bool SetupCollectionModel::askForNewCollectionPath(bool adding, int category, QString* const newPath, QString* const newLabel)
{
    QString picPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);

    if (newPath && !(*newPath).isEmpty() && QFileInfo::exists(*newPath))
    {
        picPath = *newPath;
    }

    QUrl curl       = DFileDialog::getExistingDirectoryUrl(m_dialogParentWidget,
                                                           i18nc("@title:window", "Choose the Folder Containing your Collection"),
                                                           QUrl::fromLocalFile(picPath));

    curl            = curl.adjusted(QUrl::StripTrailingSlash);

    if (curl.isEmpty())
    {
        return false;
    }

    lastAddedCollectionPath = curl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile();

    // Check path: First check with manager

    QString messageFromManager, deviceIcon;
    QList<CollectionLocation> assumeDeleted;

    for (const Item& item : std::as_const(m_collections))
    {
        if (item.deleted && !item.location.isNull())
        {
            assumeDeleted << item.location;
        }
    }

    CollectionManager::LocationCheckResult result;

    if (category == CategoryRemote)
    {
        result = CollectionManager::instance()->checkNetworkLocation(curl, assumeDeleted,
                                                                     &messageFromManager, &deviceIcon);
    }
    else
    {
        result = CollectionManager::instance()->checkLocation(curl, assumeDeleted,
                                                              &messageFromManager, &deviceIcon);
    }

    QString path = curl.toLocalFile();

    // If there are other added collections then CollectionManager does not know about them. Check here.

    for (const Item& item : std::as_const(m_collections))
    {
        if (!item.deleted && item.location.isNull())
        {
            if (!item.path.isEmpty() && path.startsWith(item.path))
            {
                if ((path == item.path) || path.startsWith(item.path + QLatin1Char('/')))
                {
                    messageFromManager = i18n("You have previously added a collection "
                                              "that contains the path \"%1\".", QDir::toNativeSeparators(path));
                    result             = CollectionManager::LocationNotAllowed;

                    break;
                }
            }
        }
    }

    // If check failed, display sorry message

    QString iconName;

    switch (result)
    {
        case CollectionManager::LocationAllRight:
        {
            iconName = QLatin1String("dialog-ok-apply");

            break;
        }

        case CollectionManager::LocationHasProblems:
        {
            iconName = QLatin1String("dialog-information");

            break;
        }

        case CollectionManager::LocationNotAllowed:
        case CollectionManager::LocationInvalidCheck:
        {
            QString warning;

            if (adding)
            {
                warning = i18nc("@title:window",
                                "Problem Adding Collection");
            }
            else
            {
                warning = i18nc("@title:window",
                                "Problem updating Collection");
            }

            QMessageBox::warning(m_dialogParentWidget, warning, messageFromManager);

            // fail

            return false;
        }
    }

    // Create a dialog that displays volume information and allows to change the name of the collection

    QDialog* const dialog     = new QDialog(m_dialogParentWidget);

    if (adding)
    {
        dialog->setWindowTitle(i18nc("@title:window", "Adding Collection"));
    }
    else
    {
        dialog->setWindowTitle(i18nc("@title:window", "Update Collection"));
    }

    QWidget* const mainWidget = new QWidget(dialog);
    QLabel* const nameLabel   = new QLabel;

    if (adding)
    {
        nameLabel->setText(i18n("Your new collection will be created with this name:"));
    }
    else
    {
        nameLabel->setText(i18n("Your collection will be updated to this name:"));
    }

    nameLabel->setWordWrap(true);

    // lineedit for collection name

    DTextEdit* const nameEdit = new DTextEdit;
    nameEdit->setLinesVisible(1);
    nameLabel->setBuddy(nameEdit);

    // label for the icon showing the type of storage (hard disk, CD, USB drive)

    QLabel* const deviceIconLabel = new QLabel;
    deviceIconLabel->setPixmap(QIcon::fromTheme(deviceIcon).pixmap(64));

    QGroupBox* const infoBox      = new QGroupBox;
/*
    infoBox->setTitle(i18n("More Information"));
*/
    // label either signalling everything is all right, or raising awareness to some problems
    // (like handling of CD identified by a label)

    QLabel* const iconLabel = new QLabel;
    iconLabel->setPixmap(QIcon::fromTheme(iconName).pixmap(48));
    QLabel* const infoLabel = new QLabel;
    infoLabel->setText(messageFromManager);
    infoLabel->setWordWrap(true);

    QHBoxLayout* const hbox1 = new QHBoxLayout;
    hbox1->addWidget(iconLabel);
    hbox1->addWidget(infoLabel);
    infoBox->setLayout(hbox1);

    QGridLayout* const grid1 = new QGridLayout;
    grid1->addWidget(deviceIconLabel, 0, 0, 3, 1);
    grid1->addWidget(nameLabel,       0, 1);
    grid1->addWidget(nameEdit,        1, 1);
    grid1->addWidget(infoBox,         2, 1);
    mainWidget->setLayout(grid1);

    QVBoxLayout* const vbx          = new QVBoxLayout(dialog);
    QDialogButtonBox* const buttons = new QDialogButtonBox(QDialogButtonBox::Ok   |
                                                           QDialogButtonBox::Help |
                                                           QDialogButtonBox::Cancel,
                                                           dialog);
    vbx->addWidget(mainWidget);
    vbx->addWidget(buttons);
    dialog->setLayout(vbx);

    connect(buttons->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
            dialog, SLOT(accept()));

    connect(buttons->button(QDialogButtonBox::Cancel), SIGNAL(clicked()),
            dialog, SLOT(reject()));

    connect(buttons->button(QDialogButtonBox::Help), SIGNAL(clicked()),
            this, SLOT(slotHelp()));

    // default to directory name as collection name

    QDir dir(path);
    nameEdit->setText(dir.dirName());

    if (dialog->exec() == QDialog::Accepted)
    {
        if (newPath && newLabel)
        {
            *newLabel = nameEdit->text();
            *newPath  = path;

            return true;
        }
    }

    return false;
}

bool SetupCollectionModel::askForNewCollectionCategory(int* const category)
{
    // Create a dialog that displays the category and allows to change the category of the collection

    QDialog* const dialog     = new QDialog(m_dialogParentWidget);
    dialog->setWindowTitle(i18nc("@title:window", "Select Category"));

    QWidget* const mainWidget = new QWidget(dialog);
    QLabel* const nameLabel   = new QLabel;
    nameLabel->setText(i18n("Your collection will use this category:"));
    nameLabel->setWordWrap(true);

    // combobox for collection category

    QComboBox* const categoryBox = new QComboBox;
    categoryBox->addItem(i18n("Local Collections"),              CategoryLocal);
    categoryBox->addItem(i18n("Collections on Removable Media"), CategoryRemovable);
    categoryBox->addItem(i18n("Collections on Network Shares"),  CategoryRemote);

    // label for the icon showing the refresh icon

    QLabel* const questionIconLabel = new QLabel;
    questionIconLabel->setPixmap(QIcon::fromTheme(QLatin1String("view-sort")).pixmap(64));

    QGridLayout* const grid1        = new QGridLayout;
    grid1->addWidget(questionIconLabel, 0, 0, 3, 1);
    grid1->addWidget(nameLabel,         0, 1);
    grid1->addWidget(categoryBox,       1, 1);
    mainWidget->setLayout(grid1);

    QVBoxLayout* const vbx          = new QVBoxLayout(dialog);
    QDialogButtonBox* const buttons = new QDialogButtonBox(QDialogButtonBox::Ok   |
                                                           QDialogButtonBox::Help |
                                                           QDialogButtonBox::Cancel,
                                                           dialog);
    vbx->addWidget(mainWidget);
    vbx->addWidget(buttons);
    dialog->setLayout(vbx);

    connect(buttons->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
            dialog, SLOT(accept()));

    connect(buttons->button(QDialogButtonBox::Cancel), SIGNAL(clicked()),
            dialog, SLOT(reject()));

    connect(buttons->button(QDialogButtonBox::Help), SIGNAL(clicked()),
            this, SLOT(slotHelp()));

    // default to current category

    if (category)
    {
        categoryBox->setCurrentIndex(categoryBox->findData(*category));
    }

    if (dialog->exec() == QDialog::Accepted)
    {
        if (category)
        {
            *category = categoryBox->currentData().toInt();
        }

        return true;
    }

    return false;
}

int SetupCollectionModel::categoryButtonMapId(const QModelIndex& index) const
{
    if (!index.isValid() || index.parent().isValid())
    {
        return INTERNALID;
    }

    return index.row();
}

int SetupCollectionModel::buttonMapId(const QModelIndex& index) const
{
    if (!index.isValid() || (index.internalId() == INTERNALID))
    {
        return INTERNALID;
    }

    return index.internalId();
}

void SetupCollectionModel::slotHelp()
{
    openOnlineDocumentation(QLatin1String("setup_application"), QLatin1String("collections_settings"));
}

} // namespace Digikam

#include "moc_setupcollectionview.cpp"