/* Polyester widget style for KDE 4
   Copyright (C) 2006 Marco Martin <notmart@gmail.com>

   based on Plastik widget style for KDE 3
   Copyright (C) 2003 Sandro Giessl <ceebx@users.sourceforge.net>

   based on the KDE style "dotNET":

   Copyright (C) 2001-2002, Chris Lee <clee@kde.org>
                            Carsten Pfeiffer <pfeiffer@kde.org>
                            Karol Szwed <gallium@kde.org>
   Drawing routines completely reimplemented from KDE3 HighColor, which was
   originally based on some stuff from the KDE2 HighColor.

   based on drawing routines of the style "Keramik":

   Copyright (c) 2002 Malte Starostik <malte@kde.org>
             (c) 2002,2003 Maksim Orlovich <mo002j@mail.rochester.edu>
   based on the KDE3 HighColor Style
   Copyright (C) 2001-2002 Karol Szwed      <gallium@kde.org>
             (C) 2001-2002 Fredrik Höglund  <fredrik@kde.org>
   Drawing routines adapted from the KDE2 HCStyle,
   Copyright (C) 2000 Daniel M. Duley       <mosfet@kde.org>
             (C) 2000 Dirk Mueller          <mueller@kde.org>
             (C) 2001 Martijn Klingens      <klingens@kde.org>
   Progressbar code based on KStyle,
   Copyright (C) 2001-2002 Karol Szwed <gallium@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
 */

#include "polyester.h"
#include <stdio.h>


void PolyesterStyle::adjustScrollbarBorders(const QRect &borderRect,
                                            QRect *surfRect,
                                            const QWidget *widget,
                                            uint *contourFlags,
                                            uint *surfaceFlags,
                                            bool *hasFocus) const
{

  if( !widget )
    return;

  QWidget *parent = widget->parentWidget();
  if( !parent )
    return;

  QWidget *grandParent = parent->parentWidget();
  if( !grandParent )
    return;

  //Up
    if( parent->pos().y()+borderRect.y() == 1 )
    {
      *contourFlags ^= Draw_Top;
      *surfaceFlags ^= Draw_Top;
      surfRect->adjust(0,-1,0,0);
    }
  //Down
    if( parent->pos().y()+borderRect.y()+borderRect.height()+1 == grandParent->height() )
    {
      *contourFlags ^= Draw_Bottom;
      *surfaceFlags ^= Draw_Bottom;
      surfRect->adjust(0,0,0,1);
    }

  //Left
    if( parent->pos().x()+borderRect.x() == 1)
    {
      *contourFlags ^= Draw_Left;
      *surfaceFlags ^= Draw_Left;
      surfRect->adjust(-1,0,0,0);
    }

  //Right
    if( parent->pos().x()+borderRect.x()+borderRect.width()+1 == grandParent->width() )
    {
      *contourFlags ^= Draw_Right;
      *surfaceFlags ^= Draw_Right;
      surfRect->adjust(0,0,1,0);
    }

    //grandparent has focus?
    *hasFocus = grandParent->hasFocus();

}


void PolyesterStyle::drawControl( ControlElement element,
                                  const QStyleOption *opt,
                                  QPainter *p,
                                  const QWidget *widget ) const
{
    bool reverseLayout = opt->direction == Qt::RightToLeft;
    const QPalette &pal = opt->palette;
    QRect r = opt->rect;
    const State &flags = opt->state;
    const bool enabled = (flags & State_Enabled);

    bool down   = flags & State_Sunken;
    bool on     = flags & State_On;
    bool sunken = flags & State_Sunken;
    bool horiz  = flags & State_Horizontal; 

    int x = r.x();
    int y = r.y();
    int w = r.width();
    int h = r.height();

    switch (element)
    {
    // PROGRESSBAR
    // -----------
        case CE_ProgressBarGroove:
        {
          break;
          if( _sunkenShadows )
            break;

          const QColor content = enabled?pal.color(QPalette::Base):pal.color(QPalette::Background);
          renderContour(p, r, pal.color(QPalette::Background), getColor(pal, ButtonContour, enabled) );

          p->setPen(content.dark(105) );
          p->drawLine(r.left()+2, r.top()+1, r.right()-2, r.top()+1 );
          p->drawLine(r.left()+1, r.top()+2, r.left()+1, r.bottom()-2);
          p->setPen(content.light(105) );
          p->drawLine(r.left()+2, r.bottom()-1, r.right()-2, r.bottom()-1 );
          p->drawLine(r.right()-1, r.top()+2, r.right()-1, r.bottom()-2);
          break;
        }

        case CE_ProgressBarContents:
        {
          const QStyleOptionProgressBar *pbarOpt;
          pbarOpt = qstyleoption_cast<const QStyleOptionProgressBar*>(opt);
          if (!pbarOpt) break;

          bool vertical = false;
          bool inverted = false;

          if( const QStyleOptionProgressBarV2 *pbarOpt2 = qstyleoption_cast<const QStyleOptionProgressBarV2*>(opt) )
          {
            vertical = (pbarOpt2->orientation == Qt::Vertical);
            inverted = pbarOpt2->invertedAppearance;
          }

          const QColor bg = enabled?pal.color(QPalette::Base):pal.color(QPalette::Background); // background
          const QColor fg = enabled?pal.color(QPalette::Highlight):pal.color(QPalette::Background).dark(110); // foreground

          if( vertical )
          {
            r = QRect(r.left(), r.top(), r.height(), r.width());
            QTransform m;

             reverseLayout = !inverted;
             m.scale(-1,1);
             m.rotate(90);

            p->setTransform(m);
          }
          else if( inverted ) //it can have reversed appearance, so re-compute reverseLayout
              reverseLayout = !reverseLayout;

            if( pbarOpt->minimum == 0 && pbarOpt->maximum == 0 )
            { // Busy indicator
                static const int barWidth = 10;
                int progress = pbarOpt->progress % (2*(r.width()-barWidth));
                if( progress < 0)
                    progress = 0;
                if( progress > r.width()-barWidth )
                    progress = (r.width()-barWidth)-(progress-(r.width()-barWidth));

                QRect rEmpty = r.adjusted(1,1,-1,-1);
                QBrush baseBrush;
                if(_sunkenShadows)
                  baseBrush = pal.color(QPalette::Base);
                else
                  baseBrush = getShadowBrush(rEmpty, pal.color(QPalette::Base), true);
                p->fillRect(rEmpty, baseBrush );
                if(_sunkenShadows)
                  renderSunkenShadow(p, rEmpty);

                renderContour( p, QRect( r.x()+progress, r.y(), barWidth, r.height() ),
                                bg, fg.dark(160),
                                Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|Round_UpperRight|
                                    Round_BottomRight|Round_UpperLeft|Round_BottomLeft );
                renderSurface(p, QRect( r.x()+progress+1, r.y()+1,
                                    barWidth-2, r.height()-2 ),
                                    bg, fg, pal.color(QPalette::Highlight),
                                    2*(_contrast/3),
                                    Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperRight|Round_BottomRight|
                                        Round_UpperLeft|Round_BottomLeft|Is_Horizontal);
                if( _sunkenShadows )
                  renderContour(p, r, pal.color(QPalette::Background), getColor(pal, ButtonContour, enabled) );
            }
            else
            {
                double percent = (double)pbarOpt->progress / (double)pbarOpt->maximum;

                int w = static_cast<int>(r.width() * percent);
                // renderContour/renderSurface handle small sizes not very well, so set a minimal
                // progressbar width...
                if(w<4) w = 4;
                int w2 = r.width()-(r.width()-w);

                QRect rEmpty;
                if(_sunkenShadows)
                  rEmpty = QRect(reverseLayout?r.left()+1:r.left()+w-2, r.top()+1,
                                     r.width()-w-1, r.height()-2 );
                else
                  rEmpty = QRect(reverseLayout?r.left():r.left()+w-1, r.top(),
                                     r.width()-w+1, r.height() );

                QRect Rcontour(reverseLayout?r.right()-w2+1:r.left(), r.top(), w2, r.height() );
                QRect Rsurface(Rcontour.left()+1, Rcontour.top()+1, w2-2, Rcontour.height()-2);


                QBrush baseBrush;
                if(_sunkenShadows)
                  baseBrush = pal.color(QPalette::Base);
                else
                  baseBrush = getShadowBrush(rEmpty, pal.color(QPalette::Base), true);
                p->fillRect(rEmpty, baseBrush );
                if(_sunkenShadows)
                  renderSunkenShadow(p, r);

                //moved after the surface in order to not get it overwritten
                //by the ugly left sharp borders of the surface
                renderContour(p, Rcontour,
                              bg, fg.dark(160),
                              Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|
                              Round_UpperRight|Round_BottomRight|Round_UpperLeft|Round_BottomLeft);

                QRegion mask(Rsurface);

                mask -= QRegion(Rsurface.left(), Rsurface.top(), 1, 1);
                mask -= QRegion(Rsurface.left(), Rsurface.bottom(), 1, 1);
                mask -= QRegion(Rsurface.right(), Rsurface.top(), 1, 1);
                mask -= QRegion(Rsurface.right(), Rsurface.bottom(), 1, 1);

                p->setClipRegion(mask);
                int counter = 0;
                QPixmap surfaceTile(21, r.height()-2);
                QPainter surfacePainter(&surfaceTile);
                // - 21 pixel -
                //  __________
                // |    `    `| <- 3
                // | 1   | 2  |
                // |____,____,| <- 3
                // 1 = light, 11 pixel, 1 pixel overlapping with 2
                // 2 = dark, 11 pixel, 1 pixel overlapping with 3
                // 3 = light edges
                const int tileHeight = surfaceTile.height();
                // 3
                renderSurface(&surfacePainter,
                                QRect(20, 0, 11, tileHeight),
                                fg.light(105), fg, pal.color(QPalette::Highlight), 2*(_contrast/3),
                                reverseLayout ? Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperLeft|Round_BottomLeft|Is_Horizontal
                                : Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperRight|Round_BottomRight|
                                        Is_Horizontal);
                // 2
                renderSurface(&surfacePainter,
                                QRect(10, 0, 11, tileHeight),
                                fg, fg.light(105), pal.color(QPalette::Highlight), 2*(_contrast/3),
                                reverseLayout ? Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperLeft|Round_BottomLeft|Is_Horizontal
                                : Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperRight|Round_BottomRight|Is_Horizontal);
                // 1
                renderSurface(&surfacePainter,
                                QRect(0, 0, 11, tileHeight),
                                fg.light(105), fg, pal.color(QPalette::Highlight), 2*(_contrast/3),
                                reverseLayout ? Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperLeft|Round_BottomLeft|Is_Horizontal
                                : Draw_Right|Draw_Left|Draw_Top|Draw_Bottom|
                                        Round_UpperRight|Round_BottomRight|Is_Horizontal);

                surfacePainter.end();
                int staticShift = 0;
                int animShift = 0;
                if (!_animateProgressBar) {
                    staticShift = (reverseLayout ? Rsurface.left() : Rsurface.right()) % 40 - 40;
                } else {
                    // find the animation Offset for the current Widget
                    QWidget* nonConstWidget = const_cast<QWidget*>(widget);
                    QMap<QWidget*, int>::const_iterator iter = progAnimWidgets.find(nonConstWidget);
                    if (iter != progAnimWidgets.end())
                        animShift = iter.value();
                }
                while( (counter*10) < (Rsurface.width()+20) )
                {
                    counter++;
                    if (reverseLayout)
                    {
                        // from right to left, overlap 1 pixel with the previously drawn tile
                        p->drawPixmap(Rsurface.right()-counter*20-animShift+40+staticShift, r.top()+1,
                                    surfaceTile);
                    }
                    else
                    {
                        // from left to right, overlap 1 pixel with the previously drawn tile
                        p->drawPixmap(Rsurface.left()+counter*20+animShift-40+staticShift, r.top()+1,
                                    surfaceTile);
                    }
                }

                p->setClipping(false);
            }
            renderContour(p, r, pal.color(QPalette::Background), getColor(pal, ButtonContour, enabled) );
            break;
        }

        case CE_ProgressBarLabel:
        {    // label of progress bar
          const QStyleOptionProgressBar *pbarOpt;
          pbarOpt = qstyleoption_cast<const QStyleOptionProgressBar*>(opt);
          if (!pbarOpt) break;
          if (pbarOpt->minimum == 0 && pbarOpt->maximum == 0) break;

          bool vertical = false;
          bool inverted = false;
          bool bottomToTop = false;

          if( const QStyleOptionProgressBarV2 *pbarOpt2 = qstyleoption_cast<const QStyleOptionProgressBarV2*>(opt) )
          {
            vertical = (pbarOpt2->orientation == Qt::Vertical);
            inverted = pbarOpt2->invertedAppearance;
            bottomToTop = pbarOpt2->bottomToTop;
          }

          if( vertical )
          {
            r = QRect(r.left(), r.top(), r.height(), r.width());
            QTransform m;
            if( bottomToTop )
            {
              reverseLayout = false;
              m.translate(0.0, r.width()+5);
              m.rotate(-90);
            }
            else
            {
              reverseLayout = true;
              m.translate(r.height(), 0.0);
              m.rotate(90);
            }
            p->setTransform(m);
          }
          if( inverted ) //it can have reversed appearance, so re-compute reverseLayout
              reverseLayout = !reverseLayout;

          int coloredWidth;
          if( opt->state & QStyle::State_Enabled )
            coloredWidth = int(((pbarOpt->progress - pbarOpt->minimum) 
                                / double(pbarOpt->maximum - pbarOpt->minimum)) * r.width());
          else
            coloredWidth = 0;

            if( reverseLayout )
              coloredWidth = r.width() - coloredWidth;

          QFont font = p->font();
          font.setWeight(QFont::Bold);
          p->setFont(font);

          p->setPen(reverseLayout ? pbarOpt->palette.base().color()
                                  : pbarOpt->palette.text().color());
          p->drawText(r, Qt::AlignCenter, pbarOpt->text);
          p->setClipRect(QRect(x,y,coloredWidth,h));
          p->setPen(!reverseLayout ? pbarOpt->palette.base().color()
                                  : pbarOpt->palette.text().color());
          p->drawText(r, Qt::AlignCenter, pbarOpt->text);

          break;
        }

      case CE_ToolBar:
      {
        drawPrimitive(PE_PanelToolBar, opt, p, widget);
        break;
      }


        case CE_Splitter:
        {
            // highlight on mouse over
            QColor color;
            if( flags & State_MouseOver )
              color = pal.color(QPalette::Background).light(100+_contrast);
            else
              color = pal.color(QPalette::Background);
            p->fillRect(r, color);

            int ycenter = r.height()/2;
            int xcenter = r.width()/2;

            qreal opacity = p->opacity();
            if (w > h)
            {
              if (h > 4)
              {
                for(int k = r.width()/2-12; k <= r.width()/2+12; k+=6)
                {
                  p->setOpacity( 1.5-((double)qAbs(k-xcenter)/12.0) );
                  renderDot(p, QPoint(k, ycenter-1), color, true, true);
                }
              }
            }
            else
            {
              if (w > 4)
              {
                for(int k = r.height()/2-12; k <= r.height()/2+12; k+=6)
                {
                  p->setOpacity( 1.5-((double)qAbs(k-ycenter)/12.0) );
                  renderDot(p, QPoint(xcenter-1, k), color, true, true);
                }
              }
            }
            p->setOpacity( opacity);

                break;
        }

        case CE_HeaderSection:
        {
          const QStyleOptionHeader *headerOpt = qstyleoption_cast<const QStyleOptionHeader *>(opt);
          if( !headerOpt )
          {
            renderButton(p, r, pal);
            break;
          }
          //HACK: hide the borders in order to merge them with the panel border
          //only if the panel border is visible
          if( QAbstractScrollArea *area = qobject_cast<QAbstractScrollArea *>(widget->parentWidget()) )
            if( area->frameStyle() == QFrame::StyledPanel | QFrame::Sunken )
            {
              r.adjust(-1,-1,0,0);
              //hide right border of the last header
              if( r.right() == area->viewport()->contentsRect().right() )
              r.adjust(0,0,1,0);
            }

          bool isFirst = headerOpt->position == QStyleOptionHeader::Beginning;
          bool isLast = headerOpt->position == QStyleOptionHeader::End;
          // header item id
          int headerId = headerOpt->section;
          //is the section sorted?
          bool sortedSection = headerOpt->sortIndicator != QStyleOptionHeader::None;
          //orientation
          Qt::Orientation orientation = headerOpt->orientation;


          //Passes always sharp, when Round is on sharp is ignored
          //so this doesn't cause damage
          uint contourFlags = Draw_Right|Draw_Bottom|
                              Sharp_BottomLeft|Sharp_BottomRight|
                              Sharp_UpperLeft|Sharp_UpperRight;

          if(!enabled) contourFlags|=Is_Disabled;

          //if horizontal draw always the top contour, else always the left one
          if( orientation == Qt::Horizontal )
            contourFlags |= Draw_Top;
          else
            contourFlags |= Draw_Left;


          //round first header contour and draw the border that usually is not drawn
          if( isFirst && orientation == Qt::Horizontal )
              contourFlags |= Draw_Left|Round_UpperLeft;
          if( isFirst && orientation == Qt::Vertical )
              contourFlags |= Draw_Top|Round_UpperLeft;

          //round last header contour
          //if it's horizontal and we are in a QListView, round only if resizemode !=NoColumn
          if( isLast && orientation == Qt::Horizontal /*&&
              (( list &&  list->resizeMode() != QListView::NoColumn) || !list)*/ )
                contourFlags |= Round_UpperRight;
          if( isLast && orientation == Qt::Vertical )
                contourFlags |= Round_BottomLeft;


          uint surfaceFlags = Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|Is_Horizontal;

          if(!enabled) surfaceFlags|=Is_Disabled;
          else
          {
            if(isFirst)
                  surfaceFlags |= Round_UpperLeft;
            if(isLast)
                  surfaceFlags |= Round_UpperRight;

            if(on||down)
              surfaceFlags|=Is_Sunken;
            else if(flags & State_MouseOver)
              surfaceFlags|=Is_Highlight|Highlight_Top;
          }

          if( headerId == 0 && !isFirst  )
            contourFlags |= Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|
                            Round_UpperRight|Round_UpperLeft|
                            Round_BottomRight|Round_BottomLeft;

          renderSurface(p, QRect(isFirst?r.left()+1:r.left(),
                                 r.top()+1, isFirst?r.width()-2:r.width()-1,
                                 r.height()-2),
                          pal.color(QPalette::Background),
                          sortedSection?
                              alphaBlendColors(pal.color(QPalette::Highlight),
                                               pal.color(QPalette::Button), 70):
                              pal.color(QPalette::Button),
                          getColor(pal,MouseOverHighlight), _contrast,
                          surfaceFlags);

          renderContour(p, r, pal.color(QPalette::Background), getColor(pal,ButtonContour),
                          contourFlags);
          break;

        }


        //Rubberband from Oxygen :)
        case CE_RubberBand:
        {
          p->save();
          QColor color = pal.color(QPalette::Highlight);
          p->setPen(color);
          color.setAlpha(100);
          p->setBrush(color);
          p->drawRect(r.adjusted(0,0,-1,-1));
          p->restore();
          break;
        }

        case CE_DockWidgetTitle:
        {
          const QStyleOptionDockWidget *dockOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt);
          if( !dockOpt )
            break;

          QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, opt, widget);
          int textWidth = opt->fontMetrics.width(dockOpt->title);

          if( !dockOpt->title.isEmpty() )
          {
            p->setPen(pal.foreground().color());
            drawItemText(p, titleRect/*r.adjusted(4, 0, -18, -1)*/,
                         Qt::AlignCenter | Qt::TextSingleLine | Qt::TextShowMnemonic,
                         pal, enabled, dockOpt->title);
          }

          int dotsY = titleRect.center().y();
          int textLeft = titleRect.center().x() - textWidth/2 -5;
          int textRight = titleRect.center().x() + textWidth/2 +5;
          if( dockOpt->title.isEmpty() )
          {
            textLeft += 2;
            textRight -= 2;
          }

          renderDot(p, QPoint(textLeft, dotsY), pal.background().color(), true, true );
          renderDot(p, QPoint(textRight, dotsY), pal.background().color(), true, true );

          qreal opacity = p->opacity();
          p->setOpacity(0.7);
          renderDot(p, QPoint(textLeft-6, dotsY), pal.background().color(), true, true );
          renderDot(p, QPoint(textRight+6, dotsY), pal.background().color(), true, true );
          p->setOpacity(0.5);
          renderDot(p, QPoint(textLeft-12, dotsY), pal.background().color(), true, true );
          renderDot(p, QPoint(textRight+12, dotsY), pal.background().color(), true, true );
          p->setOpacity(opacity);

          break;
        }

        case CE_ScrollBarSlider:
        {
            /*a little bit complicated: deciding if the scrollbar is enabled,
                pressed, with mouse over or not.
                Everything with the right dependencies*/
            const WidgetState s = enabled?(down?IsPressed:
                                                ((flags & State_MouseOver)?
                                                  IsHighlighted:IsEnabled)):IsDisabled;

            const QColor surface = getColor(pal, DragButtonSurface, s);

            uint contourFlags = Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|Sharp_UpperLeft|Sharp_UpperRight|Sharp_BottomLeft|Sharp_BottomRight;
            if(!enabled) contourFlags|=Is_Disabled;

            uint surfaceFlags = contourFlags;
            if( !_coloredScrollBar && flags & State_MouseOver )
            {
              if( !horiz )
                surfaceFlags |= Highlight_Top|Highlight_Bottom;
              else
                surfaceFlags |= Highlight_Left|Highlight_Right;
            }

            if( _scrollBarType == PlatinumStyleScrollBar
                || _scrollBarType == NoButtonsScrollBar)
            {
              if( !horiz )
              {
                contourFlags |= Round_UpperLeft|Round_UpperRight;
                surfaceFlags |= Round_UpperLeft|Round_UpperRight;
              }
              else
              {
                contourFlags |= Round_UpperLeft|Round_BottomLeft;
                surfaceFlags |= Round_UpperLeft|Round_BottomLeft;
              }
            }
            if( _scrollBarType == NextStyleScrollBar
                || _scrollBarType == NoButtonsScrollBar)
            {
              if( !horiz )
              {
                contourFlags |= Round_BottomLeft|Round_BottomRight;
                surfaceFlags |= Round_BottomLeft|Round_BottomRight;
              }
              else
              {
                contourFlags |= Round_BottomLeft|Round_UpperLeft;
                surfaceFlags |= Round_BottomLeft|Round_UpperLeft;
              }
            }

            bool hasFocus; //useless
            QRect surfRect(r.left()+1, r.top()+1, r.width()-2, r.height()-2);
            adjustScrollbarBorders(r, &surfRect, widget, &contourFlags, &surfaceFlags, &hasFocus);
            renderContour(p, r, pal.color(QPalette::Background), getColor(pal, DragButtonContour, s),
                            contourFlags);

            if(horiz) surfaceFlags|=Is_Horizontal;
            if(!enabled) surfaceFlags|=Is_Disabled;
            if(down) surfaceFlags|= Is_Sunken;
            if(r.height() >= 4)
            {
                renderSurface(p, surfRect,
                        pal.color(QPalette::Background), surface, pal.color(QPalette::Highlight),
                        _contrast+3, surfaceFlags);
            }
            //draw a fake border in case we are in a scrollarea
            p->setPen(getColor(pal, ButtonContour).light(120));
            if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Left) )
              p->drawPoint(r.left(), r.top());
            if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Right) )
              p->drawPoint(r.right(), r.top());
            if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Left) )
              p->drawPoint(r.left(), r.bottom());
            if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Right) )
              p->drawPoint(r.right(), r.bottom());



            const int xPos = r.center().x();
            const int yPos = r.center().y();
            const int displacement = 5;

            if( !horiz && r.height() > 24)
            {
              for( int i = -displacement; i <= displacement; i+=displacement)
              {
                if(_scrollBarLines)
                {
                  p->setPen(alphaBlendColors(pal.color(QPalette::Background), surface.dark(enabled?140:120), 50) );
                  p->drawLine(r.x()+1, yPos+i, r.right()-1, yPos+i);
                  p->setPen(alphaBlendColors(pal.color(QPalette::Background), surface.light(enabled?120:110), 50) );
                  p->drawLine(r.x()+1, yPos+i+1, r.right()-1, yPos+i+1);
                }
                else
                {
                  renderDot(p, QPoint(xPos-3, yPos+i), surface, true, true );
                  renderDot(p, QPoint(xPos+2, yPos+i), surface, true, true );
                }
              }
            }
            else if( r.width() > 24 )
            {
              for( int i = -displacement; i <= displacement; i+=displacement)
              {
                if(_scrollBarLines)
                {
                  p->setPen(alphaBlendColors(pal.color(QPalette::Background), surface.dark(enabled?140:120), 50) );
                  p->drawLine(xPos+i, r.y()+1, xPos+i, r.bottom()-1);
                  p->setPen(alphaBlendColors(pal.color(QPalette::Background), surface.light(enabled?120:110), 50) );
                  p->drawLine(xPos+i+1, r.y()+1, xPos+i+1, r.bottom()-1);
                }
                else
                {
                  renderDot(p, QPoint(xPos+i, yPos-3), surface, true, true );
                  renderDot(p, QPoint(xPos+i, yPos+2), surface, true, true );
                }
              }
            }

            break;
        }

        case CE_ScrollBarAddPage:
        case CE_ScrollBarSubPage:
        {

            if (on || down)
            {
                p->fillRect(r, QBrush(pal.color(QPalette::Mid).dark()));
            }
            else
            {
                uint contourFlags, surfaceFlags;
                if(horiz)
                {
                    contourFlags = Draw_Top|Draw_Bottom;
                    surfaceFlags = Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|Is_Sunken|Is_Horizontal;

                    //coordinates for the surface
                    uint xs=x,ws=w;

                    //TODO: scrollbar type
                    if( element == CE_ScrollBarSubPage
                        && ( _scrollBarType == PlatinumStyleScrollBar
                            ||_scrollBarType == NoButtonsScrollBar)  )
                    {
                      contourFlags |= Draw_Left|Round_UpperLeft|Round_BottomLeft;
                      surfaceFlags |= Round_UpperLeft|Round_BottomLeft;
                      xs++;
                      ws--;
                    }
                    else if( element == CE_ScrollBarAddPage
                             && ( _scrollBarType == NextStyleScrollBar 
                                 ||_scrollBarType == NoButtonsScrollBar) )
                    {
                      contourFlags |= Draw_Right|Round_UpperRight|Round_BottomRight;
                      surfaceFlags |= Round_UpperRight|Round_BottomRight;
                      ws--;
                    }


                    bool hasFocus; //useless
                    QRect surfRect(xs,y+1,ws,h-2);
                    adjustScrollbarBorders(r, &surfRect, widget, &contourFlags, &surfaceFlags, &hasFocus);
                    if(_sunkenShadows)
                    {
                      p->fillRect( surfRect, pal.color(QPalette::Background).light(100+_contrast));
                      renderSunkenShadow( p, surfRect, Qt::black, Draw_Top|Draw_Bottom|Draw_Left|Draw_Right|Sharp_UpperLeft|Sharp_UpperRight|Sharp_BottomLeft|Sharp_BottomRight, true );
                    }
                    else
                    {
                      QBrush brush = getShadowBrush(surfRect,
                                                    pal.color(QPalette::Background).light(100+_contrast/2),
                                                    true);
                      p->fillRect( surfRect, brush);
                    }

                    renderContour(p, r, pal.color(QPalette::Background), getColor(pal, ButtonContour),
                            contourFlags);
                    //draw a fake border in case we are in a scrollarea
                    p->setPen(getColor(pal, ButtonContour).light(120));

                    if( _scrollBarType == NextStyleScrollBar
                      ||_scrollBarType == NoButtonsScrollBar)
                    {
                      if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Right) )
                        p->drawPoint(r.right(), r.top());
                      if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Right) )
                        p->drawPoint(r.right(), r.bottom());
                    }
                    if( _scrollBarType == NoButtonsScrollBar
                        ||_scrollBarType == PlatinumStyleScrollBar )
                    {
                      if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Left) )
                        p->drawPoint(r.left(), r.bottom());
                      if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Left) )
                        p->drawPoint(r.left(), r.top());
                    }

                }
                else
                {
                    contourFlags = Draw_Left|Draw_Right;
                    surfaceFlags = Draw_Left|Draw_Right|Draw_Top|Draw_Bottom|Is_Sunken;

                    //coordinates for the surface
                    uint ys=y,hs=h;

                    if( element == CE_ScrollBarSubPage
                        && ( _scrollBarType == PlatinumStyleScrollBar
                            ||_scrollBarType == NoButtonsScrollBar) )
                    {
                      //HACK
                      p->fillRect( r, pal.color(QPalette::Background) );
                      contourFlags |= Draw_Top|Round_UpperLeft|Round_UpperRight;
                      surfaceFlags |= Round_UpperLeft|Round_UpperRight;
                      ys++;
                      hs--;
                    }
                    else if( element == CE_ScrollBarAddPage
                             && ( _scrollBarType == NextStyleScrollBar 
                                 ||_scrollBarType == NoButtonsScrollBar) )
                    {
                      //HACK
                      p->fillRect( r, pal.color(QPalette::Background) );
                      contourFlags |= Draw_Bottom|Round_BottomLeft|Round_BottomRight;
                      surfaceFlags |= Round_BottomLeft|Round_BottomRight;
                      hs--;
                    }


                    bool hasFocus; //useless
                    QRect surfRect(x+1, ys, w-2, hs);
                    adjustScrollbarBorders(r, &surfRect, widget, &contourFlags, &surfaceFlags, &hasFocus);
                    if(_sunkenShadows)
                    {
                      p->fillRect( surfRect, pal.color(QPalette::Background).light(100+_contrast/2));
                      renderSunkenShadow( p, surfRect, Qt::black, Draw_Top|Draw_Bottom|Draw_Left|Draw_Right|Sharp_UpperLeft|Sharp_UpperRight|Sharp_BottomLeft|Sharp_BottomRight, false );
                    }
                    else
                    {
                      QBrush brush = getShadowBrush(surfRect,
                                                    pal.color(QPalette::Background).light(100+_contrast),
                                                    false );
                      p->fillRect( surfRect, brush );
                    }

                    renderContour(p, r, pal.color(QPalette::Background), getColor(pal, ButtonContour),
                            contourFlags);

                    //must put a fake border?
                    if( 1/*_sunkenShadows*/)
                    {
                      p->setPen(getColor(pal, ButtonContour).light(120));
                      if( _scrollBarType == NoButtonsScrollBar
                          ||_scrollBarType == PlatinumStyleScrollBar )
                      {
                        if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Left) )
                          p->drawPoint(r.left(), r.top());
                        if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Right) )
                          p->drawPoint(r.right(), r.top());
                      }
                      if( _scrollBarType == NextStyleScrollBar
                        ||_scrollBarType == NoButtonsScrollBar)
                      {
                        if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Left) )
                          p->drawPoint(r.left(), r.bottom());
                        if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Right) )
                          p->drawPoint(r.right(), r.bottom());
                      }
                    }

                }
            }

            break;
        }

    // SCROLLBAR BUTTONS
    // -----------------
        case CE_ScrollBarSubLine:
        {
          //don't like it but it seems necessary...
          p->fillRect(r, pal.color(QPalette::Background));

          uint contourFlags = Draw_Left|Draw_Right|Draw_Top|Draw_Bottom;

          uint surfaceFlags = Draw_Left|Draw_Top|Draw_Right|Draw_Bottom;
          if(down) surfaceFlags|=Is_Sunken;
          if(!enabled)
          {
            contourFlags|=Is_Disabled;
            surfaceFlags|=Is_Disabled;
          }

          if( _scrollBarType == PlatinumStyleScrollBar )
          {
            if(horiz)
            {
              contourFlags |= Sharp_UpperLeft|Sharp_BottomLeft|Is_Horizontal;
              surfaceFlags |= Sharp_UpperLeft|Sharp_BottomLeft|Is_Horizontal;
            }
            else
            {
              contourFlags |= Sharp_UpperLeft|Sharp_UpperRight;
              surfaceFlags |= Sharp_UpperLeft|Sharp_UpperRight;
            }
          }
          else
          {
            if(horiz)
            {
              contourFlags |= Round_UpperLeft|Round_BottomLeft|Is_Horizontal;
              surfaceFlags |= Round_UpperLeft|Round_BottomLeft|Is_Horizontal;
            }
            else
            {
              contourFlags |= Round_UpperLeft|Round_UpperRight;
              surfaceFlags |= Round_UpperLeft|Round_UpperRight;
            }
          }

          if( horiz )
          {
            contourFlags |= Sharp_UpperRight|Sharp_BottomRight;
            surfaceFlags |= Sharp_UpperRight|Sharp_BottomRight;
          }
          else
          {
            contourFlags |= Sharp_BottomLeft|Sharp_BottomRight;
            surfaceFlags |= Sharp_BottomLeft|Sharp_BottomRight;
          }

          QRect buttonRect, buttonRect2;
          if( horiz )
          {
            buttonRect = QRect(r.x(), r.y(), r.height(), r.height());
            buttonRect2 = QRect(r.right()-r.height()+1, r.y(), r.height(), r.height());
          }
          else
          {
            buttonRect = QRect(r.x(), r.y(), r.width(), r.width());
            buttonRect2 = QRect(r.x(), r.bottom()-r.width()+1, r.width(), r.width());
          }

          bool hasFocus;
          QRect surfRect = buttonRect.adjusted(1,1,-1,-1);
          adjustScrollbarBorders(buttonRect, &surfRect, widget, &contourFlags, &surfaceFlags, &hasFocus);

          renderContour(p, buttonRect, pal.color(QPalette::Background), 
                        getColor(pal, ButtonContour),
                        contourFlags);
          renderSurface(p, /*QRect(r.left()+1, r.top()+1, r.width()-(r.x()==0?2:1), r.height()-(r.y()==0?2:1))*/
                        surfRect,
                        pal.color(QPalette::Background), pal.color(QPalette::Button), 
                                  getColor(pal,MouseOverHighlight), _contrast+3,
                        surfaceFlags);

          //must put a fake border?
          if( 1/*_sunkenShadows*/ )
          {
            if( hasFocus )
              p->setPen(getColor(pal, FocusHighlight));
            else
              p->setPen(getColor(pal, ButtonContour).light(120));

            if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Left) )
              p->drawPoint(r.left(), r.top());
            if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Right) )
              p->drawPoint(r.right(), r.top());
            if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Left) )
              p->drawPoint(r.left(), r.bottom());
            if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Right) )
              p->drawPoint(r.right(), r.bottom());
          }

          if( _scrollBarType == ThreeButtonScrollBar )
          {
            if( horiz )
            {
              contourFlags = Draw_Top|Draw_Bottom|Draw_Left|Sharp_UpperLeft|Sharp_BottomLeft;
              surfaceFlags |= Sharp_UpperLeft|Sharp_BottomLeft;
            }
            else
            {
              contourFlags = Draw_Top|Draw_Right|Draw_Left|Sharp_UpperLeft|Sharp_UpperRight;
              surfaceFlags |= Sharp_UpperLeft|Sharp_UpperRight;
            }

            bool hasFocus; //useless
            surfRect = buttonRect2.adjusted(1,1,-1,-1);
            adjustScrollbarBorders(buttonRect2, &surfRect, widget, &contourFlags, &surfaceFlags, &hasFocus);

            renderContour(p, buttonRect2,
                          pal.color(QPalette::Background), getColor(pal, ButtonContour),
                          contourFlags);
            renderSurface(p, surfRect,
                          pal.color(QPalette::Background), pal.color(QPalette::Button), 
                                    getColor(pal,MouseOverHighlight), _contrast+3,
                          surfaceFlags);
          }

          p->setPen(pal.color(QPalette::Foreground));

          renderArrow(p, buttonRect,
                      pal.color(QPalette::ButtonText), (horiz?Left:Up));
          if( _scrollBarType == ThreeButtonScrollBar )
            renderArrow(p, buttonRect2,
                        pal.color(QPalette::ButtonText), (horiz?Left:Up));

          break;
        }

        case CE_ScrollBarAddLine:
        {
          p->fillRect(r, pal.color(QPalette::Background));
            uint isNext = _scrollBarType == NextStyleScrollBar;
            uint contourFlags = (!isNext||!horiz||down?Draw_Left:0)|
                                 Draw_Right|
                                (!isNext||horiz||down?Draw_Top:0)|
                                 Draw_Bottom;
            uint surfaceFlags = contourFlags;
            if(down) surfaceFlags|=Is_Sunken;
            if(!enabled) {
                contourFlags|=Is_Disabled;
                surfaceFlags|=Is_Disabled;
            }
            if( horiz && !isNext) {
                contourFlags |= Round_UpperRight|Round_BottomRight|Is_Horizontal;
                surfaceFlags |= Round_UpperRight|Round_BottomRight|Is_Horizontal;
            } else if( !isNext ){
                contourFlags |= Round_BottomLeft|Round_BottomRight;
                surfaceFlags |= Round_BottomLeft|Round_BottomRight;
            } else if( horiz && isNext){
                contourFlags |= Is_Horizontal;
                surfaceFlags |= Is_Horizontal;
            }


            if( horiz )
            {
              contourFlags |= Sharp_UpperLeft|Sharp_BottomLeft;
              surfaceFlags |= Sharp_UpperLeft|Sharp_BottomLeft;
              //TODO:scrollbar type
              if( isNext )
              {
                contourFlags |= Sharp_UpperRight|Sharp_BottomRight;
                surfaceFlags |= Sharp_UpperRight|Sharp_BottomRight;
              }
            }
            else
            {
              contourFlags |= Sharp_UpperLeft|Sharp_UpperRight;
              surfaceFlags |= Sharp_UpperLeft|Sharp_UpperRight;
              if( isNext )
              {
                contourFlags |= Sharp_BottomLeft|Sharp_BottomRight;
                surfaceFlags |= Sharp_BottomLeft|Sharp_BottomRight;
              }
            }

            bool hasFocus;
            QRect surfRect = QRect(r.left()+(!isNext||!horiz?1:0), r.top()+(!isNext||horiz?1:0), r.width()-(isNext&&horiz?1:2), r.height()-(isNext&&!horiz?1:2));
            adjustScrollbarBorders(r, &surfRect, widget, &contourFlags, &surfaceFlags, &hasFocus);

            renderContour(p, r, pal.color(QPalette::Background), getColor(pal, ButtonContour),
                          contourFlags);
            renderSurface(p, surfRect,
                          pal.color(QPalette::Background), pal.color(QPalette::Button), getColor(pal,MouseOverHighlight), _contrast+3,
                          surfaceFlags);

            //draw a fake border in case we are in a scrollarea
            if( hasFocus )
              p->setPen(getColor(pal, FocusHighlight));
            else
              p->setPen(getColor(pal, ButtonContour).light(120));

            if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Left) )
              p->drawPoint(r.left(), r.top());
            if( !(contourFlags&Draw_Top)&&!(contourFlags&Draw_Right) )
              p->drawPoint(r.right(), r.top());
            if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Left) )
              p->drawPoint(r.left(), r.bottom());
            if( !(contourFlags&Draw_Bottom)&&!(contourFlags&Draw_Right) )
              p->drawPoint(r.right(), r.bottom());


            p->setPen(pal.color(QPalette::Foreground));
            drawPrimitive((horiz ? PE_IndicatorArrowRight : PE_IndicatorArrowDown), opt, p, widget);

            break;
        }


   //TABBAR TEXT (code from Qt libraries Copyright Trolltech 2006)
   //--------------
       case CE_TabBarTabLabel:
       {
          /*if ( opt.isDefault() )
             break;*/
          const QStyleOptionTab* tabOpt = qstyleoption_cast<const QStyleOptionTab*>(opt);
          if (!tabOpt) break;

          //for icons
          QStyleOptionTabV2 tabOpt2(*tabOpt);

          if( tabOpt->shape == QTabBar::RoundedWest ||
              tabOpt->shape == QTabBar::RoundedEast )
          {
#ifdef NO_KDE
          QWindowsStyle::drawControl(element, opt, p, widget);
#else
          KStyle::drawControl(element, opt, p, widget);
#endif
              break;
          }

          const uint text_flags = Qt::AlignCenter | Qt::TextDontClip |
                                  Qt::TextSingleLine | Qt::TextShowMnemonic;


          QRect tr = r;
          if (  flags & State_Selected )//t->identifier() == tb->currentTab())
          {
             tr.moveTop( tr.top() -
                         pixelMetric( QStyle::PM_TabBarTabShiftVertical, opt, widget ) );
             tr.moveLeft( tr.left() -
                          pixelMetric( QStyle::PM_TabBarTabShiftHorizontal, opt, widget ) );
          }

          if (!tabOpt2.icon.isNull())
          {
            QSize iconSize = tabOpt2.iconSize;
            if (!iconSize.isValid()) {
                int iconExtent = pixelMetric(PM_SmallIconSize);
                iconSize = QSize(iconExtent, iconExtent);
            }
            QPixmap tabIcon = tabOpt2.icon.pixmap(iconSize,
                                                (tabOpt2.state & State_Enabled) ? QIcon::Normal
                                                                                : QIcon::Disabled);
            p->drawPixmap(tr.left() + 6, tr.center().y() - tabIcon.height() / 2, tabIcon);
            tr.setLeft(tr.left() + iconSize.width() + 4);
          }

          if(_shadowedButtonsText)
          {
             p->setPen( pal.color(QPalette::Button).dark(120+_contrast));
             p->drawText(QRect(tr.x()+1, tr.y()+1, tr.width(), tr.height()),
                         text_flags, tabOpt->text);
          }

          p->setPen( pal.color(QPalette::ButtonText));
          drawItemText( p, tr, text_flags, pal,
                    enabled, tabOpt->text );

          if ( (flags & State_HasFocus) && !tabOpt->text.isEmpty() )
          {
            QStyleOptionFocusRect focusOpt;
            focusOpt.QStyleOption::operator=(*tabOpt);
            /*focusOpt.rect = subElementRect(SE_ComboBoxFocusRect,
                                          combo, widget);*/
            focusOpt.rect = QRect(r.x()+4, r.y()+4, r.width()-8, r.height()-8);
            drawPrimitive( PE_FrameFocusRect, &focusOpt, p, widget );
          }

          break;
       }

    // TABS
    // ----
        case CE_TabBarTabShape:
        {
            const QStyleOptionTab* tabOpt = qstyleoption_cast<const QStyleOptionTab*>(opt);
            if (!tabOpt) break;

            const QTabBar * tb = (const QTabBar *) widget;

            bool cornerWidget = reverseLayout ?
                            (tabOpt->cornerWidgets&QStyleOptionTab::LeftCornerWidget) :
                            (tabOpt->cornerWidgets&QStyleOptionTab::RightCornerWidget);
            QTabBar::Shape tbs = tb->shape();


            SelectedTab selected = OtherTab;
            if( tabOpt->selectedPosition == QStyleOptionTab::NextIsSelected )
              selected = NextTab;
            if( tabOpt->selectedPosition == QStyleOptionTab::PreviousIsSelected )
              selected = PrevTab;
            if( flags & State_Selected )
              selected = ThisTab;

            QStyleOptionTab::TabPosition pos = tabOpt->position;

            //TODO: disabled control doesn't have mouseover
            bool disabled = !(tabOpt->state & State_Enabled);
            bool mouseOver = (flags & State_MouseOver) &&
                             (selected != ThisTab) && !disabled;
          /*  if (opt.tab() == hoverTab) {
                mouseOver = true;
                flags |= State_MouseOver;
            }*/

            switch (tbs)
            {
              case QTabBar::TriangularNorth:
                renderTab(p, r, pal, mouseOver, selected, false, pos, true, cornerWidget, reverseLayout);
                break;
              case QTabBar::RoundedNorth:
                renderTab(p, r, pal, mouseOver, selected, false, pos, false, cornerWidget, reverseLayout);
                break;
              case QTabBar::TriangularSouth:
                renderTab(p, r, pal, mouseOver, selected, true, pos, true, cornerWidget, reverseLayout);
                break;
              case QTabBar::RoundedSouth:
                renderTab(p, r, pal, mouseOver, selected, true, pos, false, cornerWidget, reverseLayout);
                break;
              case QTabBar::TriangularEast:
              case QTabBar::RoundedEast:
              {
                r = QRect(r.left(), r.top(), r.height(), r.width());
                QTransform m;

                m.translate(-r.y(), r.y());

                m.rotate(90);
                m.scale(1,-1);

                p->save();
                p->setTransform(m);
                renderTab(p, r, pal, mouseOver, selected, true, pos,
                          (tbs == QTabBar::TriangularEast), cornerWidget, false);
                p->restore();
                break;
              }
              case QTabBar::TriangularWest:
              case QTabBar::RoundedWest:
              {
                r = QRect(r.left(), r.top(), r.height(), r.width());
                QTransform m;

                m.translate(-r.y(), r.y());

                m.rotate(90);
                m.scale(1,-1);

                p->save();
                p->setTransform(m);
                renderTab(p, r, pal, mouseOver, selected, false, pos,
                          (tbs == QTabBar::TriangularWest), cornerWidget, false);
                p->restore();
                break;
              }
              default:
#ifdef NO_KDE
                  QWindowsStyle::drawControl(element, opt, p, widget);
#else
                  KStyle::drawControl(element, opt, p, widget);
#endif
            }
            break;
        }

        case CE_PushButtonLabel:
        {
            int x, y, w, h;
            r.getRect( &x, &y, &w, &h );

            const QStyleOptionButton *buttonOpt = qstyleoption_cast<const QStyleOptionButton *>(opt);

            //Hacky thing for animation support
            QPushButton* button = (QPushButton *)( widget );

            if( !buttonOpt )
            {
#ifdef NO_KDE
              QWindowsStyle::drawControl(element, opt, p, widget);
#else
              KStyle::drawControl(element, opt, p, widget);
#endif
              break;
            }

            bool active = flags&State_On || flags&State_Sunken;
            bool cornArrow = false;
            int textWidth = 0;
            if( buttonOpt->text.length() > 0 )
            {
              const QFontMetrics &fm = buttonOpt->fontMetrics;
              textWidth = fm.boundingRect(buttonOpt->text).width();
            }

            // Shift button contents if pushed.
            if( widget && active )
            {
                x += pixelMetric(PM_ButtonShiftHorizontal, opt, widget);
                y += pixelMetric(PM_ButtonShiftVertical, opt,  widget);
                //flags |= State_Sunken;
            }
            else if( active ) //if there is no widget move only 1 pixel
            {
              x += 1;
              y += 1;
            }

            //TODO: decide if a checkbox here makes sense at all, probably not...
            /*if( button && w > (textWidth + 30) && button->isCheckable() )
            {
              int checkSize = pixelMetric(PM_IndicatorWidth, opt, widget);
              QStyleOption checkOpt;
              checkOpt.QStyleOption::operator=(*opt);

              int checkPos = (int)((double)h/2.0 - ((double)checkSize/3.5));

              x += checkSize+checkPos;
              w -= checkSize+checkPos;

              if( active )
                checkPos += pixelMetric(PM_ButtonShiftHorizontal, opt, widget);

              //otherwise drawprimitive thinks that it is a tristate
              if( !(flags&State_On) )
                checkOpt.state |= State_Off;

              checkOpt.rect = QRect(checkPos, checkPos, checkSize, checkSize);
              drawPrimitive(PE_IndicatorCheckBox, &checkOpt, p, widget);
            }*/

            // Draw the icon if there is one
            if ( !buttonOpt->icon.isNull() )
            {
                QIcon::Mode  mode  = QIcon::Disabled;
                QIcon::State state = flags&State_On ? QIcon::On : QIcon::Off;

                /*if (button->isEnabled())
                    mode = button->hasFocus() ? QIcon::Active : QIcon::Normal;
                if (button->isCheckable() && button->isChecked())
                    state = QIcon::On;*/
                if( flags&State_Enabled )
                  mode  = QIcon::Normal;
                else
                  mode  = QIcon::Disabled;

                if( mode == QIcon::Normal && flags&State_HasFocus )
                  mode = QIcon::Active;

                QPixmap pixmap = buttonOpt->icon.pixmap( pixelMetric(QStyle::PM_SmallIconSize), mode, state );

                if (buttonOpt->text.isEmpty() /*&& !button->pixmap()*/)
                    p->drawPixmap( x + w/2 - pixmap.width()/2, y + h / 2 - pixmap.height() / 2,
                                    pixmap );
                else
                    p->drawPixmap( x + 4, y + h / 2 - pixmap.height() / 2, pixmap );

#if 0
                if (cornArrow) //Draw over the icon
                {
                  QStyleOption arrowOpt;
                  arrowOpt.QStyleOption::operator=(*opt);
                  arrowOpt.rect = visualRect( arrowOpt.direction, r, QRect(x + w - 6, x + h - 6, 7, 7));
                  drawPrimitive( PE_IndicatorArrowDown, &arrowOpt, p, widget);
                }
#endif

                int  pw = pixmap.width();
                x += pw + 4;
                w -= pw + 4;
            }

            //making the text of the default button always readable with a cute animation
            int animFrame = 0;
            if( button && _animateButton
                && (!(buttonOpt->features & QStyleOptionButton::Flat) || active)
                && button->isDefault()
                && animWidgets.contains( button ))
              animFrame = animWidgets[button].animFrame;

            //12.8 is the maximum amount of blending (256) / ANIMATIONSTEPS (20)
            QColor textColor = alphaBlendColors( pal.color(QPalette::HighlightedText),
                                                 pal.color(QPalette::ButtonText),
                                                 (int)(12.8*animFrame)
                                               );
            const uint text_flags = Qt::AlignCenter | Qt::TextDontClip |
                                    Qt::TextSingleLine | Qt::TextShowMnemonic;
            // shadow on button text

            if( _shadowedButtonsText && flags&State_Enabled && !buttonOpt->text.isEmpty() )
            {
              QColor shadowColor = alphaBlendColors( pal.color(QPalette::Highlight),
                                                pal.color(QPalette::Button),
                                                (int)(12.8*animFrame)
                                              ).dark(120+_contrast);
              QPalette palCopy = pal;
              palCopy.setColor( QPalette::ButtonText, shadowColor);
              p->setPen( shadowColor );
              p->drawText(QRect(x+1, y+1, w, h),
                          text_flags, _useLowerCaseText?
                                      buttonOpt->text.toLower():
                                      buttonOpt->text);
            }

             p->setPen( textColor );
             p->drawText(QRect(x, y, w, h),
                         text_flags, _useLowerCaseText?
                                     buttonOpt->text.toLower():
                                     buttonOpt->text);


            /*if ( flags & Style_HasFocus )
            {
              QColorGroup g2 = cg;

              drawPrimitive( PE_FocusRect, p,
                             visualRect( subRect( SR_PushButtonFocusRect, widget ), widget ),
                             g2, flags, opt );
            }*/
            break;
        }

       case CE_ToolBoxTabShape:
       {
         const QStyleOptionToolBox *toolBoxOpt = qstyleoption_cast<const QStyleOptionToolBox *>(opt);
         if( !toolBoxOpt )
           break;

         uint borderFlags = Draw_Top|Draw_Bottom|Draw_Left|Draw_Right|Round_UpperLeft|Round_UpperRight;
         uint surfaceFlags = borderFlags|Is_Horizontal;

         if( opt->state & State_Selected )
         {
           surfaceFlags |= Highlight_Top;
         }
         else
         {
           borderFlags |= Round_BottomLeft|Round_BottomRight;
           surfaceFlags |= Round_BottomLeft|Round_BottomRight;
         }

         renderContour(p,r,pal.color(QPalette::Background),
                       getColor(pal, ButtonContour, true), borderFlags);
         renderSurface(p,r.adjusted(1,1,-1,-1), pal.color(QPalette::Background),
                       pal.color(QPalette::Button), getColor(pal,FocusHighlight),
                       _contrast, surfaceFlags);

         break;
       }

    // MENUBAR ITEM
    // -----------------------------------------
        case CE_MenuBarItem:
        {
            const QStyleOptionMenuItem *miOpt;
            miOpt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
            if (!miOpt) break;

            bool active  = flags & State_Selected;
            bool focused = flags & State_HasFocus;
            bool down = flags & State_Sunken;
            const int text_flags =
                Qt::AlignVCenter | Qt::AlignHCenter | Qt::TextDontClip |
                Qt::TextSingleLine | Qt::TextShowMnemonic;

            if( _menuBarEmphasis )
            {
                QMenuBar  *mb = (QMenuBar*)widget;
                renderSurface(p, mb->rect(), pal.color(QPalette::Background),
                              getColor(pal, MenuBarEmphasis),
                              pal.color(QPalette::Background),
                              _contrast+3, Is_Horizontal);
            }
            else
            {
              p->fillRect(r, pal.color(QPalette::Background));
            }

            if (active && focused)
            {
                if (down) {
                    //drawPrimitive(PE_ButtonTool, p, r, cg, flags|State_Sunken, opt);
                    //code to draw the menubar item as a tab (ugly?)
                    renderSurface(p, QRect(r.left()+1, r.top()+1, r.width()-2, r.height()),
                            pal.color(QPalette::Highlight),
                                      pal.color(QPalette::Highlight),
                                      pal.color(QPalette::Highlight),
                            _contrast, Is_Horizontal|Draw_Right|Draw_Top|Draw_Left);
                 renderContour(p, r, getColor(pal, MenuBarEmphasis),  pal.color(QPalette::Highlight).dark(100+_contrast*8), Draw_Right|Draw_Top|Draw_Left|Round_UpperRight|Round_UpperLeft);
                    //renderTab( p, QRect(r.left(), r.top(), r.width(), r.height()+2), cg, false, true, false, Single, false, false);
                } else {
                    renderSurface(p, QRect(r.left()+1, r.top()+1, r.width()-2, r.height()-2),
                            pal.color(QPalette::Background), getColor(pal, MenuBarEmphasis), pal.color(QPalette::Background),
                            _contrast, Is_Horizontal|Draw_Right|Draw_Top|Draw_Left|Draw_Bottom);
                 renderContour(p, r, getColor(pal, MenuBarEmphasis),  getColor(pal, MenuBarEmphasis).dark(120+_contrast*8), Draw_Right|Draw_Top|Draw_Left|Round_UpperRight|Round_UpperLeft|Draw_Bottom|Round_BottomRight|Round_BottomLeft);
                    //not used this because of the possible custom menubar color
                    //drawPrimitive(PE_ButtonTool, p, r, cg, flags, opt);
                }
            }

            if ( _shadowedMenuBarText ){
                if (active && focused && down)
                    p->setPen(pal.color(QPalette::Highlight).dark(100+_contrast*2) );
                else
                    p->setPen(getColor(pal, MenuBarEmphasis).dark(100+_contrast*2) );
                p->drawText(r.x()+1, r.y()+1, r.width(), r.height(), text_flags, miOpt->text);
            }
            if (active && focused && down)
                p->setPen(pal.color(QPalette::HighlightedText) );
            else
                if( _customMenuBarEmphasisColor )
                    p->setPen( (qGray(_menuBarEmphasisColor.rgb())>150?pal.color(QPalette::Foreground):Qt::white) );
                else
                    p->setPen( pal.color(QPalette::Foreground) );
            p->drawText(r, text_flags, miOpt->text);

            break;
        }

    // POPUPMENU ITEM (highlighted on mouseover)
    // ------------------------------------------
      case CE_MenuItem:
        {
          const QStyleOptionMenuItem *miOpt;
          miOpt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
          if (!miOpt) break;

          //Dolphin draws separators with menuitem separators...
          if( !::qobject_cast<const QMenu*>(widget) && miOpt->menuItemType == QStyleOptionMenuItem::Separator  )
          {
            p->setPen( pal.color(QPalette::Mid) );

            p->drawLine( r.x()+5, r.y() + 1, r.right()-5, r.y() + 1 );
            if( !_lightBorder)
            {
              p->setPen( pal.color(QPalette::Light) );
              p->drawLine( r.x()+5, r.y() + 2, r.right()-5 , r.y() + 2 );
            }
            
            break;
          }

          int stripeWidth = qMax(miOpt->maxIconWidth, 22);
          bool active = (flags & State_Selected);

          bool checked = (miOpt->checkType != QStyleOptionMenuItem::NotCheckable)
                         ? miOpt->checked : false;
          bool checkable = miOpt->checkType != QStyleOptionMenuItem::NotCheckable;

          //background
          p->fillRect( r, pal.color(QPalette::Background).light( 105 ) );
          //stripe
          if( _menuStripe )
          {
            if( !reverseLayout )
              p->fillRect( QRect(r.left(), r.top(), stripeWidth, r.height()),
                            pal.color(QPalette::Background).dark( 110+_contrast ) );
            else
              p->fillRect( QRect(r.right()-stripeWidth, r.top(), stripeWidth, r.height()),
                            pal.color(QPalette::Background).dark( 110+_contrast ) );

          }

          //active?
          if( active )
          {
            //FIXME: why i must put r.width()-3?
            QRect r2 =  QRect(r.left()+1, r.top()+1, r.width()-3, r.height()-2);
            QRect r3 =  QRect(r.left()+2, r.top()+2, r.width()-5, r.height()-4);

            //enabled?
            if( enabled )
            {
              if (_buttonMenuItem  )
              {
                  renderSurface(p, r3, pal.color(QPalette::Background), pal.color(QPalette::Highlight), pal.color(QPalette::Highlight),
                          _contrast+3, Is_Horizontal|Draw_Right|Draw_Top|Draw_Bottom|Draw_Left);
                  renderContour(p, r2, pal.color(QPalette::Background),  pal.color(QPalette::Highlight).dark(100+_contrast*8), Draw_Right|Draw_Top|Draw_Bottom|Draw_Left|Round_UpperRight|Round_UpperLeft|Round_BottomRight|Round_BottomLeft|Draw_AlphaBlend);
              }
              else
                  renderSurface(p, r, pal.color(QPalette::Background), pal.color(QPalette::Highlight), pal.color(QPalette::Highlight),
                          _contrast+3, Is_Horizontal|Draw_Top|Draw_Bottom);
            }
            else
            {
              qreal opacity = p->opacity();
              p->setOpacity(0.8);
              QColor background = pal.color(QPalette::Background);
              if (_buttonMenuItem  )
              {
                  renderSurface(p, r3, background, background.light(120), pal.color(QPalette::Highlight),
                          _contrast+3,
                           Is_Horizontal|Round_UpperLeft|
                               Round_BottomRight|Round_BottomLeft);
                  renderContour(p, r2, pal.color(QPalette::Background),  pal.color(QPalette::Background).dark(100+_contrast*5), Draw_Right|Draw_Top|Draw_Bottom|Draw_Left|Round_UpperRight|Round_UpperLeft|Round_BottomRight|Round_BottomLeft|Draw_AlphaBlend);
              }
              else
                  renderSurface(p, r, background, background.light(120), pal.color(QPalette::Highlight),
                          _contrast+3,
                           Is_Horizontal|Draw_Top|Draw_Bottom|
                             Draw_Left|Draw_Right);
              p->setOpacity(opacity);
            }
          }

          // Are we a menu item separator?
          if( miOpt->menuItemType == QStyleOptionMenuItem::Separator  )
          {
              p->setPen( pal.color(QPalette::Mid) );
              if( !reverseLayout )
              {
                  p->drawLine( r.x()+stripeWidth, r.y() + 1, r.right()-5, r.y() + 1 );
                  if( !_lightBorder)
                  {
                    p->setPen( pal.color(QPalette::Light) );
                    p->drawLine( r.x()+stripeWidth, r.y() + 2, r.right()-5 , r.y() + 2 );
                  }
              }
              else
              {
                  p->drawLine( r.x()+5, r.y() + 1, r.right()-24, r.y() + 1 );
                  if( !_lightBorder)
                  {
                    p->setPen( pal.color(QPalette::Light) );
                    p->drawLine( r.x()+5, r.y() + 2, r.right()-24 , r.y() + 2 );
                  }
              }
              break;
          }

          QRect vrect = visualRect(miOpt->direction, r,
                                   QRect(x, y, stripeWidth, h));

          //Checkbox, radiobutton or checked icon?
          //TODO: the radiobutton is drawn poorly but this is NOT going to be fixed
          //until the surfaces are drawn with QBrush
          if( checkable )
          {
            QStyleOptionMenuItem miOptCheck = *miOpt;
            miOptCheck.rect = QRect(vrect.x()+5, vrect.y()+5, 13, 13);

            if(!miOpt->icon.isNull())
            {
              if( checked )
              {
                miOptCheck.state |= State_Off;
                miOptCheck.rect = vrect;
                drawPrimitive(PE_IndicatorCheckBox, &miOptCheck, p, widget);
              }
            }
            else if( (miOpt->checkType & QStyleOptionMenuItem::Exclusive) )
            {
              if( checked )
                miOptCheck.state |= State_On;
              else
                miOptCheck.state |= State_Off;
              drawPrimitive(PE_IndicatorRadioButton, &miOptCheck, p, widget);
            }
            else
            {
              if( checked )
                miOptCheck.state |= State_On;
              else
                miOptCheck.state |= State_Off;

              drawPrimitive(PE_IndicatorCheckBox, &miOptCheck, p, widget);
            }
          }


          // Do we have an icon?
          if ( !miOpt->icon.isNull() )
          {
              QIcon::Mode mode;

              // Select the correct icon from the iconset
              if( active )
                  mode = enabled?QIcon::Active:QIcon::Disabled;
              else
                  mode = enabled?QIcon::Normal:QIcon::Disabled;

              // Draw the icon
              QPixmap pixmap = miOpt->icon.pixmap(pixelMetric(PM_SmallIconSize), mode);
              QRect pmr( 0, 0, pixmap.width(), pixmap.height() );
              pmr.moveCenter( vrect.center() );
              p->drawPixmap( pmr.topLeft(), pixmap );
          }


          //draw text
          QString text = miOpt->text;

          int xm = 2 + stripeWidth; // X position margin

          int xp = reverseLayout ? // X position
                    r.x() + miOpt->tabWidth + rightBorder + itemHMargin + itemFrame - 1 :
                    r.x() + xm;

          //int offset = reverseLayout ? -1 : 1; // Shadow offset for etched text

          // Label width (minus the width of the accelerator portion)
          int tw = r.width() - xm - miOpt->tabWidth - arrowHMargin - itemHMargin * 3 - itemFrame + 1;

          QRect trect(xp, y+itemVMargin, tw, h - 2 * itemVMargin);
          vrect = visualRect(opt->direction, r, trect);

          //p->setPen( enabled ? pal.color(QPalette::ButtonText) : pal.color(QPalette::Mid) );
          if( active && enabled )
            p->setPen( pal.color(QPalette::HighlightedText) );
          else if( enabled )
            p->setPen( pal.color(QPalette::Text) );
          else
             p->setPen( pal.color(QPalette::Mid) );

          if(!text.isEmpty())
          {
            p->save();
            //default is bold
            if (miOpt->menuItemType == QStyleOptionMenuItem::DefaultItem)
            {
              QFont font = miOpt->font;
              font.setBold(true);
              p->setFont(font);
            }

            int t = text.indexOf('\t');
            int tFlags = Qt::AlignVCenter | Qt::AlignLeft |
                          Qt::TextDontClip | Qt::TextSingleLine;
            if (styleHint(SH_UnderlineShortcut, miOpt, widget))
                tFlags |= Qt::TextShowMnemonic;
            else
                tFlags |= Qt::TextHideMnemonic;

            //(accelerator)
            if (t >= 0)
            {
                QRect tabrect = visualRect(opt->direction, r,
                                QRect(trect.topRight(),
                                      QPoint(r.right(), trect.bottom())));
                p->drawText(tabrect, tFlags, text.mid(t+1));
                text = text.left(t);
            }
            p->drawText(vrect, tFlags, text.left(t));
            p->restore();
          }

          //Draw arrow at the far end of the menu item
          if( miOpt->menuItemType == QStyleOptionMenuItem::SubMenu )
          {
            QStyleOptionMenuItem miOptArrow = *miOpt;

            PrimitiveElement arrow = reverseLayout ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
            int dim = pixelMetric(PM_MenuButtonIndicator) - 1;
            QRect vr = visualRect(miOpt->direction, r, QRect( r.left() + r.width() - 5 - 1 - dim,
                        r.y() + r.height() / 2 - dim / 2, dim, dim) );

            miOptArrow.rect = vr;

            if( active )
              miOptArrow.palette.setColor(QPalette::ButtonText,
                                          miOptArrow.palette.highlightedText().color());

              drawPrimitive(arrow, &miOptArrow, p, widget);

          }
          break;
        }




        case CE_MenuBarEmptyArea:
        {
            if( _menuBarEmphasis )
            {
              renderSurface(p, r, pal.color(QPalette::Background),
                            getColor(pal, MenuBarEmphasis),
                            pal.color(QPalette::Background),
                            _contrast+3, Is_Horizontal);

              if( _menuBarEmphasisBorder )
              {
                int margin = pixelMetric(PM_MenuBarPanelWidth, opt, widget);
                renderContour(p, QRect(r.x()+margin,r.y()+margin,r.width()-2*margin,r.height()-2*margin), pal.color(QPalette::Background), getColor(pal, MenuBarEmphasis).dark(115),
                                Draw_Left|Draw_Top|Draw_Bottom|Draw_Right|
                                Round_UpperLeft|Round_UpperRight|
                                Round_BottomRight|Round_BottomLeft);
              }
            }
            else
              p->fillRect(r, pal.color(QPalette::Background));
//             if ( _drawToolBarSeparator ) {
//                 p->setPen( getColor(pal, PanelDark) );
//                 p->drawLine( r.left(), r.bottom(), r.right(), r.bottom() );
//             }

            break;
        }
#if 0
        case CE_HeaderLabel:
        {
          const QStyleOptionHeader *headerOpt = qstyleoption_cast<const QStyleOptionHeader *>(opt);
          //const QHeader *header = static_cast< const QHeader * >( widget );
            if( !headerOpt )
              break;
          //const QS

            /*int headerId = header->sectionAt(
                                  (header->orientation()==Qt::Horizontal?r.x():r.y()) +
                                  header->offset());*/

            QString text = headerOpt->text;
            // Does the header have a text label?
            if( !text.isNull() )
            {
               int t = text.indexOf( '\t' );
               int text_flags = Qt::AlignVCenter | Qt::TextDontClip |
                                Qt::TextSingleLine | Qt::TextShowMnemonic;
               text_flags |= reverseLayout ? Qt::AlignRight : Qt::AlignLeft;
               p->setPen(pal.color(QPalette::Text));

               /*draw the text label always attempting to display the entire label,
                 except when reverse layout the text label is already shown entirely*/
               p->drawText( QRect(r.x()<=2&&!reverseLayout?2:r.x(),
                                 r.y(), r.width(), r.height()),
                                 text_flags, text.left(t) );
            }

            if( !headerOpt->icon.isNull() )
            {
              QIcon::Mode  mode  = QIcon::Normal;
              QIcon::State state = QIcon::On;

              QPixmap pixmap = headerOpt->icon.pixmap( pixelMetric(QStyle::PM_SmallIconSize) , mode, state );
              p->drawPixmap(r.x(), r.y()+r.height()/2-pixmap.height()/2, pixmap);
            }
            break;
        }
#endif
        default:
#ifdef NO_KDE
          QWindowsStyle::drawControl(element, opt, p, widget);
#else
          KStyle::drawControl(element, opt, p, widget);
#endif
    }
}
