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

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

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

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

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

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

#include <qtooltip.h>
#include <qbitmap.h>
#include <qdrawutil.h>

#include <kconfig.h>
#include <kwinmodule.h>
#include <kwin.h>
#include <kwm.h>
#include <kwinmodule.h>
#include <kpixmapeffect.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <klocale.h>
#include <kdebug.h>
#include <kiconloader.h>

#include "kasbar.h"
#include "userrectsel.h"


static unsigned char min_bits[] = {
    0x00, 0xff, 0xff, 0xff, 0x7e, 0x3c, 0x18, 0x00};
static unsigned char max_bits[] = {
    0xff, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xff};

static KPixmap *actBg = NULL, *inactBg = NULL;
static QBitmap *minPix, *maxPix;
KWinModule *kwin_module;

#define BTN_EXTENT 52

extern "C"
{
    InternalApplet* init(QWidget *, KWinModule *module)
    {
        kwin_module = module;
	//KGlobal::locale()->insertCatalogue("kasbarapplet");
        KasFrame *frame = new KasFrame(NULL, "kasbarapplet");
        frame->show();
        return(frame);
    }
}

KasFrame::KasFrame(QWidget *parent, const char *name)
    : InternalApplet(parent, name, WStyle_Customize  | WStyle_NoBorder)
{
    KConfig *config = KGlobal::config();
    config->setGroup("kasbar");
    orient = config->readBoolEntry("Horizontal", false) == false ?
        Vertical : Horizontal;
    if(config->readBoolEntry("StayOnTop", true))
        KWM::keepOnTop(winId());
    bar = new KasBar(orient, this);
    resize(bar->width()+4, bar->height()+12);
    bar->move(2, 10);
    connect(bar, SIGNAL(layoutChanged()), this, SLOT(slotLayoutChanged()));
    minimized = false;
    KWM::setSticky(winId(), true);
    setPosition((Position)config->readNumEntry("Position", (int)TopRight));
    reposition();
    inDrag = false;
	setFlags(TopLevel);

	kdDebug() << "kasbar flags: " << flags() << endl;
}

void KasFrame::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    qDrawShadePanel(&p, 0, 0, width(), height(), colorGroup(), false, 2);
    p.fillRect(2, 2, width()-4, 8, colorGroup().brush(QColorGroup::Mid));

    p.setPen(colorGroup().light());
    p.drawLine(4, 4, width()-5, 4);
    p.setPen(colorGroup().dark());
    p.drawLine(4, 5, width()-5, 5);

    p.setPen(colorGroup().light());
    p.drawLine(4, 6, width()-5, 6);
    p.setPen(colorGroup().dark());
    p.drawLine(4, 7, width()-5, 7);
}

void KasFrame::mousePressEvent(QMouseEvent *ev)
{
    dragStart = ev->pos();
    inDrag = true;

    //moveMe();
}

void KasFrame::mouseMoveEvent(QMouseEvent *ev)
{
    int delay = KGlobalSettings::dndEventDelay();
    if(inDrag){
        if(ev->x() >= dragStart.x()+delay || ev->x() <= dragStart.x()-delay ||
           ev->y() >= dragStart.y()+delay || ev->y() <= dragStart.y()-delay){
            moveMe();
            inDrag = false;
        }
    }
    else QWidget::mouseMoveEvent(ev);
}

void KasFrame::mouseReleaseEvent(QMouseEvent *ev)
{
    inDrag = false;
    QWidget::mouseReleaseEvent(ev);
}

void KasFrame::mouseDoubleClickEvent(QMouseEvent *)
{
    inDrag = false;
    minimized = !minimized;
    if(minimized){
        bar->hide();
        resize(width(), 12);
    }
    else{
        bar->show();
        slotLayoutChanged();
    }
}

void KasFrame::slotLayoutChanged()
{
    if(!minimized){
        resize(bar->width()+4, bar->height()+12);
        reposition();
        bar->move(2, 10);
    }
}

void KasFrame::reposition()
{
    QRect r(KWin::edgeClientArea());
    if(pos == TopLeft)
        move(r.left(), r.top());
    else if(pos == TopRight)
        move(r.right()-width()+1, r.top());
    else if(pos == BottomLeft)
        move(r.left(), r.bottom()-(height()+1));
    else if(pos == BottomRight)
        move(r.right()-width()+1, r.bottom()-(height()+1));
}

void KasFrame::moveMe()
{
    hide();
    QApplication::syncX();
    QValueList<QRect> rects;
    QRect r(KWin::edgeClientArea());
    rects.append(QRect(r.left(), r.top(), width(), height()));
    rects.append(QRect(r.right()-width()+1, r.top(), width(), height()));
    rects.append(QRect(r.left(), r.bottom()-(height()+1), width(), height()));
    rects.append(QRect(r.right()-width()+1, r.bottom()-(height()+1), width(), height()));
    Position newpos = (Position) UserRectSel::select(rects, pos);
    if ( newpos != pos ) {
        KConfig *config = KGlobal::config();
        config->setGroup("kasbar");
        config->writeEntry("Position", (int)newpos);
        config->sync();
        pos = newpos;
        reposition();
    }
    show();
}

KasBar::KasBar(Orientation o, QWidget* parent, const char* name )
    : QWidget(parent, name)
{
    KConfig *config = KGlobal::config();
    config->setGroup("kasbar");
    setOrientation(o);
    if ( !kwin_module )
	kwin_module = new KWinModule(this);

    /*
    maxBoxes = orient == Horizontal ?
        (QApplication::desktop()->geometry().width()-20)/BTN_EXTENT :
        (QApplication::desktop()->geometry().height()-20)/BTN_EXTENT; */

    maxBoxes = config->readNumEntry("MaxBoxes", 0);
    if(!maxBoxes){
        maxBoxes = orient == Horizontal ?
            (KWM::windowRegion(KWin::currentDesktop()).width()-20)/BTN_EXTENT :
            (KWM::windowRegion(KWin::currentDesktop()).height()-20)/BTN_EXTENT;
    }

    setFont(QFont("Helvetica", 10));
    connect( kwin_module, SIGNAL( windowAdd(WId) ), this, SLOT( windowAdd(WId) ) );
    connect( kwin_module, SIGNAL( windowRemove(WId) ), this, SLOT( windowRemove(WId) ) );
    connect( kwin_module, SIGNAL( windowChange(WId) ), this, SLOT( windowChange(WId) ) );
    connect( kwin_module, SIGNAL( windowActivate(WId) ), this, SLOT( windowActivate(WId) ) );
    connect( kwin_module, SIGNAL( desktopChange(int) ), this, SLOT( desktopChange(int) ) );
}


KasItem* KasBar::findItem( WId w )
{
    for ( KasItem* i = items.first(); i; i = items.next() ) {
        if ( i->window() == w )
            return i;
    }
    return 0;
}

void KasBar::windowAdd(WId w )
{
    if (w == topLevelWidget()->winId() || KWM::title(w) == "Kicker")
        return;
    QString s = KWM::title(w);
    if(s.right(6) == "[menu]" || s.right(7) == "[tools]")
        return;

    KasItem* i = new KasItem(w);
    items.append(i);
    updateLayout();
}

void KasBar::windowRemove(WId w )
{
    if ( w == topLevelWidget()->winId() )
	return;
    KasItem* i = findItem( w );
    if ( i ) {
	items.removeRef(i);
	delete i;
    }
    updateLayout();
}

void KasBar::windowChange(WId w)
{
    QPainter p(this);
    KasItem* i = findItem( w );

    if (i){
        i->refresh();
        repaintItem(i);
    }
}

void KasBar::windowActivate(WId w)
{
    static WId oldWin = 0;
    QPainter p(this);
    if(oldWin){
        repaintItem(findItem(oldWin));
        repaintItem(findItem(w));
    }
    else
        repaint(false);
    oldWin = w;
}

void KasBar::desktopChange(int)
{
    updateLayout();
}

void KasBar::updateLayout()
{
    static unsigned int oldR = 0, oldC = 0;
    if(!items.count()){
        resize(BTN_EXTENT, BTN_EXTENT);
        repaint(false);
        return;
    }

    unsigned int r, c;
    if(items.count() > maxBoxes){
        r = items.count()/maxBoxes;
        c = maxBoxes;
    }
    else{
        r = 1;
        c = items.count();
    }
    if(r*c < items.count()) // remainders
        ++r;

    if(oldR != r || oldC != c){
        if(orientation() == Horizontal)
            resize(c*52, r*52);
        else
            resize(r*52, c*52);
        oldR = r;
        oldC = c;
    }
    repaint(false);
}

void KasBar::drawItem(QPainter *p, KasItem *i, int x, int y)
{
    p->setPen(Qt::black);
    p->drawRect(x, y, BTN_EXTENT, BTN_EXTENT);

    qDrawShadePanel(p, x+1, y+1, BTN_EXTENT-2, BTN_EXTENT-2, colorGroup(), false,
                    1);

    p->fillRect(x+2, y+2, BTN_EXTENT-4, 13, QBrush(Qt::black));

    p->setPen(Qt::white);
    if(fontMetrics().width(i->text()) > BTN_EXTENT-4)
        p->drawText(x+2, y+2, BTN_EXTENT-4, 12, AlignLeft | AlignVCenter,
                    i->text());
    else
        p->drawText(x+2, y+2, BTN_EXTENT-4, 12, AlignCenter, i->text());

    if(!actBg){
        actBg = new KPixmap;
        actBg->resize(BTN_EXTENT-4, BTN_EXTENT-13-4);
        KPixmapEffect::gradient(*actBg, colorGroup().light(),
                                colorGroup().mid(),
                                KPixmapEffect::DiagonalGradient);
        inactBg = new KPixmap;
        inactBg->resize(BTN_EXTENT-4, BTN_EXTENT-13-4);
        KPixmapEffect::gradient(*inactBg, colorGroup().mid(),
                                colorGroup().dark(),
                                KPixmapEffect::DiagonalGradient);
    }
    if(!minPix){
        minPix = new QBitmap(8, 8, min_bits, true);
        minPix->setMask(*minPix);
        maxPix = new QBitmap(8, 8, max_bits, true);
        maxPix->setMask(*maxPix);
    }
    p->drawPixmap(x+2, y+15, KWin::activeWindow() == i->window()
                  ? *actBg : *inactBg);
    p->drawPixmap(x+4, y+16, i->icon());

    p->setPen(Qt::black);
    QString deskStr;
    deskStr.setNum(KWM::desktop(i->window()));
    p->drawText(x+BTN_EXTENT-fontMetrics().width(deskStr)-3,
                y+16+fontMetrics().ascent(), deskStr);

    if(KWin::windowState(i->window()) == KWin::NormalState)
        p->drawPixmap(x+BTN_EXTENT-11, y+BTN_EXTENT-11, *maxPix);
    else
        p->drawPixmap(x+BTN_EXTENT-11, y+BTN_EXTENT-11, *minPix);
}

void KasBar::paintEvent(QPaintEvent *ev)
{
    QRect cr;
    QPainter p(this);
    KasItem *i;
    int r=0, c=0;

    int totalcols = width()/BTN_EXTENT;
    int totalrows = height()/BTN_EXTENT;

    if(items.count()){
        for (i = items.first(); i; i = items.next()){
            if(orientation() == Horizontal){
                if(c >= totalcols){
                    c = 0; ++r;
                }
                cr.setRect(c*BTN_EXTENT, r*BTN_EXTENT, BTN_EXTENT, BTN_EXTENT);
                if(ev->rect().intersects(cr))
                    drawItem(&p, i, c*BTN_EXTENT, r*BTN_EXTENT);
                ++c;
            }
            else{
                if(r >= totalrows){
                    r = 0; ++c;
            }
                cr.setRect(c*BTN_EXTENT, r*BTN_EXTENT, BTN_EXTENT, BTN_EXTENT);
                if(ev->rect().intersects(cr))
                    drawItem(&p, i, c*BTN_EXTENT, r*BTN_EXTENT);
                ++r;
            }
        }
    }
    if(orientation() == Horizontal && c < totalcols)
        p.fillRect(c*BTN_EXTENT, r*BTN_EXTENT, width()-c*BTN_EXTENT,
                   BTN_EXTENT, colorGroup().brush(QColorGroup::Mid));
    else if(r < totalrows)
        p.fillRect(c*BTN_EXTENT, r*BTN_EXTENT, BTN_EXTENT,
                   height()-r*BTN_EXTENT, colorGroup().brush(QColorGroup::Mid));

}

void KasBar::repaintItem(KasItem *item)
{
    QPainter p(this);
    int r=0, c=0;
    KasItem *i;
    int totalcols = width()/BTN_EXTENT;
    int totalrows = height()/BTN_EXTENT;
    for (i = items.first(); i; i = items.next()){
        if(orientation() == Horizontal){
            if(c >= totalcols){
                c = 0;
                ++r;
            }
            if(i == item)
                drawItem(&p, i, c*BTN_EXTENT, r*BTN_EXTENT);
            ++c;
        }
        else{
            if(r >= totalrows){
                r = 0; ++c;
            }
            if(i == item)
                drawItem(&p, i, c*BTN_EXTENT, r*BTN_EXTENT);
            ++r;
        }
    }
}

KasItem* KasBar::itemAt(const QPoint &p)
{
    QRect cr;
    KasItem *i;
    int r=0, c=0;
    int totalcols = width()/BTN_EXTENT;
    int totalrows = height()/BTN_EXTENT;
    for (i = items.first(); i; i = items.next()){
        if(orientation() == Horizontal){
            if(c >= totalcols){
                c = 0;
                ++r;
            }
            cr.setRect(c*BTN_EXTENT, r*BTN_EXTENT, BTN_EXTENT, BTN_EXTENT);
            if(cr.contains(p))
                return(i);
            ++c;
        }
        else{
            if(r >= totalrows){
                r = 0; ++c;
            }
            cr.setRect(c*BTN_EXTENT, r*BTN_EXTENT, BTN_EXTENT, BTN_EXTENT);
            if(cr.contains(p))
                return(i);
            ++r;
        }
    }
    return(NULL);
}

void KasBar::resizeEvent(QResizeEvent *ev)
{
    QWidget::resizeEvent(ev);
    emit layoutChanged();
}

void KasBar::mousePressEvent(QMouseEvent *ev)
{
    KasItem *i = itemAt(ev->pos());
    if(i){
        if(!i->onCurrentDesktop())
            KWin::setCurrentDesktop(KWM::desktop(i->window()));
        KWin::setActiveWindow(i->window());
    }
}

KasItem::KasItem(WId w)
{
    win = w;
    refresh();
}

KasItem::~KasItem()
{
    ;
}

bool KasItem::onCurrentDesktop() const
{
    return sticky || kwin_module->currentDesktop() == desktop;
}

void KasItem::refresh()
{
    pixmap = KWM::icon( win, 32, 32 );
    if(pixmap.isNull())
        pixmap = KGlobal::iconLoader()->loadIcon("go",
		KIcon::NoGroup, KIcon::SizeMedium);
    winStr = KWM::title( win );
    desktop = KWM::desktop( win );
    sticky = KWM::isSticky( win );
}

#include "kasbar.moc"


