/*
    NXBitmapImageRep - image representation for bitmapped images

    Copyright (C) 1993, Adam Fedor.

    Implementation of display specific methods for X-Windows
*/

#include "NXBitmapImageRep.h"

#include "Application.h"
#include "dpsclient/XtGState.h"
#include "dpsclient/xwfriends.h"
#include "appkit/stdmacros.h"
#include "dpsclient/xttools.h"
#include <stdlib.h>

const char *NXBitmapImageRepInstanceName(void)
{
    return "NXBitmapImageRep";
}


@implementation NXBitmapImageRep(ToolKit)

- (BOOL)_displayDraw
{
    XWContext	context;
    XtGState	*gstate;
    XImage      *image;
    NSSize	pixsize;
    unsigned char *mapped;
    u_int	depth;

    PSxwcontext(&context);
    gstate = (XtGState *)context->gstate;
    if (!gstate || ![gstate hasDrawable]) {
        fprintf(stderr, 
	        "Error (BitmapImageRep): Focus not locked on any view\n");
        return NO;
    }
    if (![gstate hasGraphicContext]) {
        fprintf(stderr, 
	        "Error (BitmapImageRep): gstate has no graphic context\n");
        return NO;
    }

    // Map the colors correctly
    mapped = _data[0];
    depth = DefaultDepth(context->display, DefaultScreen(context->display));
    if (context->vinfo.class == PseudoColor) {
	/* FIXME: Take account for MINISWHITE images */
	if (_repFlags.bitsPerSample > 1) {
	    NX_MALLOC(mapped, char, _pixelsWide*_pixelsHigh);
	    xtMapColors(context, 
			_data, 
			(int)_colorSpace,
			_repFlags.bitsPerSample,
			_repFlags.numColors,
			_pixelsWide*_pixelsHigh,
			_moreRepFlags.isPlanar,
			mapped);
	}
    	image = XCreateImage(context->display,
			context->vinfo.visual,
			(bitsPerPixel == 1) ? 1 : depth,
			(bitsPerPixel == 1) ? XYBitmap : ZPixmap,
			0,
			mapped,
			_pixelsWide,
			_pixelsHigh,
			8,
			0);
    } else
    	image = XCreateImage(context->display,
			context->vinfo.visual,
			bitsPerPixel, 
			(bitsPerPixel == 1) ? XYBitmap : ZPixmap,
			0,
			_data[0],
			_pixelsWide,
			_pixelsHigh,
			8,
			0);
    if (!image) {
	fprintf(stderr, "Error (BitmapImageRep): Problem creating X image.\n");
	return NO;
    }
    pixsize.width  = _pixelsWide;
    pixsize.height = _pixelsHigh;
    [gstate copyImage:image ofSize: &pixsize];
    XFree(image);
    if (mapped != _data[0])
    	NX_FREE(mapped);
    return YES;


}

- (BOOL)_displayDrawIn:(const NXRect *)rect
{
    // We can't scale in X11 so just draw it
    return [self _displayDraw];
}

@end
