/*
    Rosegarden
    A MIDI and audio sequencer and musical notation editor.
 
    This program is Copyright 2000-2008
        Guillaume Laurent   <glaurent@telegraph-road.org>,
        Chris Cannam        <cannam@all-day-breakfast.com>,
        Richard Bown        <richard.bown@ferventsoftware.com>
 
    The moral rights of Guillaume Laurent, Chris Cannam, and Richard
    Bown to claim authorship of this work have been asserted.
 
    Other copyrights also apply to some parts of this work.  Please
    see the AUTHORS file and individual file headers for details.
 
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/


#include "FontViewFrame.h"
#include <tdeapplication.h>

#include <tdelocale.h>
#include <tdemessagebox.h>
#include <tqfontmetrics.h>
#include <tqframe.h>
#include <tqsize.h>
#include <tqstring.h>
#include <tqwidget.h>
#include <tqpainter.h>

#ifdef HAVE_XFT
#include <ft2build.h>
#include FT_FREETYPE_H 
#include FT_OUTLINE_H
#include FT_GLYPH_H
#include <X11/Xft/Xft.h>
#endif

namespace Rosegarden
{

FontViewFrame::FontViewFrame( int pixelSize, TQWidget* parent, const char* name ) :
        TQFrame(parent, name),
        m_fontSize(pixelSize),
        m_tableFont(0)
{
    setBackgroundMode(PaletteBase);
    setFrameStyle(Panel | Sunken);
    setMargin(8);
    setRow(0);
}

FontViewFrame::~FontViewFrame()
{
    // empty
}

void
FontViewFrame::setFont(TQString font)
{
    m_fontName = font;
    loadFont();
    update();
}

void
FontViewFrame::loadFont()
{
#ifdef HAVE_XFT
    if (m_tableFont) {
        XftFontClose(this->x11AppDisplay(), (XftFont *)m_tableFont);
    }
    m_tableFont = 0;

    static bool haveDir = false;
    if (!haveDir) {
        FcConfigAppFontAddDir(FcConfigGetCurrent(),
                              (const FcChar8 *)"/opt/trinity/share/apps/rosegarden/fonts");
        haveDir = true;
    }

    FcPattern *pattern = FcPatternCreate();
    FcPatternAddString(pattern, FC_FAMILY, (FcChar8 *)m_fontName.latin1());
    FcPatternAddInteger(pattern, FC_PIXEL_SIZE, m_fontSize);

    FcConfigSubstitute(FcConfigGetCurrent(), pattern, FcMatchPattern);

    FcResult result = FcResultMatch;
    FcPattern *match = FcFontMatch(FcConfigGetCurrent(), pattern, &result);
    FcPatternDestroy(pattern);

    if (!match || result != FcResultMatch) {
        KMessageBox::error(this, i18n("Error: Unable to match font name %1").arg(m_fontName));
        return ;
    }

    FcChar8 *matchFamily;
    FcPatternGetString(match, FC_FAMILY, 0, &matchFamily);

    if (TQString((const char *)matchFamily).lower() != m_fontName.lower()) {
        KMessageBox::sorry(this, i18n("Warning: No good match for font name %1 (best is %2)").
                           arg(m_fontName).arg(TQString((const char *)matchFamily)));
        m_fontName = (const char *)matchFamily;
    }

    m_tableFont = XftFontOpenPattern(this->x11AppDisplay(), match);

    if (!m_tableFont) {
        KMessageBox::error(this, i18n("Error: Unable to open best-match font %1").
                           arg(TQString((const char *)matchFamily)));
    }
#endif
}

void FontViewFrame::setGlyphs(bool glyphs)
{
    m_glyphs = glyphs;
    update();
}

TQSize FontViewFrame::sizeHint() const
{
    return TQSize(16 * m_fontSize * 3 / 2 + margin() + 2 * frameWidth(),
                 16 * m_fontSize * 3 / 2 + margin() + 2 * frameWidth());
}

TQSize FontViewFrame::cellSize() const
{
    TQFontMetrics fm = fontMetrics();
    return TQSize( fm.maxWidth(), fm.lineSpacing() + 1 );
}

void FontViewFrame::paintEvent( TQPaintEvent* e )
{
#ifdef HAVE_XFT
    if (!m_tableFont)
        return ;

    TQFrame::paintEvent(e);
    TQPainter p(this);

    int ll = 25;
    int ml = frameWidth() + margin() + ll + 1;
    int mt = frameWidth() + margin();
    TQSize cell((width() - 16 - ml) / 17, (height() - 16 - mt) / 17);

    if ( !cell.width() || !cell.height() )
        return ;

    TQColor body(255, 255, 192);
    TQColor negative(255, 192, 192);
    TQColor positive(192, 192, 255);
    TQColor rnegative(255, 128, 128);
    TQColor rpositive(128, 128, 255);

    Drawable drawable = (Drawable)handle();
    XftDraw *draw = XftDrawCreate(this->x11AppDisplay(), drawable,
                                  (Visual *)this->x11Visual(), this->x11Colormap());

    TQColor pen(TQt::black);
    XftColor col;
    col.color.red = pen.red () | pen.red() << 8;
    col.color.green = pen.green () | pen.green() << 8;
    col.color.blue = pen.blue () | pen.blue() << 8;
    col.color.alpha = 0xffff;
    col.pixel = pen.pixel();

    for (int j = 0; j <= 16; j++) {
        for (int i = 0; i <= 16; i++) {

            int x = i * cell.width();
            int y = j * cell.height();

            x += ml;
            y += mt; // plus ascent

            if (i == 0) {
                if (j == 0)
                    continue;
                p.setFont(kapp->font());
                TQFontMetrics afm(kapp->font());
                TQString s = TQString("%1").arg(m_row * 256 + (j - 1) * 16);
                p.drawText(x - afm.width(s), y, s);
                p.setPen(TQColor(190, 190, 255));
                p.drawLine(0, y, width(), y);
                p.setPen(TQt::black);
                continue;
            } else if (j == 0) {
                p.setFont(kapp->font());
                TQString s = TQString("%1").arg(i - 1);
                p.drawText(x, y, s);
                p.setPen(TQColor(190, 190, 255));
                p.drawLine(x, 0, x, height());
                p.setPen(TQt::black);
                continue;
            }

            p.save();

            if (m_glyphs) {
                FT_UInt ui = m_row * 256 + (j - 1) * 16 + i - 1;
                XftDrawGlyphs(draw, &col, (XftFont *)m_tableFont, x, y, &ui, 1);
            } else {
                FcChar32 ch = m_row * 256 + (j - 1) * 16 + i - 1;
                if (XftCharExists(this->x11AppDisplay(), (XftFont *)m_tableFont, ch)) {
                    XftDrawString32(draw, &col, (XftFont *)m_tableFont, x, y, &ch, 1);
                }
            }

            p.restore();
        }
    }
#endif
}

bool
FontViewFrame::hasRow(int r) const
{
#ifdef HAVE_XFT
    if (m_glyphs) {

        if (r < 256)
            return true;

    } else {

        for (int c = 0; c < 256; ++c) {
            FcChar32 ch = r * 256 + c;
            if (XftCharExists(x11AppDisplay(), (XftFont *)m_tableFont, ch)) {
                return true;
            }
        }
    }
#endif
    return false;
}

void FontViewFrame::setRow(int row)
{
    m_row = row;
    update();
}

}
#include "FontViewFrame.moc"
