// Copyright 1997-1999 Omni Development, Inc.  All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// http://www.omnigroup.com/DeveloperResources/OmniSourceLicense.html.

#import "OAColorPalette.h"

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <OmniBase/OmniBase.h>
#import <OmniFoundation/OmniFoundation.h>

RCS_ID("$Header: /Network/Developer/Source/CVS/OmniGroup/OmniAppKit/Widgets.subproj/OAColorPalette.m,v 1.7 1999/03/30 21:26:10 kc Exp $")

@implementation OAColorPalette

static NSDictionary *namedColorsDictionary = nil;

+ (void)initialize;
{
    static BOOL initialized = NO;

    [super initialize];
    if (initialized)
	return;
    initialized = YES;

    namedColorsDictionary = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle bundleForClass:self] pathForResource:@"namedColors" ofType:@"plist"]];
}

static inline double
applyGammaAndNormalize(byte sample, double gamma)
{
    double normalizedSample;

    normalizedSample = ((double)sample / 255.0);

    if (gamma == 1.0 || gamma == 0.0)
        return normalizedSample;

    return pow(normalizedSample, gamma);
}

+ (NSColor *)colorForString:(NSString *)colorString gamma:(double)gamma;
{
    unsigned int rawColor;
    unsigned int red, green, blue;

    if ([colorString hasPrefix:@"#"]) {
        // Hex color string
	colorString = [colorString substringFromIndex:1];
    } else {
        NSString *namedColorString;

        // Possibly a named color string
        namedColorString = [namedColorsDictionary objectForKey:[colorString lowercaseString]];
        if (namedColorString)
            colorString = namedColorString;
    }
    
    rawColor = [colorString hexValue];
    blue = rawColor & 0xff;
    rawColor >>= 8;
    green = rawColor & 0xff;
    rawColor >>= 8;
    red = rawColor & 0xff;

    return [NSColor colorWithCalibratedRed:applyGammaAndNormalize(red, gamma) green:applyGammaAndNormalize(green, gamma) blue:applyGammaAndNormalize(blue, gamma) alpha:1.0];
}

+ (NSColor *)colorForString:(NSString *)colorString;
{
    return [self colorForString:colorString gamma:1.0];
}

+ (NSString *)stringForColor:(NSColor *)color;
{
    float red, green, blue, alpha;

    // Note: alpha is ignored
    [[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red green:&green blue:&blue alpha:&alpha];
    return [NSString stringWithFormat:@"#%02x%02x%02x", ((int)ceil(red * 255.0)),  ((int)ceil(green * 255.0)), ((int)ceil(blue * 255.0))];
}

@end
