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

#include "ukuishellsurface.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
{

UkuiShellSurface::UkuiShellSurface(UkuiShell *shell, ::xdg_surface *surface, ::ukui_surface *ukuiSurface, QWaylandWindow *window)
    : QWaylandShellSurface(window)
    , xdg_surface(surface)
    , ukui_surface(ukuiSurface)
    , 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();
    m_window->window()->installEventFilter(this);
}

UkuiShellSurface::~UkuiShellSurface()
{
    if (m_toplevel) {
        delete m_toplevel;
        m_toplevel = nullptr;
    }
    if (m_popup) {
        delete m_popup;
        m_popup = nullptr;
    }
    xdg_surface::destroy();
    ukui_surface::destroy();

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

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

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

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

bool UkuiShellSurface::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 UkuiShellSurface::move(QWaylandInputDevice *inputDevice)
{
    if (m_toplevel && m_toplevel->isInitialized()) {
        m_toplevel->move(inputDevice->wl_seat(), inputDevice->serial());
        return true;
    }
    return false;
}

bool UkuiShellSurface::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 UkuiShellSurface::setTitle(const QString &title)
{
    if (m_toplevel)
        m_toplevel->set_title(title);
}

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

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

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

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

void UkuiShellSurface::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 UkuiShellSurface::wantsDecorations() const
{
    return m_toplevel && m_toplevel->wantsDecorations();
}

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

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

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

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

void UkuiShellSurface::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 UkuiShellSurface::requestActivate()
{
    activate();
    return true;
}

bool UkuiShellSurface::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 UkuiShellSurface::raise()
{
}

void UkuiShellSurface::lower()
{
}

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

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

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

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

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

    if (ukui_surface::isInitialized()) {
        ukui_surface::set_property(property_no_titlebar, noTitlebar);
        m_noTitlebar = noTitlebar;
    } else {
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring remove titlebar requested.";
    }
}

void UkuiShellSurface::setTheme(int theme)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_theme, theme);
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set theme requested.";
}

void UkuiShellSurface::setWindowRadius(int radius)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_window_radius, radius);
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set window radius requested.";
}

void UkuiShellSurface::setBorderWidth(int width)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_border_width, width);
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set border width requested.";
}

void UkuiShellSurface::setBorderColor(QColor color)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_border_color, color.rgba());
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set border color requested.";
}

void UkuiShellSurface::setShadowRadius(int radius)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_shadow_radius, radius);
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set shadow radius requested.";
}

void UkuiShellSurface::setShadowOffset(int offset)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_shadow_offset, offset);
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set shadow offset requested.";
}

void UkuiShellSurface::setShadowColor(QColor color)
{
    if (ukui_surface::isInitialized())
        ukui_surface::set_property(property_shadow_color, color.rgba());
    else
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set shadow color requested.";
}

void UkuiShellSurface::setWindowRole(int role)
{
    if (ukui_surface::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::set_role(role);
    } else {
        qCDebug(UKUI_SHELL) << "ukui_surface is not initialized, ignoring set window role requested.";
    }
}

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

void UkuiShellSurface::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 UkuiShellSurface::setToplevel()
{
    Q_ASSERT(!m_toplevel && !m_popup);
    m_toplevel = new Toplevel(this);
}

void UkuiShellSurface::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 UkuiShellSurface::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->ukuiShellSurface() && m_popup->ukuiShellSurface()->window())
        enter = m_popup->ukuiShellSurface()->window()->window();

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

void UkuiShellSurface::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 UkuiShellSurface::ukui_surface_position(int32_t x, int32_t y)
{
    QWindowSystemInterface::handleGeometryChange(m_window->window(), QRect(x, y, m_window->geometry().width(), m_window->geometry().height()));
}

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

void UkuiShellSurface::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_theme") == 0) {
        setTheme(window->property(name).toInt());
    } else if (strcmp(name, "ukui_surface_window_radius") == 0) {
        setWindowRadius(window->property(name).toInt());
    } else if (strcmp(name, "ukui_surface_border_width") == 0) {
        setBorderWidth(window->property(name).toInt());
    } else if (strcmp(name, "ukui_surface_border_color") == 0) {
        setBorderColor(window->property(name).value<QColor>());
    } else if (strcmp(name, "ukui_surface_shadow_radius") == 0) {
        setShadowRadius(window->property(name).toInt());
    } else if (strcmp(name, "ukui_surface_shadow_offset") == 0) {
        setShadowOffset(window->property(name).toInt());
    } else if (strcmp(name, "ukui_surface_shadow_color") == 0) {
        setShadowColor(window->property(name).value<QColor>());
    } else if (strcmp(name, "ukui_surface_role") == 0) {
        const QString role_str = window->property(name).toString().toLower();
        if (roleMap.contains(role_str)) {
            setWindowRole(roleMap[role_str]);
        } else {
            setWindowRole(UkuiShellSurface::role_normal);
            qCWarning(UKUI_SHELL) << "Unknown role property:" << role_str << ", set role to normal";
        }
    } 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_panel_takes_focus(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);
            wl_region_destroy(blurRegion);
        }
    } else if (strcmp(name, "ukui_surface_slide") == 0) {
        auto pair = window->property(name).value<QPair<QString, int>>();
        int location = QtWayland::org_kde_kwin_slide::location_bottom;
        if (pair.first == "left") {
            location = QtWayland::org_kde_kwin_slide::location_left;
        } else if (pair.first == "top") {
            location = QtWayland::org_kde_kwin_slide::location_top;
        } else if (pair.first == "right") {
            location = QtWayland::org_kde_kwin_slide::location_right;
        } else if (pair.first == "bottom") {
            location = QtWayland::org_kde_kwin_slide::location_bottom;
        } else if (pair.first == "none") {
            if (m_slide) {
                delete m_slide;
                m_slide = nullptr;
            }
            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();
    }
}

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

bool UkuiShellSurface::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
