// TestPatternPhase.m
// Checks patternPhase support by filling a rect with a pattern color that contains a single
// visible pixel and verifying that the visible pixel was drawn at the appropriate phase-offset
// location

#import <AppKit/AppKit.h>


int main()
{
    NSAutoreleasePool *autoreleasePool = [[NSAutoreleasePool alloc] init];
    NSApplication *app; 
    app = [NSApplication sharedApplication];

    NSSize patternSize = {11,13};
    NSPoint patternPhase = {7,5};
    NSRect imageBounds = NSZeroRect;
    NSImage *patternImage, *targetImage;
    NSColor *patternColor, *targetPixelColor;
    NSBitmapImageRep *targetBitmap;

    imageBounds.size = patternSize;

    patternImage = [[[NSImage alloc] initWithSize: imageBounds.size] autorelease];
    targetImage = [[[NSImage alloc] initWithSize: imageBounds.size] autorelease];

    if (!patternImage || !targetImage)
    {
        goto EXIT;
    }

    // Make a nearly-blank pattern color with a single red pixel at (0,0)

    [patternImage lockFocus];

    [[NSColor redColor] set];
    NSRectFill(NSMakeRect(0,0,1,1));

    [patternImage unlockFocus];

    patternColor = [NSColor colorWithPatternImage: patternImage];

    if (!patternColor)
        goto EXIT;

    // Set the pattern phase & fill the target image with the pattern
    [targetImage lockFocus];

    [[NSGraphicsContext currentContext] setPatternPhase: patternPhase];
    [patternColor set];
    NSRectFill(imageBounds);
 
    // Grab the bitmap data from the target image and check the red component of the pixel at
    // the phase-offset coordinates
    targetBitmap = 
        [[[NSBitmapImageRep alloc] initWithFocusedViewRect: imageBounds] autorelease];

    [targetImage unlockFocus];

    if (!targetBitmap)
        goto EXIT;

    targetPixelColor = [targetBitmap colorAtX: patternPhase.x
                                        y: imageBounds.size.height - patternPhase.y - 1]; // flipped y

    if (!targetPixelColor)
        goto EXIT;

    if ([targetPixelColor redComponent] > 0.5)
    {
        // red pixel was drawn at the correct phase offset
        NSLog(@"Passed PatternPhase check");
    }
    else
    {
        // red pixel was not drawn at the correct phase offset
        NSLog(@"ERROR: FAILED PatternPhase check");
    }

EXIT:
    [autoreleasePool release];
    
    return 0;
}

