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

Copyright (c) 2000-2001 Matthias Ettrich <ettrich@kde.org>
              2000-2001 Matthias Elter   <elter@kde.org>
              2001      Carsten Pfeiffer <pfeiffer@kde.org>
              2001      Martijn Klingens <mklingens@yahoo.com>

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 <qcursor.h>

#include <krun.h>
#include <kglobal.h>
#include <kapplication.h>
#include <klocale.h>
#include <kwinmodule.h>
#include <kconfig.h>
#include <kdebug.h>

#include "systemtrayapplet.h"
#include "systemtrayapplet.moc"

#include <X11/Xlib.h>

extern "C"
{
    KPanelApplet* init(QWidget *parent, const QString& configFile)
    {
        KGlobal::locale()->insertCatalogue("ksystemtrayapplet");
        return new SystemTrayApplet(configFile, KPanelApplet::Normal,
                                    0, parent, "ksystemtrayapplet");
    }
}

SystemTrayApplet::SystemTrayApplet(const QString& configFile, Type type, int actions,
                                   QWidget *parent, const char *name)
  : KPanelApplet(configFile, type, actions, parent, name),
    showFrame(false)
{
    KConfig *conf = config();
    conf->setGroup("General");
    KConfig *globalConf = KGlobal::config();
    globalConf->setGroup("General");

    if (conf->readBoolEntry( "ShowPanelFrame", false ))
    {
        setFrameStyle(Panel | Sunken);
    }
    else if (globalConf->readBoolEntry("FadeOutAppletHandles", false) ||
             globalConf->readBoolEntry("HideAppletHandles", false))
    {
        // only do the "show on hover" trick with the frame when we DON'T have handles
        showFrame = true;
    }

    m_Wins.setAutoDelete(true);
    setBackgroundOrigin(AncestorOrigin);

    kwin_module = new KWinModule(this);

    // register existing tray windows
    const QValueList<WId> systemTrayWindows = kwin_module->systemTrayWindows();
    bool existing = false;
    for (QValueList<WId>::ConstIterator it = systemTrayWindows.begin(); it!=systemTrayWindows.end(); ++it ) {
        embedWindow( *it, true );
        existing = true;
    }
    if (existing)
        layoutTray();

    // the KWinModule notifies us when tray windows are added or removed
    connect( kwin_module, SIGNAL( systemTrayWindowAdded(WId) ),
             this, SLOT( systemTrayWindowAdded(WId) ) );
    connect( kwin_module, SIGNAL( systemTrayWindowRemoved(WId) ),
             this, SLOT( updateTrayWindows() ) );

    QCString screenstr;
    screenstr.setNum(qt_xscreen());
    QCString trayatom = "_NET_SYSTEM_TRAY_S" + screenstr;

    Display *display = qt_xdisplay();

    net_system_tray_selection = XInternAtom( display, trayatom, FALSE );
    net_system_tray_opcode = XInternAtom( display, "_NET_SYSTEM_TRAY_OPCODE", FALSE );

    // Acquire system tray
    XSetSelectionOwner(display,
                       net_system_tray_selection,
                       winId(),
                       CurrentTime);

    WId root = qt_xrootwin();

    if (XGetSelectionOwner (display, net_system_tray_selection) == winId())
    {
        XClientMessageEvent xev;

        xev.type = ClientMessage;
        xev.window = root;

        xev.message_type = XInternAtom (display, "MANAGER", False);
        xev.format = 32;
        xev.data.l[0] = CurrentTime;
        xev.data.l[1] = net_system_tray_selection;
        xev.data.l[2] = winId();
        xev.data.l[3] = 0;        /* manager specific data */
        xev.data.l[4] = 0;        /* manager specific data */

        XSendEvent (display, root, False, StructureNotifyMask, (XEvent *)&xev);
    }
}

SystemTrayApplet::~SystemTrayApplet()
{
    m_Wins.clear();
    KGlobal::locale()->removeCatalogue("ksystemtrayapplet");
}

bool SystemTrayApplet::x11Event( XEvent *e )
{
#define SYSTEM_TRAY_REQUEST_DOCK    0
#define SYSTEM_TRAY_BEGIN_MESSAGE   1
#define SYSTEM_TRAY_CANCEL_MESSAGE  2
    if ( e->type == ClientMessage ) {
        if ( e->xclient.message_type == net_system_tray_opcode &&
             e->xclient.data.l[1] == SYSTEM_TRAY_REQUEST_DOCK) {
            for (QXEmbed* emb = m_Wins.first(); emb != 0L; emb = m_Wins.next())
                if( emb->embeddedWinId() == (WId)e->xclient.data.l[2] ) // we already manage it
                    return true;
            embedWindow( e->xclient.data.l[2], false );
            layoutTray();
            emit updateLayout();
            return true;
        }
    }
    return KPanelApplet::x11Event( e ) ;
}

void SystemTrayApplet::enterEvent( QEvent * )
{
    /*
     * NOTE: This doesn't actually work as one would expect.  Since system tray
     * icons are actually separate windows (or something like that) enter and
     * leave events are triggered when the mouse goes over the icons.
     *
     * This makes it possible to "skip" over the window (i.e. leave the system
     * tray while a popup menu from one of the systray icons is active) and no
     * leave event will be sent, thus leaving the border shown.
     */

    if ( showFrame && ( frameStyle() == NoFrame ) )
    {
        setFrameStyle( Panel|Sunken );
        repaint();
    }
}

void SystemTrayApplet::leaveEvent( QEvent * )
{
    if ( showFrame && !geometry().contains( mapFromGlobal( QCursor::pos() ) ) )
    {
        setFrameStyle( NoFrame );
        repaint();
    }
}

void SystemTrayApplet::systemTrayWindowAdded( WId w )
{
    for (QXEmbed* emb = m_Wins.first(); emb != 0L; emb = m_Wins.next())
        if( emb->embeddedWinId() == w ) // we already manage it
            return;
    embedWindow( w, true );
    layoutTray();
    emit updateLayout();
}

void SystemTrayApplet::embedWindow( WId w, bool kde_tray )
{
    TrayEmbed* emb = new TrayEmbed(kde_tray,this);
    emb->setAutoDelete(false);
    emb->setBackgroundOrigin(AncestorOrigin);
    emb->setBackgroundMode(X11ParentRelative);

    if( kde_tray )
    {
        static Atom hack_atom = XInternAtom( qt_xdisplay(), "_KDE_SYSTEM_TRAY_EMBEDDING", False );
        XChangeProperty( qt_xdisplay(), w, hack_atom, hack_atom, 32, PropModeReplace, NULL, 0 );
        emb->embed(w);
        XDeleteProperty( qt_xdisplay(), w, hack_atom );
    }
    else
        emb->embed(w);
        
    if( emb->embeddedWinId() == 0 ) // error embedding
    {
        delete emb;
        return;
    }

    m_Wins.append(emb);
    connect(emb, SIGNAL(embeddedWindowDestroyed()), SLOT(updateTrayWindows()));
    emb->resize(24, 24);
    emb->show();
}

void SystemTrayApplet::updateTrayWindows()
{
    TrayEmbed* emb = m_Wins.first();
    while ((emb = m_Wins.current()) != 0L) {
        WId wid = emb->embeddedWinId();
        if ((wid == 0)
             || ( emb->kdeTray() && !kwin_module->systemTrayWindows().contains(wid)))
        {
//            emb->setMapAfterRelease( false ); // don't map, they went away on their own
            m_Wins.remove(emb);
        }
        else
            m_Wins.next();
    }
    layoutTray();
    emit updateLayout();
}

int SystemTrayApplet::maxIconWidth() const
{
    int largest = 24;
    for (TrayEmbedList::const_iterator emb = m_Wins.begin(); emb != m_Wins.end(); ++emb)
    {
        if (*emb == 0)
        {
            continue;
        }

        int width = (*emb)->sizeHint().width();
        if (width > largest)
        {
            largest = width;
        }
    }

    return largest;
}

int SystemTrayApplet::maxIconHeight() const
{
    int largest = 24;
    for (TrayEmbedList::const_iterator emb = m_Wins.begin(); emb != m_Wins.end(); ++emb)
    {
        if (*emb == 0)
        {
            continue;
        }

        int height = (*emb)->sizeHint().height();
        if (height > largest)
        {
            largest = height;
        }
    }

    return largest;
}

int SystemTrayApplet::widthForHeight(int h) const
{
    int iconWidth = maxIconWidth(), iconHeight = maxIconHeight();

    if (h < iconHeight)
    {
        // avoid div by 0 later
        h = iconHeight;
    }

    int ret = ( ( ( m_Wins.count() - 1 ) / ( h / iconHeight ) ) + 1 ) * iconWidth + 4;

    if (ret < iconWidth + 4)
    {
        ret = 0;
    }

    return ret;
}

int SystemTrayApplet::heightForWidth(int w) const
{
    int iconWidth = maxIconWidth(), iconHeight = maxIconHeight();

    if (w < iconWidth)
    {
        // avoid div by 0 later
        w = iconWidth;
    }
    int ret = ( ( ( m_Wins.count() - 1 ) / ( w / iconWidth ) ) + 1 ) * iconHeight + 4;

    if (ret < iconHeight + 4)
    {
        ret = 0;
    }

    return ret;
}

void SystemTrayApplet::resizeEvent( QResizeEvent* )
{
    layoutTray();
}

void SystemTrayApplet::layoutTray()
{
    if (m_Wins.count() == 0)
        return;

    /* heightWidth = height or width in pixels (depends on orientation())
     * nbrOfLines = number of rows or cols (depends on orientation())
     * spacing = size of spacing in pixels between lines (rows or cols) 
     * line = what line to draw an icon in */
    int i = 0, line, spacing, nbrOfLines, heightWidth; 

    int iconWidth = maxIconWidth(), iconHeight = maxIconHeight();

    QXEmbed* emb;
    int col = 0; // col = column och row, depends on orientation(), the opposit direction of line

    if (orientation() == Vertical) {
        heightWidth = width();
        heightWidth = heightWidth < iconWidth ? iconWidth : heightWidth; // to avoid nbrOfLines=0
        nbrOfLines = heightWidth / iconWidth;
        spacing = ( heightWidth - iconWidth*nbrOfLines ) / ( nbrOfLines + 1 );
        for (emb = m_Wins.first(); emb != 0L; emb = m_Wins.next()) {
            line = i % nbrOfLines;
            emb->move( spacing*(line+1) + line*iconWidth, 2 + col*iconHeight );
            if ( line + 1 == nbrOfLines )
                col++;
            i++;
        }
    }
    else {
        heightWidth = height();
        heightWidth = heightWidth < iconHeight ? iconHeight : heightWidth; // to avoid nbrOfLines=0
        nbrOfLines = heightWidth / iconHeight;
        spacing = ( heightWidth - iconHeight*nbrOfLines ) / ( nbrOfLines + 1 );
        for (emb = m_Wins.first(); emb != 0L; emb = m_Wins.next()) {
            line = i % nbrOfLines; 
            emb->move( 2 + col*iconWidth, spacing*(line+1) + line*iconHeight );
            if ( line + 1 == nbrOfLines )
                col++;
            i++;
        }
    }
    updateGeometry();
}

void SystemTrayApplet::paletteChange(const QPalette & /* oldPalette */)
{
    for (QXEmbed* emb = m_Wins.first(); emb != 0L; emb = m_Wins.next()) {
        emb->hide();
        emb->show();
    }
}

TrayEmbed::TrayEmbed( bool kdeTray, QWidget* parent )
    : QXEmbed( parent ), kde_tray( kdeTray )
{
//    if( kde_tray ) // after QXEmbed reparents windows to the root window as unmapped.
//        setMapAfterRelease( true ); // systray one will have to be made visible somehow
}
