/*
 * Copyright (c) KylinSoft Co., Ltd. 2022.All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "appinputareamanager.h"

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
#include <KWindowEffects>
#include <KX11Extras>
#include <NETWM>
#else
#include <KWindowSystem>
#endif

AppInputAreaManager::AppInputAreaManager(QObject *parent)
    : QObject(parent), dummyWidget_(nullptr), oneshotTimer_(nullptr) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    KX11Extras::setType(dummyWidget_.winId(), NET::Dock);
#else
    KWindowSystem::setType(dummyWidget_.winId(), NET::Dock);
#endif
    dummyWidget_.setWindowFlags(Qt::FramelessWindowHint);
    dummyWidget_.setAttribute(Qt::WA_TranslucentBackground);
    oneshotTimer_.setSingleShot(true);
    connectSignal();
}

void AppInputAreaManager::connectSignal() {
    QObject::connect(&oneshotTimer_, &QTimer::timeout, this, [this]() {
        dummyWidget_.setGeometry(virtualKeyboardRect_);
        dummyWidget_.show();
        // 使用KWin接口调整工作区域，仅在X11下有效
        // 该接口对全屏应用无效
        // 该接口需在winId对象显示前后调用，否则可能不生效
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
        KX11Extras::setExtendedStrut(dummyWidget_.winId(), 0, 0, 0, 0, 0, 0, 0,
                                     0, 0, virtualKeyboardRect_.height(),
                                     virtualKeyboardRect_.x(),
                                     virtualKeyboardRect_.width() - 1);
#else
        KWindowSystem::setExtendedStrut(dummyWidget_.winId(), 0, 0, 0, 0, 0, 0,
                                        0, 0, 0, virtualKeyboardRect_.height(),
                                        virtualKeyboardRect_.x(),
                                        virtualKeyboardRect_.width() - 1);
#endif
    });
}

void AppInputAreaManager::raiseInputArea(const QRect &virtualKeyboardRect) {
    virtualKeyboardRect_ = virtualKeyboardRect;

    oneshotTimer_.start(SHOW_DELAY_TIME);
}

void AppInputAreaManager::fallInputArea() {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    KX11Extras::setExtendedStrut(dummyWidget_.winId(), 0, 0, 0, 0, 0, 0, 0, 0,
                                 0, 0, 0, 0);
#else
    KWindowSystem::setExtendedStrut(dummyWidget_.winId(), 0, 0, 0, 0, 0, 0, 0,
                                    0, 0, 0, 0, 0);
#endif

    dummyWidget_.hide();
    oneshotTimer_.stop();
}
