summaryrefslogtreecommitdiffstats
path: root/src/declarative/fx/qfxgridview.cpp
blob: 11b630ab1cdf3fa347ccdd7000b83a6e0d1a2cbd (plain)
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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qfxvisualitemmodel.h"
#include "qlistmodelinterface.h"
#include "qmlfollow.h"
#include "private/qfxflickable_p.h"
#include "qfxgridview.h"

QT_BEGIN_NAMESPACE

class QFxGridViewAttached : public QObject
{
    Q_OBJECT
public:
    QFxGridViewAttached(QObject *parent)
        : QObject(parent), m_isCurrent(false), m_delayRemove(false) {}
    ~QFxGridViewAttached() {
        attachedProperties.remove(parent());
    }

    Q_PROPERTY(QFxGridView *view READ view);
    QFxGridView *view() { return m_view; }

    Q_PROPERTY(bool isCurrentItem READ isCurrentItem NOTIFY currentItemChanged);
    bool isCurrentItem() const { return m_isCurrent; }
    void setIsCurrentItem(bool c) {
        if (m_isCurrent != c) {
            m_isCurrent = c;
            emit currentItemChanged();
        }
    }

    Q_PROPERTY(bool delayRemove READ delayRemove WRITE setDelayRemove NOTIFY delayRemoveChanged);
    bool delayRemove() const { return m_delayRemove; }
    void setDelayRemove(bool delay) {
        if (m_delayRemove != delay) {
            m_delayRemove = delay;
            emit delayRemoveChanged();
        }
    }

    static QFxGridViewAttached *properties(QObject *obj) {
        QFxGridViewAttached *rv = attachedProperties.value(obj);
        if (!rv) {
            rv = new QFxGridViewAttached(obj);
            attachedProperties.insert(obj, rv);
        }
        return rv;
    }

    void emitAdd() { emit add(); }
    void emitRemove() { emit remove(); }

signals:
    void currentItemChanged();
    void delayRemoveChanged();
    void add();
    void remove();

public:
    QFxGridView *m_view;
    bool m_isCurrent;
    bool m_delayRemove;

    static QHash<QObject*, QFxGridViewAttached*> attachedProperties;
};

QHash<QObject*, QFxGridViewAttached*> QFxGridViewAttached::attachedProperties;


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

class FxGridItem
{
public:
    FxGridItem(QFxItem *i, QFxGridView *v) : item(i), view(v) {
        attached = QFxGridViewAttached::properties(item);
        attached->m_view = view;
    }
    ~FxGridItem() {}

    qreal rowPos() const { return (view->flow() == QFxGridView::LeftToRight ? item->y() : item->x()); }
    qreal colPos() const { return (view->flow() == QFxGridView::LeftToRight ? item->x() : item->y()); }
    qreal endRowPos() const {
        return view->flow() == QFxGridView::LeftToRight
                                ? item->y() + view->cellHeight() - 1
                                : item->x() + view->cellWidth() - 1;
    }
    void setPosition(qreal col, qreal row) {
        if (view->flow() == QFxGridView::LeftToRight) {
            item->setPos(QPointF(col, row));
        } else {
            item->setPos(QPointF(row, col));
        }
    }

    QFxItem *item;
    QFxGridView *view;
    QFxGridViewAttached *attached;
    int index;
};

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

class QFxGridViewPrivate : public QFxFlickablePrivate
{
    Q_DECLARE_PUBLIC(QFxGridView);

public:
    QFxGridViewPrivate()
    : model(0), currentItem(0), tmpCurrent(0), flow(QFxGridView::LeftToRight)
    , visiblePos(0), visibleIndex(0) , currentIndex(-1)
    , cellWidth(100), cellHeight(100), columns(1), requestedIndex(-1)
    , highlightComponent(0), highlight(0), trackedItem(0)
    , moveReason(Other), buffer(0), highlightXAnimator(0), highlightYAnimator(0)
    , keyPressed(false), ownModel(false), wrap(false), autoHighlight(true)
    , fixCurrentVisibility(false) {}

    void init();
    void clear();
    FxGridItem *createItem(int modelIndex);
    void releaseItem(FxGridItem *item);
    void refill(qreal from, qreal to);

    void updateGrid();
    void layout(bool removed=false);
    void updateUnrequestedIndexes();
    void updateUnrequestedPositions();
    void updateTrackedItem();
    void createHighlight();
    void updateHighlight();
    void updateCurrent(int modelIndex);

    FxGridItem *visibleItem(int modelIndex) const {
        if (modelIndex >= visibleIndex && modelIndex < visibleIndex + visibleItems.count()) {
            for (int i = modelIndex - visibleIndex; i < visibleItems.count(); ++i) {
                FxGridItem *item = visibleItems.at(i);
                if (item->index == modelIndex)
                    return item;
            }
        }
        return 0;
    }

    qreal position() const {
        Q_Q(const QFxGridView);
        return flow == QFxGridView::LeftToRight ? q->yPosition() : q->xPosition();
    }
    void setPosition(qreal pos) {
        Q_Q(QFxGridView);
        if (flow == QFxGridView::LeftToRight)
            q->setYPosition(pos);
        else
            q->setXPosition(pos);
    }
    int size() const {
        Q_Q(const QFxGridView);
        return flow == QFxGridView::LeftToRight ? q->height() : q->width();
    }
    qreal startPosition() const {
        qreal pos = 0;
        if (!visibleItems.isEmpty())
            pos = visibleItems.first()->rowPos() - visibleIndex / columns * rowSize();
        return pos;
    }

    qreal endPosition() const {
        qreal pos = 0;
        if (model && model->count())
            pos = rowPosAt(model->count() - 1) + rowSize();
        return pos;
    }

    bool isValid() const {
        return model && model->count() && (!ownModel || model->delegate());
    }

    int rowSize() const {
        return flow == QFxGridView::LeftToRight ? cellHeight : cellWidth;
    }
    int colSize() const {
        return flow == QFxGridView::LeftToRight ? cellWidth : cellHeight;
    }

    qreal colPosAt(int modelIndex) const {
        if (FxGridItem *item = visibleItem(modelIndex))
            return item->colPos();
        if (!visibleItems.isEmpty()) {
            if (modelIndex < visibleIndex) {
                int count = (visibleIndex - modelIndex) % columns;
                int col = visibleItems.first()->colPos() / colSize();
                col = (columns - count + col) % columns;
                return col * colSize();
            } else {
                int count = columns - 1 - (modelIndex - visibleItems.last()->index - 1) % columns;
                return visibleItems.last()->colPos() - count * colSize();
            }
        } else {
            return (modelIndex % columns) * colSize();
        }
        return 0;
    }
    qreal rowPosAt(int modelIndex) const {
        if (FxGridItem *item = visibleItem(modelIndex))
            return item->rowPos();
        if (!visibleItems.isEmpty()) {
            if (modelIndex < visibleIndex) {
                int firstCol = visibleItems.first()->colPos() / colSize();
                int col = visibleIndex - modelIndex + (columns - firstCol - 1);
                int rows = col / columns;
                return visibleItems.first()->rowPos() - rows * rowSize();
            } else {
                int count = modelIndex - visibleItems.last()->index;
                int col = visibleItems.last()->colPos() + count * colSize();
                int rows = col / (columns * colSize());
                return visibleItems.last()->rowPos() + rows * rowSize();
            }
        } else {
             return (modelIndex / columns) * rowSize();
        }
        return 0;
    }

    // Map a model index to visibleItems list index.
    // These may differ if removed items are still present in the visible list,
    // e.g. doing a removal animation
    int mapFromModel(int modelIndex) const {
        if (modelIndex < visibleIndex || modelIndex >= visibleIndex + visibleItems.count())
            return -1;
        for (int i = 0; i < visibleItems.count(); ++i) {
            FxGridItem *listItem = visibleItems.at(i);
            if (listItem->index == modelIndex)
                return i + visibleIndex;
            if (listItem->index > modelIndex)
                return -1;
        }
        return -1; // Not in visibleList
    }

    // for debugging only
    void checkVisible() const {
        int skip = 0;
        for (int i = 0; i < visibleItems.count(); ++i) {
            FxGridItem *listItem = visibleItems.at(i);
            if (listItem->index == -1) {
                ++skip;
            } else if (listItem->index != visibleIndex + i - skip) {
                for (int j = 0; j < visibleItems.count(); j++)
                    qDebug() << " index" << j << "item index" << visibleItems.at(j)->index;
                qFatal("index %d %d %d", visibleIndex, i, listItem->index);
            }
        }
    }

    QFxVisualItemModel *model;
    QVariant modelVariant;
    QList<FxGridItem*> visibleItems;
    QHash<QFxItem*,int> unrequestedItems;
    FxGridItem *currentItem;
    QFxItem *tmpCurrent;
    QFxGridView::Flow flow;
    int visiblePos;
    int visibleIndex;
    int currentIndex;
    int cellWidth;
    int cellHeight;
    int columns;
    int requestedIndex;
    QmlComponent *highlightComponent;
    FxGridItem *highlight;
    FxGridItem *trackedItem;
    enum MovementReason { Other, Key, Mouse };
    MovementReason moveReason;
    int buffer;
    QmlFollow *highlightXAnimator;
    QmlFollow *highlightYAnimator;

    int keyPressed : 1;
    int ownModel : 1;
    int wrap : 1;
    int autoHighlight : 1;
    int fixCurrentVisibility : 1;
};

void QFxGridViewPrivate::init()
{
    Q_Q(QFxGridView);
    q->setOptions(QFxGridView::IsFocusRealm);
    QObject::connect(q, SIGNAL(widthChanged()), q, SLOT(sizeChange()));
    QObject::connect(q, SIGNAL(heightChanged()), q, SLOT(sizeChange()));
}

void QFxGridViewPrivate::clear()
{
    for (int i = 0; i < visibleItems.count(); ++i)
        releaseItem(visibleItems.at(i));
    visibleItems.clear();
    visiblePos = 0;
    visibleIndex = 0;
    releaseItem(currentItem);
    currentItem = 0;
    currentIndex = -1;
    createHighlight();
    trackedItem = 0;
}

FxGridItem *QFxGridViewPrivate::createItem(int modelIndex)
{
    Q_Q(QFxGridView);
    // create object
    requestedIndex = modelIndex;
    FxGridItem *listItem = 0;
    if (QFxItem *item = model->item(modelIndex, false)) {
        listItem = new FxGridItem(item, q);
        listItem->index = modelIndex;
        // complete
        model->completeItem();
        listItem->item->setZ(modelIndex + 1);
        listItem->item->setParent(q->viewport());
    }
    requestedIndex = 0;
    return listItem;
}


void QFxGridViewPrivate::releaseItem(FxGridItem *item)
{
    Q_Q(QFxGridView);
    if (!item)
        return;
    if (trackedItem == item) {
        QObject::disconnect(trackedItem->item, SIGNAL(yChanged()), q, SLOT(trackedPositionChanged()));
        QObject::disconnect(trackedItem->item, SIGNAL(xChanged()), q, SLOT(trackedPositionChanged()));
        trackedItem = 0;
    }
    if (model->release(item->item) == 0) {
        // item was not destroyed, and we no longer reference it.
        unrequestedItems.insert(item->item, model->indexOf(item->item, q));
    }
    delete item;
}

void QFxGridViewPrivate::refill(qreal from, qreal to)
{
    Q_Q(QFxGridView);
    if (!isValid() || !q->isComponentComplete())
        return;

    from -= buffer;
    to += buffer;
    bool changed = false;

    int colPos = 0;
    int rowPos = 0;
    int modelIndex = 0;
    if (visibleItems.count()) {
        rowPos = visibleItems.last()->rowPos();
        colPos = visibleItems.last()->colPos() + colSize();
        if (colPos > colSize() * (columns-1)) {
            colPos = 0;
            rowPos += rowSize();
        }
        int i = visibleItems.count() - 1;
        while (i > 0 && visibleItems.at(i)->index == -1)
            --i;
        modelIndex = visibleItems.at(i)->index + 1;
    }

    FxGridItem *item = 0;
    while (modelIndex < model->count() && rowPos <= to) {
        //qDebug() << "refill: append item" << modelIndex;
        if (!(item = createItem(modelIndex)))
            break;
        item->setPosition(colPos, rowPos);
        visibleItems.append(item);
        colPos += colSize();
        if (colPos > colSize() * (columns-1)) {
            colPos = 0;
            rowPos += rowSize();
        }
        ++modelIndex;
        changed = true;
    }

    if (visibleItems.count()) {
        rowPos = visibleItems.first()->rowPos();
        colPos = visibleItems.first()->colPos() - colSize();
        if (colPos < 0) {
            colPos = colSize() * (columns - 1);
            rowPos -= rowSize();
        }
    }
    while (visibleIndex > 0 && rowPos + rowSize() - 1 >= from){
        //qDebug() << "refill: prepend item" << visibleIndex-1 << "top pos" << rowPos << colPos;
        if (!(item = createItem(visibleIndex-1)))
            break;
        --visibleIndex;
        item->setPosition(colPos, rowPos);
        visibleItems.prepend(item);
        colPos -= colSize();
        if (colPos < 0) {
            colPos = colSize() * (columns - 1);
            rowPos -= rowSize();
        }
        changed = true;
    }

    while (visibleItems.count() > 1 && (item = visibleItems.first()) && item->endRowPos() < from) {
        if (item->attached->delayRemove())
            break;
        //qDebug() << "refill: remove first" << visibleIndex << "top end pos" << item->endRowPos();
        if (item->index != -1)
            visibleIndex++;
        visibleItems.removeFirst();
        releaseItem(item);
        changed = true;
    }
    while (visibleItems.count() > 1 && (item = visibleItems.last()) && item->rowPos() > to) {
        if (item->attached->delayRemove())
            break;
        //qDebug() << "refill: remove last" << visibleIndex+visibleItems.count()-1;
        visibleItems.removeLast();
        releaseItem(item);
        changed = true;
    }
    if (changed) {
        if (flow == QFxGridView::LeftToRight)
            q->setViewportHeight(endPosition() - startPosition());
        else
            q->setViewportWidth(endPosition() - startPosition());
    }
}

void QFxGridViewPrivate::updateGrid()
{
    Q_Q(QFxGridView);
    columns = (int)qMax((flow == QFxGridView::LeftToRight ? q->width() : q->height()) / colSize(), qreal(1.));
    if (isValid()) {
        if (flow == QFxGridView::LeftToRight)
            q->setViewportHeight(endPosition() - startPosition());
        else
            q->setViewportWidth(endPosition() - startPosition());
    }
}

void QFxGridViewPrivate::layout(bool removed)
{
    Q_Q(QFxGridView);
    if (visibleItems.count()) {
        qreal rowPos = visibleItems.first()->rowPos();
        qreal colPos = visibleItems.first()->colPos();
        if (visibleIndex % columns != 0) {
            if (removed)
                rowPos -= rowSize();
            colPos = (visibleIndex % columns) * colSize();
            visibleItems.first()->setPosition(colPos, rowPos);
        } else if (colPos != 0) {
            colPos = 0;
            visibleItems.first()->setPosition(colPos, rowPos);
        }
        for (int i = 1; i < visibleItems.count(); ++i) {
            FxGridItem *item = visibleItems.at(i);
            colPos += colSize();
            if (colPos > colSize() * (columns-1)) {
                colPos = 0;
                rowPos += rowSize();
            }
            item->setPosition(colPos, rowPos);
        }
    }
    q->refill();
    q->trackedPositionChanged();
    updateHighlight();
    if (flow == QFxGridView::LeftToRight) {
        q->setViewportHeight(endPosition() - startPosition());
        fixupY();
    } else {
        q->setViewportWidth(endPosition() - startPosition());
        fixupX();
    }
    updateUnrequestedPositions();
}

void QFxGridViewPrivate::updateUnrequestedIndexes()
{
    Q_Q(QFxGridView);
    QHash<QFxItem*,int>::iterator it;
    for (it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it)
        *it = model->indexOf(it.key(), q);
}

void QFxGridViewPrivate::updateUnrequestedPositions()
{
    QHash<QFxItem*,int>::const_iterator it;
    for (it = unrequestedItems.begin(); it != unrequestedItems.end(); ++it) {
        if (flow == QFxGridView::LeftToRight) {
            it.key()->setPos(QPointF(colPosAt(*it), rowPosAt(*it)));
        } else {
            it.key()->setPos(QPointF(rowPosAt(*it), colPosAt(*it)));
        }
    }
}

void QFxGridViewPrivate::updateTrackedItem()
{
    Q_Q(QFxGridView);
    FxGridItem *item = currentItem;
    if (highlight)
        item = highlight;

    if (trackedItem && item != trackedItem) {
        QObject::disconnect(trackedItem->item, SIGNAL(yChanged()), q, SLOT(trackedPositionChanged()));
        QObject::disconnect(trackedItem->item, SIGNAL(xChanged()), q, SLOT(trackedPositionChanged()));
        trackedItem = 0;
    }

    if (!trackedItem && item) {
        trackedItem = item;
        QObject::connect(trackedItem->item, SIGNAL(yChanged()), q, SLOT(trackedPositionChanged()));
        QObject::connect(trackedItem->item, SIGNAL(xChanged()), q, SLOT(trackedPositionChanged()));
        q->trackedPositionChanged();
    }
    if (trackedItem)
        q->trackedPositionChanged();
}

void QFxGridViewPrivate::createHighlight()
{
    Q_Q(QFxGridView);
    if (highlight) {
        if (trackedItem == highlight)
            trackedItem = 0;
        delete highlight->item;
        delete highlight;
        highlight = 0;
        delete highlightXAnimator;
        delete highlightYAnimator;
        highlightXAnimator = 0;
        highlightYAnimator = 0;
    }

    if (!highlightComponent)
        return;

    if (currentItem) {
        QmlContext *highlightContext = new QmlContext(qmlContext(q));
        QObject *nobj = highlightComponent->create(highlightContext);
        if (nobj) {
            highlightContext->setParent(nobj);
            QFxItem *item = qobject_cast<QFxItem *>(nobj);
            if (item) {
                item->setParent(q->viewport());
                highlight = new FxGridItem(item, q);
                highlightXAnimator = new QmlFollow(q);
                highlightXAnimator->setTarget(QmlMetaProperty(highlight->item, QLatin1String("x")));
                highlightXAnimator->setSpring(3);
                highlightXAnimator->setDamping(0.3);
                highlightXAnimator->setEnabled(autoHighlight);
                highlightYAnimator = new QmlFollow(q);
                highlightYAnimator->setTarget(QmlMetaProperty(highlight->item, QLatin1String("y")));
                highlightYAnimator->setSpring(3);
                highlightYAnimator->setDamping(0.3);
                highlightYAnimator->setEnabled(autoHighlight);
            } else {
                delete highlightContext;
            }
        }
    }
}

void QFxGridViewPrivate::updateHighlight()
{
    if ((!currentItem && highlight) || (currentItem && !highlight))
        createHighlight();
    updateTrackedItem();
    if (currentItem && autoHighlight && highlight) {
        // auto-update highlight
        highlightXAnimator->setSourceValue(currentItem->item->x());
        highlightYAnimator->setSourceValue(currentItem->item->y());
        highlight->item->setWidth(currentItem->item->width());
        highlight->item->setHeight(currentItem->item->height());
    }
}

void QFxGridViewPrivate::updateCurrent(int modelIndex)
{
    Q_Q(QFxGridView);
    if (!isValid() || modelIndex < 0 || modelIndex >= model->count()) {
        if (currentItem) {
            currentItem->attached->setIsCurrentItem(false);
            releaseItem(currentItem);
            currentItem = 0;
            currentIndex = -1;
            updateHighlight();
            emit q->currentIndexChanged();
        }
        return;
    }

    if (currentItem && currentIndex == modelIndex) {
        updateHighlight();
        return;
    }

    if (tmpCurrent) {
        delete tmpCurrent;
        tmpCurrent = 0;
    }
    FxGridItem *oldCurrentItem = currentItem;
    currentIndex = modelIndex;
    currentItem = createItem(modelIndex);
    fixCurrentVisibility = true;
    if (oldCurrentItem && (!currentItem || oldCurrentItem->item != currentItem->item))
        oldCurrentItem->attached->setIsCurrentItem(false);
    if (currentItem) {
        currentItem->setPosition(colPosAt(modelIndex), rowPosAt(modelIndex));
        currentItem->item->setFocus(true);
        currentItem->attached->setIsCurrentItem(true);
    }
    updateHighlight();
    emit q->currentIndexChanged();
    releaseItem(oldCurrentItem);
}

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

/*!
    \qmlclass GridView
    \inherits Flickable
    \brief The GridView item provides a grid view of items provided by a model.

    The model is typically provided by a QAbstractListModel "C++ model object",
    but can also be created directly in QML.

    The items are laid out top to bottom (vertically) or left to right (horizontally)
    and may be flicked to scroll.

    The below example creates a very simple grid, using a QML model.

    \image gridview.png

    \snippet doc/src/snippets/declarative/gridview/gridview.qml 3

    The model is defined as a ListModel using QML:
    \quotefile doc/src/snippets/declarative/gridview/dummydata/ContactModel.qml

    In this case ListModel is a handy way for us to test our UI.  In practice
    the model would be implemented in C++, or perhaps via a SQL data source.


*/
QFxGridView::QFxGridView(QFxItem *parent)
    : QFxFlickable(*(new QFxGridViewPrivate), parent)
{
    Q_D(QFxGridView);
    d->init();
}

QFxGridView::~QFxGridView()
{
    Q_D(QFxGridView);
    if (d->ownModel)
        delete d->model;
}

/*!
  \qmlproperty model GridView::model
  This property holds the model providing data for the grid.

  The model provides a set of data that is used to create the items
  for the view.  For large or dynamic datasets the model is usually
  provided by a C++ model object.  The C++ model object must be a \l
  {QAbstractItemModel} subclass, a VisualModel, or a simple list.
*/
QVariant QFxGridView::model() const
{
    Q_D(const QFxGridView);
    return d->modelVariant;
}

void QFxGridView::setModel(const QVariant &model)
{
    Q_D(QFxGridView);
    if (d->model) {
        disconnect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
        disconnect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
        disconnect(d->model, SIGNAL(createdItem(int, QFxItem*)), this, SLOT(createdItem(int,QFxItem*)));
        disconnect(d->model, SIGNAL(destroyingItem(QFxItem*)), this, SLOT(destroyingItem(QFxItem*)));
    }
    d->clear();
    d->modelVariant = model;
    QObject *object = qvariant_cast<QObject*>(model);
    QFxVisualItemModel *vim = 0;
    if (object && (vim = qobject_cast<QFxVisualItemModel *>(object))) {
        if (d->ownModel) {
            delete d->model;
            d->ownModel = false;
        }
        d->model = vim;
    } else {
        if (!d->ownModel) {
            d->model = new QFxVisualItemModel(qmlContext(this));
            d->ownModel = true;
        }
        d->model->setModel(model);
    }
    if (d->model) {
        if (d->currentIndex >= d->model->count() || d->currentIndex < 0)
            setCurrentIndex(0);
        else
            d->updateCurrent(d->currentIndex);
        connect(d->model, SIGNAL(itemsInserted(int,int)), this, SLOT(itemsInserted(int,int)));
        connect(d->model, SIGNAL(itemsRemoved(int,int)), this, SLOT(itemsRemoved(int,int)));
        connect(d->model, SIGNAL(createdItem(int, QFxItem*)), this, SLOT(createdItem(int,QFxItem*)));
        connect(d->model, SIGNAL(destroyingItem(QFxItem*)), this, SLOT(destroyingItem(QFxItem*)));
        refill();
        emit countChanged();
    }
}

/*!
  \qmlproperty component GridView::delegate

  The delegate provides a template describing what each item in the view should look and act like.

  Here is an example delegate:
  \snippet doc/src/snippets/declarative/gridview/gridview.qml 0
*/
QmlComponent *QFxGridView::delegate() const
{
    Q_D(const QFxGridView);
    return d->model ? d->model->delegate() : 0;
}

void QFxGridView::setDelegate(QmlComponent *delegate)
{
    Q_D(QFxGridView);
    if (!d->ownModel) {
        d->model = new QFxVisualItemModel(qmlContext(this));
        d->ownModel = true;
    }
    d->model->setDelegate(delegate);
    d->updateCurrent(d->currentIndex);
    refill();
}

/*!
  \qmlproperty int GridView::currentIndex
  \qmlproperty Item GridView::current

  \c currentIndex holds the index of the current item.
  \c current is the current item.  Note that the position of the current item
  may only be approximate until it becomes visible in the view.
*/
int QFxGridView::currentIndex() const
{
    Q_D(const QFxGridView);
    return d->currentIndex;
}

void QFxGridView::setCurrentIndex(int index)
{
    Q_D(QFxGridView);
    if (d->isValid() && index != d->currentIndex && index < d->model->count() && index >= 0)
        d->updateCurrent(index);
    else
        d->currentIndex = index;
}

QFxItem *QFxGridView::currentItem()
{
    Q_D(QFxGridView);
    if (!d->currentItem) {
        // Always return something valid
        if (!d->tmpCurrent) 
            d->tmpCurrent = new QFxItem(viewport());
        return d->tmpCurrent;
    }
    return d->currentItem->item;
}

/*!
  \qmlproperty int GridView::count
  This property holds the number of items in the view.
*/
int QFxGridView::count() const
{
    Q_D(const QFxGridView);
    if (d->model)
        return d->model->count();
    return 0;
}

/*!
  \qmlproperty component GridView::highlight
  This property holds the component to use as the highlight.

  An instance of the highlight component will be created for each view.
  The geometry of the resultant component instance will be managed by the view
  so as to stay with the current item, unless the autoHighlight property is false.

  The below example demonstrates how to make a simple highlight:
  \snippet doc/src/snippets/declarative/gridview/gridview.qml 1

  \sa autoHighlight
*/
QmlComponent *QFxGridView::highlight() const
{
    Q_D(const QFxGridView);
    return d->highlightComponent;
}

void QFxGridView::setHighlight(QmlComponent *highlight)
{
    Q_D(QFxGridView);
    delete d->highlightComponent;
    d->highlightComponent = highlight;
    d->updateCurrent(d->currentIndex);
}

/*!
  \qmlproperty component GridView::autoHighlight
  This property sets whether the highlight is managed by the view.

  If autoHighlight is true, the highlight will be moved smoothly
  to follow the current item.  If autoHighlight is false, the
  highlight will not be moved by the view, and must be implemented
  by the highlight component, for example:

  \code
  Component {
      id: Highlight
      Rect {
          id: Wrapper; color: "lightsteelblue"; radius: 4; width: 320; height: 60 >
          y: Follow { source: Wrapper.GridView.view.current.y; spring: 3; damping: 0.2 }
          x: Follow { source: Wrapper.GridView.view.current.x; spring: 3; damping: 0.2 }
      }
  }
  \endcode
*/
bool QFxGridView::autoHighlight() const
{
    Q_D(const QFxGridView);
    return d->autoHighlight;
}

void QFxGridView::setAutoHighlight(bool autoHighlight)
{
    Q_D(QFxGridView);
    d->autoHighlight = autoHighlight;
    if (d->highlightXAnimator) {
        d->highlightXAnimator->setEnabled(d->autoHighlight);
        d->highlightYAnimator->setEnabled(d->autoHighlight);
    }
    d->updateHighlight();
}

/*!
  \qmlproperty enumeration GridView::flow
  This property holds the flow of the grid.

  Possible values are \c LeftToRight (default) and \c TopToBottom.

  If \a flow is \c LeftToRight, the view will scroll vertically.
  If \a flow is \c TopToBottom, the view will scroll horizontally.
*/
QFxGridView::Flow QFxGridView::flow() const
{
    Q_D(const QFxGridView);
    return d->flow;
}

void QFxGridView::setFlow(Flow flow)
{
    Q_D(QFxGridView);
    if (d->flow != flow) {
        d->flow = flow;
        if (d->flow == LeftToRight)
            setViewportWidth(-1);
        else
            setViewportHeight(-1);
        d->clear();
        d->updateGrid();
        refill();
        d->updateCurrent(d->currentIndex);
    }
}

/*!
  \qmlproperty bool GridView::wrap
  This property holds whether the grid wraps key navigation

  If this property is true then key presses to move off of one end of the grid will cause the
  selection to jump to the other side.
*/
bool QFxGridView::isWrapEnabled() const
{
    Q_D(const QFxGridView);
    return d->wrap;
}

void QFxGridView::setWrapEnabled(bool wrap)
{
    Q_D(QFxGridView);
    d->wrap = wrap;
}

/*!
  \qmlproperty int GridView::cacheBuffer
  This property holds the number of off-screen pixels to cache.

  This property determines the number of pixels above the top of the view
  and below the bottom of the view to cache.  Setting this value can make
  scrolling the view smoother at the expense of additional memory usage.
*/

/*!
  \property QFxGridView::cacheBuffer
  \brief sets the number of off-screen pixels to cache.

  This property determines the number of pixels above the top of the view
  and below the bottom of the view to cache.  Setting this value can make
  scrolling the view smoother at the expense of additional memory usage.
*/
int QFxGridView::cacheBuffer() const
{
    Q_D(const QFxGridView);
    return d->buffer;
}

void QFxGridView::setCacheBuffer(int buffer)
{
    Q_D(QFxGridView);
    if (d->buffer != buffer) {
        d->buffer = buffer;
        if (isComponentComplete())
            refill();
    }
}

/*!
  \qmlproperty int GridView::cellWidth
  \qmlproperty int GridView::cellHeight

  These properties holds the width and height of each cell in the grid

  The default sell size is 100x100.
*/
int QFxGridView::cellWidth() const
{
    Q_D(const QFxGridView);
    return d->cellWidth;
}

void QFxGridView::setCellWidth(int cellWidth)
{
    Q_D(QFxGridView);
    if (cellWidth != d->cellWidth && cellWidth > 0) {
        d->cellWidth = qMax(1, cellWidth);
        d->updateGrid();
        emit cellSizeChanged();
        d->layout();
    }
}

int QFxGridView::cellHeight() const
{
    Q_D(const QFxGridView);
    return d->cellHeight;
}

void QFxGridView::setCellHeight(int cellHeight)
{
    Q_D(QFxGridView);
    if (cellHeight != d->cellHeight && cellHeight > 0) {
        d->cellHeight = qMax(1, cellHeight);
        d->updateGrid();
        emit cellSizeChanged();
        d->layout();
    }
}

void QFxGridView::sizeChange()
{
    Q_D(QFxGridView);
    if (isComponentComplete()) {
        d->updateGrid();
        d->layout();
    }
}

/*!
  \reimp
*/
void QFxGridView::viewportMoved()
{
    QFxFlickable::viewportMoved();
    refill();
}

/*!
  \reimp
*/
qreal QFxGridView::minYExtent() const
{
    Q_D(const QFxGridView);
    if (d->flow == QFxGridView::TopToBottom)
        return QFxFlickable::minYExtent();
    return -d->startPosition();
}

/*!
  \reimp
*/
qreal QFxGridView::maxYExtent() const
{
    Q_D(const QFxGridView);
    if (d->flow == QFxGridView::TopToBottom)
        return QFxFlickable::maxYExtent();
    return -(d->endPosition() - height());
}

/*!
  \reimp
*/
qreal QFxGridView::minXExtent() const
{
    Q_D(const QFxGridView);
    if (d->flow == QFxGridView::LeftToRight)
        return QFxFlickable::minXExtent();
    return -d->startPosition();
}

/*!
  \reimp
*/
qreal QFxGridView::maxXExtent() const
{
    Q_D(const QFxGridView);
    if (d->flow == QFxGridView::LeftToRight)
        return QFxFlickable::maxXExtent();
    return -(d->endPosition() - height());
}

/*!
  \reimp
*/
void QFxGridView::keyPressEvent(QKeyEvent *event)
{
    Q_D(QFxGridView);
    if (d->model && d->model->count() && !d->locked) {
        if ((d->flow == QFxGridView::LeftToRight && event->key() == Qt::Key_Up)
            || (d->flow == QFxGridView::TopToBottom && event->key() == Qt::Key_Left)) {
            if (currentIndex() >= d->columns || d->wrap) {
                d->keyPressed = true;
                d->moveReason = QFxGridViewPrivate::Key;
                int index = currentIndex() - d->columns;
                setCurrentIndex(index >= 0 ? index : d->model->count()-1);
                event->accept();
            }
            return;
        } else if ((d->flow == QFxGridView::LeftToRight && event->key() == Qt::Key_Down)
                || (d->flow == QFxGridView::TopToBottom && event->key() == Qt::Key_Right)) {
            if (currentIndex() < d->model->count() - d->columns || d->wrap) {
                d->keyPressed = true;
                d->moveReason = QFxGridViewPrivate::Key;
                int index = currentIndex()+d->columns;
                setCurrentIndex(index < d->model->count() ? index : 0);
                event->accept();
            }
            return;
        } else if ((d->flow == QFxGridView::LeftToRight && event->key() == Qt::Key_Left)
                || (d->flow == QFxGridView::TopToBottom && event->key() == Qt::Key_Up)) {
            if (currentIndex() > 0 || d->wrap) {
                d->keyPressed = true;
                d->moveReason = QFxGridViewPrivate::Key;
                int index = currentIndex() - 1;
                setCurrentIndex(index >= 0 ? index : d->model->count()-1);
                event->accept();
            }
            return;
        } else if ((d->flow == QFxGridView::LeftToRight && event->key() == Qt::Key_Right)
                || (d->flow == QFxGridView::TopToBottom && event->key() == Qt::Key_Down)) {
            if (currentIndex() < d->model->count() - 1 || d->wrap) {
                d->keyPressed = true;
                d->moveReason = QFxGridViewPrivate::Key;
                int index = currentIndex() + 1;
                setCurrentIndex(index < d->model->count() ? index : 0);
                event->accept();
            }
            return;
        }
    }
    d->moveReason = QFxGridViewPrivate::Other;
    QFxFlickable::keyPressEvent(event);
}

/*!
  \reimp
*/
void QFxGridView::keyReleaseEvent(QKeyEvent *event)
{
    Q_D(QFxGridView);
    d->keyPressed = false;
    QFxFlickable::keyReleaseEvent(event);
}

/*!
  \reimp
*/
void QFxGridView::componentComplete()
{
    Q_D(QFxGridView);
    QFxFlickable::componentComplete();
    d->updateGrid();
    if (d->currentIndex < 0)
        d->updateCurrent(0);
    refill();
}

void QFxGridView::trackedPositionChanged()
{
    Q_D(QFxGridView);
    if (!d->trackedItem)
        return;
    if (!isFlicking() && !d->pressed && d->moveReason == QFxGridViewPrivate::Key) {
        if (d->trackedItem->rowPos() < d->position()) {
            d->setPosition(d->trackedItem->rowPos());
        } else if (d->trackedItem->endRowPos() > d->position() + d->size()) {
            qreal pos = d->trackedItem->endRowPos() - d->size();
            if (d->rowSize() > d->size())
                pos = d->trackedItem->rowPos();
            d->setPosition(pos);
        }
    }
}

void QFxGridView::itemsInserted(int modelIndex, int count)
{
    Q_D(QFxGridView);
    if (!d->visibleItems.count() || d->model->count() <= 1) {
        refill();
        d->updateCurrent(qMax(0, qMin(d->currentIndex, d->model->count()-1)));
        emit countChanged();
        return;
    }

    int index = d->mapFromModel(modelIndex);
    if (index == -1) {
        int i = d->visibleItems.count() - 1;
        while (i > 0 && d->visibleItems.at(i)->index == -1)
            --i;
        if (d->visibleItems.at(i)->index + 1 == modelIndex) {
            // Special case of appending an item to the model.
            index = d->visibleIndex + d->visibleItems.count();
        } else {
            if (modelIndex + count - 1 < d->visibleIndex) {
                // Insert before visible items
                d->visibleIndex += count;
                for (int i = 0; i < d->visibleItems.count(); ++i) {
                    FxGridItem *listItem = d->visibleItems.at(i);
                    if (listItem->index != -1)
                        listItem->index += count;
                }
            }
            if (d->currentIndex >= modelIndex) {
                // adjust current item index
                d->currentIndex += count;
                if (d->currentItem)
                    d->currentItem->index = d->currentIndex;
            }
            d->layout();
            emit countChanged();
            return;
        }
    }

    // At least some of the added items will be visible
    int insertCount = count;
    if (index < d->visibleIndex) {
        insertCount -= d->visibleIndex - index;
        index = d->visibleIndex;
        modelIndex = d->visibleIndex;
    }

    index -= d->visibleIndex;
    int to = d->buffer+d->position()+d->size()-1;
    int colPos, rowPos;
    if (index < d->visibleItems.count()) {
        colPos = d->visibleItems.at(index)->colPos();
        rowPos = d->visibleItems.at(index)->rowPos();
    } else {
        // appending items to visible list
        colPos = d->visibleItems.at(index-1)->colPos() + d->colSize();
        rowPos = d->visibleItems.at(index-1)->rowPos();
        if (colPos > d->colSize() * (d->columns-1)) {
            colPos = 0;
            rowPos += d->rowSize();
        }
    }

    QList<FxGridItem*> added;
    int i = 0;
    for (; i < insertCount && rowPos + d->rowSize() - 1 <= to; ++i) {
        int mod = (modelIndex+i) % d->columns;
        while (mod++ < d->columns && modelIndex + i < d->model->count() && i < insertCount) {
            FxGridItem *item = d->createItem(modelIndex + i);
            d->visibleItems.insert(index, item);
            item->setPosition(colPos, rowPos);
            added.append(item);
            colPos += d->colSize();
            if (colPos > d->colSize() * (d->columns-1)) {
                colPos = 0;
                rowPos += d->rowSize();
            }
            ++index;
            ++i;
        }
    }

    if (d->currentIndex >= modelIndex) {
        // adjust current item index
        d->currentIndex += count;
        if (d->currentItem) {
            d->currentItem->index = d->currentIndex;
            d->currentItem->setPosition(d->colPosAt(d->currentIndex), d->rowPosAt(d->currentIndex));
        }
    }
    if (i < insertCount) {
        // We didn't insert all our new items, which means anything
        // beyond the current index is not visible - remove it.
        while (d->visibleItems.count() > index)
            d->releaseItem(d->visibleItems.takeLast());
    } else {
        // Update the indexes of the following visible items.
        for (; index < d->visibleItems.count(); ++index) {
            FxGridItem *listItem = d->visibleItems.at(index);
            if (listItem->index != -1)
                listItem->index += count;
        }
    }
    // everything is in order now - emit add() signal
    for (int j = 0; j < added.count(); ++j)
        added.at(j)->attached->emitAdd();
    d->layout();
    emit countChanged();
}

void QFxGridView::itemsRemoved(int modelIndex, int count)
{
    Q_D(QFxGridView);
    int index = d->mapFromModel(modelIndex);
    if (index == -1) {
        if (modelIndex + count - 1 < d->visibleIndex) {
            // Items removed before our visible items.
            d->visibleIndex -= count;
            for (int i = 0; i < d->visibleItems.count(); ++i) {
                FxGridItem *listItem = d->visibleItems.at(i);
                if (listItem->index != -1)
                    listItem->index -= count;
            }
        }
        if (d->currentIndex >= modelIndex + count) {
            d->currentIndex -= count;
            if (d->currentItem)
                d->currentItem->index -= count;
        } else if (d->currentIndex >= modelIndex && d->currentIndex < modelIndex + count) {
            // current item has been removed.
            d->releaseItem(d->currentItem);
            d->currentItem = 0;
            d->currentIndex = -1;
            d->updateCurrent(qMin(modelIndex, d->model->count()-1));
        }
        d->layout(true);
        emit countChanged();
        return;
    }

    // Remove the items from the visible list, skipping anything already marked for removal
    QList<FxGridItem*>::Iterator it = d->visibleItems.begin();
    while (it != d->visibleItems.end()) {
        FxGridItem *item = *it;
        if (item->index == -1 || item->index < modelIndex) {
            // already removed, or before removed items
            ++it;
        } else if (item->index >= modelIndex + count) {
            // after removed items
            item->index -= count;
            ++it;
        } else {
            // removed item
            item->attached->emitRemove();
            if (item->attached->delayRemove()) {
                item->index = -1;
                connect(item->attached, SIGNAL(delayRemoveChanged()), this, SLOT(destroyRemoved()), Qt::QueuedConnection);
                ++it;
            } else {
                it = d->visibleItems.erase(it);
                d->releaseItem(item);
            }
        }
    }

    // fix current
    if (d->currentIndex >= modelIndex + count) {
        d->currentIndex -= count;
        if (d->currentItem)
            d->currentItem->index -= count;
    } else if (d->currentIndex >= modelIndex && d->currentIndex < modelIndex + count) {
        // current item has been removed.
        d->releaseItem(d->currentItem);
        d->currentItem = 0;
        d->currentIndex = -1;
        d->updateCurrent(qMin(modelIndex, d->model->count()-1));
    }

    // update visibleIndex
    for (it = d->visibleItems.begin(); it != d->visibleItems.end(); ++it) {
        if ((*it)->index != -1) {
            d->visibleIndex = (*it)->index;
            break;
        }
    }

    if (d->visibleItems.isEmpty()) {
        d->visibleIndex = 0;
        d->setPosition(0);
        refill();
    } else {
        // Correct the positioning of the items
        d->layout();
    }
    emit countChanged();
}

void QFxGridView::destroyRemoved()
{
    Q_D(QFxGridView);
    for (QList<FxGridItem*>::Iterator it = d->visibleItems.begin();
            it != d->visibleItems.end();) {
        FxGridItem *listItem = *it;
        if (listItem->index == -1 && listItem->attached->delayRemove() == false) {
            d->releaseItem(listItem);
            it = d->visibleItems.erase(it);
        } else {
            ++it;
        }
    }

    // Correct the positioning of the items
    d->layout();
}

void QFxGridView::createdItem(int index, QFxItem *item)
{
    Q_D(QFxGridView);
    item->setItemParent(this);
    if (d->requestedIndex != index) {
        item->setItemParent(this);
        d->unrequestedItems.insert(item, index);
        if (d->flow == QFxGridView::LeftToRight) {
            item->setPos(QPointF(d->colPosAt(index), d->rowPosAt(index)));
        } else {
            item->setPos(QPointF(d->rowPosAt(index), d->colPosAt(index)));
        }
    }
}

void QFxGridView::destroyingItem(QFxItem *item)
{
    Q_D(QFxGridView);
    d->unrequestedItems.remove(item);
}


void QFxGridView::refill()
{
    Q_D(QFxGridView);
    d->refill(d->position(), d->position()+d->size()-1);
}


QObject *QFxGridView::qmlAttachedProperties(QObject *obj)
{
    return QFxGridViewAttached::properties(obj);
}

QML_DEFINE_TYPE(QFxGridView,GridView)

QT_END_NAMESPACE

#include "qfxgridview.moc"