summaryrefslogtreecommitdiffstats
path: root/src/declarative/fx/qfxpathview.cpp
blob: 99f6e8649fcc790866d1fe1d68d6bdead3481e99 (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
/****************************************************************************
**
** 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 <math.h>
#include <QDebug>
#include <QPen>
#include <QEvent>
#include <gfxeasing.h>
#include "qmlbindablevalue.h"
#include "qmlstate.h"
#include "qlistmodelinterface.h"
#include "qmlopenmetaobject.h"

#include "qfxpathview.h"
#include "qfxpathview_p.h"
#include <QGraphicsSceneEvent>
#include <QTimer>

static const int FlickThreshold = 5;

QT_BEGIN_NAMESPACE

QML_DEFINE_TYPE(QFxPathView,PathView);

class QFxPathViewAttached : public QObject
{
    Q_OBJECT
public:
    QFxPathViewAttached(QObject *parent)
    : QObject(parent), mo(new QmlOpenMetaObject(this))
    {
    }

    QVariant value(const QByteArray &name) const 
    { 
        return mo->value(name); 
    }
    void setValue(const QByteArray &name, const QVariant &val)
    {
        mo->setValue(name, val);
    }

private:
    QmlOpenMetaObject *mo;
};


/*!
    \internal
    \class QFxPathView
    \brief The QFxPathView class lays out items provided by a model on a path.

    \ingroup group_views

    The model must be a \l QListModelInterface subclass.

    \sa QFxPath
*/

/*!
    \qmlclass PathView
    \brief The PathView element lays out model-provided items on a path.
    \inherits Item

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

    The items are laid out along a path defined by a \l Path and may be flicked to scroll.

    \code
    <PathView id="pathview" delegate="{contactDelegate}">
        <resources><Component id="contactDelegate">...</Component></resources>
        <model>...</model>
        <path>...</path>
    </PathView>
    \endcode

    \image pathview.gif

    \sa Path
*/

QFxPathView::QFxPathView(QFxItem *parent)
  : QFxItem(*(new QFxPathViewPrivate), parent)
{
    Q_D(QFxPathView);
    d->init();
}

QFxPathView::QFxPathView(QFxPathViewPrivate &dd, QFxItem *parent)
  : QFxItem(dd, parent)
{
    Q_D(QFxPathView);
    d->init();
}

QFxPathView::~QFxPathView()
{
}

/*!
    \qmlproperty model PathView::model
    This property holds the model providing data for the view.

    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.
    However, models can also be created directly in XML, for example:
    \code
<model>
    <ListModel>
        <Contact>
            <portrait>pics/john.png</portrait>
            <firstName>John</firstName>
            <lastName>Smith</lastName>
        </Contact>
        <Contact>
            <portrait>pics/bill.png</portrait>
            <firstName>Bill</firstName>
            <lastName>Jones</lastName>
        </Contact>
        <Contact>
            <portrait>pics/jane.png</portrait>
            <firstName>Jane</firstName>
            <lastName>Doe</lastName>
        </Contact>
    </ListModel>
</model>
    \endcode
*/

/*!
    \property QFxPathView::model
    \brief the model providing data for the view.

    The model must be either a \l QListModelInterface or
    \l QFxVisualItemModel subclass.
*/
QVariant QFxPathView::model() const
{
    Q_D(const QFxPathView);
    return d->model ? d->model->model() : QVariant();
}

void QFxPathView::setModel(const QVariant &model)
{
    Q_D(QFxPathView);
    if (QFxVisualItemModel *m = qvariant_cast<QFxVisualItemModel*>(model)) {
        if (d->ownModel) {
            delete d->model;
            d->ownModel = false;
        }
        d->model = m;
    } else {
        if (!d->ownModel) {
            d->model = new QFxVisualItemModel;
            d->ownModel = true;
        }
        d->model->setModel(model);
    }
    d->regenerate();
    d->fixOffset();
}

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

/*!
    \qmlproperty Path PathView::path
    \default
    This property holds the path used to lay out the items.
    For more information see the \l Path documentation.
*/
QFxPath *QFxPathView::path() const
{
    Q_D(const QFxPathView);
    return d->path;
}

void QFxPathView::setPath(QFxPath *path)
{
    Q_D(QFxPathView);
    d->path = path;
    connect(d->path, SIGNAL(changed()), this, SLOT(refill()));
    d->regenerate();
}

/*!
    \qmlproperty int PathView::currentIndex
    This property holds the index of the current item.
*/
int QFxPathView::currentIndex() const
{
    Q_D(const QFxPathView);
    return d->currentIndex;
}

void QFxPathView::setCurrentIndex(int idx)
{
    Q_D(QFxPathView);
    if (d->model && d->model->count())
        idx = qAbs(idx % d->model->count());
    if (d->model && idx != d->currentIndex) {
        d->currentIndex = idx;
        d->snapToCurrent();
        int itemIndex = (idx - d->firstIndex + d->model->count()) % d->model->count();
        if(itemIndex < d->items.count())
            d->items.at(itemIndex)->setFocus(true);
        emit currentIndexChanged();
    }
}

/*!
    \qmlproperty real PathView::offset

    The offset specifies how far along the path the items are from their initial positions.
*/
qreal QFxPathView::offset() const
{
    Q_D(const QFxPathView);
    return d->_offset;
}

void QFxPathView::setOffset(qreal offset)
{
    Q_D(QFxPathView);
    d->setOffset(offset);
    d->updateCurrent();
}

void QFxPathViewPrivate::setOffset(qreal o)
{
    Q_Q(QFxPathView);
    if (_offset != o) {
        _offset = fmod(o, 100.0);
        if (_offset < 0)
            _offset = 100.0 + _offset;
        q->refill();
    }
}

/*!
    \qmlproperty real PathView::snapPosition
    This property holds the position (0-100) the current item snaps to.
*/

/*!
    \property QFxPathView::snapPosition
    \brief sets the position (0-100) the current item snaps to.

    This property determines the position the nearest item will snap to.
*/
qreal QFxPathView::snapPosition() const
{
    Q_D(const QFxPathView);
    return d->snapPos;
}

void QFxPathView::setSnapPosition(qreal pos)
{
    Q_D(QFxPathView);
    d->snapPos = pos/100;
    d->fixOffset();
}

/*!
    \qmlproperty real PathView::dragMargin
    This property holds the maximum distance from the path that initiate mouse dragging.

    By default the path can only be dragged by clicking on an item.  If
    dragMargin is greater than zero, a drag can be initiated by clicking
    within dragMargin pixels of the path.
*/
qreal QFxPathView::dragMargin() const
{
    Q_D(const QFxPathView);
    return d->dragMargin;
}

void QFxPathView::setDragMargin(qreal dragMargin)
{
    Q_D(QFxPathView);
    d->dragMargin = dragMargin;
}

/*!
    \qmlproperty component PathView::delegate

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

    Here is an example delegate:
    \code
    <PathView delegate="{contactDelegate}" ...>
        <resources>
            <Component id="contactDelegate">
                <Item id="wrapper" scale="{PathView.sc}" opacity="{PathView.op}" z="{PathView.z}">
                    <Image id="pic" width="100" height="100" file="{portrait}"
                            anchors.horizontalCenter="{parent.horizontalCenter}"/>
                    <Text id="name" text="{firstName + ' ' + lastName}"
                            font.size="20"
                            anchors.top="{pic.bottom}" anchors.topMargin="5"
                            anchors.horizontalCenter="{parent.horizontalCenter}"/>
                </Item>
            </Component>
        </resources>
        ...
    </PathView>
    \endcode
*/

/*!
    \property QFxPathView::delegate
    \brief the component to use to render the items.

    The delegate is a component that the view will instantiate and destroy
    as needed to display the items.

*/
QmlComponent *QFxPathView::delegate() const
{
    Q_D(const QFxPathView);
    return d->model ? d->model->delegate() : 0;
}

void QFxPathView::setDelegate(QmlComponent *c)
{
    Q_D(QFxPathView);
    if (!d->ownModel) {
        d->model = new QFxVisualItemModel;
        d->ownModel = true;
    }
    d->model->setDelegate(c);
    d->regenerate();
}

/*!
  \property QFxPathView::pathItemCount
  \brief the number of items visible on the path at any one time
  */
/*!
  \qmlproperty int PathView::pathItemCount
  This property holds the number of items visible on the path at any one time
*/
int QFxPathView::pathItemCount() const
{
    Q_D(const QFxPathView);
    return d->pathItems;
}

void QFxPathView::setPathItemCount(int i)
{
    Q_D(QFxPathView);
    if(i == d->pathItems)
        return;
    d->pathItems = i;
    d->regenerate();
}

QPointF QFxPathViewPrivate::pointNear(const QPointF &point, qreal *nearPercent) const
{
    //XXX maybe do recursively at increasing resolution.
    qreal mindist = 1e10; // big number
    QPointF nearPoint = path->pointAt(0);
    qreal nearPc = 0;
    for (qreal i=1; i < 1000; i++) {
        QPointF pt = path->pointAt(i/1000.0);
        QPointF diff = pt - point;
        qreal dist = diff.x()*diff.x() + diff.y()*diff.y();
        if (dist < mindist) {
            nearPoint = pt;
            nearPc = i;
            mindist = dist;
        }
    }

    if (nearPercent)
        *nearPercent = nearPc / 10.0;

    return nearPoint;
}


void QFxPathView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    Q_D(QFxPathView);
    QPointF scenePoint = mapToScene(event->pos());
    int idx = 0;
    for (; idx < d->items.count(); ++idx) {
        QRectF rect = d->items.at(idx)->boundingRect();
        rect = d->items.at(idx)->mapToScene(rect);
        if (rect.contains(scenePoint))
            break;
    }
    if (idx == d->items.count() && d->dragMargin == 0.)  // didn't click on an item
        return;

    d->startPoint = d->pointNear(event->pos(), &d->startPc);
    if (idx == d->items.count()) {
        qreal distance = qAbs(event->pos().x() - d->startPoint.x()) + qAbs(event->pos().y() - d->startPoint.y());
        if (distance > d->dragMargin)
            return;
    }

    d->stealMouse = false;
    d->lastElapsed = 0;
    d->lastDist = 0;
    d->lastPosTime.start();
    d->tl.clear();
}

void QFxPathView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    Q_D(QFxPathView);
    if (d->lastPosTime.isNull())
        return;

    if (!d->stealMouse) {
        QPointF delta = event->pos() - d->startPoint;
        if (qAbs(delta.x()) > FlickThreshold && qAbs(delta.y()) > FlickThreshold)
            d->stealMouse = true;
    }

    if (d->stealMouse) {
        d->moveReason = QFxPathViewPrivate::Mouse;
        qreal newPc;
        d->pointNear(event->pos(), &newPc);
        qreal diff = newPc - d->startPc;
        if (diff) {
            setOffset(d->_offset + diff);

            if (diff > 50)
                diff -= 100;
            else if (diff < -50)
                diff += 100;

            d->lastElapsed = d->lastPosTime.restart();
            d->lastDist = diff;
            d->startPc = newPc;
        }
    }
}

void QFxPathView::mouseReleaseEvent(QGraphicsSceneMouseEvent *)
{
    Q_D(QFxPathView);
    if (d->lastPosTime.isNull())
        return;

    qreal elapsed = qreal(d->lastElapsed + d->lastPosTime.elapsed()) / 1000.;
    qreal velocity = elapsed > 0. ? d->lastDist / elapsed : 0;
    if (d->model && d->model->count() && qAbs(velocity) > 5) {
        if (velocity > 100)
            velocity = 100;
        else if (velocity < -100)
            velocity = -100;
        qreal inc = fmod(d->_offset - d->snapPos, 100.0 / d->model->count());
        qreal dist = qAbs(velocity/2 - fmod(velocity/2, 100.0 / d->model->count()) - inc);
        d->moveOffset.setValue(d->_offset);
        d->tl.accel(d->moveOffset, velocity, 10, dist);
        d->tl.execute(d->fixupOffsetEvent);
    } else {
        d->fixOffset();
    }

    d->lastPosTime = QTime();
    d->stealMouse = false;
}

bool QFxPathView::sendMouseEvent(QGraphicsSceneMouseEvent *event)
{
    Q_D(QFxPathView);
    QGraphicsSceneMouseEvent mouseEvent(event->type());
    QRectF myRect = mapToScene(QRectF(0, 0, width(), height()));
    QFxItem *grabber = static_cast<QFxItem*>(mouseGrabberItem());
    if ((d->stealMouse || myRect.contains(event->scenePos().toPoint())) && (!grabber || !grabber->keepMouseGrab())) {
        mouseEvent.setAccepted(false);
        for (int i = 0x1; i <= 0x10; i <<= 1) {
            if (event->buttons() & i) {
                Qt::MouseButton button = Qt::MouseButton(i);
                mouseEvent.setButtonDownPos(button, mapFromScene(event->buttonDownPos(button)));
            }
        }
        mouseEvent.setScenePos(event->scenePos());
        mouseEvent.setLastScenePos(event->lastScenePos());
        mouseEvent.setPos(mapFromScene(event->scenePos()));
        mouseEvent.setLastPos(mapFromScene(event->lastScenePos()));

        switch(mouseEvent.type()) {
        case QEvent::GraphicsSceneMouseMove:
            mouseMoveEvent(&mouseEvent);
            break;
        case QEvent::GraphicsSceneMousePress:
            mousePressEvent(&mouseEvent);
            break;
        case QEvent::GraphicsSceneMouseRelease:
            mouseReleaseEvent(&mouseEvent);
            break;
        default:
            break;
        }
        grabber = static_cast<QFxItem*>(mouseGrabberItem());
        if (grabber && d->stealMouse && !grabber->keepMouseGrab())
            mouseGrabberItem()->ungrabMouse();

        return d->stealMouse;
    } else if (!d->lastPosTime.isNull()) {
        d->lastPosTime = QTime();
    }
    return false;
}

bool QFxPathView::mouseFilter(QGraphicsSceneMouseEvent *e)
{
    if(!isVisible())
        return false;

    switch (e->type()) {
    case QEvent::GraphicsSceneMousePress:
    case QEvent::GraphicsSceneMouseMove:
    case QEvent::GraphicsSceneMouseRelease:
        {
            bool ret = sendMouseEvent(e);
            if (e->type() == QEvent::GraphicsSceneMouseRelease)
                return ret;
            break;
        }
    default:
        break;
    }

    return false;
}

void QFxPathViewPrivate::regenerate()
{
    Q_Q(QFxPathView);
    if (!model || model->count() <= 0 || !model->delegate() || !path)
        return;

    for(int i=0; i<items.count(); i++){
        QFxItem *p = items[i];
        q->attachedProperties.remove(p);
        model->release(p);
    }
    items.clear();

    firstIndex = 0;
    pathOffset = 0;

    int numItems = (pathItems>=0 ? pathItems : model->count());
    qreal minDiff = 1e9;
    int minI = -1;
    for(int i=0; i<numItems; i++){
        QFxItem *item = model->item(i);
        items.append(item);
        item->setZ(i);
        item->setParent(q);
        qreal percent = i * (100.0 / (numItems));
        percent /= 100.0;
        updateItem(items.last(), percent);
        qreal diff = qAbs(percent - snapPos);
        if(diff < minDiff){
            minDiff = diff;
            minI = i;
        }
    }
    q->setCurrentIndex(minI);

    q->refill();
}

void QFxPathViewPrivate::updateItem(QFxItem *item, qreal percent)
{
    if(QObject *obj = QFxPathView::attachedProperties.value(item)) {
        foreach(QString attr, path->attributes())
            static_cast<QFxPathViewAttached *>(obj)->setValue(attr.toLatin1(), path->attributeAt(attr, percent));
    }

    QPointF pf = path->pointAt(percent);
    item->setX(pf.x() - item->width()*item->scale()/2);
    item->setY(pf.y() - item->height()*item->scale()/2);
}

void QFxPathView::refill()
{
    Q_D(QFxPathView);
    if (!d->model || d->model->count() <= 0)
        return;

    QList<qreal> positions;
    for(int i=0; i<d->items.count(); i++){
        qreal percent = i * (100. / d->items.count());
        percent = percent + d->_offset;
        percent = fmod(percent,100.);
        positions << qAbs(percent/100.0);
    }

    if(d->pathItems==-1){
        for(int i=0; i<positions.count(); i++){
            d->updateItem(d->items.at(i), positions[i]);
        }
        return;
    }

    QList<qreal> rotatedPositions;
    for(int i=0; i<d->items.count(); i++)
        rotatedPositions << positions[(i + d->pathOffset + d->items.count()) % d->items.count()];

    int firstFind = -1;
    int i;
    for(i=0; i<d->items.count()-1; i++)
    {
        if(rotatedPositions[i] > rotatedPositions[i+1]){
            firstFind = i;
            break;
        }
    }
    if(firstFind!=-1 ){
        //A wraparound has occured
        if(firstFind<(d->items.count()/2)){
            while(firstFind-- >= 0){
                QFxItem* p = d->items.takeFirst();
                attachedProperties.remove(p);
                d->model->release(p);
                d->firstIndex++;
                d->firstIndex%=d->model->count();
                int index = (d->firstIndex + d->items.count())%d->model->count();
                d->items << d->model->item(index);
                d->items.last()->setZ(i);
                d->items.last()->setParent(this);
                d->pathOffset++;
                d->pathOffset=d->pathOffset % d->items.count();
            }
        }else{
            while(firstFind++ < (d->items.count()-1)){
                QFxItem* p = d->items.takeLast();
                attachedProperties.remove(p);
                d->model->release(p);
                d->firstIndex--;
                if(d->firstIndex<0)
                    d->firstIndex = d->model->count() - 1;
                d->items.prepend(d->model->item(d->firstIndex));
                d->items.first()->setZ(d->firstIndex);
                d->items.first()->setParent(this);
                d->pathOffset--;
                if(d->pathOffset<0)
                    d->pathOffset = d->items.count() - 1;
            }
        }
        for(int i=0; i<d->items.count(); i++)
            rotatedPositions[i] = positions[(i + d->pathOffset + d->items.count())
                % d->items.count()];
    }
    for(int i=0; i<d->items.count(); i++){
        d->updateItem(d->items.at(i), rotatedPositions[i]);
    }
}

void QFxPathView::ticked()
{
    Q_D(QFxPathView);
    d->updateCurrent();
}

// find the item closest to the snap position
int QFxPathViewPrivate::calcCurrentIndex()
{
    int current = -1;
    if (model && items.count()) {
        _offset = fmod(_offset, 100.0);
        if(_offset < 0)
            _offset += 100.0;

        if(pathItems == -1){
            qreal delta = fmod(_offset - snapPos, 100.0);
            if (delta < 0)
                delta = 100.0 + delta;
            int ii = model->count() - qRound(delta * model->count() / 100);
            if(ii < 0)
                ii = 0;
            current = ii;
        }else{
            qreal bestDiff=1e9;
            int bestI=-1;
            for(int i=0; i<items.count(); i++){
                qreal percent = i * (100. / items.count());
                percent = percent + _offset;
                percent = fmod(percent,100.);
                qreal diff = qAbs(snapPos - (percent/100.0));
                if(diff < bestDiff){
                    bestDiff = diff;
                    bestI = i;
                }
            }
            int modelIndex = (bestI - pathOffset + items.count())%items.count();
            modelIndex += firstIndex;
            current = modelIndex;
        }
        current = qAbs(current % model->count());
    }

    return current;
}

void QFxPathViewPrivate::updateCurrent()
{
    Q_Q(QFxPathView);
    if (moveReason != Mouse)
        return;
    int idx = calcCurrentIndex();
    if (model && idx != currentIndex) {
        currentIndex = idx;
        int itemIndex = (idx - firstIndex + model->count()) % model->count();
        if(itemIndex < items.count())
            items.at(itemIndex)->setFocus(true);
        emit q->currentIndexChanged();
    }
}

void QFxPathViewPrivate::fixOffset()
{
    Q_Q(QFxPathView);
    if (model && items.count()) {
        int curr = calcCurrentIndex();
        if (curr != currentIndex)
            q->setCurrentIndex(curr);
        else
            snapToCurrent();
    }
}

void QFxPathViewPrivate::snapToCurrent()
{
    if (!model || model->count() <= 0)
        return;

    int itemIndex = (currentIndex - firstIndex + model->count())%model->count();

    //Rounds is the number of times round to make the current item visible
    int rounds = itemIndex / items.count();
    int otherWayRounds = (model->count() - (itemIndex))/items.count() + 1;
    if(otherWayRounds < rounds)
        rounds = -otherWayRounds;

    itemIndex += pathOffset;
    itemIndex %= items.count();
    qreal targetOffset = fmod(100 + (snapPos*100) - 100.0 * itemIndex / items.count(), 100);

    if (targetOffset < 0)
        targetOffset = 100.0 + targetOffset;
    if (targetOffset == _offset && rounds==0)
        return;

    moveReason = Other;
    tl.clear();
    moveOffset.setValue(_offset);

    if(rounds!=0){
        //Compensate if the targetOffset would bring the target it from off the screen
        qreal distance = targetOffset - _offset;
        if(distance <= -50)
            rounds--;
        if(distance > 50)
            rounds++;
        tl.move(moveOffset, targetOffset + 100.0*(-rounds), GfxEasing(GfxEasing::InOutQuad),
                int(100*items.count()*qMax((qreal)(2.0/items.count()),(qreal)qAbs(rounds))));
        tl.execute(fixupOffsetEvent);
        return;
    }

    if (targetOffset - _offset > 50.0) {
        qreal distance = 100 - targetOffset + _offset;
        tl.move(moveOffset, 0.0, GfxEasing(GfxEasing::OutQuad), int(200 * _offset / distance));
        tl.set(moveOffset, 100.0);
        tl.move(moveOffset, targetOffset, GfxEasing(GfxEasing::InQuad), int(200 * (100-targetOffset) / distance));
    } else if (targetOffset - _offset <= -50.0) {
        qreal distance = 100 - _offset + targetOffset;
        tl.move(moveOffset, 100.0, GfxEasing(GfxEasing::OutQuad), int(200 * (100-_offset) / distance));
        tl.set(moveOffset, 0.0);
        tl.move(moveOffset, targetOffset, GfxEasing(GfxEasing::InQuad), int(200 * targetOffset / distance));
    } else {
        tl.move(moveOffset, targetOffset, GfxEasing(GfxEasing::InOutQuad), 200);
    }
}

QHash<QObject*, QObject*> QFxPathView::attachedProperties;
QObject *QFxPathView::qmlAttachedProperties(QObject *obj)
{
    if(!attachedProperties.contains(obj)) {
        QFxPathViewAttached *rv = new QFxPathViewAttached(obj);
        attachedProperties.insert(obj, rv);
    }
    return attachedProperties.value(obj);
}

QT_END_NAMESPACE

#include "qfxpathview.moc"