/*************************************************************************
 *                                                                       *
 *  KTheme                                                               *
 *                                                                       *
 * This file is part of the KTheme-Package. For detail information about *
 * this program have a look at the README-File.                          *
 *                                                                       *
 * Copyright(c) 1998 Christian Poulter.                                  *
 *                                                                       *
 * Parts take from the KDE Display color scheme setup module,            *
 *  Copyright (c)  Mark Donohoe 1997                                     *
 *  Converted to a kcc module by Matthias Hoelzer 1997                   *
 *                                                                       *
 * 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 - version 2.                             *
 *                                                                       *
 * 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 in file COPYING for more details.          *
 *                                                                       *
 * You should have received a copy of the GNU General Public License     *
 * along with this program; if not, write to the Free Software           *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.             *
 *                                                                       *
 *  On the Net at http://www.wilhelmshaven-online.de/benutzer/cpoulter   *
 *  Email to cpoulter@ebs-net.com                                        *
 *                                                                       *
 *************************************************************************/

#include <qdir.h>
#include <qlistbox.h>

#include <kapp.h>
#include <ksimpleconfig.h>
#include <klocale.h>

#include <X11/Xlib.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>

#include "kthemecolorconfig.h"
#include "widgetcanvas.h"

static bool GUI;

KThemeColorConfig::~KThemeColorConfig (){
	if (GUI){
	}
}

KThemeColorConfig::KThemeColorConfig (QWidget * parent, const char *name, bool init):KConfigWidget (parent, name){
	if (init)
		GUI = FALSE;
	else
		GUI = TRUE;
	
	if (GUI){

		path_scheme=KApplication::kde_datadir()+"/ktheme/color-schemes";

		kde_display = x11Display();
		KDEChangePalette = XInternAtom( kde_display, "KDEChangePalette", False);
		screen = DefaultScreen(kde_display);
		root = RootWindow(kde_display, screen);

		preview = new WidgetCanvas( this );
		preview->setFixedHeight( 150 );

		loadSettings();

		scheme_Listbox = new QListBox( this, "listBox" );
		scheme_Listbox->resize(200,200);
		scheme_Listbox->setAutoUpdate( FALSE );

		QDir d(path_scheme);
		d.setFilter( QDir::Files );
		d.setSorting( QDir::Name );
		d.setNameFilter("*.kcsrc");

		int citem=0;

		scheme_Listbox->clear();
		scheme_Listbox->insertItem( klocale->translate("Current scheme"));
		scheme_Listbox->setCurrentItem(0);
		for ( unsigned int i=0; i<d.count(); i++ ) {
			QString tmp=d[i];
			tmp=tmp.left(tmp.length()-6);
			scheme_Listbox->insertItem(tmp);
			if (tmp==oldscheme) citem=i;
		}
		scheme_Listbox->setAutoUpdate(TRUE);

		scheme_Listbox->setCurrentItem(citem);
		loadScheme(path_scheme+"/"+scheme_Listbox->text(0)+".kcsrc");
		preview->drawSampleWidgets();


		connect( scheme_Listbox, SIGNAL(highlighted(int)),SLOT(selectScheme(int)));

		resize(450,430);
		setMinimumSize(size());
		oldscheme=scheme_Listbox->text(scheme_Listbox->currentItem());
	}
}

void KThemeColorConfig::resizeEvent(QResizeEvent *){
	preview->setGeometry(20,20,width()-40,200);
	preview->drawSampleWidgets();
	scheme_Listbox->setGeometry(20,190,width()-40,height()-210);
}

void KThemeColorConfig::selectScheme(int index){
		QApplication::setOverrideCursor( waitCursor );
		QString tmp=scheme_Listbox->text(index);
		loadScheme(path_scheme+"/"+tmp+".kcsrc");
		preview->drawSampleWidgets();
		QApplication::restoreOverrideCursor();
}

void KThemeColorConfig::loadSettings(){
	KConfigBase *config;
	config=	KApplication::getKApplication()->getConfig();
	config->setGroup("General");
	oldscheme=config->readEntry("LastColorScheme");	
}

void KThemeColorConfig::loadScheme(QString name){

	KConfigBase *config;
	
	QString tmp=path_scheme+"/"+scheme_Listbox->text(0)+".kcsrc";

	if (name==tmp){
		config=kapp->getConfig();		
	}else{
		config=new KSimpleConfig(name);
	}

	if (name==tmp)
		config->setGroup( "General" );
	else
		config->setGroup( "Color Scheme" );

	preview->txt		=config->readColorEntry( "foreground", &black );
	preview->back		=config->readColorEntry( "background", &lightGray );
	preview->select		=config->readColorEntry( "selectBackground", &darkBlue);
	preview->selectTxt	=config->readColorEntry( "selectForeground", &white );
	preview->window		=config->readColorEntry( "windowBackground", &white );
	preview->windowTxt 	=config->readColorEntry( "windowForeground", &black );
	
	if (name==tmp) config->setGroup( "WM" );
	
	preview->iaTitle	=config->readColorEntry( "inactiveBackground", &darkGray);
	preview->iaTxt		=config->readColorEntry( "inactiveForeground", &lightGray );
	preview->iaBlend	=config->readColorEntry( "inactiveBlend", &lightGray );
	preview->aTitle		=config->readColorEntry( "activeBackground", &darkBlue );
	preview->aTxt		=config->readColorEntry( "activeForeground", &white );
	preview->aBlend		=config->readColorEntry( "activeBlend", &black );

	if (name==tmp) config->setGroup( "KDE" );

	preview->contrast	=config->readNumEntry( "contrast", 7 );

}

void KThemeColorConfig::writeSettings(){
	KConfigBase *config;
	config=kapp->getConfig();

	config->setGroup( "General" );
	config->writeEntry("background", preview->back, true, true);
	config->writeEntry("selectBackground", preview->select, true, true);
	config->writeEntry("foreground", preview->txt, true, true);
	config->writeEntry("windowForeground", preview->windowTxt, true, true);
	config->writeEntry("windowBackground", preview->window, true, true);
	config->writeEntry("selectForeground", preview->selectTxt, true, true);
	config->setGroup( "WM" );
	config->writeEntry("activeForeground", preview->aTxt, true, true);
	config->writeEntry("inactiveBackground", preview->iaTitle, true, true);
	config->writeEntry("inactiveBlend", preview->iaBlend, true, true);
	config->writeEntry("activeBackground", preview->aTitle, true, true);
	config->writeEntry("activeBlend", preview->aBlend, true, true);
	config->writeEntry("inactiveForeground", preview->iaTxt, true, true);
	config->setGroup( "KDE" );
	config->writeEntry("contrast", preview->contrast, true, true);
	config->sync();

	config=	KApplication::getKApplication()->getConfig();
	config->setGroup("General");
	config->writeEntry("LastColorScheme",oldscheme);	
	config->sync();

}



void KThemeColorConfig::applySettings(){
	QString tmp=scheme_Listbox->text(scheme_Listbox->currentItem());
	if (oldscheme!=tmp){
		oldscheme=tmp;
		writeSettings();
		apply();
	}
}

static int _getprop(Window w, Atom a, Atom type, long len, unsigned char **p){
  Atom real_type;
  int format;
  unsigned long n, extra;
  int status;
  
  status = XGetWindowProperty(qt_xdisplay(), w, a, 0L, len, False, type, &real_type, &format, &n, &extra, p);
  if (status != Success || *p == 0)
    return -1;
  if (n == 0)
    XFree((void*) *p);
  return n;
}

static bool getSimpleProperty(Window w, Atom a, long &result){
  long *p = 0;
  
  if (_getprop(w, a, a, 1L, (unsigned char**)&p) <= 0){
    return FALSE;
  }
  
  result = p[0];
  XFree((char *) p);
  return TRUE;
}

int dropError(Display *, XErrorEvent *)
{
	return 0;
}

void KThemeColorConfig::apply(){
	XEvent ev;
	unsigned int i, nrootwins;
	Window dw1, dw2, *rootwins;
	int (*defaultHandler)(Display *, XErrorEvent *);
	defaultHandler=XSetErrorHandler(dropError);
	XQueryTree(kde_display, root, &dw1, &dw2, &rootwins, &nrootwins);
	Atom a = XInternAtom(qt_xdisplay(), "KDE_DESKTOP_WINDOW", False);
	for (i = 0; i < nrootwins; i++) {
	  long result = 0;
	  getSimpleProperty(rootwins[i],a, result);
	  if (result){
	    ev.xclient.type = ClientMessage;
	    ev.xclient.display = kde_display;
	    ev.xclient.window = rootwins[i];
	    ev.xclient.message_type = KDEChangePalette;
	    ev.xclient.format = 32;
	    
	    XSendEvent(kde_display, rootwins[i] , False, 0L, &ev);
	  }
	}
	XFlush(kde_display);
	XSetErrorHandler(defaultHandler);
	
	XFree((void *) rootwins);
}

