/*
  This file was generated by the Html5 Application wizard of Qt Creator.
  Html5ApplicationViewer is a convenience class containing mobile device specific
  code such as screen orientation handling.
  It is recommended not to modify this file, since newer versions of Qt Creator
  may offer an updated version of it.
*/

#include <QWebFrame>
#include "webtouchscroller.h"

void qtwebkit_webframe_scrollRecursively(QWebFrame* qFrame, int dx, int dy, const QPoint &pos)
{
    Q_UNUSED(pos);

    if (!qFrame)
        return;

    bool scrollHorizontal = false;
    bool scrollVertical = false;

    do {
        if (qFrame->scrollBarPolicy(Qt::Horizontal) == Qt::ScrollBarAlwaysOn) {
            if (dx > 0)  // scroll right
                scrollHorizontal = qFrame->scrollBarValue(Qt::Horizontal) < qFrame->scrollBarMaximum(Qt::Horizontal);
            else if (dx < 0)  // scroll left
                scrollHorizontal = qFrame->scrollBarValue(Qt::Horizontal) > qFrame->scrollBarMinimum(Qt::Horizontal);
        } else {
            scrollHorizontal = true;
        }

        if (qFrame->scrollBarPolicy(Qt::Vertical) == Qt::ScrollBarAlwaysOn) {
            if (dy > 0)  // scroll down
                scrollVertical = qFrame->scrollBarValue(Qt::Vertical) < qFrame->scrollBarMaximum(Qt::Vertical);
            else if (dy < 0) //scroll up
                scrollVertical = qFrame->scrollBarValue(Qt::Vertical) > qFrame->scrollBarMinimum(Qt::Vertical);
        } else {
            scrollVertical = true;
        }

        if (scrollHorizontal || scrollVertical) {
            qFrame->scroll(dx, dy);
            return;
        }

        qFrame = qFrame->parentFrame();
    } while (qFrame);
}

WebTouchScroller::WebTouchScroller(QObject *parent)
    : QObject(parent)
    , m_webFrame(0)
{
}

WebTouchScroller::~WebTouchScroller()
{
}

void WebTouchScroller::setFrame(QWebFrame* frame)
{
    m_webFrame = frame;
}

void WebTouchScroller::scroll(const QPointF &delta, const QPoint &scrollStartPoint)
{
    if (!m_webFrame)
        return;

    qtwebkit_webframe_scrollRecursively(m_webFrame, delta.x(), delta.y(),
                                        scrollStartPoint - m_webFrame->scrollPosition());
}
