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

  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 "kicker.h"
#include "kicker.moc"

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

	Kicker::Kicker()
	: KUniqueApplication()
	, kMenu( 0 )
, keys( 0 )
{
	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();
}

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

	delete kMenu;
}

void Kicker::slotKMenuAccel()
{
	if( !kMenu->isVisible() ) {
		// Popup the K-menu at the center of the screen.
		QDesktopWidget* desktop = KApplication::desktop();
		QRect r = desktop->screenGeometry(
				desktop->screenNumber(QCursor::pos()));
		kMenu->popup(r.center() - kMenu->rect().center());

		// 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->setActiveItem(0);
}

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

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

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();
}

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()
{
    QStringList args;
    QString prog = locate("exe", "kcmshell");
    args << "kicker_config";
    args << "kicker_config_appearance";
    args << "kcmtaskbar";
    kapp->kdeinitExec(prog, args);
}


