/* This file is part of the KDE project
   Copyright (C) 2001 Simon Hausmann <hausmann@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the Artistic License.
*/


#include "topic.h"

#include <qapplication.h>
#include <qtimer.h>

KSircTopic::KSircTopic( QWidget *parent, const char *name )
    : QLabel( parent, name )
{
    m_editor = 0;
    m_doEdit = false;
    setBackgroundColor( colorGroup().light() );
    setFrameStyle( QFrame::StyledPanel | QFrame::Sunken );
    setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum ) );
    setTextFormat( PlainText );
    setAlignment( alignment() | WordBreak );
}

void KSircTopic::mouseDoubleClickEvent( QMouseEvent * )
{
    m_doEdit = true;
}

void KSircTopic::mouseReleaseEvent( QMouseEvent * )
{
    if ( m_doEdit ) {
        m_doEdit = false;

        if ( m_editor )
            return;

        m_editor = new KSircTopicEditor( this );
        m_editor->setGeometry( geometry() );
        m_editor->setText( text() );
        m_editor->setFocus();
        m_editor->show();

        connect( m_editor, SIGNAL( returnPressed() ),
                 this, SLOT( setNewTopic() ) );
    }
}

void KSircTopic::setNewTopic()
{
    QString topic = m_editor->text();
    QTimer::singleShot( 0, m_editor, SLOT( close() ) );
    setText( topic );
    emit topicChange( topic );
}

KSircTopicEditor::KSircTopicEditor( QWidget *parent, const char *name )
    : QLineEdit( parent, name )
{
    setWFlags( WDestructiveClose );
    setFocusPolicy( QWidget::ClickFocus );
}

void KSircTopicEditor::keyPressEvent( QKeyEvent *ev )
{
    if ( ev->key() == Key_Escape )
    {
        ev->accept();
        QTimer::singleShot( 0, this, SLOT( close() ) );
        return;
    }
    QLineEdit::keyPressEvent( ev );
}

void KSircTopicEditor::focusOutEvent( QFocusEvent * )
{
    // we don't want to quit editing when someone brings up QLE's popup
    // menu
    if ( QFocusEvent::reason() == QFocusEvent::Popup  )
    {
        QWidget *focusw = qApp->focusWidget();
        if ( focusw && m_popup && focusw == m_popup )
            return;
    }

    QTimer::singleShot( 0, this, SLOT( close() ) );
}

QPopupMenu *KSircTopicEditor::createPopupMenu()
{
    QPopupMenu *popup = QLineEdit::createPopupMenu();
    m_popup = popup;
    return popup;
}

#include "topic.moc"
