aboutsummaryrefslogtreecommitdiff
path: root/src/libui_sdl/libui/darwin/image.m
blob: b62de31d8cfdc1a1a07235e28ef1b2b00f83bfb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// 25 june 2016
#import "uipriv_darwin.h"

struct uiImage {
	NSImage *i;
	NSSize size;
	NSMutableArray *swizzled;
};

uiImage *uiNewImage(double width, double height)
{
	uiImage *i;

	i = uiNew(uiImage);
	i->size = NSMakeSize(width, height);
	i->i = [[NSImage alloc] initWithSize:i->size];
	i->swizzled = [NSMutableArray new];
	return i;
}

void uiFreeImage(uiImage *i)
{
	NSValue *v;

	[i->i release];
	// to be safe, do this after releasing the image
	for (v in i->swizzled)
		uiFree([v pointerValue]);
	[i->swizzled release];
	uiFree(i);
}

void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int pixelStride)
{
	NSBitmapImageRep *repCalibrated, *repsRGB;
	uint8_t *swizzled, *bp, *sp;
	int x, y;
	unsigned char *pix[1];

	// OS X demands that R and B are in the opposite order from what we expect
	// we must swizzle :(
	// LONGTERM test on a big-endian system
	swizzled = (uint8_t *) uiAlloc((pixelStride * pixelHeight * 4) * sizeof (uint8_t), "uint8_t[]");
	bp = (uint8_t *) pixels;
	sp = swizzled;
	for (y = 0; y < pixelHeight * pixelStride; y += pixelStride)
		for (x = 0; x < pixelStride; x++) {
			sp[0] = bp[2];
			sp[1] = bp[1];
			sp[2] = bp[0];
			sp[3] = bp[3];
			sp += 4;
			bp += 4;
		}

	pix[0] = (unsigned char *) swizzled;
	repCalibrated = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:pix
		pixelsWide:pixelWidth
		pixelsHigh:pixelHeight
		bitsPerSample:8
		samplesPerPixel:4
		hasAlpha:YES
		isPlanar:NO
		colorSpaceName:NSCalibratedRGBColorSpace
		bitmapFormat:0
		bytesPerRow:pixelStride
		bitsPerPixel:32];
	repsRGB = [repCalibrated bitmapImageRepByRetaggingWithColorSpace:[NSColorSpace sRGBColorSpace]];
	[repCalibrated release];

	[i->i addRepresentation:repsRGB];
	[repsRGB setSize:i->size];
	[repsRGB release];

	// we need to keep swizzled alive for NSBitmapImageRep
	[i->swizzled addObject:[NSValue valueWithPointer:swizzled]];
}

NSImage *imageImage(uiImage *i)
{
	return i->i;
}