//#include <tqdir.h>
#include "baghira.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <tqapplication.h>
#include <tqbrush.h>
#include <tqcolor.h>
#include <tqcombobox.h>
#include <tqcursor.h>
#include <tqdialog.h>
#include <tqframe.h>
#include <tqfile.h>
#include <tqheader.h>
#include <tqgroupbox.h>
//#include <tqiconview.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqlistbox.h>
#include <tdelistview.h>
#include <tdemenubar.h>
#include <tqpalette.h>
#include <tqpainter.h>
#include <tqpopupmenu.h>
#include <tqpushbutton.h>
#include <tqscrollbar.h>
#include <tqscrollview.h>
#include <tqsizepolicy.h>
#include <tqslider.h>
#include <tqtabbar.h>
#include <tqtoolbar.h>
#include <tqtoolbutton.h>
#include <tdeversion.h>
#include <kpixmapeffect.h>
#include <tdeglobalsettings.h>
#include <twin.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>

#include <fixx11h.h>
#define OPAQUE	0xffffffff
#define OPACITY	"_KDE_WM_WINDOW_OPACITY"
#define _FORCE_SCROLLBARS_ 0

#ifndef CLAMP
#define CLAMP(x,l,u) x < l ? l :\
x > u ? u :\
x
#endif


void LiquidStyle::polish( TQPalette &pal )
{
   if ( inExitPolish )
      return ;
   // clear out all old colorized pixmaps
   int i;
   for ( i = 0; i < BITMAP_ITEMS; ++i )
   {
      if ( pixmaps[ i ] )
      {
         delete pixmaps[ i ];
         pixmaps[ i ] = NULL;
      }
   }
   // clear out all dicts
   btnDict.clear();
   btnShadowedDict.clear();
   // reset brushes
   pagerHoverBrush = TQBrush();
   pagerBrush = TQBrush();

   bool newPalette = false;
   struct stat buffer;
   if ( stat( TQFile::encodeName( TQDir::homeDirPath() + "/.qt/qtrc" ), &buffer ) == 0 )
   {
      unsigned int lastModTime = ( unsigned int ) buffer.st_mtime;
      if ( lastModTime > qtrcModificationTime )
      {
         qtrcModificationTime = lastModTime;
         newPalette = true;
      }
   }
   else if ( !initialPaletteLoaded )  // Hack, should always have qtrc in KDE
      newPalette = true;
   initialPaletteLoaded = true;

   if ( !newPalette )
   {
      pal = polishedPalette;
      return ;
   }

   originalBgColor = pal.color(TQPalette::Active, TQColorGroup::Background);
   if (optionHandler->style() == Brushed)
      pal.setColor(TQColorGroup::Background, brushedMetalColor(optionHandler->BrushTint()));
   if (isOOO)
      pal.setColor( TQColorGroup::Button, pal.active().background() );
   else if (optionHandler->custCols[0] != -1)
   {
      pal.setColor(TQColorGroup::Background, TQColor(optionHandler->custCols[0]));
      pal.setColor(TQColorGroup::Button, TQColor(optionHandler->custCols[1]));
      pal.setColor(TQColorGroup::Base, TQColor(optionHandler->custCols[2]));
      pal.setColor(TQPalette::Active, TQColorGroup::Text, TQColor(optionHandler->custCols[3]));
      pal.setColor(TQPalette::Active, TQColorGroup::Foreground, TQColor(optionHandler->custCols[3]));
      pal.setColor(TQColorGroup::Highlight, TQColor(optionHandler->custCols[4]));
      pal.setColor(TQPalette::Active, TQColorGroup::HighlightedText, TQColor(optionHandler->custCols[5]));
      pal.setColor(TQPalette::Active, TQColorGroup::ButtonText, TQColor(optionHandler->custCols[6]));
      pal.setColor(TQColorGroup::Mid, TQColor((tqRed(optionHandler->custCols[2])+tqRed(optionHandler->custCols[3]))/2,(tqGreen(optionHandler->custCols[2])+tqGreen(optionHandler->custCols[3]))/2,(tqBlue(optionHandler->custCols[2])+tqBlue(optionHandler->custCols[3]))/2));

      pal.setColor(TQPalette::Inactive, TQColorGroup::Text, TQColor(optionHandler->custCols[3]));
      pal.setColor(TQPalette::Inactive, TQColorGroup::HighlightedText, TQColor(optionHandler->custCols[5]));
      pal.setColor(TQPalette::Inactive, TQColorGroup::ButtonText, TQColor(optionHandler->custCols[6]));
   }
   else
      pal.setColor( TQColorGroup::Button, optionHandler->CustomButtonColor() );
#if 0
   if ( isKicker )
   {
      origPanelBrush = pal.brush( TQPalette::Active, TQColorGroup::Background );
      origPanelPalette = pal;
      TQColor c( pal.active().background() );

      if ( optionHandler->usePanelCustomColor() && optionHandler->panelCustomColor().isValid() )
         c = optionHandler->panelCustomColor();

      kickerColor = c;

      pal.setColor( TQColorGroup::Mid, optionHandler->CustomButtonColor().dark( 110 ) );
      pal.setColor( TQColorGroup::Dark, optionHandler->CustomButtonColor().dark( 130 ) );
      pal.setColor( TQColorGroup::Midlight, optionHandler->CustomButtonColor().light( 110 ) );
      pal.setColor( TQColorGroup::Light, optionHandler->CustomButtonColor().light( 115 ) );
      pal.setColor( TQColorGroup::Button, optionHandler->CustomButtonColor());

      if (optionHandler->style() == Brushed)
      {
         TQBrush brush( c, gradBrush );
         pal.setBrush( TQColorGroup::Background, brush );
      }
      else if ( optionHandler->usePanelStipple() )
      {
         TQPixmap stipple( 64, 64 );
         stipple.fill( c.rgb() );
         TQPainter p( &stipple );
         p.setPen( c.dark( 100 + (int)(optionHandler->stippleContrast()/4) ) );
         for ( int i = 1; i < 64; i += 4 )
         {
            p.drawLine( 0, i, 63, i );
            p.drawLine( 0, i+2, 63, i+2 );
         }
         p.setPen( c.dark( 100 + optionHandler->stippleContrast()) );
         for ( int i = 2; i < 63; i += 4 )
            p.drawLine( 0, i, 63, i );
         p.end();
         TQBrush brush( c, stipple );
         pal.setBrush( TQColorGroup::Background, brush );
      }
      else
         pal.setBrush( TQColorGroup::Background, c );
   }
#endif
   /*else*/ if (optionHandler->style() == Brushed)
   {
      TQColor c( pal.active().background() );
      TQBrush brush( c, gradBrush );
      pal.setBrush( TQColorGroup::Background, brush );
   }
   else if ( !isPlain() )
   {
      TQColor c( pal.active().background() );
      TQPixmap stipple( 64, 64 );
      stipple.fill( c.rgb() );
      TQPainter p;
      p.begin( &stipple );
      p.setPen( c.dark( 100 + (int)(optionHandler->stippleContrast()/2) ) );
      for ( i = 1; i < 64; i += 4 )
      {
         p.drawLine( 0, i, 63, i );
         p.drawLine( 0, i+2, 63, i+2 );
      }
      p.setPen( c.dark( 100 + optionHandler->stippleContrast() ) );
      for ( i = 2; i < 63; i += 4 )
         p.drawLine( 0, i, 63, i );
      p.end();
      TQBrush brush( c, stipple );
      pal.setBrush( TQColorGroup::Background, brush );
   }

   if (optionHandler->bevelHighlights())
   {
      TQColor c(pal.active().highlight());
      TQColor c2(c.light(140));
      TQPixmap pix2 = TQPixmap(48,48);
      TQPainter coolPainter(&pix2);
      KPixmap pix = TQPixmap(48,24);
      KPixmapEffect::gradient(pix,c,c2,KPixmapEffect::VerticalGradient,0);
      coolPainter.drawPixmap(0,0,pix);
      KPixmapEffect::gradient(pix,c2,c,KPixmapEffect::VerticalGradient,0);
      coolPainter.drawPixmap(0,24,pix);
      TQBrush brush(c, pix2);
      pal.setBrush(TQColorGroup::Highlight, brush);
   }
   polishedPalette = pal;
   optionHandler->reset();
}

void LiquidStyle::applicationUnPolish( const TQStyleControlElementData &ceData, ControlElementFlags elementFlags, void *ptr )
{
	if (ceData.widgetObjectTypes.contains(TQAPPLICATION_OBJECT_NAME_STRING)) {
		TQApplication *app = reinterpret_cast<TQApplication*>(ptr);
		popupBack.resize(0,0);
		TQPalette pal( app->palette() );
		inExitPolish = true;

		if ( !isPlain() ) {
			// reset any stipples
			if ( pal.brush( TQPalette::Active, TQColorGroup::Background ).pixmap() )
				pal.setBrush( TQColorGroup::Background, pal.active().background() );
			if ( pal.brush( TQPalette::Active, TQColorGroup::Button ).pixmap() )
				pal.setBrush( TQColorGroup::Button, pal.active().button() );
//			app->blockSignals( TRUE );
			app->setPalette( pal );
//			app->blockSignals( FALSE );
		}

	inExitPolish = false;
	}
}

Atom baghira_deco_design = XInternAtom(tqt_xdisplay(), "BAGHIRA_DECO_DESIGN", False);

void LiquidStyle::polish( const TQStyleControlElementData &ceData, ControlElementFlags elementFlags, void *ptr )
{
//     bool testWidget = w->inherits("Splash");
//     int testInt = 0;
//     if (w->sizePolicy().horData() == TQSizePolicy::Minimum || w->sizePolicy().horData() == TQSizePolicy::MinimumExpanding)
// 	tqWarning("%s, \"%s\"",w->className(), w->name());
//	installObjectEventHandler(ceData, elementFlags, ptr, this);
  if (ceData.widgetObjectTypes.contains(TQWIDGET_OBJECT_NAME_STRING)) {
    TQWidget *w = reinterpret_cast<TQWidget*>(ptr);

    bool tmpBool = false;
    bool isViewport = qstrcmp( w->name(), "qt_viewport" ) == 0 ||
                      qstrcmp( w->name(), "qt_clipped_viewport" ) == 0;
    bool isViewportChild = w->parent() &&
                     ( ( qstrcmp( w->parent() ->name(), "qt_viewport" ) == 0 ) ||
                     ( qstrcmp( w->parent() ->name(), "qt_clipped_viewport" ) == 0 ) );

    if (w->isTopLevel())
    {
        if ( ::tqt_cast<TQPopupMenu*>(w)) // popup menu designs
        {
            switch (optionHandler->MenuBackground())
            {
            case Plain:
               w->setBackgroundMode( TQWidget::PaletteBackground );
               if (optionHandler->UseCustomMenuColor())
                  w->setPaletteBackgroundColor(optionHandler->Color());
               else if (optionHandler->MenuColorButton())
                  w->setPaletteBackgroundColor(optionHandler->buttonColor());
               else
                  w->setPaletteBackgroundColor(optionHandler->bgColor());
                break;
            case Stipples:
            {
                TQColor c;
                if (optionHandler->UseCustomMenuColor())
                    c = TQColor( optionHandler->Color() );
                else if (optionHandler->MenuColorButton())
                    c = TQColor( optionHandler->buttonColor() );
                else
                   c = TQColor( originalBgColor );
                if (popupBack.isNull())
                {
                    popupBack = TQPixmap(64,64);
                    TQPixmap *stipple = &popupBack;
                    stipple->fill( c.rgb() );
                    TQPainter p;
                    p.begin( stipple );
                    if (optionHandler->UseCustomMenuColor())
                    {
                        TQColor c2 = TQColor( optionHandler->Color2() );
                        p.setPen(TQColor((3*c.red()+c2.red())/4,
                                        (3*c.green()+c2.green())/4,
                                        (3*c.blue()+c2.blue())/4));
                        for ( int i = 1; i < 64; i += 4 )
                        {
                            p.drawLine( 0, i, 63, i );
                            p.drawLine( 0, i+2, 63, i+2 );
                        }
                        p.setPen(c2);
                        for ( int i = 2; i < 63; i += 4 )
                        {
                            p.drawLine( 0, i, 63, i );
                        }
                    }
                    else
                    {
                        p.setPen( c.dark( 100 + (int)(optionHandler->stippleContrast()/4) ) );
                        for ( int i = 1; i < 64; i += 4 )
                        {
                            p.drawLine( 0, i, 63, i );
                            p.drawLine( 0, i+2, 63, i+2 );
                        }
                        p.setPen( c.dark( 100 + optionHandler->stippleContrast() ) );
                        for ( int i = 2; i < 63; i += 4 )
                        {
                            p.drawLine( 0, i, 63, i );
                        }
                    }
                    p.end();
                }
                w->setBackgroundMode( TQWidget::NoBackground );
                break;
            }
            case Gradient:
            {
               w->setBackgroundMode( TQWidget::PaletteBackground );
               KPixmap tmpPix = TQPixmap(w->width(), 32);
               w->setPaletteBackgroundPixmap(KPixmapEffect::unbalancedGradient(tmpPix, optionHandler->Color(), optionHandler->Color2(),KPixmapEffect::HorizontalGradient, 100, 100, 16));
               installObjectEventHandler(ceData, elementFlags, ptr, this);
               break;
            }
            default:
               w->setBackgroundMode( TQWidget::PaletteBackground );
               break;
            }
            //set popup menu opacity for them as they bypass the windowmanager
            unsigned long opacity = optionHandler->MenuOpacity()/100.0*OPAQUE;
            XChangeProperty(tqt_xdisplay(), w->winId(), XInternAtom(tqt_xdisplay(), OPACITY, False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &opacity, 1L);
            goto kstpolish;
        }
        else
        {
            if (optionHandler->wmDesign < 5) // set deco design X Property
            {
               unsigned char *data = 0;
               Atom actual;
               int format, result;
               unsigned long n, left;
               result = XGetWindowProperty(tqt_xdisplay(), w->winId(), baghira_deco_design, 0L, 1L, False, XA_CARDINAL, &actual, &format, &n, &left, &data);
               if (result != Success || data == NULL) // not found set design
               {
            int tmp = optionHandler->wmDesign != Tiger ? optionHandler->wmDesign : Panther;
                  XChangeProperty(tqt_xdisplay(), w->winId(), baghira_deco_design, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &(tmp), 1L);
               }
            }
           if ((optionHandler->style() == Brushed) && !( ::tqt_cast<TQPopupMenu*>(w) || ::tqt_cast<TQMenuBar*>(w) || w->isDesktop() || ::tqt_cast<TQListBox*>(w) || w->inherits("TQTipLabel") || w->inherits("AlphaWidget") || w->inherits("ScrollWidget") || w->inherits("PlayerWidget")))
                // install resize event filter, allowing us to update the b/m gradient on horizontal resizes. some widgets must be excluded though
            {
                if (!isKicker)
                    w->installEventFilter( bmShower );
                installObjectEventHandler(ceData, elementFlags, ptr, this);
            }
        }
    } // TopLevel Widgets

   if (w->inherits("KURLBar")/*ListBox*/)
   {
      w->setPaletteBackgroundColor(tqApp->palette().color(TQPalette::Active, TQColorGroup::Base));
//	((TQListBox*)w)->viewport()->setPaletteBackgroundColor(tqApp->palette().color(TQPalette::Active, TQColorGroup::Base));
	goto kstpolish;
    }


    if (w->inherits("KColorGrid"))
    {
        // kiconedit doesn't check for the paintevent rect size, but tries to create a (possibly) NULL Pixmap (after palette change event e.g.)
        // so we catch it's paint event and destroy it if the size is NULL
        // remove this after kiconedit corrected its code
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        goto kstpolish;
    }

    if (w->inherits("BGMonitor") || w->inherits("mapWidget") || w->isA("MyButton") || (w->parentWidget() && w->parentWidget()->inherits("Thumbnail")))
        // don't touch these widgets at all - they don't like it
    {
        goto kstpolish;
    }



    if (qstrcmp( w->name(), "tde toolbar widget" ) == 0 )
        installObjectEventHandler(ceData, elementFlags, ptr, this);

    if (::tqt_cast<TQButton*>(w))
    {
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
        if (::tqt_cast<TQPushButton*>(w))
        {
           if (w->inherits("KKeyButton"))
           {
              w->setBackgroundMode( TQWidget::PaletteBackground);
              TQPalette pal( w->palette() );
              pal.setBrush( TQColorGroup::Background, tqApp->palette().active().background() );
              w->setPalette( pal );
           }
           else if (w->inherits("KCalcButton"))
           {
              w->setBackgroundMode( TQWidget::PaletteBackground);
              TQPalette pal( w->palette() );
              pal.setBrush( TQColorGroup::Background, tqApp->palette().brush(TQPalette::Active, TQColorGroup::Background));
              w->setPalette( pal );
           }
            else
            w->setBackgroundMode( TQWidget::NoBackground);

            installObjectEventHandler(ceData, elementFlags, ptr, this);
            goto kstpolish;
        }
        else if (w->inherits( "TQRadioButton" ) || w->inherits( "TQCheckBox" ))
         {
            w->setBackgroundOrigin(TQWidget::WindowOrigin);
            installObjectEventHandler(ceData, elementFlags, ptr, this);
            goto kstpolish;
         }
    }

    if ( ::tqt_cast<TQToolBar*>(w))
    {
        if (optionHandler->useToolButtonFrame() && w->inherits("TDEToolBar"))
            ((TQToolBar*)w)->boxLayout()->setSpacing( 0 );
        ((TQToolBar*)w)->setMargin( 4 );
        w->setBackgroundMode(PaletteBackground);
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
      if (optionHandler->style() > Panther)
      {
         installObjectEventHandler(ceData, elementFlags, ptr, this);
         if (optionHandler->wmDesign == Tiger)
         {
            XChangeProperty(tqt_xdisplay(), w->topLevelWidget()->winId(), baghira_deco_design, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &(optionHandler->wmDesign), 1L);
         }
      }

        goto kstpolish ;
    }
        //if (testWidget) tqWarning("testwidget stage %d",testInt++);

    if (tmpBool = ::tqt_cast<TQToolButton*>(w) ||  w->inherits( "TQToolBarSeparator" ) ||  w->inherits( "TDEToolBarSeparator" ) )
    {
        if (tmpBool && w->parentWidget() && ::tqt_cast<TQToolBar*>(w->parentWidget()) )
        {
            w->setSizePolicy(TQSizePolicy::Fixed, TQSizePolicy::Fixed);
        }
        w->setBackgroundMode( TQWidget::PaletteBackground );
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        goto kstpolish;
    }

    if (::tqt_cast<TQComboBox*>(w))
    {
        w->setBackgroundMode(NoBackground);
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
        goto kstpolish;
    }

    if (w->inherits("TaskBar"))
    {
        w->setBackgroundOrigin(TQWidget::WidgetOrigin);
        goto kstpolish;
    }

    if (w->inherits("TQSpinWidget") || w->inherits("KDockWidgetAbstractHeaderDrag")){
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        goto kstpolish;
    }

    if ( !isPlain () && (w->inherits( "KonqIconViewWidget" ) || w->inherits( "tdehtml")/* || w->inherits( "TQtVisionView")*/))
    {
    // if you want custom backgrounds in konqueror, you have to reset pixmap, since Konq animation can't handle it
    // original liquid did this on tdehtml, too (at speed loss) so we'll see, if we get errors from this...
        TQPalette pal( w->palette() );
        pal.setBrush( TQColorGroup::Background, pal.active().background() );
        w->setPalette( pal );
    }

    if (::tqt_cast<TQSlider*>(w))
    {
        //avoid flicker
        w->setBackgroundMode( TQWidget::NoBackground );
        goto kstpolish;
    }

    if ((::tqt_cast<TQScrollView*>(w) || w->inherits("KateView") || w->inherits("TEWidget") || w->inherits("CHexViewWidget")) && !(w->isA("KOAgenda")))
    {
       if (::tqt_cast<TDEListView*>(w)  && optionHandler->custCols[7] != -1 && ((TDEListView*)w)->alternateBackground() == TDEGlobalSettings::alternateBackgroundColor())
       {
          ((TDEListView*)w)->setAlternateBackground(TQColor(optionHandler->custCols[7]));
       }
#if _FORCE_SCROLLBARS_
        if (::tqt_cast<TQScrollView*>(w) && !w->inherits( "KActiveLabel" ))
        {
            ((TQScrollView*)w)->setVScrollBarMode(TQScrollView::AlwaysOn);
        }
#endif
        if (::tqt_cast<TQListBox*>(w) && w->isTopLevel())
            //set opacity for them as they bypass the windowmanager
        {
            uint opacity = 0.8*OPAQUE;
            XChangeProperty(tqt_xdisplay(), w->winId(), XInternAtom(tqt_xdisplay(), OPACITY, False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &opacity, 1L);
        }
#if 0
        // doesn't work properly - best would be to have the items drawn via style()
        int height = ((TQListBox*)w)->itemHeight();
        if (height >  0)
        {
            TQPalette pal = w->palette();
            TQColor c(pal.active().highlight());
            TQColor c2(c.light(140));
            KPixmap pix = TQPixmap(48,height);
            KPixmapEffect::gradient(pix,c2,c,KPixmapEffect::VerticalGradient,0);
            TQBrush brush(c, pix);
            pal.setBrush(TQColorGroup::Highlight, brush);
            w->setPalette(pal);
        }
#endif
        // listen to enter events - highlightning the scrollbars
        w->setMouseTracking( true );
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        goto kstpolish;
    }

    if (w->inherits("TQStatusBar"))
    {
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
       if ( qstrcmp( w->name(), "KonquerorFrameStatusBar" ) == 0 )
            // konqueror resets the statusbars background to TQt::White as soon as you open a new tab - our eventfilter will block this
        {
            installObjectEventHandler(ceData, elementFlags, ptr, this);
       }
        goto kstpolish;
    }

    if (w->inherits( "TQLineEdit" ) || w->inherits("TQSplitterHandle") || w->isA( "AppletHandleDrag" ) || w->inherits( "KMiniPagerButton" ))
    {
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        goto kstpolish;
    }

    if (w->inherits( "TaskContainer" ))
    {
        installObjectEventHandler(ceData, elementFlags, ptr, this);
        goto kstpolish;
    }

    if (w->inherits( "KickerTip" ))
        // kickers new tooltip uses backgroundColor() instead of paletteBackgroundColor() - causing TQt::black
    {
      w->setPaletteBackgroundColor(tqApp->palette().color(TQPalette::Active, TQColorGroup::Button));
      w->setBackgroundMode( TQWidget::NoBackground );
      goto kstpolish;
    }

    if ( !isPlain() )
    {
        if ( !isViewport && w->parent() && qstrcmp( w->parent() ->name(), "proxyview" ) == 0 )
        {
            w->setBackgroundOrigin( TQWidget::WindowOrigin );
            goto kstpolish ;
        }

        if ( w->inherits( "PanelButtonBase" ) )
            goto kstpolish ;
        if ( !isKicker&& !isViewport && !isViewportChild && !w->testWFlags( WType_Popup ) && !w->inherits( "KDesktop" ) && !w->inherits( "PasswordDlg" ))
        {
            if ( w->backgroundMode() == TQWidget::PaletteBackground || w->backgroundMode() == TQWidget::PaletteButton )
            {
                w->setBackgroundOrigin( TQWidget::WindowOrigin );
            }
        }
    }
    if ( ::tqt_cast<TQPushButton*>(w) || ::tqt_cast<TQComboBox*>(w)) goto kstpolish;
    if ( ::tqt_cast<TQMenuBar*>(w))
    {
//             if (optionHandler->SupportAppleBar() && w->isTopLevel()){
// //                 TQPalette pal(w->palette());
//                 tqWarning("resetting erase pixmap");
//                 TQColor c( w->palette().active().background() );
//                 TQPixmap stipple( 64, 64 );
//                 stipple.fill( c.rgb() );
//                 TQPainter p;
//                 p.begin( &stipple );
//                 p.setPen( c.dark( 100 + (int)(optionHandler->stippleContrast()/2) ) );
//                 for (int i = 1; i < 64; i += 4 ) {
//                     p.drawLine( 0, i, 63, i );
//                     p.drawLine( 0, i+2, 63, i+2 );
//                 }
//                 p.setPen( c.dark( 100 + optionHandler->stippleContrast()) );
//                         for ( int i = 2; i < 63; i += 4 ) {
//                                 p.drawLine( 0, i, 63, i );
//                                 }
//                 p.end();
// //                 TQBrush brush( c, stipple );
// //                 pal.setBrush( TQColorGroup::Background, brush );
// //                 w->setPalette( pal );
//                 w->setErasePixmap(stipple);
//             }
        w->setBackgroundMode( TQWidget::PaletteBackground );
       if (optionHandler->UseCustomMenuColor())
       {
          TQPalette pal( w->palette() );
          pal.setBrush( TQColorGroup::Highlight, optionHandler->menuColorHigh() );
          pal.setBrush( TQColorGroup::HighlightedText, optionHandler->textColorHigh() );
          w->setPalette( pal );
       }
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
        installObjectEventHandler(ceData, elementFlags, ptr, this);
#if 0
        if (!::tqt_cast<KMenuBar*>(w))
        {
           bool bold = w->font().bold();
           bool italic = w->font().italic();
           bool underline = w->font().underline();
           bool overline = w->font().overline();
           w->setFont(TDEGlobalSettings::menuFont());
           if (bold)
              (const_cast<TQFont*>(&w->font()))->setBold(true);
           if (italic)
              (const_cast<TQFont*>(&w->font()))->setItalic(true);
           if (underline)
              (const_cast<TQFont*>(&w->font()))->setUnderline(true);
           if (overline)
              (const_cast<TQFont*>(&w->font()))->setOverline(true);
        }
#endif
        goto kstpolish ;
    }

    if (::tqt_cast<TQFrame*>(w))
    {
        w->setBackgroundOrigin(TQWidget::WindowOrigin);
        if ( ::tqt_cast<TQLabel*>(w))
        {
            if (w->parentWidget() && w->parentWidget()->inherits("Kontact::Splash"))
                goto kstpolish;
            else if ( !isPlain() && !(w->inherits( "TQTipLabel" ) || w->inherits( "KSystemTray" )))
            {
                w->setBackgroundMode( TQWidget::PaletteBackground );
            }
            else if ( w->inherits( "TQTipLabel" ) )
            {
                w->setPalette( tooltipPalette );
                w->setBackgroundOrigin(TQWidget::WidgetOrigin);
                installObjectEventHandler(ceData, elementFlags, ptr, this);
            }
        }
        if (qstrcmp( w->name(), "backdrop" ) == 0) //kscd
        {
            ((TQFrame *)w)->setFrameShape(TQFrame::LineEditPanel);
            ((TQFrame *)w)->setFrameShadow(TQFrame::Sunken);
            goto kstpolish;
        }
        if (w->inherits( "KWinInternal::TabBox" ))
        {
            uint opacity = 0.8*OPAQUE;
            XChangeProperty(tqt_xdisplay(), w->winId(), XInternAtom(tqt_xdisplay(), OPACITY, False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &opacity, 1L);
            goto kstpolish;
        }
        else if (w->inherits( "KAnimWidget" ))
        {
            ((TQFrame *)w)->setFrameShape(TQFrame::NoFrame);
            installObjectEventHandler(ceData, elementFlags, ptr, this); // the widget resets it's frameshape on mouseevents - looks crap!
            goto kstpolish ;
        }
                else if (((TQFrame *)w)->frameShape() >= TQFrame::Box && ((TQFrame *)w)->frameShape() <= TQFrame::WinPanel){
			((TQFrame *)w)->setFrameShape(TQFrame::StyledPanel);
                        goto kstpolish ;
		}
	}
        //if (testWidget) tqWarning("testwidget stage %d",testInt++);


	 if ( w->parentWidget() && ( ( ::tqt_cast<TQListBox*>(w) && ::tqt_cast<TQPushButton*>(w->parentWidget())) || w->inherits( "TDECompletionBox" ) ) ) {
		TQListBox* listbox = (TQListBox*) w;
		listbox->setBackgroundMode( NoBackground );
		installObjectEventHandler(ceData, elementFlags, ptr, this);
		goto kstpolish;
	}
        //if (testWidget) tqWarning("testwidget stage %d",testInt++);


	if (::tqt_cast<TQHeader*>(w)){
//                 if (::tqt_cast<TQListView*>(w->parentWidget()))
//                     headerSortID = ((TQListView*)w->parentWidget())->sortColumn();
//    	if (w->parentWidget()) tqWarning(w->parentWidget()->className());
		w->setBackgroundMode( NoBackground );
		installObjectEventHandler(ceData, elementFlags, ptr, this);
		goto kstpolish;
	}
        //if (testWidget) tqWarning("testwidget stage %d",testInt++);


	if (::tqt_cast<TQTabBar*>(w)){
//                tqWarning("installing tab event");
		w->setMouseTracking( true );
		installObjectEventHandler(ceData, elementFlags, ptr, this);
                w->setBackgroundOrigin(TQWidget::WindowOrigin);
		goto kstpolish;
	}

   if (::tqt_cast<TQGroupBox*>(w) && ((TQGroupBox*)w)->frameShape() == TQFrame::GroupBoxPanel && !((TQGroupBox*)w)->isFlat())
   {
      if ( optionHandler->drawGroupBoxShadow() )
      {
            w->setPaletteBackgroundPixmap ( *groupShadow );
         if (((TQGroupBox*)w)->isCheckable())
         {
            TQWidget *cb = (TQWidget*)w->child("qt_groupbox_checkbox",0,false);
            cb->setPalette(w->parentWidget() ? w->parentWidget()->palette() : tqApp->palette());
            TQFont font( cb->font() );
            font.setBold( true );
            cb->setFont( font );
         }
      }
      w->setBackgroundOrigin(TQWidget::WindowOrigin);
      installObjectEventHandler(ceData, elementFlags, ptr, this);
   }
   //if (testWidget) tqWarning("testwidget stage %d",testInt++);


	if (w->inherits("TQProgressBar"))
	{
		w->setBackgroundMode( NoBackground );
		installObjectEventHandler(ceData, elementFlags, ptr, this);
                connect(w, SIGNAL(destroyed(TQObject*)), this, SLOT(progressBarDestroyed(TQObject*)));
		goto kstpolish;
	}

	if ( w->inherits( "TQDockWindow" ) ) {
		w->setBackgroundMode( TQWidget::PaletteBackground );
		w->setBackgroundOrigin(TQWidget::WindowOrigin);
		installObjectEventHandler(ceData, elementFlags, ptr, this);
		goto kstpolish ;
	}

	if ( ::tqt_cast<TQScrollBar*>(w)) {
		TQCursor tmpCursor(TQt::PointingHandCursor);
                w->setCursor(tmpCursor);
		installObjectEventHandler(ceData, elementFlags, ptr, this);
		w->setBackgroundMode( TQWidget::NoBackground );
		goto kstpolish ;
	}
        if ( w->inherits( "KdetvView")) {
            w->setBackgroundMode( TQWidget::NoBackground );
        }
  }
   //if (testWidget) tqWarning("testwidget stage %d",testInt++);
   kstpolish:	TDEStyle::polish( ceData, elementFlags, ptr ); // nothing of all above? do default kde stuff
}



void LiquidStyle::unPolish( const TQStyleControlElementData &ceData, ControlElementFlags elementFlags, void *ptr ) {

    if (ceData.widgetObjectTypes.contains(TQWIDGET_OBJECT_NAME_STRING)) {
        TQWidget *w = reinterpret_cast<TQWidget*>(ptr);

	bool isViewport;
	bool isViewportChild;

        // general - better than querying for each and ever widget if it got one...
        w->removeEventFilter( this );


	if (w->inherits("KColorGrid")){
            goto kstunpolish;
        }

        if ( w->inherits("TQToolBar") || qstrcmp( w->name(), "tde toolbar widget" ) == 0 ) {
		w->setBackgroundOrigin( TQWidget::WidgetOrigin );
// 		w->unsetPalette();
		goto kstunpolish;
		}
	if ( w->inherits( "TQPopupMenu" ) ) {
		w->unsetPalette();
		w->setBackgroundMode( TQWidget::PaletteButton );
		w->removeEventFilter( this );
                XDeleteProperty (tqt_xdisplay(), w->winId(), XInternAtom(tqt_xdisplay(), OPACITY, False));
		goto kstunpolish;
		}
        if (::tqt_cast<TQListBox*>(w) && w->isTopLevel()){
            XDeleteProperty (tqt_xdisplay(), w->winId(), XInternAtom(tqt_xdisplay(), OPACITY, False));
            goto kstunpolish;
        }
	if ( !isPlain () && w->inherits( "KonqIconViewWidget" ) ||
	        w->inherits( "TDEHTMLView" ) ) {
		w->unsetPalette();
		goto kstunpolish;
		}
	if (w->inherits("KateView") || w->inherits("TEWidget") || w->inherits("CHexViewWidget")){
//		w->setMouseTracking( false );
		goto kstunpolish;
	}

	if (w->isA( "TQViewportWidget" ) || w->inherits( "TQClipperWidget" ) )
		goto kstunpolish;

	if ( !isPlain() ) {
		if ( w->inherits( "KActiveLabel" ) || w->inherits( "TQTipLabel" ) ) {
			w->unsetPalette();
			goto kstunpolish;
			}
		/*
		else if(w->inherits("KdmClock")){
		    ; // Check this!
		    return;
			}*/
		}
	else if ( w->inherits( "TQMenuBar" ) ) {
		w->setBackgroundMode( TQWidget::PaletteButton );
		if ( !isPlain() )
			w->setBackgroundOrigin( TQWidget::WidgetOrigin );
		goto kstunpolish;
		}else if ( w->inherits( "TQDockWindow" ) ) {
		w->setBackgroundMode( TQWidget::PaletteButton );
		if ( !isPlain() )
			w->setBackgroundOrigin( TQWidget::WidgetOrigin );
		goto kstunpolish;
		} else if ( w->inherits( "TQComboBox" ) || w->inherits( "TQPushButton" ) ) {
                    if (w->inherits( "TQPushButton" ))
                    {
                        ButtonFadeInfo *bfi_ = bfi[w->winId()];
                        if (bfi_){
                        if (bfi_->timerId != 0)
                            w->killTimer(bfi_->timerId);
                        bfi.setAutoDelete(TRUE);
                        bfi.remove(w->winId());
                        }
                    }
		  w->setBackgroundMode( TQWidget::PaletteButton );
		} else if ( w->inherits( "TQScrollBar" ) ) {
//		if (!w->isEnabled()) w->setEnabled(true);
		w->setBackgroundMode( TQWidget::PaletteBackground );
		goto kstunpolish;
		} else if ( w->inherits( "TQHeader" ) ) {
		w->setMouseTracking( false );
		}

	if ( w->inherits( "TQToolButton" ) ) {
// 		w->unsetPalette();
		w->setBackgroundMode( TQWidget::PaletteButton );
		if ( !isPlain() )
			w->setBackgroundOrigin( TQWidget::WidgetOrigin );
		goto kstunpolish;
		}

	isViewport = qstrcmp( w->name(), "qt_viewport" ) == 0 ||
	                  qstrcmp( w->name(), "qt_clipped_viewport" ) == 0;
	isViewportChild = w->parent() &&
	                       ( ( qstrcmp( w->parent() ->name(), "qt_viewport" ) == 0 ) ||
	                         ( qstrcmp( w->parent() ->name(), "qt_clipped_viewport" ) == 0 ) );

	if ( isViewportChild ) {
		if ( w->inherits( "TQRadioButton" ) || w->inherits( "TQComboBox" ) || w->inherits( "TQPushButton" ) ) {
			if ( isHTMLWidget( w ) ) {
				w->setBackgroundMode( TQWidget::PaletteBackground );
				goto kstunpolish;
				}
			}
		}

	if ( !isPlain() ) {
		if ( !isViewport && w->parent() && qstrcmp( w->parent() ->name(), "proxyview" ) == 0 ) {
			w->setBackgroundOrigin( TQWidget::WidgetOrigin );
			goto kstunpolish;
			}
		if ( w->ownPalette() && !w->inherits( "TQButton" ) && !w->inherits( "TQComboBox" ) )
			goto kstunpolish;
		if ( w->inherits( "PanelButtonBase" ) )
			goto kstunpolish;

		if ( !isViewport && !isViewportChild && !w->testWFlags( WType_Popup ) &&
		        !w->inherits( "KDesktop" ) && !w->inherits( "PasswordDlg" ) ) {

			if ( w->backgroundOrigin() == TQWidget::WindowOrigin )
				w->setBackgroundOrigin( TQWidget::WidgetOrigin );
			goto kstunpolish;
			}
		}
    }
kstunpolish:	TDEStyle::unPolish( ceData, elementFlags, ptr );
}
