/*****************************************************************

  Copyright (c) 1996-2001 the kicker authors. See file AUTHORS.

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
  AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
  AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 ******************************************************************/

#include <stdlib.h>
#include <unistd.h>

#include <qfile.h>
#include <qtimer.h>
#include <qcursor.h>
#include <qtooltip.h>

#include <kglobal.h>
#include <kstandarddirs.h>
#include <kimageio.h>
#include <klocale.h>
#include <kglobalaccel.h>
#include <dcopclient.h>
#include <kcmdlineargs.h>
#include <kconfig.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "extensionmanager.h"
#include "menumanager.h"
#include "panel.h"
#include "k_mnu.h"
#include "showdesktop.h"
#include "panelmanager.h"
#include "panelbutton.h"
#include "popupposition.h"

#include "kicker.h"
#include "kicker.moc"

Kicker* Kicker::kicker() { return (Kicker*)kapp; }

	Kicker::Kicker()
	: KUniqueApplication()
	, kMenu( 0 )
	, keys( 0 )
	, kButton( 0 )
{
        // Make kicker immutable if configuration modules have been marked immutable
        if (!config()->isImmutable() && kapp->authorizeControlModules(Kicker::configModules(true)).isEmpty())
        {
            config()->setReadOnly(true);
            config()->reparseConfiguration();
        }

	dcopClient()->setDefaultObject("Panel");
	dcopClient()->send( "ksplash", "", "upAndRunning(QString)", KCmdLineArgs::appName());

	disableSessionManagement();

	KGlobal::dirs()->addResourceType("mini", KStandardDirs::kde_default("data") +
			"kicker/pics/mini");

	KGlobal::dirs()->addResourceType("icon", KStandardDirs::kde_default("data") +
			"kicker/pics");

	KGlobal::dirs()->addResourceType("applets", KStandardDirs::kde_default("data") +
			"kicker/applets");

	KGlobal::dirs()->addResourceType("tiles", KStandardDirs::kde_default("data") +
			"kicker/tiles");

	KGlobal::dirs()->addResourceType("extensions", KStandardDirs::kde_default("data") +
			"kicker/extensions");

	KImageIO::registerFormats();

	KGlobal::iconLoader()->addExtraDesktopThemes();

	KGlobal::locale()->insertCatalogue("libkonq");

	Panel* p = Panel::the();
	setMainWidget(p);

	kMenu = new PanelKMenu( p );

	// client menu stuff
	new MenuManager( kMenu, this, "kickerMenuManager" );

	connect( this, SIGNAL(settingsChanged(int)),
			SLOT(slotSettingsChanged(int)));

	keys = new KGlobalAccel( this );
#define KICKER_ALL_BINDINGS
#include "kickerbindings.cpp"
#undef KICKER_ALL_BINDINGS
	keys->readSettings();
	keys->updateConnections();

	p->initialize();

	ExtensionManager::the()->initialize();

	configure();

	PanelManager::the()->showAll();
	
#if (QT_VERSION-0 >= 0x030200) // XRANDR support
	connect( desktop(), SIGNAL( resized( int )), SLOT( slotDesktopResized()));
#endif
}

Kicker::~Kicker()
{
	PanelManager::the()->shutdown();

	delete kMenu;
}

void Kicker::slotKMenuAccel()
{
	if( !kMenu->isVisible() ) {
		kMenu->initialize();
		QPoint p;
		// Popup the K-menu at the center of the screen.
		QDesktopWidget* desktop = KApplication::desktop();
		QRect r = desktop->screenGeometry(
				desktop->screenNumber(QCursor::pos()));
		// kMenu->rect() is not valid before showing, use sizeHint()
		p = r.center() - QRect( QPoint( 0, 0 ), kMenu->sizeHint()).center();
		kMenu->popup(p);

		// when the cursor is in the area where the menu pops up,
		// the item under the cursor gets selected. The single shot
		// avoids this from happening by allowing the item to be selected
		// when the event loop is enterred, and then resetting it.
		QTimer::singleShot(0, this, SLOT(slotSetKMenuItemActive()));
	}
}

void Kicker::slotSetKMenuItemActive()
{
	kMenu->selectFirstItem();
}

void Kicker::slotDesktopAccel()
{
	ShowDesktop::the()->toggle();
}

void Kicker::slotSettingsChanged( int category )
{
	if( category == (int) KApplication::SETTINGS_SHORTCUTS ) {
		keys->readSettings();
		keys->updateConnections();
	}
}

bool Kicker::highlightMenuItem( const QString &menuId )
{
    return kMenu->highlightMenuItem( menuId );
}

void Kicker::showKMenu()
{
    kMenu->showMenu();
}

void Kicker::popupKMenu( const QPoint &p )
{
//    kdDebug(1210) << "popupKMenu()" << endl;
    if( kMenu->isVisible() ) {
        kMenu->hide();
    } else {
        if ( p.isNull() )
            kMenu->popup( QCursor::pos() );
        else
            kMenu->popup( p );
    }
}

void Kicker::configure()
{
    KConfig* c = KGlobal::config();
    c->reparseConfiguration();

    emit configurationChanged();

    c->setGroup( "General" );
    bool _showToolTips = c->readBoolEntry( "ShowToolTips", true);
    QToolTip::setGloballyEnabled( _showToolTips );
//    kdDebug(1210) << "tooltips " << ( _showToolTips ? "enabled" : "disabled" ) << endl;

    PanelManager::the()->readConfig();
}


int Kicker::maxButtonDim() const
{   return 2*iconMargin(maxIconDim())+maxIconDim(); }

int Kicker::maxIconDim() const
{   return MAX_ICON_DIMENSION;}


int Kicker::iconMargin(int iconDim) const
{    return iconDim/16; }

bool Kicker::conserveSpace() const
{   return true;}

void Kicker::restart()
{
    // do this on a timer to give us time to return true
    QTimer::singleShot(0, this, SLOT(slotRestart()));
}

void Kicker::slotRestart()
{
    PanelManager::the()->shutdown();

    char ** o_argv = new char*[2];
    o_argv[0] = strdup("kicker");
    o_argv[1] = 0L;
    execv(QFile::encodeName(locate("exe", "kdeinit_wrapper")), o_argv);

    exit(1);
}

bool Kicker::isImmutable() const
{
    return config()->isImmutable();
}

void Kicker::addExtension( const QString &desktopFile )
{
   ExtensionManager::the()->addExtension( desktopFile );
}

void Kicker::slotLaunchConfig()
{
    slotLaunchConfig(QString::null);
}

QStringList Kicker::configModules(bool controlCenter)
{
    QStringList args;

    if (controlCenter)
    {
        args  << "kde-panel.desktop";
    }
    else
    {
        args  << "kde-kicker_config.desktop";
    }
    args << "kde-kcmtaskbar.desktop";
    return args;
}

void Kicker::slotLaunchConfig(const QString& configPath)
{
    m_panelConfiged = configPath;
    QStringList args;
    QString prog = locate("exe", "kcmshell");
    args << "--caption" << i18n("Panel")
         << "--icon" << "kcmkicker";
    args += configModules(false);
    kapp->kdeinitExec(prog, args);
}

void Kicker::configLaunched()
{
    if (!m_panelConfiged.isEmpty())
    {
        QByteArray data;
        QDataStream stream(data, IO_WriteOnly);
        stream << m_panelConfiged;
        emitDCOPSignal("configSwitchToPanel(QString)", data);
        m_panelConfiged = QString::null;
    }
}

void Kicker::slotDesktopResized()
{
    configure(); // reposition on the desktop
}

void Kicker::clearQuickStartMenu()
{
    kMenu->clearRecentMenuItems();
}

