// 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 QObject, public QtWayland::zwlr_screencopy_manager_v1
{
    Q_OBJECT
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;

    QPixmap pixmap();

Q_SIGNALS:
    void ready();
    void failed();

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

private:
    QImage mImage;

    QWaylandDisplay *mDisplay = nullptr;
    wl_buffer *mBuffer = nullptr;
	QSize mBufferDimensions;
	uint32_t mBufferFormat;
	uint32_t mBufferStride;
	bool mFormatGiven = false;
	size_t mBufferSize;
	uchar *mBufferData;
    bool mBufferReady = false;
};

} // namespace QtWaylandClient

QT_END_NAMESPACE
