// SPDX-FileCopyrightText: 2024 KylinSoft Co., Ltd.
//
// SPDX-License-Identifier: GPL-1.0-or-later

#pragma once

#include <QtWaylandClient/private/qwayland-wlr-screencopy-unstable-v1.h>

#include <QtWaylandClient/qtwaylandclientglobal.h>
#include <QtWaylandClient/private/qwaylandshmbackingstore_p.h>

#include <QtCore/QObject>

QT_BEGIN_NAMESPACE

class QRect;

namespace QtWaylandClient {

class QWaylandDisplay;
class QWaylandScreen;
class QWaylandBuffer;
class QWaylandScreenCopyFrameV1;

class QWaylandScreenCopyManagerV1 : public QtWayland::zwlr_screencopy_manager_v1
{
public:
    explicit QWaylandScreenCopyManagerV1(QWaylandDisplay *display, uint id, uint version);
    QWaylandDisplay *display() const { return mDisplay; }

    QPixmap captureScreen(wl_output *output, bool hasCursor = true);
    QPixmap captureScreenRegion(wl_output *output, int32_t x, int32_t y, int32_t width, int32_t height, bool hasCursor = true);

private:
    QWaylandDisplay *mDisplay = nullptr;
};

class QWaylandScreenCopyFrameV1 : public QObject, public QtWayland::zwlr_screencopy_frame_v1
{
    Q_OBJECT
public:
    explicit QWaylandScreenCopyFrameV1(QWaylandDisplay *display, struct ::zwlr_screencopy_frame_v1 *object);
    ~QWaylandScreenCopyFrameV1() override;

    bool copyDone() const { return mCopyDone; }
    QPixmap pixmap();

protected:
    void zwlr_screencopy_frame_v1_ready(uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec) override;
    void zwlr_screencopy_frame_v1_flags(uint32_t flags) override;
    void zwlr_screencopy_frame_v1_failed() override;
    void zwlr_screencopy_frame_v1_buffer(uint32_t format, uint32_t width, uint32_t height, uint32_t stride) override;

private:
    QWaylandDisplay *mDisplay = nullptr;
    wl_buffer *mBuffer = nullptr;

    QImage mImage;

    bool mYInvert = false;
    bool mCopyDone = false;
};

} // namespace QtWaylandClient

QT_END_NAMESPACE
