/* This file is part of the KDE libraries

   Copyright (C) 1999 Reginald Stadlbauer <reggie@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 as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   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., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "kcharselect.h"
#include "kcharselect.moc"

#include <tqbrush.h>
#include <tqcolor.h>
#include <tqevent.h>
#include <tqfont.h>
#include <tqfontdatabase.h>
#include <tqhbox.h>
#include <tqkeycode.h>
#include <tqlabel.h>
#include <tqpainter.h>
#include <tqpen.h>
#include <tqregexp.h>
#include <tqstyle.h>
#include <tqstylesheet.h>
#include <tqtooltip.h>
#include <tqvalidator.h>

#include <tdeapplication.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klineedit.h>
#include <tdelocale.h>

class KCharSelectTableToolTip;
class KCharSelectTable::KCharSelectTablePrivate
{
public:
    KCharSelectTableToolTip *t = nullptr;
};

class KCharSelect::KCharSelectPrivate
{
public:
    TQLineEdit *unicodeLine = nullptr;
    TQScrollBar *scrollBar = nullptr;
};

TQFontDatabase * KCharSelect::fontDataBase = 0;

void KCharSelect::cleanupFontDatabase()
{
    delete fontDataBase;
    fontDataBase = 0;
}

/******************************************************************/
/* Class: KCharSelectTableToolTip                                 */
/******************************************************************/

/**
 * A small helper class to display tooltips in KCharSelectTable .
 */
class KCharSelectTableToolTip : public TQToolTip
{
public:
    // Note: we pass TQToolTip becuse we want to display tooltips in vieport's coordinates.
    KCharSelectTableToolTip(KCharSelectTable * parent)
        : TQToolTip(parent->viewport()), cst(parent) {}

protected:
    void maybeTip( const TQPoint &pnt) {
        // Point in content coodrinates; since we don't move viewport in KCharSelectTableToolTip
        // it should be exactly the same, but to be on the safe side we assume it's not
        TQPoint cPnt = cst->viewportToContents(pnt);

        int col = cst->columnAt( cPnt.x() );
        int row = cst->rowAt( cPnt.y() );
        if ( col < 0 || row < 0 || col > cst->numCols()-1 || row > cst->numRows()-1 ) {
            return;
        }
        TQChar ch = cst->charAt( row, col );
        if (ch.isNull()) {
            return;
        }

        TQRect r = cst->cellGeometry( row, col );
        r = TQRect( cst->contentsToViewport(r.topLeft()), r.size());

        TQString hex = TQString().sprintf( "%04X", ch.unicode() );
        TQString character = TQStyleSheet::escape(ch); // Character sometimes need to be escaped

        tip(r, i18n( "Character",
                    "<qt><font size=\"+4\" face=\"%1\">%2</font>"
                    "<br>Unicode code point: U+%3"
                    "<br>(In decimal: %4)"
                    "<br>(Character: %5)"
                    "</qt>" ).arg( cst->fontName() )
                             .arg( character )
                             .arg( hex )
                             .arg( ch.unicode() )
                             .arg( character )
           );
    }
private:
    KCharSelectTable *cst;
};


/******************************************************************/
/* Class: KCharSelectTable					  */
/******************************************************************/

//==================================================================
KCharSelectTable::KCharSelectTable( TQWidget *parent, const char *name, const TQString &_font,
				    const TQChar &_chr, int _tableNum )
    : TQGridView( parent, name, TQt::WNoAutoErase ), vFont( _font ), vChr( _chr ),
      vTableNum( _tableNum ), vPos( 0, 0 ), focusItem( _chr ), focusPos( 0, 0 ),
      d(new KCharSelectTable::KCharSelectTablePrivate)
{
    // Note: when updating we are completely overpainting the widget to
    //       avoid flickering, hence we use TQt::WNoAutoErase.
    setCellWidth( 20 );
    setCellHeight( 25 );

    setNumCols( 32 );
    setNumRows( 8 );

    updateContents();

    d->t = new KCharSelectTableToolTip(this);

    setFocusPolicy( TQWidget::StrongFocus );
}

KCharSelectTable::~KCharSelectTable () {
    delete d->t;
    delete d;
}

//==================================================================
void KCharSelectTable::setFont( const TQString &_font )
{
    if(_font == vFont)
       return;
    vFont = _font;
    updateContents();
}

//==================================================================
void KCharSelectTable::setChar( const TQChar &_chr )
{
    if(_chr == vChr)
       return;
    vChr = _chr;
    updateContents();
}

//==================================================================
void KCharSelectTable::setTableNum( int _tableNum )
{
    if(_tableNum == vTableNum)
       return;
    focusItem = TQChar( _tableNum * 256 );

    vTableNum = _tableNum;
    updateContents();

    emit tableNumChanged(vTableNum);
}

//==================================================================
TQSize KCharSelectTable::sizeHint() const
{
    int w = cellWidth();
    int h = cellHeight();

    w *= numCols();
    h *= numRows();

    return TQSize( w, h );
}

//==================================================================
void KCharSelectTable::viewportResizeEvent( TQResizeEvent * e )
{
    const int new_w   = e->size().width()  / numCols();
    const int new_h   = e->size().height() / numRows();

    if( new_w !=  cellWidth())
        setCellWidth( new_w );
    if( new_h !=  cellHeight())
        setCellHeight( new_h );

    TQGridView::viewportResizeEvent(e);
}

//==================================================================
void KCharSelectTable::paintCell( class TQPainter* p, int row, int col )
{
    const int w = cellWidth();
    const int h = cellHeight();
    const int x2 = w - 1;
    const int y2 = h - 1;

    //if( row == 0 && col == 0 ) {
    //    printf("Repaint %d\n", temp++);
    //    fflush( stdout );
    //    }

    TQFont font = TQFont( vFont );
    font.setPixelSize( int(.7 * h) );

    unsigned short c = vTableNum * 256;
    c += row * numCols();
    c += col;

    if ( c == vChr.unicode() ) {
	p->setBrush( TQBrush( colorGroup().highlight() ) );
	p->setPen( NoPen );
	p->drawRect( 0, 0, w, h );
	p->setPen( colorGroup().highlightedText() );
	vPos = TQPoint( col, row );
    } else {
	TQFontMetrics fm = TQFontMetrics( font );
	if( fm.inFont( c ) )
		p->setBrush( TQBrush( colorGroup().base() ) );
	else
		p->setBrush( TQBrush( colorGroup().button() ) );
	p->setPen( NoPen );
	p->drawRect( 0, 0, w, h );
	p->setPen( colorGroup().text() );
    }

    if ( c == focusItem.unicode() && hasFocus() ) {
	style().drawPrimitive( TQStyle::PE_FocusRect, p, TQRect( 2, 2, w - 4, h - 4 ),
			       colorGroup() );
	focusPos = TQPoint( col, row );
    }

    p->setFont( font );

    p->drawText( 0, 0, x2, y2, AlignHCenter | AlignVCenter, TQString( TQChar( c ) ) );

    p->setPen( colorGroup().text() );
    p->drawLine( x2, 0, x2, y2 );
    p->drawLine( 0, y2, x2, y2 );

    if ( row == 0 )
	p->drawLine( 0, 0, x2, 0 );
    if ( col == 0 )
	p->drawLine( 0, 0, 0, y2 );
}

//==================================================================
void KCharSelectTable::contentsMousePressEvent( TQMouseEvent *e )
{
    contentsMouseMoveEvent(e);
}

//==================================================================
void KCharSelectTable::contentsMouseDoubleClickEvent ( TQMouseEvent *e )
{
    contentsMouseMoveEvent(e);
    emit doubleClicked();
}

//==================================================================
void KCharSelectTable::contentsMouseReleaseEvent( TQMouseEvent *e )
{
    contentsMouseMoveEvent( e );

    if( e->isAccepted() ) {
        emit activated( chr() );
        emit activated();
    }
}

//==================================================================
void KCharSelectTable::contentsMouseMoveEvent( TQMouseEvent *e )
{
    const int row = rowAt( e->y() );
    const int col = columnAt( e->x() );
    if ( row >= 0 && row < numRows() && col >= 0 && col < numCols() ) {
	const TQPoint oldPos = vPos;

	vPos.setX( col );
	vPos.setY( row );

	vChr = charAt( vPos.y(), vPos.x() );

	const TQPoint oldFocus = focusPos;

	focusPos = vPos;
	focusItem = vChr;

	updateCell( oldFocus.y(), oldFocus.x() );
	updateCell( oldPos.y(),   oldPos.x()   );
	updateCell( vPos.y(),     vPos.x()     );

	emit highlighted( vChr );
	emit highlighted();

	emit focusItemChanged( focusItem );
	emit focusItemChanged();

        e->accept();
    } else {
        e->ignore();
    }
}

//==================================================================
void KCharSelectTable::keyPressEvent( TQKeyEvent *e )
{
    switch ( e->key() ) {
    case Key_Left:
	gotoLeft();
	break;
    case Key_Right:
	gotoRight();
	break;
    case Key_Up:
	gotoUp();
	break;
    case Key_Down:
	gotoDown();
	break;
    case Key_Next:
        if ( tableNum() < 255 ) {
            setTableNum( tableNum() + 1 );
        }
	break;
    case Key_Prior:
        if ( tableNum() > 0 ) {
            setTableNum( tableNum() - 1 );
        }
	break;
    case Key_Space:
	emit activated( ' ' );
	emit activated();
	emit highlighted( ' ' );
	emit highlighted();
        break;
    case Key_Enter: case Key_Return: {
	const TQPoint oldPos = vPos;

	vPos = focusPos;
	vChr = focusItem;

	updateCell( oldPos.y(), oldPos.x() );
	updateCell( vPos.y(),   vPos.x()   );

	emit activated( vChr );
	emit activated();
	emit highlighted( vChr );
	emit highlighted();
    } break;
    }
}

//==================================================================
void KCharSelectTable::gotoLeft()
{
    if ( focusPos.x() > 0 ) {
        doGoto(-1, 0);
    }
}

//==================================================================
void KCharSelectTable::gotoRight()
{
    if ( focusPos.x() < numCols()-1 ) {
        doGoto(1, 0);
    }
}

//==================================================================
void KCharSelectTable::gotoUp()
{
    if ( focusPos.y() > 0 ) {
        doGoto(0, -1);
    } else if ( tableNum() > 0 ) {
        emit tableNumChanged(--vTableNum);
        doGoto(0, numRows()-1);
        repaintContents( false );
    }
}

//==================================================================
void KCharSelectTable::gotoDown()
{
    if ( focusPos.y() < numRows()-1 ) {
        doGoto(0, +1);
    } else if ( tableNum() < 255 ) {
        emit tableNumChanged(++vTableNum);
        doGoto(0, -(numRows()-1));
        repaintContents( false );
    }
}

//==================================================================
void KCharSelectTable::doGoto(int dx, int dy)
{
    TQPoint oldPos = focusPos;
    focusPos += TQPoint(dx, dy);
    focusItem = charAt( focusPos.y(), focusPos.x() );

    updateCell( oldPos.y(),   oldPos.x()   );
    updateCell( focusPos.y(), focusPos.x() );

    emit focusItemChanged( vChr );
    emit focusItemChanged();
}

//==================================================================
TQChar KCharSelectTable::charAt(int row, int col) const
{
    return TQChar( vTableNum * 256 + numCols() * row + col );
}

/******************************************************************/
/* Class: KCharSelect						  */
/******************************************************************/

//==================================================================
KCharSelect::KCharSelect( TQWidget *parent, const char *name, const TQString &_font, const TQChar &_chr, int _tableNum )
  : TQVBox( parent, name ), d(new KCharSelectPrivate)
{
    setSpacing( KDialog::spacingHint() );
    TQHBox* const bar = new TQHBox( this );
    bar->setSpacing( KDialog::spacingHint() );

    TQLabel* const lFont = new TQLabel( i18n( "Font:" ), bar );
    lFont->resize( lFont->sizeHint() );
    lFont->setAlignment( TQt::AlignRight | TQt::AlignVCenter );
    lFont->setMaximumWidth( lFont->sizeHint().width() );

    fontCombo = new TQComboBox( true, bar );
    fillFontCombo();
    fontCombo->resize( fontCombo->sizeHint() );

    connect( fontCombo, TQ_SIGNAL( activated( const TQString & ) ), this, TQ_SLOT( fontSelected( const TQString & ) ) );

    TQLabel* const lTable = new TQLabel( i18n( "Table:" ), bar );
    lTable->resize( lTable->sizeHint() );
    lTable->setAlignment( TQt::AlignRight | TQt::AlignVCenter );
    lTable->setMaximumWidth( lTable->sizeHint().width() );

    tableSpinBox = new TQSpinBox( 0, 255, 1, bar );
    tableSpinBox->resize( tableSpinBox->sizeHint() );

    TQLabel* const lUnicode = new TQLabel( i18n( "&Unicode code point:" ), bar );
    lUnicode->resize( lUnicode->sizeHint() );
    lUnicode->setAlignment( TQt::AlignRight | TQt::AlignVCenter );
    lUnicode->setMaximumWidth( lUnicode->sizeHint().width() );

    const TQRegExp rx( "[a-fA-F0-9]{1,4}" );
    TQValidator* const validator = new TQRegExpValidator( rx, this );

    d->unicodeLine = new KLineEdit( bar );
    d->unicodeLine->setValidator(validator);
    lUnicode->setBuddy(d->unicodeLine);
    d->unicodeLine->resize( d->unicodeLine->sizeHint() );
    slotUpdateUnicode(_chr);

    connect( d->unicodeLine, TQ_SIGNAL( returnPressed() ), this, TQ_SLOT( slotUnicodeEntered() ) );

    TQHBox* const box = new TQHBox(this);
    box->setSpacing(0);

    charTable = new KCharSelectTable( box, name, _font.isEmpty() ? TQString(TQVBox::font().family()) : _font, _chr, _tableNum );
    const TQSize sz( charTable->contentsWidth()  +  4 ,
                    charTable->contentsHeight() +  4 );
    charTable->resize( sz );
    //charTable->setMaximumSize( sz );
    charTable->setMinimumSize( sz );
    charTable->setHScrollBarMode( TQScrollView::AlwaysOff );
    charTable->setVScrollBarMode( TQScrollView::AlwaysOff );
    charTable->installEventFilter( this );

    d->scrollBar = new TQScrollBar(0, 255, 1, 1, 0, TQt::Vertical, box);

    setFont( _font.isEmpty() ? TQString(TQVBox::font().family()) : _font );
    setTableNum( _tableNum );

    connect( tableSpinBox, TQ_SIGNAL( valueChanged( int ) ), this, TQ_SLOT( tableChanged( int ) ) );
    connect( d->scrollBar, TQ_SIGNAL( valueChanged( int ) ), this, TQ_SLOT( tableChanged( int ) ) );
    connect( charTable, TQ_SIGNAL( tableNumChanged( int ) ), this, TQ_SLOT( tableChanged( int ) ) );

    connect( charTable, TQ_SIGNAL( highlighted( const TQChar & ) ), this, TQ_SLOT( slotUpdateUnicode( const TQChar & ) ) );
    connect( charTable, TQ_SIGNAL( highlighted( const TQChar & ) ), this, TQ_SLOT( charHighlighted( const TQChar & ) ) );
    connect( charTable, TQ_SIGNAL( highlighted() ), this, TQ_SLOT( charHighlighted() ) );
    connect( charTable, TQ_SIGNAL( activated( const TQChar & ) ), this, TQ_SLOT( charActivated( const TQChar & ) ) );
    connect( charTable, TQ_SIGNAL( activated() ), this, TQ_SLOT( charActivated() ) );
    connect( charTable, TQ_SIGNAL( focusItemChanged( const TQChar & ) ),
	     this, TQ_SLOT( charFocusItemChanged( const TQChar & ) ) );
    connect( charTable, TQ_SIGNAL( focusItemChanged() ), this, TQ_SLOT( charFocusItemChanged() ) );

    connect( charTable, TQ_SIGNAL(doubleClicked()),this,TQ_SLOT(slotDoubleClicked()));

    setFocusPolicy( TQWidget::StrongFocus );
    setFocusProxy( charTable );
}

KCharSelect::~KCharSelect()
{
    delete d;
}

//==================================================================
TQSize KCharSelect::sizeHint() const
{
    return TQVBox::sizeHint();
}

//==================================================================
void KCharSelect::setFont( const TQString &_font )
{
    const TQValueList<TQString>::Iterator it = fontList.find( _font );
    if ( it != fontList.end() ) {
	TQValueList<TQString>::Iterator it2 = fontList.begin();
	int pos = 0;
	for ( ; it != it2; ++it2, ++pos);
	fontCombo->setCurrentItem( pos );
	charTable->setFont( _font );
    }
    else
	kdWarning() << "Can't find Font: " << _font << endl;
}

//==================================================================
void KCharSelect::setChar( const TQChar &_chr )
{
    charTable->setChar( _chr );
    slotUpdateUnicode( _chr );
}

//==================================================================
void KCharSelect::setTableNum( int _tableNum )
{
    tableSpinBox->setValue( _tableNum );
    d->scrollBar->setValue( _tableNum );
    charTable->setTableNum( _tableNum );
}

//==================================================================
void KCharSelect::fillFontCombo()
{
    if ( !fontDataBase ) {
	fontDataBase = new TQFontDatabase();
	tqAddPostRoutine( cleanupFontDatabase );
    }
    fontList=fontDataBase->families();
    fontCombo->insertStringList( fontList );
}

//==================================================================
void KCharSelect::fontSelected( const TQString &_font )
{
    charTable->setFont( _font );
    emit fontChanged( _font );
}

//==================================================================
void KCharSelect::tableChanged( int _value )
{
    setTableNum( _value );
}

//==================================================================
void KCharSelect::slotUnicodeEntered( )
{
    const TQString s = d->unicodeLine->text();
    if (s.isEmpty())
        return;

    bool ok;
    const int uc = s.toInt(&ok, 16);
    if (!ok)
        return;

    const int table = uc / 256;
    charTable->setTableNum( table );
    tableSpinBox->setValue(table);
    d->scrollBar->setValue(table);
    const TQChar ch(uc);
    charTable->setChar( ch );
    charActivated( ch );
}

//==================================================================
void KCharSelect::slotUpdateUnicode( const TQChar &c )
{
    const int uc = c.unicode();
    TQString s;
    s.sprintf("%04X", uc);
    d->unicodeLine->setText(s);
}

//==================================================================
bool KCharSelect::eventFilter( TQObject *obj, TQEvent *e )
{
    if ( obj == charTable && e->type() == TQEvent::Wheel ) {
        // just pass charTable's mouse wheel events to the scrollBar
        return TQApplication::sendEvent( d->scrollBar, e );
    }
    return false;
}

//==================================================================
void KCharSelectTable::virtual_hook( int, void*)
{ /*BASE::virtual_hook( id, data );*/ }

void KCharSelect::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }

