//===========================================================================
//
// This file is part of the KDE project
//
// Copyright (c) 1999 Martin R. Jones <mjones@kde.org>
//


#include <config.h>

#include <stdlib.h>

#include <kstandarddirs.h>
#include <kapplication.h>
#include <kservicegroup.h>
#include <kdebug.h>
#include <klocale.h>
#include <qfile.h>
#include <assert.h>

#include "lockeng.h"
#include "lockeng.moc"

#include <X11/Xlib.h>

//===========================================================================
//
// Screen saver engine. Doesn't handle the actual screensaver window,
// starting screensaver hacks, or password entry. That's done by
// a newly started process.
//
SaverEngine::SaverEngine()
    : QWidget(),
      DCOPObject("KScreensaverIface")
{
    kapp->installX11EventFilter(this);

    // Save X screensaver parameters
    XGetScreenSaver(qt_xdisplay(), &mXTimeout, &mXInterval,
                    &mXBlanking, &mXExposures);

    // We'll handle blanking
    XSetScreenSaver(qt_xdisplay(), 0, mXInterval, mXBlanking, mXExposures);

    mState = Waiting;
    mXAutoLock = 0;
    mEnabled = false;

    connect(&mLockProcess, SIGNAL(processExited(KProcess *)),
                        SLOT(lockProcessExited()));

    configure();
}

//---------------------------------------------------------------------------
//
// Destructor - usual cleanups.
//
SaverEngine::~SaverEngine()
{
    mLockProcess.detach(); // don't kill it if we crash
    delete mXAutoLock;

    // Restore X screensaver parameters
    XSetScreenSaver(qt_xdisplay(), mXTimeout, mXInterval, mXBlanking,
                    mXExposures);
}

//---------------------------------------------------------------------------
void SaverEngine::lock()
{
    if (mState == Waiting)
    {
        startLockProcess( ForceLock );
    }
}

//---------------------------------------------------------------------------
void SaverEngine::save()
{
    if (mState == Waiting)
    {
        startLockProcess( DefaultLock );
    }
}

//---------------------------------------------------------------------------
void SaverEngine::quit()
{
    if (mState == Saving)
    {
        stopLockProcess();
    }
}

//---------------------------------------------------------------------------
bool SaverEngine::isEnabled()
{
  return mEnabled;
}

//---------------------------------------------------------------------------
bool SaverEngine::enable( bool e )
{
    if ( e == mEnabled )
	return true;

    // If we aren't in a suitable state, we will not reconfigure.
    if (mState != Waiting)
        return false;

    mEnabled = e;

    if (mEnabled)
    {
	if ( !mXAutoLock ) {
	    mXAutoLock = new XAutoLock();
	    connect(mXAutoLock, SIGNAL(timeout()), SLOT(idleTimeout()));
	}
        mXAutoLock->setTimeout(mTimeout);
        mXAutoLock->start();

        kdDebug(1204) << "Saver Engine started, timeout: " << mTimeout << endl;
    }
    else
    {
	if (mXAutoLock)
	{
	    delete mXAutoLock;
	    mXAutoLock = 0;
	}

        kdDebug(1204) << "Saver Engine disabled" << endl;
    }

    return true;
}

//---------------------------------------------------------------------------
bool SaverEngine::isBlanked()
{
  return (mState != Waiting);
}

//---------------------------------------------------------------------------
//
// Read and apply configuration.
//
void SaverEngine::configure()
{
    // If we aren't in a suitable state, we will not reconfigure.
    if (mState != Waiting)
        return;

    // create a new config obj to ensure we read the latest options
    KConfig *config = KGlobal::config();
    config->reparseConfiguration();

    config->setGroup("ScreenSaver");

    bool e  = config->readBoolEntry("Enabled", false);
    mTimeout = config->readNumEntry("Timeout", 300);

    mEnabled = !e;   // force the enable()

    enable( e );
}

//---------------------------------------------------------------------------
//
// Start the screen saver.
//
void SaverEngine::startLockProcess( LockType lock_type )
{
    if (mState != Waiting)
    {
        kdWarning(1204) << "SaverEngine::startSaver() saver already active" << endl;
        return;
    }

    kdDebug(1204) << "SaverEngine: starting saver" << endl;
    emitDCOPSignal("KDE_start_screensaver()", QByteArray());

    if (mLockProcess.isRunning())
    {
        stopLockProcess();
    }
    mLockProcess.clearArguments();
    QString path = KStandardDirs::findExe( "kdesktop_lock" );
    if( path.isEmpty())
    {
	kdDebug( 1204 ) << "Can't find kdesktop_lock!" << endl;
	return;
    }
    mLockProcess << path;
    switch( lock_type )
    {
	case ForceLock:
    	    mLockProcess << QString( "--forcelock" );
	  break;
	case DontLock:
	    mLockProcess << QString( "--dontlock" );
	  break;
	default:
	  break;
    }
    if (mLockProcess.start() == false )
    {
	kdDebug( 1204 ) << "Failed to start kdesktop_lock!" << endl;
	return;
    }
    
    mState = Saving;
    if (mXAutoLock)
    {
        mXAutoLock->stop();
    }
}

//---------------------------------------------------------------------------
//
// Stop the screen saver.
//
void SaverEngine::stopLockProcess()
{
    if (mState == Waiting)
    {
        kdWarning(1204) << "SaverEngine::stopSaver() saver not active" << endl;
        return;
    }
    kdDebug(1204) << "SaverEngine: stopping lock" << endl;

    mLockProcess.kill();
    
    if (mXAutoLock)
    {
        mXAutoLock->start();
    }
    mState = Waiting;
}

void SaverEngine::lockProcessExited()
{
    kdDebug(1204) << "SaverEngine: lock exited" << endl;
    if( mState == Waiting )
	return;
    if (mXAutoLock)
    {
        mXAutoLock->start();
    }
    mState = Waiting;
}

//---------------------------------------------------------------------------
//
// XAutoLock has detected the required idle time.
//
void SaverEngine::idleTimeout()
{
    startLockProcess( DefaultLock );
}

//---------------------------------------------------------------------------
//
// X11 Event.
//
bool SaverEngine::x11Event(XEvent *event)
{
    if (!mEnabled && mState == Waiting)
    {
        return false;
    }

    switch (event->type)
    {
        case KeyPress:
	    {
	    if (!event->xkey.send_event && mXAutoLock && mState == Waiting)
    		mXAutoLock->keyPressed();
	    break;
	    }

        case CreateNotify:
//            if (event->xcreatewindow.window == winId() ||
//                (mPassDlg && event->xcreatewindow.window == mPassDlg->winId()))
//            {
//                break;
//            }
            if (mXAutoLock)
            {
                mXAutoLock->windowCreated(event->xcreatewindow.window);
            }
            break;

    }
    return false;
}
