/*
 *
 * Copyright (C) 2004 Dirk Ziegelmeier <dziegel@gmx.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include <kapplication.h>

#include <config-kdetv.h>

#include <qwidget.h>
#include <qtimer.h>
#include <qevent.h>
#include <qdesktopwidget.h>

#include <klocale.h>
#include <kdebug.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <QX11Info>

#include "overlaycontroller.h"

OverlayController::OverlayController(QWidget *w)
    : QWidget(w),
      _filterRefresh(false),
      _visibility(VisibilityUnobscured),
      _w(w)
{
    setObjectName("OverlayController");
    _repaintTimer = new QTimer();
    connect(_repaintTimer, SIGNAL( timeout() ),
            this, SLOT( doRepaintScreen() ));

    _reclipTimer = new QTimer();
    connect(_reclipTimer, SIGNAL( timeout() ),
            this, SLOT( doReclip() ));

    _top  = topLevelWidget();

    int scn = QApplication::desktop()->screenNumber(_w);
    _root   = QApplication::desktop()->screen(scn);

    // tv window -- need visibility, structure
    XSelectInput(QX11Info::display(),
                 _w->winId(),
                 ButtonPressMask      |
                 ButtonReleaseMask    |
                 ExposureMask         |
                 PointerMotionMask    |
                 VisibilityChangeMask |
                 StructureNotifyMask  |
                 SubstructureNotifyMask);

    // root window -- need visibility, sub-, structure
    XSelectInput(QX11Info::display(),
                 _root->winId(),
                 VisibilityChangeMask |
                 FocusChangeMask      |
                 StructureNotifyMask  |
                 SubstructureNotifyMask);

    kapp->installX11EventFilter(this);
    _w->installEventFilter(this);
    _top->installEventFilter(this);

    scheduleRepaintScreen();
}

OverlayController::~OverlayController()
{
    delete _repaintTimer;
    delete _reclipTimer;
    emit enableVideo(false);
    doRepaintScreen();
}

bool OverlayController::eventFilter(QObject* obj, QEvent* e)
{
    //    kDebug() << "event: " << e->type() << " for: " << obj->name();

    // ---------------------------------- Shell and view widget
    if(e->type() == QEvent::Move) {
        // The main window or the widget has moved
        kDebug() << "Overlay: View moved";
        emit moved();
        scheduleRepaintScreen();

    } else if(e->type() == QEvent::Show) {
        // Show main window or tv widget
        kDebug() << "Overlay: View shown";
        emit enableVideo(true);
        scheduleRepaintScreen();

    } else if(e->type() == QEvent::Hide) {
        // Hide main window or tv widget
        kDebug() << "Overlay: View hidden";
        emit enableVideo(false);
        scheduleRepaintScreen();
    }

    // ---------------------------------- View widget only
    if (obj == _w) {
        if(e->type() == QEvent::Resize) {
            // The widget has changed its size
            // and maybe as a consequence its position (-> aspect ratio)
            //            kDebug() << "Overlay: View resized";
            emit resized();
            emit moved();
            scheduleRepaintScreen();

        } else if(e->type() == QEvent::Paint) {
            // The widget is being unobscured (unmap, expose)
            //            kDebug() << "Overlay: Paint (expose)";
            scheduleReclip();
        }
    }

    return false;
}

void OverlayController::scheduleRepaintScreen()
{
    //    kDebug() << "Overlay: Schedule Repaint";

    _filterRefresh = true;
    _repaintTimer->setSingleShot(true);
    _repaintTimer->start(0);
}

void OverlayController::scheduleReclip()
{
    //    kDebug() << "Overlay: Schedule Reclip";
    _reclipTimer->setSingleShot(true);
    _reclipTimer->start(0);
}

void OverlayController::doRepaintScreen()
{
    //    kDebug() << "Overlay: Repaint Screen";

    _filterRefresh = true;
    emit updateClipping();
    emit repaintScreen();
}

void OverlayController::doReclip()
{
    //    kDebug() << "Overlay: Reclip";

    emit updateClipping();
}

bool OverlayController::x11Event(XEvent* e)
{
    /*
    switch (e->type) {
    case Expose:
        kDebug() << "Expose";
        break;
    case GraphicsExpose:
        kDebug() << "Graphics expose";
        break;
    case VisibilityNotify:
        switch (e->xvisibility.state) {
        case VisibilityFullyObscured:
            kDebug() << "Visibility obscured";
            break;
        case VisibilityPartiallyObscured:
            kDebug() << "Visibility";
            break;
        case VisibilityUnobscured:
            kDebug() << "Visibility unobscured";
            break;
        default:
            break;
        }
    break;
    case ConfigureNotify:
        kDebug() << "Configure notify";
        break;
    case ConfigureRequest:
        kDebug() << "Configure request notify";
        break;
    case MapNotify:
        kDebug() << "Map notify";
        break;
    case UnmapNotify:
        kDebug() << "Unmap notify";
        break;
    case MappingNotify:
        kDebug() << "Mapping notify";
        break;
    case PropertyNotify:
        kDebug() << "Property notify";
        break;
    case EnterNotify:
        kDebug() << "Enter notify";
        break;
    case LeaveNotify:
        kDebug() << "Leave notify";
        break;
    default:
        kDebug() << "UNINTERESTING X11 Event: " << e->type << " for window: " << e->xany.window;
        return false;
    }
    if (e->xany.window == _w->winId()) {
        kDebug() << "X11 Event for TV widget";
    } else if (e->xany.window == _root->winId()) {
        kDebug() << "X11 Event for desktop";
    } else {
        kDebug() << "X11 Event for unknown window: " << e->xany.window;
    }

    kDebug() << "Will filter: " << _filterRefresh;
    */

    // --------------------------------------- Events for the TV widget
    if ( e->xany.window == _w->winId() ) {
        if (e->type == VisibilityNotify) {
            _visibility = e->xvisibility.state;
            if (!_filterRefresh) {
                scheduleRepaintScreen();
            } else if (_visibility != VisibilityFullyObscured) {
                _filterRefresh = false;
            }
        } else if (e->type == MapNotify) {
            // A child widget is shown, reclip immediately
            emit updateClipping();
        } else if (e->type == ConfigureNotify) {
            // A child widget changes size
            emit updateClipping();
            scheduleRepaintScreen();
        }

    // --------------------------------------- Events for the desktop
    } else if ( e->xany.window == _root->winId() ) {
        if (e->type == ConfigureNotify) {
            // A window is moved into the TV widget and obscures it some more
            if (!_filterRefresh && 
                (_visibility == VisibilityPartiallyObscured)) {
                scheduleRepaintScreen();
            }
        }
    }

    return false;
}

#include "overlaycontroller.moc"
