UIListView.cpp 28.3 KB
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
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include "ui/UIListView.h"
#include "ui/UIHelper.h"

NS_CC_BEGIN

static const float DEFAULT_TIME_IN_SEC_FOR_SCROLL_TO_ITEM = 1.0f;

namespace ui {
    
IMPLEMENT_CLASS_GUI_INFO(ListView)

ListView::ListView():
_model(nullptr),
_gravity(Gravity::CENTER_VERTICAL),
_magneticType(MagneticType::NONE),
_magneticAllowedOutOfBoundary(true),
_itemsMargin(0.0f),
_leftPadding(0.0f),
_topPadding(0.0f),
_rightPadding(0.0f),
_bottomPadding(0.0f),
_scrollTime(DEFAULT_TIME_IN_SEC_FOR_SCROLL_TO_ITEM),
_curSelectedIndex(-1),
_innerContainerDoLayoutDirty(true),
_eventCallback(nullptr)
{
    this->setTouchEnabled(true);
}

ListView::~ListView()
{
    _items.clear();
    CC_SAFE_RELEASE(_model);
}

ListView* ListView::create()
{
    ListView* widget = new (std::nothrow) ListView();
    if (widget && widget->init())
    {
        widget->autorelease();
        return widget;
    }
    CC_SAFE_DELETE(widget);
    return nullptr;
}

bool ListView::init()
{
    if (ScrollView::init())
    {
        setDirection(Direction::VERTICAL);
        return true;
    }
    return false;
}

void ListView::setItemModel(Widget *model)
{
    if (nullptr == model)
    {
        CCLOG("Can't set a nullptr to item model!");
        return;
    }
    CC_SAFE_RELEASE_NULL(_model);
    _model = model;
    CC_SAFE_RETAIN(_model);
}

void ListView::handleReleaseLogic(Touch *touch)
{
    ScrollView::handleReleaseLogic(touch);
    
    if(!_autoScrolling)
    {
        startMagneticScroll();
    }
}

void ListView::onItemListChanged()
{
    _outOfBoundaryAmountDirty = true;
}

void ListView::updateInnerContainerSize()
{
    switch (_direction)
    {
        case Direction::VERTICAL:
        {
            size_t length = _items.size();
            float totalHeight = (length == 0) ? 0.0f : (length - 1) * _itemsMargin + (_topPadding + _bottomPadding);
            for (auto& item : _items)
            {
                totalHeight += item->getContentSize().height;
            }
            float finalWidth = _contentSize.width;
            float finalHeight = totalHeight;
            setInnerContainerSize(Size(finalWidth, finalHeight));
            break;
        }
        case Direction::HORIZONTAL:
        {
            size_t length = _items.size();
            float totalWidth = (length == 0) ? 0.0f : (length - 1) * _itemsMargin + (_leftPadding + _rightPadding);
            for (auto& item : _items)
            {
                totalWidth += item->getContentSize().width;
            }
            float finalWidth = totalWidth;
            float finalHeight = _contentSize.height;
            setInnerContainerSize(Size(finalWidth, finalHeight));
            break;
        }
        default:
            break;
    }
}
    
void ListView::remedyVerticalLayoutParameter(LinearLayoutParameter* layoutParameter, ssize_t itemIndex)
{
    CCASSERT(nullptr != layoutParameter, "Layout parameter can't be nullptr!");
    
    switch (_gravity)
    {
        case Gravity::LEFT:
            layoutParameter->setGravity(LinearLayoutParameter::LinearGravity::LEFT);
            break;
        case Gravity::RIGHT:
            layoutParameter->setGravity(LinearLayoutParameter::LinearGravity::RIGHT);
            break;
        case Gravity::CENTER_HORIZONTAL:
            layoutParameter->setGravity(LinearLayoutParameter::LinearGravity::CENTER_HORIZONTAL);
            break;
        default:
            break;
    }
    
    if (0 == itemIndex)
    {
        layoutParameter->setMargin(Margin(_leftPadding, _topPadding, _rightPadding, 0.f));
    }
    else if (_items.size() - 1 == itemIndex)
    {
        layoutParameter->setMargin(Margin(_leftPadding, _itemsMargin, _rightPadding, _bottomPadding));
    }
    else
    {
        layoutParameter->setMargin(Margin(_leftPadding, _itemsMargin, _rightPadding, 0.0f));
    }
}
    
void ListView::remedyHorizontalLayoutParameter(LinearLayoutParameter* layoutParameter, ssize_t itemIndex)
{
    CCASSERT(nullptr != layoutParameter, "Layout parameter can't be nullptr!");
    
    switch (_gravity)
    {
        case Gravity::TOP:
            layoutParameter->setGravity(LinearLayoutParameter::LinearGravity::TOP);
            break;
        case Gravity::BOTTOM:
            layoutParameter->setGravity(LinearLayoutParameter::LinearGravity::BOTTOM);
            break;
        case Gravity::CENTER_VERTICAL:
            layoutParameter->setGravity(LinearLayoutParameter::LinearGravity::CENTER_VERTICAL);
            break;
        default:
            break;
    }
    if (0 == itemIndex)
    {
        layoutParameter->setMargin(Margin(_leftPadding, _topPadding, 0.f, _bottomPadding));
    }
    else if (_items.size() == itemIndex)
    {
        layoutParameter->setMargin(Margin(_itemsMargin, _topPadding, _rightPadding, _bottomPadding));
    }
    else
    {
        layoutParameter->setMargin(Margin(_itemsMargin, _topPadding, 0.f, _bottomPadding));
    }
}

void ListView::remedyLayoutParameter(Widget *item)
{
    CCASSERT(nullptr != item, "ListView Item can't be nullptr!");
    
    LinearLayoutParameter* linearLayoutParameter = (LinearLayoutParameter*)(item->getLayoutParameter());
    bool isLayoutParameterExists = true;
    if (!linearLayoutParameter)
    {
        linearLayoutParameter = LinearLayoutParameter::create();
        isLayoutParameterExists = false;
    }
    ssize_t itemIndex = getIndex(item);
    
    switch (_direction)
    {
        case Direction::VERTICAL:
        {
            this->remedyVerticalLayoutParameter(linearLayoutParameter, itemIndex);
            break;
        }
        case Direction::HORIZONTAL:
        {
            this->remedyHorizontalLayoutParameter(linearLayoutParameter, itemIndex);
            break;
        }
        default:
            break;
    }
    if (!isLayoutParameterExists)
    {
        item->setLayoutParameter(linearLayoutParameter);
    }
}

void ListView::pushBackDefaultItem()
{
    if (nullptr == _model)
    {
        return;
    }
    Widget* newItem = _model->clone();
    remedyLayoutParameter(newItem);
    addChild(newItem);
    requestDoLayout();
}

void ListView::insertDefaultItem(ssize_t index)
{
    if (nullptr == _model)
    {
        return;
    }
    insertCustomItem(_model->clone(), index);
}


void ListView::pushBackCustomItem(Widget* item)
{
    remedyLayoutParameter(item);
    addChild(item);
    requestDoLayout();
}
    
void ListView::addChild(cocos2d::Node *child, int zOrder, int tag)
{
    ScrollView::addChild(child, zOrder, tag);

    Widget* widget = dynamic_cast<Widget*>(child);
    if (nullptr != widget)
    {
        _items.pushBack(widget);
        onItemListChanged();
    }
}
    
void ListView::addChild(cocos2d::Node *child)
{
    ListView::addChild(child, child->getLocalZOrder(), child->getName());
}

void ListView::addChild(cocos2d::Node *child, int zOrder)
{
    ListView::addChild(child, zOrder, child->getName());
}
 
void ListView::addChild(Node* child, int zOrder, const std::string &name)
{
    ScrollView::addChild(child, zOrder, name);
    
    Widget* widget = dynamic_cast<Widget*>(child);
    if (nullptr != widget)
    {
        _items.pushBack(widget);
        onItemListChanged();
    }
}
    
void ListView::removeChild(cocos2d::Node *child, bool cleanup)
{
    Widget* widget = dynamic_cast<Widget*>(child);
    if (nullptr != widget)
    {
        if (-1 != _curSelectedIndex)
        {
            auto removedIndex = getIndex(widget);
            if (_curSelectedIndex > removedIndex)
            {
                _curSelectedIndex -= 1;
            }
            else if (_curSelectedIndex == removedIndex)
            {
                _curSelectedIndex = -1;
            }
        }
        _items.eraseObject(widget);
        onItemListChanged();
    }
   
    ScrollView::removeChild(child, cleanup);
    requestDoLayout();
}
    
void ListView::removeAllChildren()
{
    this->removeAllChildrenWithCleanup(true);
}
    
void ListView::removeAllChildrenWithCleanup(bool cleanup)
{
    ScrollView::removeAllChildrenWithCleanup(cleanup);
    _curSelectedIndex = -1;
    _items.clear();
    onItemListChanged();
}

void ListView::insertCustomItem(Widget* item, ssize_t index)
{
    if (-1 != _curSelectedIndex)
    {
        if (_curSelectedIndex >= index)
        {
            _curSelectedIndex += 1;
        }
    }
    _items.insert(index, item);
    onItemListChanged();

    ScrollView::addChild(item);

    remedyLayoutParameter(item);
    requestDoLayout();
}

void ListView::removeItem(ssize_t index)
{
    Widget* item = getItem(index);
    if (nullptr == item)
    {
        return;
    }
    removeChild(item, true);
}

void ListView::removeLastItem()
{
    removeItem(_items.size() -1);
}
    
void ListView::removeAllItems()
{
    removeAllChildren();
}

Widget* ListView::getItem(ssize_t index) const
{
    if (index < 0 || index >= _items.size())
    {
        return nullptr;
    }
    return _items.at(index);
}

Vector<Widget*>& ListView::getItems()
{
    return _items;
}

ssize_t ListView::getIndex(Widget *item) const
{
    if (nullptr == item)
    {
        return -1;
    }
    return _items.getIndex(item);
}

void ListView::setGravity(Gravity gravity)
{
    if (_gravity == gravity)
    {
        return;
    }
    _gravity = gravity;
    requestDoLayout();
}

void ListView::setMagneticType(MagneticType magneticType)
{
    _magneticType = magneticType;
    _outOfBoundaryAmountDirty = true;
    startMagneticScroll();
}

ListView::MagneticType ListView::getMagneticType() const
{
    return _magneticType;
}

void ListView::setMagneticAllowedOutOfBoundary(bool magneticAllowedOutOfBoundary)
{
    _magneticAllowedOutOfBoundary = magneticAllowedOutOfBoundary;
}

bool ListView::getMagneticAllowedOutOfBoundary() const
{
    return _magneticAllowedOutOfBoundary;
}

void ListView::setItemsMargin(float margin)
{
    if (_itemsMargin == margin)
    {
        return;
    }
    _itemsMargin = margin;
    requestDoLayout();
}
    
float ListView::getItemsMargin()const
{
    return _itemsMargin;
}

void ListView::setPadding(float l, float t, float r, float b)
{
    if (l == _leftPadding && t == _topPadding && r == _rightPadding && b == _bottomPadding)
    {
        return;
    }
    _leftPadding = l;
    _topPadding = t;
    _rightPadding = r;
    _bottomPadding = b;
    requestDoLayout();
}

void ListView::setLeftPadding(float l)
{
    if (l == _leftPadding)
    {
        return;
    }
    _leftPadding = l;
    requestDoLayout();
}

void ListView::setTopPadding(float t)
{
    if (t == _topPadding)
    {
        return;
    }
    _topPadding = t;
    requestDoLayout();
}

void ListView::setRightPadding(float r)
{
    if (r == _rightPadding)
    {
        return;
    }
    _rightPadding = r;
    requestDoLayout();
}

void ListView::setBottomPadding(float b)
{
    if (b == _bottomPadding)
    {
        return;
    }
    _bottomPadding = b;
    requestDoLayout();
}

float ListView::getLeftPadding() const
{
    return _leftPadding;
}

float ListView::getTopPadding() const
{
    return _topPadding;
}

float ListView::getRightPadding() const
{
    return _rightPadding;
}

float ListView::getBottomPadding() const
{
    return _bottomPadding;
}

void ListView::setScrollDuration(float time)
{
    if (time >= 0)
        _scrollTime = time;
}

float ListView::getScrollDuration() const 
{
    return _scrollTime;
}

void ListView::setDirection(Direction dir)
{
    switch (dir)
    {
        case Direction::NONE:
        case Direction::BOTH:
            break;
        case Direction::VERTICAL:
            setLayoutType(Type::VERTICAL);
            break;
        case Direction::HORIZONTAL:
            setLayoutType(Type::HORIZONTAL);
            break;
        default:
            return;
            break;
    }
    ScrollView::setDirection(dir);
}

void ListView::requestDoLayout()
{
    _innerContainerDoLayoutDirty = true;
}

void ListView::doLayout()
{
    if(!_innerContainerDoLayoutDirty)
    {
        return;
    }

    ssize_t length = _items.size();
    for (int i = 0; i < length; ++i)
    {
        Widget* item = _items.at(i);
        item->setLocalZOrder(i);
        remedyLayoutParameter(item);
    }
    updateInnerContainerSize();
    _innerContainer->forceDoLayout();
    _innerContainerDoLayoutDirty = false;
}
    
void ListView::addEventListener(const ccListViewCallback& callback)
{
    _eventCallback = callback;
}
    
void ListView::selectedItemEvent(TouchEventType event)
{
    this->retain();
    switch (event)
    {
        case TouchEventType::BEGAN:
        {
            if (_eventCallback) {
                _eventCallback(this,EventType::ON_SELECTED_ITEM_START);
            }
            if (_ccEventCallback)
            {
                _ccEventCallback(this, static_cast<int>(EventType::ON_SELECTED_ITEM_START));
            }
        }
        break;
        default:
        {
            if (_eventCallback) {
                _eventCallback(this, EventType::ON_SELECTED_ITEM_END);
            }
            if (_ccEventCallback)
            {
                _ccEventCallback(this, static_cast<int>(EventType::ON_SELECTED_ITEM_END));
            }
        }
        break;
    }
    this->release();
}
    
void ListView::interceptTouchEvent(TouchEventType event, Widget *sender, Touch* touch)
{
    ScrollView::interceptTouchEvent(event, sender, touch);
    if (!_touchEnabled)
    {
        return;
    }
    if (event != TouchEventType::MOVED)
    {
        Widget* parent = sender;
        while (parent)
        {
            if (parent && (parent->getParent() == _innerContainer))
            {
                _curSelectedIndex = getIndex(parent);
                break;
            }
            parent = dynamic_cast<Widget*>(parent->getParent());
        }
        if (sender->isHighlighted()) {
            selectedItemEvent(event);
        }
    }
}
    
static Vec2 calculateItemPositionWithAnchor(Widget* item, const Vec2& itemAnchorPoint)
{
    Vec2 origin(item->getLeftBoundary(), item->getBottomBoundary());
    Size size = item->getContentSize();
    return origin + Vec2(size.width * itemAnchorPoint.x, size.height * itemAnchorPoint.y);
}
    
static Widget* findClosestItem(const Vec2& targetPosition, const Vector<Widget*>& items, const Vec2& itemAnchorPoint, ssize_t firstIndex, float distanceFromFirst, ssize_t lastIndex, float distanceFromLast)
{
    CCASSERT(firstIndex >= 0 && lastIndex < items.size() && firstIndex <= lastIndex, "");
    if (firstIndex == lastIndex)
    {
        return items.at(firstIndex);
    }
    if (lastIndex - firstIndex == 1)
    {
        if (distanceFromFirst <= distanceFromLast)
        {
            return items.at(firstIndex);
        }
        else
        {
            return items.at(lastIndex);
        }
    }
    
    // Binary search
    ssize_t midIndex = (firstIndex + lastIndex) / 2;
    Vec2 itemPosition = calculateItemPositionWithAnchor(items.at(midIndex), itemAnchorPoint);
    float distanceFromMid = (targetPosition - itemPosition).length();
    if (distanceFromFirst <= distanceFromLast)
    {
        // Left half
        return findClosestItem(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, midIndex, distanceFromMid);
    }
    else
    {
        // Right half
        return findClosestItem(targetPosition, items, itemAnchorPoint, midIndex, distanceFromMid, lastIndex, distanceFromLast);
    }
}

Widget* ListView::getClosestItemToPosition(const Vec2& targetPosition, const Vec2& itemAnchorPoint) const
{
    if (_items.empty())
    {
        return nullptr;
    }
    
    // Find the closest item through binary search
    ssize_t firstIndex = 0;
    Vec2 firstPosition = calculateItemPositionWithAnchor(_items.at(firstIndex), itemAnchorPoint);
    float distanceFromFirst = (targetPosition - firstPosition).length();
    
    ssize_t lastIndex = _items.size() - 1;
    Vec2 lastPosition = calculateItemPositionWithAnchor(_items.at(lastIndex), itemAnchorPoint);
    float distanceFromLast = (targetPosition - lastPosition).length();
    
    return findClosestItem(targetPosition, _items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast);
}

Widget* ListView::getClosestItemToPositionInCurrentView(const Vec2& positionRatioInView, const Vec2& itemAnchorPoint) const
{
    // Calculate the target position
    Size contentSize = getContentSize();
    Vec2 targetPosition = -_innerContainer->getPosition();
    targetPosition.x += contentSize.width * positionRatioInView.x;
    targetPosition.y += contentSize.height * positionRatioInView.y;
    return getClosestItemToPosition(targetPosition, itemAnchorPoint);
}

Widget* ListView::getCenterItemInCurrentView() const
{
    return getClosestItemToPositionInCurrentView(Vec2::ANCHOR_MIDDLE, Vec2::ANCHOR_MIDDLE);
}

Widget* ListView::getLeftmostItemInCurrentView() const
{
    if (_direction == Direction::HORIZONTAL)
    {
        return getClosestItemToPositionInCurrentView(Vec2::ANCHOR_MIDDLE_LEFT, Vec2::ANCHOR_MIDDLE);
    }
    return nullptr;
}

Widget* ListView::getRightmostItemInCurrentView() const
{
    if (_direction == Direction::HORIZONTAL)
    {
        return getClosestItemToPositionInCurrentView(Vec2::ANCHOR_MIDDLE_RIGHT, Vec2::ANCHOR_MIDDLE);
    }
    return nullptr;
}

Widget* ListView::getTopmostItemInCurrentView() const
{
    if (_direction == Direction::VERTICAL)
    {
        return getClosestItemToPositionInCurrentView(Vec2::ANCHOR_MIDDLE_TOP, Vec2::ANCHOR_MIDDLE);
    }
    return nullptr;
}

Widget* ListView::getBottommostItemInCurrentView() const
{
    if (_direction == Direction::VERTICAL)
    {
        return getClosestItemToPositionInCurrentView(Vec2::ANCHOR_MIDDLE_BOTTOM, Vec2::ANCHOR_MIDDLE);
    }
    return nullptr;
}

void ListView::jumpToBottom()
{
    doLayout();
    ScrollView::jumpToBottom();
}

void ListView::jumpToTop()
{
    doLayout();
    ScrollView::jumpToTop();
}

void ListView::jumpToLeft()
{
    doLayout();
    ScrollView::jumpToLeft();
}

void ListView::jumpToRight()
{
    doLayout();
    ScrollView::jumpToRight();
}

void ListView::jumpToTopLeft()
{
    doLayout();
    ScrollView::jumpToTopLeft();
}

void ListView::jumpToTopRight()
{
    doLayout();
    ScrollView::jumpToTopRight();
}

void ListView::jumpToBottomLeft()
{
    doLayout();
    ScrollView::jumpToBottomLeft();
}

void ListView::jumpToBottomRight()
{
    doLayout();
    ScrollView::jumpToBottomRight();
}

void ListView::jumpToPercentVertical(float percent)
{
    doLayout();
    ScrollView::jumpToPercentVertical(percent);
}

void ListView::jumpToPercentHorizontal(float percent)
{
    doLayout();
    ScrollView::jumpToPercentHorizontal(percent);
}

void ListView::jumpToPercentBothDirection(const Vec2& percent)
{
    doLayout();
    ScrollView::jumpToPercentBothDirection(percent);
}

Vec2 ListView::calculateItemDestination(const Vec2& positionRatioInView, Widget* item, const Vec2& itemAnchorPoint)
{
    const Size& contentSize = getContentSize();
    Vec2 positionInView;
    positionInView.x += contentSize.width * positionRatioInView.x;
    positionInView.y += contentSize.height * positionRatioInView.y;

    Vec2 itemPosition = calculateItemPositionWithAnchor(item, itemAnchorPoint);
    return -(itemPosition - positionInView);
}

void ListView::jumpToItem(ssize_t itemIndex, const Vec2& positionRatioInView, const Vec2& itemAnchorPoint)
{
    Widget* item = getItem(itemIndex);
    if (item == nullptr)
    {
        return;
    }
    doLayout();

    Vec2 destination = calculateItemDestination(positionRatioInView, item, itemAnchorPoint);
    if(!_bounceEnabled)
    {
        Vec2 delta = destination - getInnerContainerPosition();
        Vec2 outOfBoundary = getHowMuchOutOfBoundary(delta);
        destination += outOfBoundary;
    }
    jumpToDestination(destination);
}

void ListView::scrollToItem(ssize_t itemIndex, const Vec2& positionRatioInView, const Vec2& itemAnchorPoint)
{
    scrollToItem(itemIndex, positionRatioInView, itemAnchorPoint, _scrollTime);
}

void ListView::scrollToItem(ssize_t itemIndex, const Vec2& positionRatioInView, const Vec2& itemAnchorPoint, float timeInSec)
{
    Widget* item = getItem(itemIndex);
    if (item == nullptr)
    {
        return;
    }
    Vec2 destination = calculateItemDestination(positionRatioInView, item, itemAnchorPoint);
    startAutoScrollToDestination(destination, timeInSec, true);
}

ssize_t ListView::getCurSelectedIndex() const
{
    return _curSelectedIndex;
}

void ListView::setCurSelectedIndex(int itemIndex)
{
    Widget* item = getItem(itemIndex);
    if (item == nullptr)
    {
        return;
    }
    _curSelectedIndex = itemIndex;
    this->selectedItemEvent(cocos2d::ui::Widget::TouchEventType::ENDED);
}

void ListView::onSizeChanged()
{
    ScrollView::onSizeChanged();
    requestDoLayout();
}

std::string ListView::getDescription() const
{
    return "ListView";
}

Widget* ListView::createCloneInstance()
{
    return ListView::create();
}

void ListView::copyClonedWidgetChildren(Widget* model)
{
    auto& arrayItems = static_cast<ListView*>(model)->getItems();
    for (auto& item : arrayItems)
    {
        pushBackCustomItem(item->clone());
    }
}

void ListView::copySpecialProperties(Widget *widget)
{
    ListView* listViewEx = dynamic_cast<ListView*>(widget);
    if (listViewEx)
    {
        ScrollView::copySpecialProperties(widget);
        setItemModel(listViewEx->_model);
        setItemsMargin(listViewEx->_itemsMargin);
        setGravity(listViewEx->_gravity);
        _eventCallback = listViewEx->_eventCallback;
    }
}

Vec2 ListView::getHowMuchOutOfBoundary(const Vec2& addition)
{
    if(!_magneticAllowedOutOfBoundary || _items.empty())
    {
        return ScrollView::getHowMuchOutOfBoundary(addition);
    }
    else if(_magneticType == MagneticType::NONE || _magneticType == MagneticType::BOTH_END)
    {
        return ScrollView::getHowMuchOutOfBoundary(addition);
    }
    else if(addition == Vec2::ZERO && !_outOfBoundaryAmountDirty)
    {
        return _outOfBoundaryAmount;
    }
    
    // If it is allowed to be out of boundary by magnetic, adjust the boundaries according to the magnetic type.
    float leftBoundary = _leftBoundary;
    float rightBoundary = _rightBoundary;
    float topBoundary = _topBoundary;
    float bottomBoundary = _bottomBoundary;
    {
        ssize_t lastItemIndex = _items.size() - 1;
        Size contentSize = getContentSize();
        Vec2 firstItemAdjustment, lastItemAdjustment;
        if(_magneticType == MagneticType::CENTER)
        {
            firstItemAdjustment = (contentSize - _items.at(0)->getContentSize()) / 2;
            lastItemAdjustment = (contentSize - _items.at(lastItemIndex)->getContentSize()) / 2;
        }
        else if(_magneticType == MagneticType::LEFT)
        {
            lastItemAdjustment = contentSize - _items.at(lastItemIndex)->getContentSize();
        }
        else if(_magneticType == MagneticType::RIGHT)
        {
            firstItemAdjustment = contentSize - _items.at(0)->getContentSize();
        }
        else if(_magneticType == MagneticType::TOP)
        {
            lastItemAdjustment = contentSize - _items.at(lastItemIndex)->getContentSize();
        }
        else if(_magneticType == MagneticType::BOTTOM)
        {
            firstItemAdjustment = contentSize - _items.at(0)->getContentSize();
        }
        leftBoundary += firstItemAdjustment.x;
        rightBoundary -= lastItemAdjustment.x;
        topBoundary -= firstItemAdjustment.y;
        bottomBoundary += lastItemAdjustment.y;
    }
    
    // Calculate the actual amount
    Vec2 outOfBoundaryAmount;
    if(_innerContainer->getLeftBoundary() + addition.x > leftBoundary)
    {
        outOfBoundaryAmount.x = leftBoundary - (_innerContainer->getLeftBoundary() + addition.x);
    }
    else if(_innerContainer->getRightBoundary() + addition.x < rightBoundary)
    {
        outOfBoundaryAmount.x = rightBoundary - (_innerContainer->getRightBoundary() + addition.x);
    }
    
    if(_innerContainer->getTopBoundary() + addition.y < topBoundary)
    {
        outOfBoundaryAmount.y = topBoundary - (_innerContainer->getTopBoundary() + addition.y);
    }
    else if(_innerContainer->getBottomBoundary() + addition.y > bottomBoundary)
    {
        outOfBoundaryAmount.y = bottomBoundary - (_innerContainer->getBottomBoundary() + addition.y);
    }
    
    if(addition == Vec2::ZERO)
    {
        _outOfBoundaryAmount = outOfBoundaryAmount;
        _outOfBoundaryAmountDirty = false;
    }
    return outOfBoundaryAmount;
}

static Vec2 getAnchorPointByMagneticType(ListView::MagneticType magneticType)
{
    switch(magneticType)
    {
        case ListView::MagneticType::NONE: return Vec2::ZERO;
        case ListView::MagneticType::BOTH_END: return Vec2::ANCHOR_TOP_LEFT;
        case ListView::MagneticType::CENTER: return Vec2::ANCHOR_MIDDLE;
        case ListView::MagneticType::LEFT: return Vec2::ANCHOR_MIDDLE_LEFT;
        case ListView::MagneticType::RIGHT: return Vec2::ANCHOR_MIDDLE_RIGHT;
        case ListView::MagneticType::TOP: return Vec2::ANCHOR_MIDDLE_TOP;
        case ListView::MagneticType::BOTTOM: return Vec2::ANCHOR_MIDDLE_BOTTOM;
    }
    return Vec2::ZERO;
}

void ListView::startAttenuatingAutoScroll(const Vec2& deltaMove, const Vec2& initialVelocity)
{
    Vec2 adjustedDeltaMove = deltaMove;
    
    if(!_items.empty() && _magneticType != MagneticType::NONE)
    {
        adjustedDeltaMove = flattenVectorByDirection(adjustedDeltaMove);

        // If the destination is out of boundary, do nothing here. Because it will be handled by bouncing back.
        if(getHowMuchOutOfBoundary(adjustedDeltaMove) == Vec2::ZERO)
        {
            MagneticType magType = _magneticType;
            if(magType == MagneticType::BOTH_END)
            {
                if(_direction == Direction::HORIZONTAL)
                {
                    magType = (adjustedDeltaMove.x > 0 ? MagneticType::LEFT : MagneticType::RIGHT);
                }
                else if(_direction == Direction::VERTICAL)
                {
                    magType = (adjustedDeltaMove.y > 0 ? MagneticType::BOTTOM : MagneticType::TOP);
                }
            }
            
            // Adjust the delta move amount according to the magnetic type
            Vec2 magneticAnchorPoint = getAnchorPointByMagneticType(magType);
            Vec2 magneticPosition = -_innerContainer->getPosition();
            magneticPosition.x += getContentSize().width * magneticAnchorPoint.x;
            magneticPosition.y += getContentSize().height * magneticAnchorPoint.y;
            
            Widget* pTargetItem = getClosestItemToPosition(magneticPosition - adjustedDeltaMove, magneticAnchorPoint);
            Vec2 itemPosition = calculateItemPositionWithAnchor(pTargetItem, magneticAnchorPoint);
            adjustedDeltaMove = magneticPosition - itemPosition;
        }
    }
    ScrollView::startAttenuatingAutoScroll(adjustedDeltaMove, initialVelocity);
}

void ListView::startMagneticScroll()
{
    if(_items.empty() || _magneticType == MagneticType::NONE)
    {
        return;
    }
    
    // Find the closest item
    Vec2 magneticAnchorPoint = getAnchorPointByMagneticType(_magneticType);
    Vec2 magneticPosition = -_innerContainer->getPosition();
    magneticPosition.x += getContentSize().width * magneticAnchorPoint.x;
    magneticPosition.y += getContentSize().height * magneticAnchorPoint.y;
    
    Widget* pTargetItem = getClosestItemToPosition(magneticPosition, magneticAnchorPoint);
    scrollToItem(getIndex(pTargetItem), magneticAnchorPoint, magneticAnchorPoint);
}

}
NS_CC_END