/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * 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 "./FocusPolicyEventFilter.h"


FocusPolicyEventFilter::FocusPolicyEventFilter(Qt::FocusPolicy policy, QObject *parent):
    m_policy(policy),QObject(parent)
{

}

FocusPolicyEventFilter::~FocusPolicyEventFilter()
{

}

void FocusPolicyEventFilter::setFocusPolicyForAllWidgets(QWidget *parent, Qt::FocusPolicy policy)
{
    if (!parent) 
    {
        return;
    }
    QList<QWidget *> widgets = parent->findChildren<QWidget *>();
    for (QWidget *widget: widgets)
    {
        if (widget->focusPolicy() != policy)
        {
            widget->setFocusPolicy(policy);
        }
        setFocusPolicyForAllWidgets(widget,policy);
    }
}

bool FocusPolicyEventFilter::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::ChildAdded)
    {
        QChildEvent *childEvent = dynamic_cast<QChildEvent *>(event);
        if (childEvent && childEvent->child()->isWidgetType())
        {
            QWidget *childWidget = qobject_cast<QWidget*>(childEvent->child());
            this->setFocusPolicyForAllWidgets(childWidget,m_policy);

        }
    }
    return QObject::eventFilter(obj, event);
}
