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

#include "ukuishellsurfacev1.h"
#include "logging.h"
#include "ukuiblur.h"
#include "kde-slide.h"
#include "xdgactivationv1.h"
#include "xdgdecorationv1.h"
#include "xdgdialogv1.h"
#include "xdgpopup.h"
#include "xdgtoplevel.h"

#include <QtWaylandClient/private/qwaylandabstractdecoration_p.h>
#include <QtWaylandClient/private/qwaylanddisplay_p.h>
#include <QtWaylandClient/private/qwaylandinputdevice_p.h>
#include <QtWaylandClient/private/qwaylandsurface_p.h>
#include <QtWaylandClient/private/qwaylandwindow_p.h>

#include <QtGui/private/qwindow_p.h>

#include <QEvent>

namespace QtWaylandClient
{

UkuiShellSurfaceV1::UkuiShellSurfaceV1(UkuiShell *shell, ::xdg_surface *surface, ::ukui_surface_v1 *ukuiSurface, ::ukui_decoration_v1 *decoration, QWaylandWindow *window)
    : QWaylandShellSurface(window)
    , xdg_surface(surface)
    , ukui_surface_v1(ukuiSurface)
    , m_ukuiDecoration(new QtWayland::ukui_decoration_v1(decoration))
    , m_shell(shell)
    , m_window(window)
{
    auto *display = window->display();
    Qt::WindowType type = window->window()->type();
    auto *transientParent = window->transientParent();

    if (type == Qt::ToolTip && transientParent) {
        setPopup(transientParent);
    } else if (type == Qt::Popup && transientParent && display->lastInputDevice()) {
        setGrabPopup(transientParent, display->lastInputDevice(), display->lastInputSerial());
    } else {
        setToplevel();
    }
    setSizeHints();

    initWindowByProperties();
    
    QString startupGeometryStr = qEnvironmentVariable("UKUI_SURFACE_STARTUP_GEOMETRY");
    if (!startupGeometryStr.isEmpty()) {
        QStringList startupGeometry = startupGeometryStr.split(QLatin1Char(','));
        if (startupGeometry.size() == 4) {
            QRect geometry(startupGeometry.at(0).toInt(), startupGeometry.at(1).toInt(),
                           startupGeometry.at(2).toInt(), startupGeometry.at(3).toInt());
            set_startup_geometry(geometry.x(), geometry.y(), geometry.width(), geometry.height());
        }
    }

    m_window->window()->installEventFilter(this);
}

UkuiShellSurfaceV1::~UkuiShellSurfaceV1()
{
    if (m_toplevel) {
        delete m_toplevel;
        m_toplevel = nullptr;
    }
    if (m_popup) {
        delete m_popup;
        m_popup = nullptr;
    }
    xdg_surface::destroy();
    ukui_surface_v1::destroy();

    if (m_blur) {
        m_blur->destroy();
        m_blur = nullptr;
    }
    if (m_slide) {
        m_slide->release();
        m_slide = nullptr;
    }

    if (m_ukuiDecoration) {
        m_ukuiDecoration->destroy();
        m_ukuiDecoration = nullptr;
    }
}

UkuiShell *UkuiShellSurfaceV1::shell()
{
    return m_shell;
}

Toplevel *UkuiShellSurfaceV1::toplevel()
{
    return m_toplevel;
}

Popup *UkuiShellSurfaceV1::popup()
{
    return m_popup;
}

bool UkuiShellSurfaceV1::resize(QWaylandInputDevice *inputDevice, Qt::Edges edges)
{
    if (!m_toplevel || !m_toplevel->isInitialized())
        return false;

    auto resizeEdges = Toplevel::convertToResizeEdges(edges);
    m_toplevel->resize(inputDevice->wl_seat(), inputDevice->serial(), resizeEdges);
    return true;
}

bool UkuiShellSurfaceV1::move(QWaylandInputDevice *inputDevice)
{
    if (m_toplevel && m_toplevel->isInitialized()) {
        m_toplevel->move(inputDevice->wl_seat(), inputDevice->serial());
        return true;
    }
    return false;
}

bool UkuiShellSurfaceV1::showWindowMenu(QWaylandInputDevice *seat)
{
    if (m_toplevel && m_toplevel->isInitialized()) {
        QPoint position = seat->pointerSurfacePosition().toPoint();
        m_toplevel->show_window_menu(seat->wl_seat(), seat->serial(), position.x(), position.y());
        return true;
    }
    return false;
}

void UkuiShellSurfaceV1::setTitle(const QString &title)
{
    if (m_toplevel)
        m_toplevel->set_title(title);
}

void UkuiShellSurfaceV1::setAppId(const QString &appId)
{
    m_appId = appId;
    if (m_toplevel)
        m_toplevel->set_app_id(appId);
}

void UkuiShellSurfaceV1::setWindowFlags(Qt::WindowFlags flags)
{
    if (m_toplevel) {
        m_toplevel->requestWindowFlags(flags);
    }

    uint32_t mask = 0;
    uint32_t value = 0;
    if (flags & Qt::WindowStaysOnBottomHint) {
        mask |= ukui_surface_v1::state_keep_below;
        value |= ukui_surface_v1::state_keep_below;
    }

    if (flags & Qt::WindowStaysOnTopHint) {
        mask |= ukui_surface_v1::state_keep_above;
        value |= ukui_surface_v1::state_keep_above;
    }

    if (flags & Qt::WindowDoesNotAcceptFocus) {
        mask |= ukui_surface_v1::state_focusable | ukui_surface_v1::state_activatable;
    }

    if (mask)
        set_state(mask, value);
}

bool UkuiShellSurfaceV1::isExposed() const
{
    return m_configured || m_pendingConfigureSerial;
}

bool UkuiShellSurfaceV1::handleExpose(const QRegion &region)
{
    if (!isExposed() && !region.isEmpty()) {
        m_exposeRegion = region;
        return true;
    }
    return false;
}

void UkuiShellSurfaceV1::applyConfigure()
{
    // It is a redundant ack_configure, so skipped.
    if (m_pendingConfigureSerial == m_appliedConfigureSerial)
        return;

    if (m_toplevel)
        m_toplevel->applyConfigure();
    m_appliedConfigureSerial = m_pendingConfigureSerial;

    m_configured = true;
    ack_configure(m_appliedConfigureSerial);
}

bool UkuiShellSurfaceV1::wantsDecorations() const
{
    return m_toplevel && m_toplevel->wantsDecorations();
}

void UkuiShellSurfaceV1::propagateSizeHints()
{
    setSizeHints();

    if (m_toplevel && m_window)
        m_window->commit();
}

void UkuiShellSurfaceV1::setContentGeometry(const QRect &rect)
{
    set_window_geometry(rect.x(), rect.y(), rect.width(), rect.height());
}

void UkuiShellSurfaceV1::setWindowPosition(const QPoint &position)
{
    set_position(position.x(), position.y());
}

void UkuiShellSurfaceV1::setSizeHints()
{
    if (m_toplevel && m_window) {
        const int minWidth = qMax(0, m_window->windowMinimumSize().width());
        const int minHeight = qMax(0, m_window->windowMinimumSize().height());
        m_toplevel->set_min_size(minWidth, minHeight);

        int maxWidth = qMax(minWidth, m_window->windowMaximumSize().width());
        if (maxWidth == QWINDOWSIZE_MAX)
            maxWidth = 0;
        int maxHeight = qMax(minHeight, m_window->windowMaximumSize().height());
        if (maxHeight == QWINDOWSIZE_MAX)
            maxHeight = 0;
        m_toplevel->set_max_size(maxWidth, maxHeight);
    }
}

bool UkuiShellSurfaceV1::requestActivate()
{
    activate();
    return true;
}

bool UkuiShellSurfaceV1::requestActivateOnShow()
{
    const Qt::WindowType type = m_window->window()->type();
    if (type == Qt::ToolTip || type == Qt::Popup || type == Qt::SplashScreen)
        return false;

    if (m_window->window()->property("_q_showWithoutActivating").toBool())
        return false;

    return requestActivate();
}

void UkuiShellSurfaceV1::raise()
{
}

void UkuiShellSurfaceV1::lower()
{
}

void UkuiShellSurfaceV1::setContentOrientationMask(Qt::ScreenOrientations orientation)
{
}

void UkuiShellSurfaceV1::sendProperty(const QString &name, const QVariant &value)
{
}

std::any UkuiShellSurfaceV1::surfaceRole() const
{
    if (m_toplevel)
        return m_toplevel->object();
    if (m_popup)
        return m_popup->object();
    return {};
}

void UkuiShellSurfaceV1::setSkipTaskbar(bool skip)
{
    if (ukui_surface_v1::isInitialized())
        ukui_surface_v1::set_skip_taskbar(skip);
    else
        qWarning(UKUI_SHELL) << "ukui_surface_v1 is not initialized, ignoring skip taskbar requested.";
}

void UkuiShellSurfaceV1::setSkipSwitcher(bool skip)
{
    if (ukui_surface_v1::isInitialized())
        ukui_surface_v1::set_skip_switcher(skip);
    else
        qWarning(UKUI_SHELL) << "ukui_surface_v1 is not initialized, ignoring skip switcher requested.";
}

void UkuiShellSurfaceV1::setNoTitlebar(bool noTitlebar)
{
    if ((m_window->window()->flags() & Qt::FramelessWindowHint) && !m_noTitlebar) {
        return;
    }

    if (ukui_surface_v1::isInitialized() && m_ukuiDecoration && m_ukuiDecoration->isInitialized()) {
        m_ukuiDecoration->set_no_titlebar(noTitlebar);
        m_noTitlebar = noTitlebar;
    } else {
        qCDebug(UKUI_SHELL) << "ukui_surface_v1 is not initialized, ignoring remove titlebar requested.";
    }
}

void UkuiShellSurfaceV1::setWindowRole(int role)
{
    if (ukui_surface_v1::isInitialized()) {
        if (!window()->window()->dynamicPropertyNames().contains("ukui_surface_skip_taskbar"))
            setSkipTaskbar(role != role_normal);
        if (!window()->window()->dynamicPropertyNames().contains("ukui_surface_skip_switcher"))
            setSkipSwitcher(role != role_normal);
        ukui_surface_v1::set_role(role);
    } else {
        qCDebug(UKUI_SHELL) << "ukui_surface_v1 is not initialized, ignoring set window role requested.";
    }
}

void UkuiShellSurfaceV1::setWindowIcon(const QString &icon_name)
{
    if (ukui_surface_v1::isInitialized())
        ukui_surface_v1::set_icon(icon_name);
    else
        qCDebug(UKUI_SHELL) << "ukui_surface_v1 is not initialized, ignoring set window icon requested.";
}

void UkuiShellSurfaceV1::requestWindowStates(Qt::WindowStates states)
{
    if (m_toplevel)
        m_toplevel->requestWindowStates(states);
    else
        qCDebug(UKUI_SHELL) << "Ignoring window states requested by non-toplevel zxdg_surface_v6.";
}

void UkuiShellSurfaceV1::setToplevel()
{
    Q_ASSERT(!m_toplevel && !m_popup);
    m_toplevel = new Toplevel(this);
}

void UkuiShellSurfaceV1::setPopup(QWaylandWindow *parent)
{
    Q_ASSERT(!m_toplevel && !m_popup);

    auto positioner = new QtWayland::xdg_positioner(m_shell->create_positioner());
    // set_popup expects a position relative to the parent
    QPoint transientPos = m_window->geometry().topLeft(); // this is absolute
    transientPos -= parent->geometry().topLeft();
    if (parent->decoration()) {
        transientPos.setX(transientPos.x() + parent->decoration()->margins().left());
        transientPos.setY(transientPos.y() + parent->decoration()->margins().top());
    }
    positioner->set_anchor_rect(transientPos.x(), transientPos.y(), 1, 1);
    positioner->set_anchor(QtWayland::xdg_positioner::anchor_top_left);
    positioner->set_gravity(QtWayland::xdg_positioner::gravity_bottom_right);
    positioner->set_size(m_window->geometry().width(), m_window->geometry().height());
    positioner->set_constraint_adjustment(QtWayland::xdg_positioner::constraint_adjustment_slide_x
        | QtWayland::xdg_positioner::constraint_adjustment_slide_y);
    m_popup = new Popup(this, parent, positioner);
    positioner->destroy();

    delete positioner;
}

void UkuiShellSurfaceV1::setGrabPopup(QWaylandWindow *parent, QWaylandInputDevice *device, int serial)
{
    setPopup(parent);
    m_popup->grab(device, serial);

    // Synthesize Qt enter/leave events for popup
    if (!parent)
        return;
    QWindow *current = QGuiApplication::topLevelAt(QCursor::pos());
    QWindow *leave = parent->window();
    if (current != leave)
        return;

    QWindowSystemInterface::handleLeaveEvent(leave);

    QWindow *enter = nullptr;
    if (m_popup && m_popup->ukuiShellSurfaceV1() && m_popup->ukuiShellSurfaceV1()->window())
        enter = m_popup->ukuiShellSurfaceV1()->window()->window();

    if (enter)
        QWindowSystemInterface::handleEnterEvent(enter, enter->mapFromGlobal(QCursor::pos()), QCursor::pos());
}

void UkuiShellSurfaceV1::xdg_surface_configure(uint32_t serial)
{
    m_pendingConfigureSerial = serial;
    if (!m_configured) {
        // We have to do the initial applyConfigure() immediately, since that is the expose.
        applyConfigure();
        m_exposeRegion = QRegion(QRect(QPoint(), m_window->geometry().size()));
    } else {
        // Later configures are probably resizes, so we have to queue them up for a time when we
        // are not painting to the window.
        m_window->applyConfigureWhenPossible();
    }

    if (!m_exposeRegion.isEmpty()) {
        m_window->handleExpose(m_exposeRegion);
        m_exposeRegion = QRegion();
    }
}

void UkuiShellSurfaceV1::ukui_surface_v1_position(int32_t x, int32_t y)
{
    QWindowSystemInterface::handleGeometryChange(m_window->window(), QRect(x, y, m_window->geometry().width(), m_window->geometry().height()));
}

void UkuiShellSurfaceV1::ukui_surface_v1_surface_state(uint32_t flags)
{
    if (!m_toplevel)
        return;

    // Only sync the window states from the wayland compositor but not really change it.
    Qt::WindowStates states = Qt::WindowNoState;

    if (flags & ukui_surface_v1::surface_state_maximized)
        states |= Qt::WindowMaximized;
    if (flags & ukui_surface_v1::surface_state_fullscreen)
        states |= Qt::WindowFullScreen;
    if (flags & ukui_surface_v1::surface_state_minimized)
        states |= Qt::WindowMinimized;
    if (flags & ukui_surface_v1::surface_state_active)
        states |= Qt::WindowActive;
    m_window->handleWindowStatesChanged(states, true);

    if (flags & ukui_surface_v1::surface_state_above)
        m_window->window()->setFlag(Qt::WindowStaysOnTopHint, true);
    else
        m_window->window()->setFlag(Qt::WindowStaysOnTopHint, false);

    if (flags & ukui_surface_v1::surface_state_below)
        m_window->window()->setFlag(Qt::WindowStaysOnBottomHint, true);
    else
        m_window->window()->setFlag(Qt::WindowStaysOnBottomHint, false);
}

QMap<QString, UkuiShellSurfaceV1::role> roleV1Map = {
    {"normal", UkuiShellSurfaceV1::role_normal},
    {"desktop", UkuiShellSurfaceV1::role_desktop},
    {"panel", UkuiShellSurfaceV1::role_panel},
    {"onscreendisplay", UkuiShellSurfaceV1::role_onscreendisplay},
    {"notification", UkuiShellSurfaceV1::role_notification},
    {"tooltip", UkuiShellSurfaceV1::role_tooltip},
    {"criticalnotification", UkuiShellSurfaceV1::role_criticalnotification},
    {"appletpopup", UkuiShellSurfaceV1::role_appletpopup},
    {"screenlock", UkuiShellSurfaceV1::role_screenlock},
    {"watermark", UkuiShellSurfaceV1::role_watermark},
    {"systemwindow", UkuiShellSurfaceV1::role_systemwindow},
    {"inputpanel", UkuiShellSurfaceV1::role_inputpanel},
    {"logout", UkuiShellSurfaceV1::role_logout},
    {"screenlocknotification", UkuiShellSurfaceV1::role_screenlocknotification},
    {"switcher", UkuiShellSurfaceV1::role_switcher},
    {"authentication", UkuiShellSurfaceV1::role_authentication}};

void UkuiShellSurfaceV1::slotWindowPropertyChanged(const char *name)
{
    QWindow *window = m_window->window();
    if (strcmp(name, "ukui_surface_no_titlebar") == 0) {
        setNoTitlebar(window->property(name).toBool());
    } else if (strcmp(name, "ukui_surface_role") == 0) {
        const QString role_str = window->property(name).toString().toLower();
        if (roleV1Map.contains(role_str)) {
            setWindowRole(roleV1Map[role_str]);
        } else {
            setWindowRole(UkuiShellSurfaceV1::role_normal);
            qCWarning(UKUI_SHELL) << "Unknown role property:" << role_str << ", set role to normal";
        }
    } else if (strcmp(name, "ukui_surface_role_v1") == 0) {
        setWindowRole(window->property(name).toInt());
    } else if (strcmp(name, "ukui_surface_icon") == 0) {
        setWindowIcon(window->property(name).toString());
    } else if (strcmp(name, "ukui_surface_panel_auto_hide") == 0) {
        set_panel_auto_hide(window->property(name).toBool());
    } else if (strcmp(name, "ukui_surface_grab_keyboard") == 0) {
        grab_keyboard(m_window->display()->inputDevices().first()->object());
    } else if (strcmp(name, "ukui_surface_open_under_cursor") == 0) {
        const auto point = window->property(name).toPoint();
        open_under_cursor(point.x(), point.y());
    } else if (strcmp(name, "ukui_surface_skip_taskbar") == 0) {
        setSkipTaskbar(window->property(name).toBool());
    } else if (strcmp(name, "ukui_surface_skip_switcher") == 0) {
        setSkipSwitcher(window->property(name).toBool());
    } else if (strcmp(name, "ukui_surface_panel_takes_focus") == 0) {
        set_state(ukui_surface_v1::state_focusable, window->property(name).toBool());
    } else if (strcmp(name, "ukui_surface_blur") == 0) {
        auto pair = window->property(name).value<QPair<QRegion, int>>();
        if (pair.second < 0) {
            if (m_blur) {
                delete m_blur;
                m_blur = nullptr;
            }
        } else {
            if (!m_blur) {
                m_blur = m_shell->blurManager()->getUkuiBlur(m_window->wlSurface());
            }
            auto blurRegion = m_window->display()->createRegion(pair.first);
            m_blur->set_region(blurRegion);
            m_blur->set_level(pair.second);
            m_window->commit();
            wl_region_destroy(blurRegion);
        }
    } else if (strcmp(name, "ukui_surface_slide") == 0) {
        auto pair = window->property(name).value<QPair<int, int>>();
        int location = pair.first;
        if (location < 0) {
            if (m_slide) {
                delete m_slide;
                m_slide = nullptr;
                m_shell->slideManager()->unset(m_window->wlSurface());
            }
            return;
        }

        if (!m_slide) {
            m_slide = m_shell->slideManager()->getKdeSlide(m_window->wlSurface());
        }
        int offset  = pair.second;
        m_slide->set_location(location);
        m_slide->set_offset(offset);
        m_slide->commit();
    } else if (strcmp(name, "ukui_surface_state") == 0) {
        auto pair = window->property(name).value<QPair<uint32_t, uint32_t>>();
        if (pair.first)
            set_state(pair.first, pair.second);
    } else if (strcmp(name, "ukui_surface_show_tile_flyout") == 0) {
        QRect rect = window->property(name).toRect();
        show_tile_flyout(m_window->display()->inputDevices().first()->object(), rect.x(), rect.y(), rect.width(), rect.height());
    } else if (strcmp(name, "ukui_surface_decoration_state") == 0 || strcmp(name, "ukui_surface_decoration_components") == 0) {
        if (m_ukuiDecoration)
            m_ukuiDecoration->set_decoration_components(window->property(name).toUInt());
    } else if (strcmp(name, "ukui_surface_opaque_region") == 0) {
        if (window->requestedFormat().alphaBufferSize() <= 0)
            return;

        QRegion opaqueRegion = window->property(name).value<QRegion>();
        auto opaqueRegionObject = m_window->display()->createRegion(opaqueRegion);
        wl_surface_set_opaque_region(m_window->wlSurface(), opaqueRegionObject);
        wl_region_destroy(opaqueRegionObject);
    }
}

void UkuiShellSurfaceV1::initWindowByProperties()
{
    QWindow *window = m_window->window();
    const QList<QByteArray> properties_list = window->dynamicPropertyNames();
    for (const QByteArray &property : properties_list) {
        slotWindowPropertyChanged(property.constData());
    }
}

bool UkuiShellSurfaceV1::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == m_window->window()) {
        if (event->type() == QEvent::DynamicPropertyChange) {
            QDynamicPropertyChangeEvent *propEvent = static_cast<QDynamicPropertyChangeEvent *>(event);
            slotWindowPropertyChanged(propEvent->propertyName().constData());
        }
    }
    return false;
}

} // namespace QtWaylandClient
