#include "fpscounter.h"

FpsCounter::FpsCounter(QObject *parent)
    : QObject(parent)
{
    m_timer.start();
}

void FpsCounter::componentComplete()
{
    QObject *p = parent();
    while (p) {
        if (auto w = qobject_cast<QQuickWindow *>(p)) {
            connect(w, &QQuickWindow::frameSwapped, this, [this]{
                    ++m_frames;
                    const auto elapsed = m_timer.elapsed();
                    if (elapsed >= 1000) {
                        m_fps = double(m_frames) / (double(elapsed) / 1000.);
                        m_frames = 0;
                        m_timer.restart();
                        QMetaObject::invokeMethod(this, &FpsCounter::fpsChanged, Qt::QueuedConnection);
                    }
                }, Qt::DirectConnection);
            break;
        }
        p = p->parent();
    }
}
