/****************************************************************************
** $Id: qmime_pm.cpp 8 2005-11-16 19:36:46Z dmik $
**
** Implementation of OS/2 PM MIME <-> clipboard converters
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
** Copyright (C) 2004 Norman ASA.  Initial OS/2 Port.
** Copyright (C) 2005 netlabs.org.  Further OS/2 Development.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#include "qmime.h"

#ifndef QT_NO_MIME

#include "qstrlist.h"
#include "qimage.h"
#include "qdatastream.h"
#include "qdragobject.h"
#include "qbuffer.h"
#include "qapplication_p.h"
#include "qtextcodec.h"
#include "qregexp.h"
#include "qt_os2.h"


static QPtrList<QPMMime> mimes;

/*!
  \class QPMMime qmime.h
  \brief The QPMMime class maps open-standard MIME to OS/2 PM Clipboard formats.
  \ingroup io
  \ingroup draganddrop
  \ingroup misc

  Qt's drag-and-drop and clipboard facilities use the MIME standard.
  On X11, this maps trivially to the Xdnd protocol, but on OS/2
  although some applications use MIME types to describe clipboard
  formats, others use arbitrary non-standardized naming conventions,
  or unnamed built-in formats of OS/2.

  By instantiating subclasses of QPMMime that provide conversions
  between OS/2 PM Clipboard and MIME formats, you can convert
  proprietary clipboard formats to MIME formats.

  Qt has predefined support for the following OS/2 PM Clipboard formats:
  \list
    \i CF_TEXT - converted to "text/plain;charset=system" or "text/plain"
	    and supported by QTextDrag.
    \i CF_BITMAP - converted to "image/*", where * is
		a \link QImage::outputFormats() Qt image format\endlink,
	    and supported by QImageDrag.
  \endlist

  An example use of this class would be to map the OS/2 Metafile
  clipboard format (CF_METAFILE) to and from the MIME type "image/x-metafile".
  This conversion might simply be adding or removing a header, or even
  just passing on the data.  See the
  \link dnd.html Drag-and-Drop documentation\endlink for more information
  on choosing and definition MIME types.

  You can check if a MIME type is convertible using canConvert() and
  can perform conversions with convertToMime() and convertFromMime().
*/

/*!
  Constructs a new conversion object, adding it to the globally accessed
  list of available convertors.
*/
QPMMime::QPMMime()
{
    mimes.append( this );
}

/*!
  Destroys a conversion object, removing it from the global
  list of available convertors.
*/
QPMMime::~QPMMime()
{
    mimes.remove( this );
}



struct QPMRegisteredMimeType {
    QPMRegisteredMimeType( ulong c, const char *m ) :
	cf( c ), mime( m ) {}
    ulong cf;
    QCString mime;
};

static QPtrList<QPMRegisteredMimeType> mimetypes;


class QPMMimeAnyMime : public QPMMime {
public:
    const char* convertorName();
    int countCf();
    ulong cf( int index );
    ulong flFor( ulong cf );
    ulong cfFor( const char* mime );
    const char* mimeFor( ulong cf );
    bool canConvert( const char* mime, ulong cf );
    QByteArray convertToMime( QByteArray data, const char *, ulong );
    QByteArray convertFromMime( QByteArray data, const char *, ulong );
};

const char* QPMMimeAnyMime::convertorName()
{
    return "Any-Mime";
}

int QPMMimeAnyMime::countCf()
{
    return mimetypes.count();
}

ulong QPMMimeAnyMime::cf( int index )
{
    return mimetypes.at( index )->cf;
}

ulong QPMMimeAnyMime::flFor( ulong cf )
{
    // all formats in this converter assume CFI_POINTER data storage type
    return CFI_POINTER;
}

ulong QPMMimeAnyMime::cfFor( const char* mime )
{
    QPMRegisteredMimeType *mt = mimetypes.current();
    if ( mt ) // quick check with most-recent
	if ( qstricmp( mt->mime, mime ) == 0 )
            return mt->cf;
    for ( mt = mimetypes.first(); mt; mt = mimetypes.next() )
	if ( qstricmp( mt->mime, mime ) == 0 )
	    return mt->cf;
    // try to register the mime type
    return registerMimeType( mime );
}

const char* QPMMimeAnyMime::mimeFor( ulong cf )
{
    QPMRegisteredMimeType *mt = mimetypes.current();
    if ( mt ) // quick check with most-recent
	if ( mt->cf == cf )
	    return mt->mime;
    for ( mt = mimetypes.first(); mt; mt = mimetypes.next() )
	if ( mt->cf == cf )
	    return mt->mime;
    return 0;
}

bool QPMMimeAnyMime::canConvert( const char* mime, ulong cf )
{
    QPMRegisteredMimeType *mt = mimetypes.current();
    do {
        if ( mt ) // quick check with most-recent
            if ( mt->cf == cf )
                break;
        for ( mt = mimetypes.first(); mt; mt = mimetypes.next() )
            if ( mt->cf == cf )
                break;
        if ( !mt ) {
            ulong f = registerMimeType( mime );
            return f && f == cf;
        }
    } while ( 0 );

    return qstricmp( mt->mime, mime ) == 0;
}

QByteArray QPMMimeAnyMime::convertToMime( QByteArray data, const char *, ulong )
{
    return data;
}

QByteArray QPMMimeAnyMime::convertFromMime( QByteArray data, const char *, ulong )
{
    return data;
}



class QPMMimeText : public QPMMime {
public:
    QPMMimeText();
    const char* convertorName();
    int countCf();
    ulong cf( int index );
    ulong flFor( ulong cf );
    ulong cfFor( const char* mime );
    const char* mimeFor( ulong cf );
    bool canConvert( const char* mime, ulong cf );
    QByteArray convertToMime( QByteArray data, const char *, ulong cf );
    QByteArray convertFromMime( QByteArray data, const char *, ulong cf );
private:
    const ulong CF_TextUnicode;
};

QPMMimeText::QPMMimeText() :
    // register a clipboard format for unicode text
    // ("text/unicode" is what Mozilla uses to for unicode, so Qt apps will
    // be able to interchange unicode text with Mozilla apps)
    CF_TextUnicode ( WinAddAtom( WinQuerySystemAtomTable(), "text/unicode" ) )
{
}

const char* QPMMimeText::convertorName()
{
    return "Text";
}

int QPMMimeText::countCf()
{
    return 2;
}

ulong QPMMimeText::cf( int index )
{
    if ( index == 0 )
        return CF_TextUnicode;
    else if ( index == 1 )
        return CF_TEXT;
    return 0;
}

ulong QPMMimeText::flFor( ulong cf )
{
    // both CF_TEXT and CF_TextUnicode use CFI_POINTER
    return cf == CF_TEXT || cf == CF_TextUnicode ? CFI_POINTER : 0;
}

ulong QPMMimeText::cfFor( const char* mime )
{
/// @todo (dmik) do we want to accept "text/plain" w/o "charset="?
//    if ( qstricmp( mime, "text/plain" ) == 0 )
//	return CF_TEXT;

    QCString m( mime );
    int i = m.find( "charset=" );
    if ( i >= 0 ) {
	QCString cs( m.data() + i + 8 );
	i = cs.find( ";" );
	if ( i >= 0 )
	    cs = cs.left( i );
	if ( cs == "system" )
	    return CF_TEXT;
	if ( cs == "ISO-10646-UCS-2" )
	    return CF_TextUnicode;
    }
    return 0;
}

const char* QPMMimeText::mimeFor( ulong cf )
{
    if ( cf == CF_TEXT )
	return "text/plain;charset=system";
    else if ( cf == CF_TextUnicode )
        return "text/plain;charset=ISO-10646-UCS-2";
    return 0;
}

bool QPMMimeText::canConvert( const char* mime, ulong cf )
{
    if ( !cf )
        return FALSE;

    return cfFor( mime ) == cf;
}

/*
    text/plain is defined as using CRLF, but so many programs don't,
    and programmers just look for '\n' in strings.
    OS/2 really needs CRLF, so we ensure it here.
*/

QByteArray QPMMimeText::convertToMime( QByteArray data, const char* , ulong cf )
{
    if ( cf == CF_TEXT ) {
        const char* d = data.data();
        const int s = qstrlen( d );
        QByteArray r( data.size() + 1 );
        char* o = r.data();
        int j = 0;
        for ( int i = 0; i < s; i++ ) {
            char c = d[i];
            if ( c != '\r' )
                o[j++] = c;
        }
        o[j] = 0;
        return r;
    } else if ( cf == CF_TextUnicode ) {
        // Mozilla uses un-marked little-endian nul-terminated Unicode
        // for "text/unicode"
        int sz = data.size();
        int len = 0;
        // Find NUL
        for ( ; len < sz - 1 && (data[len+0] || data[len+1]); len += 2 )
            ;

        QByteArray r( len + 2 );
        r[0] = uchar( 0xff ); // BOM
        r[1] = uchar( 0xfe );
        memcpy( r.data() + 2, data.data(), len );
        return r;
    }

    return QByteArray();
}

extern QTextCodec* qt_findcharset( const QCString& mimetype );

QByteArray QPMMimeText::convertFromMime( QByteArray data, const char *mime, ulong cf )
{
    if ( cf == CF_TEXT ) {
        // Anticipate required space for CRLFs at 1/40
        int maxsize = data.size() + data.size() / 40 + 3;
        QByteArray r( maxsize );
        char* o = r.data();
        const char* d = data.data();
        const int s = data.size();
        bool cr = FALSE;
        int j = 0;
        for ( int i = 0; i < s; i++ ) {
            char c = d[i];
            if ( c == '\r' )
                cr = TRUE;
            else {
                if ( c == '\n' ) {
                    if ( !cr )
                        o[j++]='\r';
                }
                cr = FALSE;
            }
            o[j++] = c;
            if ( j + 3 >= maxsize ) {
                maxsize += maxsize / 4;
                r.resize( maxsize );
                o = r.data();
            }
        }
        o[j] = 0;
        return r;
    } else if ( cf == CF_TextUnicode ) {
        QTextCodec *codec = qt_findcharset( mime );
        QString str = codec->toUnicode( data );
        const QChar *u = str.unicode();
        QString res;
        const int s = str.length();
        int maxsize = s + s / 40 + 3;
        res.setLength( maxsize );
        int ri = 0;
        bool cr = FALSE;
        for ( int i = 0; i < s; ++ i ) {
            if ( *u == '\r' )
                cr = TRUE;
            else {
                if ( *u == '\n' && !cr )
                    res[ri++] = QChar('\r');
                cr = FALSE;
            }
            res[ri++] = *u;
            if ( ri + 3 >= maxsize ) {
                maxsize += maxsize / 4;
                res.setLength( maxsize );
            }
            ++u;
        }
        res.truncate( ri );
        const int byteLength = res.length() * 2;
        QByteArray r( byteLength + 2 );
        memcpy( r.data(), res.unicode(), byteLength );
        r[byteLength] = 0;
        r[byteLength+1] = 0;
        return r;
    }

    return QByteArray();
}


class QPMMimeImage : public QPMMime {
public:
    const char* convertorName();
    int countCf();
    ulong cf( int index );
    ulong flFor( ulong cf );
    ulong cfFor( const char* mime );
    const char* mimeFor( ulong cf );
    bool canConvert( const char* mime, ulong cf );
    QByteArray convertToMime( QByteArray data, const char *mime, ulong cf );
    QByteArray convertFromMime( QByteArray data, const char *mime, ulong cf );
};

const char* QPMMimeImage::convertorName()
{
    return "Image";
}

int QPMMimeImage::countCf()
{
    return 1;
}

ulong QPMMimeImage::cf( int index )
{
    return index == 0 ? CF_BITMAP : 0;
}

ulong QPMMimeImage::flFor( ulong cf )
{
    // CF_BITMAP uses CFI_HANDLE
    return cf == CF_BITMAP ? CFI_HANDLE : 0;
}

ulong QPMMimeImage::cfFor( const char *mime )
{
    if ( qstrnicmp( mime, "image/", 6 ) == 0 ) {
	QStrList ofmts = QImage::outputFormats();
	for ( const char *fmt = ofmts.first(); fmt; fmt = ofmts.next() )
	    if ( qstricmp( fmt, mime + 6 ) == 0 )
                return CF_BITMAP;
    }
    return 0;
}

const char* QPMMimeImage::mimeFor( ulong cf )
{
    if ( cf == CF_BITMAP )
        return "image/bmp";
    return 0;
}

bool QPMMimeImage::canConvert( const char* mime, ulong cf )
{
    if ( cf == CF_BITMAP && qstrnicmp( mime, "image/", 6 ) == 0 ) {
        QStrList ofmts = QImage::outputFormats();
        for ( const char* fmt = ofmts.first(); fmt; fmt = ofmts.next() )
            if ( qstricmp( fmt, mime + 6 ) == 0 )
                return TRUE;
    }
    return FALSE;
}

QByteArray QPMMimeImage::convertToMime( QByteArray data, const char *mime, ulong cf )
{
    if ( qstrnicmp( mime, "image/", 6 ) != 0 || cf != CF_BITMAP )  // Sanity
	return QByteArray();

    HBITMAP hbm = (HBITMAP) *(ULONG *) data.data();

    QPixmap pm;
    pm.attachHandle( hbm );
    QImage img = pm.convertToImage();
    pm.detachHandle(); // prevent hbm from being deleted

    QCString ofmt = mime + 6;
    QByteArray ba;
    QBuffer iod( ba );
    iod.open( IO_WriteOnly );
    QImageIO iio( &iod, ofmt.upper() );
    iio.setImage( img );
    if ( iio.write() ) {
        iod.close();
        return ba;
    }

    // Failed
    return QByteArray();
}

QByteArray QPMMimeImage::convertFromMime( QByteArray data, const char *mime, ulong cf )
{
    if ( qstrnicmp( mime, "image/", 6 ) != 0 || cf != CF_BITMAP )  // Sanity
	return QByteArray();

    QImage img;
    img.loadFromData( (unsigned char *) data.data(), data.size() );
    if ( !img.isNull() ) {
        HBITMAP hbm = QPixmap( img ).detachHandle();
        if ( hbm ) {
            QByteArray ba ( sizeof(HBITMAP) );
            *(HBITMAP *) ba.data() = hbm;
            return ba;
        }
    }

    // Failed
    return QByteArray();
}


static QPMMimeAnyMime *anymime = 0;

static
void cleanup_mimes()
{
    QPMMime* wm;
    while ( (wm = mimes.first()) ) {
	delete wm;
    }
    mimetypes.setAutoDelete( TRUE );
    mimetypes.clear();
    anymime = 0;
}

/*!
  This is an internal function.
*/
void QPMMime::initialize()
{
    if ( mimes.isEmpty() ) {
	new QPMMimeImage;
	new QPMMimeText;
	anymime = new QPMMimeAnyMime;

	qAddPostRoutine( cleanup_mimes );
    }
}

/*!
    \internal
  This is an internal function.
*/
ulong QPMMime::registerMimeType( const char *mime )
{
    // first, look if other non-QPMMimeAnyMime convertors support this mime,
    // to avoid double handling of this mime type by another (probably,
    // system-integrated and most likely more specialized) convertor and the
    // dummy "pass-through" QPMMimeAnyMime convertor (which will handle the
    // given mime type after once we call mimetyes.append (...)).
    QPtrListIterator<QPMMime> it( mimes );
    for ( QPMMime* c; (c = *it); ++ it )
        if ( c != anymime && c->cfFor( mime ) )
            return 0;

    ulong f = WinAddAtom( WinQuerySystemAtomTable(), mime );
    if ( !f ) {
#ifndef QT_NO_DEBUG
	qSystemWarning( "QPMMime: Failed to register clipboard format" );
#endif
        return 0;
    }
    QPMRegisteredMimeType *mt = mimetypes.current();
    if ( !mt || mt->cf != f ) {
	for ( mt = mimetypes.first(); mt && mt->cf != f; mt = mimetypes.next() )
	    ;
	if ( !mt ) {
	    mimetypes.append( new QPMRegisteredMimeType ( f, mime ) );
            // successful memory allocation check
            if ( !(mt = mimetypes.current()) || mt->cf != f )
                return 0;
	}
    }
    return f;
}

/*!
  Returns the most-recently created QPMMime that can convert
  between the \a mime and \a cf formats.  Returns 0 if no such convertor
  exists.
*/
QPMMime *
QPMMime::convertor( const char *mime, ulong cf )
{
    // return nothing for illegal requests
    if ( !cf )
	return 0;

    QPMMime* wm;
    for ( wm = mimes.first(); wm; wm = mimes.next() ) {
	if ( wm->canConvert( mime, cf ) ) {
	    return wm;
	}
    }
    return 0;
}


/*!
  Returns a MIME type for \a cf, or 0 if none exists.
*/
const char* QPMMime::cfToMime( ulong cf )
{
    const char* m = 0;
    QPMMime* wm;
    for ( wm = mimes.first(); wm && !m; wm = mimes.next() ) {
	m = wm->mimeFor( cf );
    }
    return m;
}

/*!
  Returns a list of all currently defined QPMMime objects.
*/
QPtrList<QPMMime> QPMMime::all()
{
    return mimes;
}

/*!
  \fn const char* QPMMime::convertorName()

  Returns a name for the convertor.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn int QPMMime::countCf()

  Returns the number of OS/2 PM Clipboard formats supported by this
  convertor.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn ulong QPMMime::cf(int index)

  Returns the OS/2 PM Clipboard format supported by this convertor
  that is ordinarily at position \a index. This means that cf(0)
  returns the first OS/2 PM Clipboard format supported, and
  cf(countCf()-1) returns the last. If \a index is out of range the
  return value is undefined.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn ulong QPMMime::flFor(ulong cf)

  Returns the data storage flag for the OS/2 PM Clipboard type \a cf
  (either \c CFI_POINTER or \c CFI_HANDLE) used by this convertor,
  or 0 if invalid \a cf is specified.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn bool QPMMime::canConvert( const char* mime, ulong cf )

  Returns TRUE if the convertor can convert (both ways) between
  \a mime and \a cf; otherwise returns FALSE.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn const char* QPMMime::mimeFor(ulong cf)

  Returns the MIME type used for OS/2 PM Clipboard format \a cf, or
  0 if this convertor does not support \a cf.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn ulong QPMMime::cfFor(const char* mime)

  Returns the OS/2 PM Clipboard type used for MIME type \a mime, or
  0 if this convertor does not support \a mime.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn QByteArray QPMMime::convertToMime( QByteArray data, const char* mime, ulong cf )

  Returns \a data converted from OS/2 PM Clipboard format \a cf
  to MIME type \a mime.

  Note that OS/2 PM Clipboard formats must all be self-terminating.  The
  input \a data may contain trailing data. If flFor(ulong) for the given \a cf
  has the \c CFI_HANDLE flag set, then first 4 bytes of \a data represent a
  valid OS/2 handle of the appropriate type, otherwise \a data contains data
  itself.

  All subclasses must reimplement this pure virtual function.
*/

/*!
  \fn QByteArray QPMMime::convertFromMime( QByteArray data, const char* mime, ulong cf )

  Returns \a data converted from MIME type \a mime
  to OS/2 PM Clipboard format \a cf.

  Note that OS/2 PM Clipboard formats must all be self-terminating.  The
  return value may contain trailing data. If flFor(ulong) for the given \a cf
  has the \c CFI_HANDLE flag set, then first 4 bytes of the returned array
  must represent a valid OS/2 handle of the appropriate type, otherwise the array
  contains data itself.

  All subclasses must reimplement this pure virtual function.
*/

#endif // QT_NO_MIME
