code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#import <Foundation/Foundation.h> #import "CPAxisLabel.h" @interface CPAxisTitle : CPAxisLabel { } @end
08iteng-ipad
framework/Source/CPAxisTitle.h
Objective-C
bsd
109
#import "CPDefinitions.h" #import "CPResponder.h" @class CPLayer; @class CPPlotRange; @class CPGraph; @class CPPlotSpace; extern NSString * const CPPlotSpaceCoordinateMappingDidChangeNotification; /** @brief Plot space delegate. **/ @protocol CPPlotSpaceDelegate <NSObject> @optional /// @name Scrolling /// @{ /** @brief Informs the receiver that it should uniformly scale (e.g., in response to a pinch on iOS) * @param space The plot space. * @param interactionScale The scaling factor. * @param interactionPoint The coordinates of the scaling centroid. * @return YES should be returned if the gesture should be handled by the plot space, and NO to prevent handling. * In either case, the delegate may choose to take extra actions, or handle the scaling itself. **/ -(BOOL)plotSpace:(CPPlotSpace*)space shouldScaleBy:(CGFloat)interactionScale aboutPoint:(CGPoint)interactionPoint; /** @brief Notifies that plot space intercepted a device down event. * @param space The plot space. * @param event The native event (e.g., UIEvent on iPhone) * @param point The point in the host view. * @return Whether the plot space should handle the event or not. * In either case, the delegate may choose to take extra actions, or handle the scaling itself. **/ -(BOOL)plotSpace:(CPPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event atPoint:(CGPoint)point; /** @brief Notifies that plot space intercepted a device dragged event. * @param space The plot space. * @param event The native event (e.g., UIEvent on iPhone) * @param point The point in the host view. * @return Whether the plot space should handle the event or not. * In either case, the delegate may choose to take extra actions, or handle the scaling itself. **/ -(BOOL)plotSpace:(CPPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)point; /** @brief Notifies that plot space intercepted a device cancelled event. * @param space The plot space. * @param event The native event (e.g., UIEvent on iPhone) * @return Whether the plot space should handle the event or not. * In either case, the delegate may choose to take extra actions, or handle the scaling itself. **/ -(BOOL)plotSpace:(CPPlotSpace *)space shouldHandlePointingDeviceCancelledEvent:(id)event; /** @brief Notifies that plot space intercepted a device up event. * @param space The plot space. * @param event The native event (e.g., UIEvent on iPhone) * @param point The point in the host view. * @return Whether the plot space should handle the event or not. * In either case, the delegate may choose to take extra actions, or handle the scaling itself. **/ -(BOOL)plotSpace:(CPPlotSpace *)space shouldHandlePointingDeviceUpEvent:(id)event atPoint:(CGPoint)point; /** @brief Notifies that plot space is going to scroll. * @param space The plot space. * @param proposedDisplacementVector The proposed amount by which the plot space will shift * @return The displacement actually applied. **/ -(CGPoint)plotSpace:(CPPlotSpace *)space willDisplaceBy:(CGPoint)proposedDisplacementVector; /** @brief Notifies that plot space is going to change a plot range. * @param space The plot space. * @param newRange The proposed new plot range. * @param coordinate The coordinate of the range. * @return The new plot range to be used. **/ -(CPPlotRange *)plotSpace:(CPPlotSpace *)space willChangePlotRangeTo:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate; /** @brief Notifies that plot space has changed a plot range. * @param space The plot space. * @param coordinate The coordinate of the range. **/ -(void)plotSpace:(CPPlotSpace *)space didChangePlotRangeForCoordinate:(CPCoordinate)coordinate; /// @} @end #pragma mark - @interface CPPlotSpace : NSObject <CPResponder> { @private __weak CPGraph *graph; id <NSCopying, NSObject> identifier; __weak id <CPPlotSpaceDelegate> delegate; BOOL allowsUserInteraction; } @property (nonatomic, readwrite, copy) id <NSCopying, NSObject> identifier; @property (nonatomic, readwrite, assign) BOOL allowsUserInteraction; @property (nonatomic, readwrite, assign) __weak CPGraph *graph; @property (nonatomic, readwrite, assign) __weak id <CPPlotSpaceDelegate> delegate; @end #pragma mark - /** @category CPPlotSpace(AbstractMethods) * @brief CPPlotSpace abstract methods—must be overridden by subclasses **/ @interface CPPlotSpace(AbstractMethods) /// @name Coordinate Space Conversions /// @{ -(CGPoint)plotAreaViewPointForPlotPoint:(NSDecimal *)plotPoint; -(CGPoint)plotAreaViewPointForDoublePrecisionPlotPoint:(double *)plotPoint; -(void)plotPoint:(NSDecimal *)plotPoint forPlotAreaViewPoint:(CGPoint)point; -(void)doublePrecisionPlotPoint:(double *)plotPoint forPlotAreaViewPoint:(CGPoint)point; /// @} /// @name Coordinate Range /// @{ -(void)setPlotRange:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate; -(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coordinate; /// @} /// @name Adjusting Ranges /// @{ -(void)scaleToFitPlots:(NSArray *)plots; -(void)scaleBy:(CGFloat)interactionScale aboutPoint:(CGPoint)interactionPoint; /// @} @end
08iteng-ipad
framework/Source/CPPlotSpace.h
Objective-C
bsd
5,165
#import "CPUtilities.h" // cache common values to improve performance #define kCacheSize 3 static NSDecimal cache[kCacheSize]; static BOOL cacheValueInitialized[kCacheSize] = {NO, NO, NO}; #pragma mark Convert NSDecimal to primitive types /** * @brief Converts an NSDecimal value to an 8-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ int8_t CPDecimalCharValue(NSDecimal decimalNumber) { return (int8_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] charValue]; } /** * @brief Converts an NSDecimal value to a 16-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ int16_t CPDecimalShortValue(NSDecimal decimalNumber) { return (int16_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] shortValue]; } /** * @brief Converts an NSDecimal value to a 32-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ int32_t CPDecimalLongValue(NSDecimal decimalNumber) { return (int32_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] longValue]; } /** * @brief Converts an NSDecimal value to a 64-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ int64_t CPDecimalLongLongValue(NSDecimal decimalNumber) { return (int64_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] longLongValue]; } /** * @brief Converts an NSDecimal value to an int. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ int CPDecimalIntValue(NSDecimal decimalNumber) { return (int)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] intValue]; } /** * @brief Converts an NSDecimal value to an NSInteger. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ NSInteger CPDecimalIntegerValue(NSDecimal decimalNumber) { return (NSInteger)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] integerValue]; } /** * @brief Converts an NSDecimal value to an unsigned 8-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ uint8_t CPDecimalUnsignedCharValue(NSDecimal decimalNumber) { return (uint8_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] unsignedCharValue]; } /** * @brief Converts an NSDecimal value to an unsigned 16-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ uint16_t CPDecimalUnsignedShortValue(NSDecimal decimalNumber) { return (uint16_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] unsignedShortValue]; } /** * @brief Converts an NSDecimal value to an unsigned 32-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ uint32_t CPDecimalUnsignedLongValue(NSDecimal decimalNumber) { return (uint32_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] unsignedLongValue]; } /** * @brief Converts an NSDecimal value to an unsigned 64-bit integer. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ uint64_t CPDecimalUnsignedLongLongValue(NSDecimal decimalNumber) { return (uint64_t)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] unsignedLongLongValue]; } /** * @brief Converts an NSDecimal value to an unsigned int. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ unsigned int CPDecimalUnsignedIntValue(NSDecimal decimalNumber) { return (unsigned int)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] unsignedIntValue]; } /** * @brief Converts an NSDecimal value to an NSUInteger. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ NSUInteger CPDecimalUnsignedIntegerValue(NSDecimal decimalNumber) { return (NSUInteger)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] unsignedIntegerValue]; } /** * @brief Converts an NSDecimal value to a float. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ float CPDecimalFloatValue(NSDecimal decimalNumber) { return (float)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] doubleValue]; } /** * @brief Converts an NSDecimal value to a double. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ double CPDecimalDoubleValue(NSDecimal decimalNumber) { return (double)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] doubleValue]; } /** * @brief Converts an NSDecimal value to an NSString. * @param decimalNumber The NSDecimal value. * @return The converted value. **/ NSString *CPDecimalStringValue(NSDecimal decimalNumber) { return (NSString *)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] stringValue]; } #pragma mark - #pragma mark Convert primitive types to NSDecimal /** * @brief Converts an 8-bit integer value to an NSDecimal. * @param i The integer value. * @return The converted value. **/ NSDecimal CPDecimalFromChar(int8_t i) { if ( (i >= 0) && (i < kCacheSize) ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithChar:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithChar:i] decimalValue]; } /** * @brief Converts a 16-bit integer value to an NSDecimal. * @param i The integer value. * @return The converted value. **/ NSDecimal CPDecimalFromShort(int16_t i) { if ( (i >= 0) && (i < kCacheSize) ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithShort:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithShort:i] decimalValue]; } /** * @brief Converts a 32-bit integer value to an NSDecimal. * @param i The integer value. * @return The converted value. **/ NSDecimal CPDecimalFromLong(int32_t i) { if ( (i >= 0) && (i < kCacheSize) ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithLong:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithLong:i] decimalValue]; } /** * @brief Converts a 64-bit integer value to an NSDecimal. * @param i The integer value. * @return The converted value. **/ NSDecimal CPDecimalFromLongLong(int64_t i) { if ( (i >= 0) && (i < kCacheSize) ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithLongLong:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithLongLong:i] decimalValue]; } /** * @brief Converts an int value to an NSDecimal. * @param i The int value. * @return The converted value. **/ NSDecimal CPDecimalFromInt(int i) { if ( (i >= 0) && (i < kCacheSize) ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithInt:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithInt:i] decimalValue]; } /** * @brief Converts an NSInteger value to an NSDecimal. * @param i The NSInteger value. * @return The converted value. **/ NSDecimal CPDecimalFromInteger(NSInteger i) { if ( (i >= 0) && (i < kCacheSize) ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithInteger:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithInteger:i] decimalValue]; } /** * @brief Converts an unsigned 8-bit integer value to an NSDecimal. * @param i The unsigned integer value. * @return The converted value. **/ NSDecimal CPDecimalFromUnsignedChar(uint8_t i) { if ( i < kCacheSize ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithUnsignedChar:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithUnsignedChar:i] decimalValue]; } /** * @brief Converts an unsigned 16-bit integer value to an NSDecimal. * @param i The unsigned integer value. * @return The converted value. **/ NSDecimal CPDecimalFromUnsignedShort(uint16_t i) { if ( i < kCacheSize ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithUnsignedShort:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithUnsignedShort:i] decimalValue]; } /** * @brief Converts an unsigned 32-bit integer value to an NSDecimal. * @param i The unsigned integer value. * @return The converted value. **/ NSDecimal CPDecimalFromUnsignedLong(uint32_t i) { if ( i < kCacheSize ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithUnsignedLong:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithUnsignedLong:i] decimalValue]; } /** * @brief Converts an unsigned 64-bit integer value to an NSDecimal. * @param i The unsigned integer value. * @return The converted value. **/ NSDecimal CPDecimalFromUnsignedLongLong(uint64_t i) { if ( i < kCacheSize ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithUnsignedLongLong:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithUnsignedLongLong:i] decimalValue]; } /** * @brief Converts an unsigned int value to an NSDecimal. * @param i The unsigned int value. * @return The converted value. **/ NSDecimal CPDecimalFromUnsignedInt(unsigned int i) { if ( i < kCacheSize ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithUnsignedInt:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithUnsignedInt:i] decimalValue]; } /** * @brief Converts an NSUInteger value to an NSDecimal. * @param i The NSUInteger value. * @return The converted value. **/ NSDecimal CPDecimalFromUnsignedInteger(NSUInteger i) { if ( i < kCacheSize ) { if ( !cacheValueInitialized[i] ) { cache[i] = [[NSNumber numberWithUnsignedInteger:i] decimalValue]; cacheValueInitialized[i] = YES; } return cache[i]; } return [[NSNumber numberWithUnsignedInteger:i] decimalValue]; } /** * @brief Converts a float value to an NSDecimal. * @param f The float value. * @return The converted value. **/ NSDecimal CPDecimalFromFloat(float f) { return [[NSNumber numberWithFloat:f] decimalValue]; } /** * @brief Converts a double value to an NSDecimal. * @param d The double value. * @return The converted value. **/ NSDecimal CPDecimalFromDouble(double d) { return [[NSNumber numberWithDouble:d] decimalValue]; } /** * @brief Parses a string and extracts the numeric value as an NSDecimal. * @param stringRepresentation The string value. * @return The numeric value extracted from the string. **/ NSDecimal CPDecimalFromString(NSString *stringRepresentation) { // The following NSDecimalNumber-based creation of NSDecimals from strings is slower than // the NSScanner-based method: (307000 operations per second vs. 582000 operations per second for NSScanner) /* NSDecimalNumber *newNumber = [[NSDecimalNumber alloc] initWithString:@"1.0" locale:[NSLocale currentLocale]]; newDecimal = [newNumber decimalValue]; [newNumber release];*/ NSDecimal result; NSScanner *theScanner = [[NSScanner alloc] initWithString:stringRepresentation]; [theScanner scanDecimal:&result]; [theScanner release]; return result; } #pragma mark - #pragma mark NSDecimal arithmetic /** * @brief Adds two NSDecimals together. * @param leftOperand The left-hand side of the addition operation. * @param rightOperand The right-hand side of the addition operation. * @return The result of the addition. **/ NSDecimal CPDecimalAdd(NSDecimal leftOperand, NSDecimal rightOperand) { NSDecimal result; NSDecimalAdd(&result, &leftOperand, &rightOperand, NSRoundBankers); return result; } /** * @brief Subtracts one NSDecimal from another. * @param leftOperand The left-hand side of the subtraction operation. * @param rightOperand The right-hand side of the subtraction operation. * @return The result of the subtraction. **/ NSDecimal CPDecimalSubtract(NSDecimal leftOperand, NSDecimal rightOperand) { NSDecimal result; NSDecimalSubtract(&result, &leftOperand, &rightOperand, NSRoundBankers); return result; } /** * @brief Multiplies two NSDecimals together. * @param leftOperand The left-hand side of the multiplication operation. * @param rightOperand The right-hand side of the multiplication operation. * @return The result of the multiplication. **/ NSDecimal CPDecimalMultiply(NSDecimal leftOperand, NSDecimal rightOperand) { NSDecimal result; NSDecimalMultiply(&result, &leftOperand, &rightOperand, NSRoundBankers); return result; } /** * @brief Divides one NSDecimal by another. * @param numerator The numerator of the multiplication operation. * @param denominator The denominator of the multiplication operation. * @return The result of the division. **/ NSDecimal CPDecimalDivide(NSDecimal numerator, NSDecimal denominator) { NSDecimal result; NSDecimalDivide(&result, &numerator, &denominator, NSRoundBankers); return result; } #pragma mark - #pragma mark NSDecimal comparison /** * @brief Checks to see if one NSDecimal is greater than another. * @param leftOperand The left side of the comparison. * @param rightOperand The right side of the comparison. * @return YES if the left operand is greater than the right, NO otherwise. **/ BOOL CPDecimalGreaterThan(NSDecimal leftOperand, NSDecimal rightOperand) { return (NSDecimalCompare(&leftOperand, &rightOperand) == NSOrderedDescending); } /** * @brief Checks to see if one NSDecimal is greater than or equal to another. * @param leftOperand The left side of the comparison. * @param rightOperand The right side of the comparison. * @return YES if the left operand is greater than or equal to the right, NO otherwise. **/ BOOL CPDecimalGreaterThanOrEqualTo(NSDecimal leftOperand, NSDecimal rightOperand) { return (NSDecimalCompare(&leftOperand, &rightOperand) != NSOrderedAscending); } /** * @brief Checks to see if one NSDecimal is less than another. * @param leftOperand The left side of the comparison. * @param rightOperand The right side of the comparison. * @return YES if the left operand is less than the right, NO otherwise. **/ BOOL CPDecimalLessThan(NSDecimal leftOperand, NSDecimal rightOperand) { return (NSDecimalCompare(&leftOperand, &rightOperand) == NSOrderedAscending); } /** * @brief Checks to see if one NSDecimal is less than or equal to another. * @param leftOperand The left side of the comparison. * @param rightOperand The right side of the comparison. * @return YES if the left operand is less than or equal to the right, NO otherwise. **/ BOOL CPDecimalLessThanOrEqualTo(NSDecimal leftOperand, NSDecimal rightOperand) { return (NSDecimalCompare(&leftOperand, &rightOperand) != NSOrderedDescending); } /** * @brief Checks to see if one NSDecimal is equal to another. * @param leftOperand The left side of the comparison. * @param rightOperand The right side of the comparison. * @return YES if the left operand is equal to the right, NO otherwise. **/ BOOL CPDecimalEquals(NSDecimal leftOperand, NSDecimal rightOperand) { return (NSDecimalCompare(&leftOperand, &rightOperand) == NSOrderedSame); } #pragma mark - #pragma mark NSDecimal utilities /** * @brief Creates and returns an NSDecimal struct that represents the value "not a number". * * Calling <code>NSDecimalIsNotANumber()</code> on this value will return <code>YES</code>. * * @return An NSDecimal struct that represents the value "not a number". **/ NSDecimal CPDecimalNaN(void) { NSDecimal decimalNaN = [[NSDecimalNumber zero] decimalValue]; decimalNaN._length = 0; decimalNaN._isNegative = YES; return decimalNaN; } #pragma mark - #pragma mark Ranges /** * @brief Expands an NSRange by the given amount. * * The <code>location</code> of the resulting NSRange will be non-negative. * * @param range The NSRange to expand. * @param expandBy The amount the expand the range by. * @return The expanded range. **/ NSRange CPExpandedRange(NSRange range, NSInteger expandBy) { NSInteger loc = MAX(0, (int)range.location - expandBy); NSInteger lowerExpansion = range.location - loc; NSInteger length = range.length + lowerExpansion + expandBy; return NSMakeRange(loc, length); } #pragma mark - #pragma mark Colors /** * @brief Extracts the color information from a CGColorRef and returns it as a CPRGBAColor. * * Supports RGBA and grayscale colorspaces. * * @param color The color. * @return The RGBA components of the color. **/ CPRGBAColor CPRGBAColorFromCGColor(CGColorRef color) { CPRGBAColor rgbColor; size_t numComponents = CGColorGetNumberOfComponents(color); if (numComponents == 2) { const CGFloat *components = CGColorGetComponents(color); CGFloat all = components[0]; rgbColor.red = all; rgbColor.green = all; rgbColor.blue = all; rgbColor.alpha = components[1]; } else { const CGFloat *components = CGColorGetComponents(color); rgbColor.red = components[0]; rgbColor.green = components[1]; rgbColor.blue = components[2]; rgbColor.alpha = components[3]; } return rgbColor; } #pragma mark - #pragma mark Coordinates /** * @brief Determines the CPCoordinate that is orthogonal to the one provided. * * The current implementation is two-dimensional--X is orthogonal to Y and Y is orthogonal to X. * * @param coord The CPCoordinate. * @return The orthogonal CPCoordinate. **/ CPCoordinate CPOrthogonalCoordinate(CPCoordinate coord) { return ( coord == CPCoordinateX ? CPCoordinateY : CPCoordinateX ); } #pragma mark - #pragma mark Quartz pixel-alignment functions /** * @brief Aligns a point in user space to integral coordinates in device space. * * Ensures that the x and y coordinates are at a pixel corner in device space. * Drawn from <i>Programming with Quartz</i> by D. Gelphman, B. Laden. * * @param context The graphics context. * @param p The point in user space. * @return The device aligned point in user space. **/ CGPoint CPAlignPointToUserSpace(CGContextRef context, CGPoint p) { // Compute the coordinates of the point in device space. p = CGContextConvertPointToDeviceSpace(context, p); // Ensure that coordinates are at exactly the corner // of a device pixel. p.x = round(p.x) + 0.5f; p.y = round(p.y) + 0.5f; // Convert the device aligned coordinate back to user space. return CGContextConvertPointToUserSpace(context, p); } /** * @brief Adjusts a size in user space to integral dimensions in device space. * * Ensures that the width and height are an integer number of device pixels. * Drawn from <i>Programming with Quartz</i> by D. Gelphman, B. Laden. * * @param context The graphics context. * @param s The size in user space. * @return The device aligned size in user space. **/ CGSize CPAlignSizeToUserSpace(CGContextRef context, CGSize s) { // Compute the size in device space. s = CGContextConvertSizeToDeviceSpace(context, s); // Ensure that size is an integer multiple of device pixels. s.width = round(s.width); s.height = round(s.height); // Convert back to user space. return CGContextConvertSizeToUserSpace(context, s); } /** * @brief Aligns a rectangle in user space to integral coordinates in device space. * * Ensures that the x and y coordinates are at a pixel corner in device space * and the width and height are an integer number of device pixels. * Drawn from <i>Programming with Quartz</i> by D. Gelphman, B. Laden. * * @note This function produces a width and height * that is less than or equal to the original width. * @param context The graphics context. * @param r The rectangle in user space. * @return The device aligned rectangle in user space. **/ CGRect CPAlignRectToUserSpace(CGContextRef context, CGRect r) { // Compute the coordinates of the rectangle in device space. r = CGContextConvertRectToDeviceSpace(context, r); // Ensure that the x and y coordinates are at a pixel corner. r.origin.x = round(r.origin.x) + 0.5f; r.origin.y = round(r.origin.y) + 0.5f; // Ensure that the width and height are an integer number of // device pixels. We now use ceil to make something at least as large as the original r.size.width = round(r.size.width); r.size.height = round(r.size.height); // Convert back to user space. return CGContextConvertRectToUserSpace(context, r); } #pragma mark - #pragma mark String formatting for Core Graphics structs /** @brief Creates a string representation of the given point. * @param p The point. * @return A string with the format <code>{x, y}</code>. **/ NSString *CPStringFromPoint(CGPoint p) { return [NSString stringWithFormat:@"{%g, %g}", p.x, p.y]; } /** @brief Creates a string representation of the given point. * @param s The size. * @return A string with the format <code>{width, height}</code>. **/ NSString *CPStringFromSize(CGSize s) { return [NSString stringWithFormat:@"{%g, %g}", s.width, s.height]; } /** @brief Creates a string representation of the given point. * @param r The rectangle. * @return A string with the format <code>{{x, y}, {width, height}}</code>. **/ NSString *CPStringFromRect(CGRect r) { return [NSString stringWithFormat:@"{{%g, %g}, {%g, %g}}", r.origin.x, r.origin.y, r.size.width, r.size.height]; }
08iteng-ipad
framework/Source/CPUtilities.m
Objective-C
bsd
21,415
#import "CPTextStyle.h" #import "CPMutableTextStyle.h" #import "CPColor.h" /** @cond */ @interface CPTextStyle () @property(readwrite, copy, nonatomic) NSString *fontName; @property(readwrite, assign, nonatomic) CGFloat fontSize; @property(readwrite, copy, nonatomic) CPColor *color; @end /** @endcond */ /** @brief Immutable wrapper for various text style properties. * * If you need to customize properties, you should create a CPMutableTextStyle. **/ @implementation CPTextStyle /** @property fontSize * @brief The font size. **/ @synthesize fontSize; /** @property fontName * @brief The font name. **/ @synthesize fontName; /** @property color * @brief The current text color. **/ @synthesize color; #pragma mark - #pragma mark Factory Methods /** @brief Creates and returns a new CPTextStyle instance. * @return A new CPTextStyle instance. **/ +(id)textStyle { return [[[self alloc] init] autorelease]; } #pragma mark - #pragma mark Initialization and teardown -(id)init { if ( self = [super init] ) { fontName = @"Helvetica"; fontSize = 12.0; color = [[CPColor blackColor] retain]; } return self; } -(void)dealloc { [fontName release]; [color release]; [super dealloc]; } #pragma mark - #pragma mark NSCoding methods -(void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.fontName forKey:@"fontName"]; [coder encodeDouble:self.fontSize forKey:@"fontSize"]; [coder encodeObject:self.color forKey:@"color"]; } -(id)initWithCoder:(NSCoder *)coder { self = [super init]; if ( self ) { self->fontName = [[coder decodeObjectForKey:@"fontName"] copy]; self->fontSize = [coder decodeDoubleForKey:@"fontSize"]; self->color = [[coder decodeObjectForKey:@"color"] copy]; } return self; } #pragma mark - #pragma mark Copying -(id)copyWithZone:(NSZone *)zone { CPTextStyle *newCopy = [[CPTextStyle allocWithZone:zone] init]; newCopy->fontName = [self->fontName copy]; newCopy->color = [self->color copy]; newCopy->fontSize = self->fontSize; return newCopy; } -(id)mutableCopyWithZone:(NSZone *)zone { CPTextStyle *newCopy = [[CPMutableTextStyle allocWithZone:zone] init]; newCopy->fontName = [self->fontName copy]; newCopy->color = [self->color copy]; newCopy->fontSize = self->fontSize; return newCopy; } @end
08iteng-ipad
framework/Source/CPTextStyle.m
Objective-C
bsd
2,303
#import <Foundation/Foundation.h> #import "CPAxis.h" #import "CPDefinitions.h" @class CPConstrainedPosition; @interface CPXYAxis : CPAxis { @private BOOL isFloatingAxis; NSDecimal orthogonalCoordinateDecimal; CPConstraints constraints; CPConstrainedPosition *constrainedPosition; } /// @name Positioning /// @{ @property (nonatomic, readwrite) NSDecimal orthogonalCoordinateDecimal; @property (nonatomic, readwrite) CPConstraints constraints; @property (nonatomic, readwrite) BOOL isFloatingAxis; /// @} @end
08iteng-ipad
framework/Source/CPXYAxis.h
Objective-C
bsd
526
#import "CPNumericData.h" #import "CPNumericData+TypeConversion.h" #import "CPMutableNumericData.h" #import "CPExceptions.h" #import "CPUtilities.h" #import "complex.h" /** @cond */ @interface CPNumericData() -(void)commonInitWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; -(NSData *)dataFromArray:(NSArray *)newData dataType:(CPNumericDataType)newDataType; @end /** @endcond */ #pragma mark - /** @brief An annotated NSData type. * * CPNumericData combines a data buffer with information * about the data (shape, data type, size, etc.). * The data is assumed to be an array of one or more dimensions * of a single type of numeric data. Each numeric value in the array, * which can be more than one byte in size, is referred to as a "sample". * The structure of this object is similar to the NumPy ndarray * object. * * The supported data types are: * - 1, 2, 4, and 8-byte signed integers * - 1, 2, 4, and 8-byte unsigned integers * - <code>float</code> and <code>double</code> floating point numbers * - <code>float complex</code> and <code>double complex</code> floating point complex numbers * - NSDecimal base-10 numbers * * All integer and floating point types can be represented using big endian or little endian * byte order. Complex and decimal types support only the the host system's native byte order. **/ @implementation CPNumericData /** @property data * @brief The data buffer. **/ @synthesize data; /** @property bytes * @brief Returns a pointer to the data buffer’s contents. **/ @dynamic bytes; /** @property length * @brief Returns the number of bytes contained in the data buffer. **/ @dynamic length; /** @property dataType * @brief The type of data stored in the data buffer. **/ @synthesize dataType; /** @property dataTypeFormat * @brief The format of the data stored in the data buffer. **/ @dynamic dataTypeFormat; /** @property sampleBytes * @brief The number of bytes in a single sample of data. **/ @dynamic sampleBytes; /** @property byteOrder * @brief The byte order used to store each sample in the data buffer. **/ @dynamic byteOrder; /** @property shape * @brief The shape of the data buffer array. * * The shape describes the dimensions of the sample array stored in * the data buffer. Each entry in the shape array represents the * size of the corresponding array dimension and should be an unsigned * integer encoded in an instance of NSNumber. **/ @synthesize shape; /** @property numberOfDimensions * @brief The number dimensions in the data buffer array. **/ @dynamic numberOfDimensions; /** @property numberOfSamples * @brief The number of samples of dataType stored in the data buffer. **/ @dynamic numberOfSamples; #pragma mark - #pragma mark Factory Methods /** @brief Creates and returns a new CPNumericData instance. * @param newData The data buffer. * @param newDataType The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return A new CPNumericData instance. **/ +(CPNumericData *)numericDataWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray { return [[[CPNumericData alloc] initWithData:newData dataType:newDataType shape:shapeArray] autorelease]; } /** @brief Creates and returns a new CPNumericData instance. * @param newData The data buffer. * @param newDataTypeString The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return A new CPNumericData instance. **/ +(CPNumericData *)numericDataWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray { return [[[CPNumericData alloc] initWithData:newData dataType:CPDataTypeWithDataTypeString(newDataTypeString) shape:shapeArray] autorelease]; } /** @brief Creates and returns a new CPNumericData instance. * * Objects in newData should be instances of NSNumber, NSDecimalNumber, NSString, or NSNull. * Numbers and strings will be converted to newDataType and stored in the receiver. * Any instances of NSNull will be treated as "not a number" (NAN) values for floating point types and "0" for integer types. * @param newData An array of numbers. * @param newDataType The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return A new CPNumericData instance. **/ +(CPNumericData *)numericDataWithArray:(NSArray *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray { return [[[CPNumericData alloc] initWithArray:newData dataType:newDataType shape:shapeArray] autorelease]; } /** @brief Creates and returns a new CPNumericData instance. * * Objects in newData should be instances of NSNumber, NSDecimalNumber, NSString, or NSNull. * Numbers and strings will be converted to newDataTypeString and stored in the receiver. * Any instances of NSNull will be treated as "not a number" (NAN) values for floating point types and "0" for integer types. * @param newData An array of numbers. * @param newDataTypeString The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return A new CPNumericData instance. **/ +(CPNumericData *)numericDataWithArray:(NSArray *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray { return [[[CPNumericData alloc] initWithArray:newData dataType:CPDataTypeWithDataTypeString(newDataTypeString) shape:shapeArray] autorelease]; } #pragma mark - #pragma mark Init/Dealloc /** @brief Initializes a newly allocated CPNumericData object with the provided data. This is the designated initializer. * @param newData The data buffer. * @param newDataType The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return The initialized CPNumericData instance. **/ -(id)initWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray { if ( self = [super init] ) { [self commonInitWithData:newData dataType:newDataType shape:shapeArray]; } return self; } /** @brief Initializes a newly allocated CPNumericData object with the provided data. * @param newData The data buffer. * @param newDataTypeString The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return The initialized CPNumericData instance. **/ -(id)initWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray { return [self initWithData:newData dataType:CPDataTypeWithDataTypeString(newDataTypeString) shape:shapeArray]; } /** @brief Initializes a newly allocated CPNumericData object with the provided data. * * Objects in newData should be instances of NSNumber, NSDecimalNumber, NSString, or NSNull. * Numbers and strings will be converted to newDataType and stored in the receiver. * Any instances of NSNull will be treated as "not a number" (NAN) values for floating point types and "0" for integer types. * @param newData An array of numbers. * @param newDataType The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return The initialized CPNumericData instance. **/ -(id)initWithArray:(NSArray *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray { return [self initWithData:[self dataFromArray:newData dataType:newDataType] dataType:newDataType shape:shapeArray]; } /** @brief Initializes a newly allocated CPNumericData object with the provided data. * * Objects in newData should be instances of NSNumber, NSDecimalNumber, NSString, or NSNull. * Numbers and strings will be converted to newDataTypeString and stored in the receiver. * Any instances of NSNull will be treated as "not a number" (NAN) values for floating point types and "0" for integer types. * @param newData An array of numbers. * @param newDataTypeString The type of data stored in the buffer. * @param shapeArray The shape of the data buffer array. * @return The initialized CPNumericData instance. **/ -(id)initWithArray:(NSArray *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray { return [self initWithArray:newData dataType:CPDataTypeWithDataTypeString(newDataTypeString) shape:shapeArray]; } -(void)commonInitWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray { NSParameterAssert(CPDataTypeIsSupported(newDataType)); data = [newData copy]; dataType = newDataType; if ( shapeArray == nil ) { shape = [[NSArray arrayWithObject:[NSNumber numberWithUnsignedInteger:self.numberOfSamples]] retain]; } else { NSUInteger prod = 1; for ( NSNumber *cNum in shapeArray ) { prod *= [cNum unsignedIntegerValue]; } if ( prod != self.numberOfSamples ) { [NSException raise:CPNumericDataException format:@"Shape product (%u) does not match data size (%u)", prod, self.numberOfSamples]; } shape = [shapeArray copy]; } } -(void)dealloc { [data release]; [shape release]; [super dealloc]; } #pragma mark - #pragma mark Accessors -(NSUInteger)numberOfDimensions { return self.shape.count; } -(const void *)bytes { return self.data.bytes; } -(NSUInteger)length { return self.data.length; } -(NSUInteger)numberOfSamples { return (self.length / self.dataType.sampleBytes); } -(CPDataTypeFormat)dataTypeFormat { return self.dataType.dataTypeFormat; } -(size_t)sampleBytes { return self.dataType.sampleBytes; } -(CFByteOrder)byteOrder { return self.dataType.byteOrder; } #pragma mark - #pragma mark Samples /** @brief Gets the value of a given sample in the data buffer. * @param sample The index into the sample array. The array is treated as if it only has one dimension. * @return The sample value wrapped in an instance of NSNumber or <code>nil</code> if the sample index is out of bounds. * * NSNumber does not support complex numbers. Complex number types will be cast to * <code>float</code> or <code>double</code> before being wrapped in an instance of NSNumber. **/ -(NSNumber *)sampleValue:(NSUInteger)sample { NSNumber *result = nil; if ( sample < self.numberOfSamples ) { // Code generated with "CPNumericData+TypeConversions_Generation.py" // ======================================================================== switch ( self.dataTypeFormat ) { case CPUndefinedDataType: [NSException raise:NSInvalidArgumentException format:@"Unsupported data type (CPUndefinedDataType)"]; break; case CPIntegerDataType: switch ( self.sampleBytes ) { case sizeof(int8_t): result = [NSNumber numberWithChar:*(int8_t *)[self samplePointer:sample]]; break; case sizeof(int16_t): result = [NSNumber numberWithShort:*(int16_t *)[self samplePointer:sample]]; break; case sizeof(int32_t): result = [NSNumber numberWithLong:*(int32_t *)[self samplePointer:sample]]; break; case sizeof(int64_t): result = [NSNumber numberWithLongLong:*(int64_t *)[self samplePointer:sample]]; break; } break; case CPUnsignedIntegerDataType: switch ( self.sampleBytes ) { case sizeof(uint8_t): result = [NSNumber numberWithUnsignedChar:*(uint8_t *)[self samplePointer:sample]]; break; case sizeof(uint16_t): result = [NSNumber numberWithUnsignedShort:*(uint16_t *)[self samplePointer:sample]]; break; case sizeof(uint32_t): result = [NSNumber numberWithUnsignedLong:*(uint32_t *)[self samplePointer:sample]]; break; case sizeof(uint64_t): result = [NSNumber numberWithUnsignedLongLong:*(uint64_t *)[self samplePointer:sample]]; break; } break; case CPFloatingPointDataType: switch ( self.sampleBytes ) { case sizeof(float): result = [NSNumber numberWithFloat:*(float *)[self samplePointer:sample]]; break; case sizeof(double): result = [NSNumber numberWithDouble:*(double *)[self samplePointer:sample]]; break; } break; case CPComplexFloatingPointDataType: switch ( self.sampleBytes ) { case sizeof(float complex): result = [NSNumber numberWithFloat:*(float complex *)[self samplePointer:sample]]; break; case sizeof(double complex): result = [NSNumber numberWithDouble:*(double complex *)[self samplePointer:sample]]; break; } break; case CPDecimalDataType: switch ( self.sampleBytes ) { case sizeof(NSDecimal): result = [NSDecimalNumber decimalNumberWithDecimal:*(NSDecimal *)[self samplePointer:sample]]; break; } break; } // End of code generated with "CPNumericData+TypeConversions_Generation.py" // ======================================================================== } return result; } /** @brief Gets a pointer to a given sample in the data buffer. * @param sample The index into the sample array. The array is treated as if it only has one dimension. * @return A pointer to the sample or <code>NULL</code> if the sample index is out of bounds. **/ -(void *)samplePointer:(NSUInteger)sample { if ( sample < self.numberOfSamples ) { return (void *) ((char *)self.bytes + sample * self.sampleBytes); } else { return NULL; } } /** @brief Gets an array data samples from the receiver. * @return An NSArray of NSNumber objects representing the data from the receiver. **/ -(NSArray *)sampleArray { NSUInteger sampleCount = self.numberOfSamples; NSMutableArray *samples = [[NSMutableArray alloc] initWithCapacity:sampleCount]; for ( NSUInteger i = 0; i < sampleCount; i++ ) { [samples addObject:[self sampleValue:i]]; } NSArray *result = [NSArray arrayWithArray:samples]; [samples release]; return result; } -(NSData *)dataFromArray:(NSArray *)newData dataType:(CPNumericDataType)newDataType { NSParameterAssert(CPDataTypeIsSupported(newDataType)); NSParameterAssert(newDataType.dataTypeFormat != CPUndefinedDataType); NSParameterAssert(newDataType.dataTypeFormat != CPComplexFloatingPointDataType); NSMutableData *sampleData = [[NSMutableData alloc] initWithLength:newData.count * newDataType.sampleBytes]; // Code generated with "CPNumericData+TypeConversions_Generation.py" // ======================================================================== switch ( newDataType.dataTypeFormat ) { case CPUndefinedDataType: // Unsupported break; case CPIntegerDataType: switch ( newDataType.sampleBytes ) { case sizeof(int8_t): { int8_t *toBytes = (int8_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(charValue)] ) { *toBytes++ = (int8_t)[(NSNumber *)sample charValue]; } else { *toBytes++ = 0; } } } break; case sizeof(int16_t): { int16_t *toBytes = (int16_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(shortValue)] ) { *toBytes++ = (int16_t)[(NSNumber *)sample shortValue]; } else { *toBytes++ = 0; } } } break; case sizeof(int32_t): { int32_t *toBytes = (int32_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(longValue)] ) { *toBytes++ = (int32_t)[(NSNumber *)sample longValue]; } else { *toBytes++ = 0; } } } break; case sizeof(int64_t): { int64_t *toBytes = (int64_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(longLongValue)] ) { *toBytes++ = (int64_t)[(NSNumber *)sample longLongValue]; } else { *toBytes++ = 0; } } } break; } break; case CPUnsignedIntegerDataType: switch ( newDataType.sampleBytes ) { case sizeof(uint8_t): { uint8_t *toBytes = (uint8_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(unsignedCharValue)] ) { *toBytes++ = (uint8_t)[(NSNumber *)sample unsignedCharValue]; } else { *toBytes++ = 0; } } } break; case sizeof(uint16_t): { uint16_t *toBytes = (uint16_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(unsignedShortValue)] ) { *toBytes++ = (uint16_t)[(NSNumber *)sample unsignedShortValue]; } else { *toBytes++ = 0; } } } break; case sizeof(uint32_t): { uint32_t *toBytes = (uint32_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(unsignedLongValue)] ) { *toBytes++ = (uint32_t)[(NSNumber *)sample unsignedLongValue]; } else { *toBytes++ = 0; } } } break; case sizeof(uint64_t): { uint64_t *toBytes = (uint64_t *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(unsignedLongLongValue)] ) { *toBytes++ = (uint64_t)[(NSNumber *)sample unsignedLongLongValue]; } else { *toBytes++ = 0; } } } break; } break; case CPFloatingPointDataType: switch ( newDataType.sampleBytes ) { case sizeof(float): { float *toBytes = (float *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(floatValue)] ) { *toBytes++ = (float)[(NSNumber *)sample floatValue]; } else { *toBytes++ = NAN; } } } break; case sizeof(double): { double *toBytes = (double *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(doubleValue)] ) { *toBytes++ = (double)[(NSNumber *)sample doubleValue]; } else { *toBytes++ = NAN; } } } break; } break; case CPComplexFloatingPointDataType: switch ( newDataType.sampleBytes ) { case sizeof(float complex): { float complex *toBytes = (float complex *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(floatValue)] ) { *toBytes++ = (float complex)[(NSNumber *)sample floatValue]; } else { *toBytes++ = NAN; } } } break; case sizeof(double complex): { double complex *toBytes = (double complex *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(doubleValue)] ) { *toBytes++ = (double complex)[(NSNumber *)sample doubleValue]; } else { *toBytes++ = NAN; } } } break; } break; case CPDecimalDataType: switch ( newDataType.sampleBytes ) { case sizeof(NSDecimal): { NSDecimal *toBytes = (NSDecimal *)sampleData.mutableBytes; for ( id sample in newData ) { if ( [sample respondsToSelector:@selector(decimalValue)] ) { *toBytes++ = (NSDecimal)[(NSNumber *)sample decimalValue]; } else { *toBytes++ = CPDecimalNaN(); } } } break; } break; } // End of code generated with "CPNumericData+TypeConversions_Generation.py" // ======================================================================== if ( (newDataType.byteOrder != CFByteOrderGetCurrent()) && (newDataType.byteOrder != CFByteOrderUnknown) ) { [self swapByteOrderForData:sampleData sampleSize:newDataType.sampleBytes]; } return [sampleData autorelease]; } #pragma mark - #pragma mark Description -(NSString *)description { NSUInteger sampleCount = self.numberOfSamples; NSMutableString *descriptionString = [NSMutableString stringWithCapacity:sampleCount * 3]; [descriptionString appendFormat:@"<%@ [", [super description]]; for ( NSUInteger i = 0; i < sampleCount; i++ ) { if ( i > 0 ) { [descriptionString appendFormat:@","]; } [descriptionString appendFormat:@" %@", [self sampleValue:i]]; } [descriptionString appendFormat:@" ] {%@, %@}>", CPDataTypeStringFromDataType(self.dataType), self.shape]; return descriptionString; } #pragma mark - #pragma mark NSMutableCopying -(id)mutableCopyWithZone:(NSZone *)zone { if ( NSShouldRetainWithZone(self, zone)) { return [self retain]; } return [[CPMutableNumericData allocWithZone:zone] initWithData:self.data dataType:self.dataType shape:self.shape]; } #pragma mark - #pragma mark NSCopying -(id)copyWithZone:(NSZone *)zone { return [[[self class] allocWithZone:zone] initWithData:self.data dataType:self.dataType shape:self.shape]; } #pragma mark - #pragma mark NSCoding -(void)encodeWithCoder:(NSCoder *)encoder { //[super encodeWithCoder:encoder]; if ( [encoder allowsKeyedCoding] ) { [encoder encodeObject:self.data forKey:@"data"]; CPNumericDataType selfDataType = self.dataType; [encoder encodeInteger:selfDataType.dataTypeFormat forKey:@"dataType.dataTypeFormat"]; [encoder encodeInteger:selfDataType.sampleBytes forKey:@"dataType.sampleBytes"]; [encoder encodeInteger:selfDataType.byteOrder forKey:@"dataType.byteOrder"]; [encoder encodeObject:self.shape forKey:@"shape"]; } else { [encoder encodeObject:self.data]; CPNumericDataType selfDataType = self.dataType; [encoder encodeValueOfObjCType:@encode(CPDataTypeFormat) at:&(selfDataType.dataTypeFormat)]; [encoder encodeValueOfObjCType:@encode(NSUInteger) at:&(selfDataType.sampleBytes)]; [encoder encodeValueOfObjCType:@encode(CFByteOrder) at:&(selfDataType.byteOrder)]; [encoder encodeObject:self.shape]; } } -(id)initWithCoder:(NSCoder *)decoder { if ( self = [super init] ) { NSData *newData; CPNumericDataType newDataType; NSArray *shapeArray; if ( [decoder allowsKeyedCoding] ) { newData = [decoder decodeObjectForKey:@"data"]; newDataType = CPDataType([decoder decodeIntegerForKey:@"dataType.dataTypeFormat"], [decoder decodeIntegerForKey:@"dataType.sampleBytes"], [decoder decodeIntegerForKey:@"dataType.byteOrder"]); shapeArray = [decoder decodeObjectForKey:@"shape"]; } else { newData = [decoder decodeObject]; [decoder decodeValueOfObjCType:@encode(CPDataTypeFormat) at:&(newDataType.dataTypeFormat)]; [decoder decodeValueOfObjCType:@encode(NSUInteger) at:&(newDataType.sampleBytes)]; [decoder decodeValueOfObjCType:@encode(CFByteOrder) at:&(newDataType.byteOrder)]; shapeArray = [decoder decodeObject]; } [self commonInitWithData:newData dataType:newDataType shape:shapeArray]; } return self; } @end
08iteng-ipad
framework/Source/CPNumericData.m
Objective-C
bsd
23,706
#import "CPTextLayer.h" #import "CPPlatformSpecificFunctions.h" #import "CPColor.h" #import "CPColorSpace.h" #import "CPPlatformSpecificCategories.h" #import "CPUtilities.h" const CGFloat kCPTextLayerMarginWidth = 1.0; /** @brief A Core Animation layer that displays a single line of text drawn in a uniform style. **/ @implementation CPTextLayer /** @property text * @brief The text to display. **/ @synthesize text; /** @property textStyle * @brief The text style used to draw the text. **/ @synthesize textStyle; #pragma mark - #pragma mark Initialization and teardown /** @brief Initializes a newly allocated CPTextLayer object with the provided text and style. This is the designated initializer. * @param newText The text to display. * @param newStyle The text style used to draw the text. * @return The initialized CPTextLayer object. **/ -(id)initWithText:(NSString *)newText style:(CPTextStyle *)newStyle { if (self = [super initWithFrame:CGRectZero]) { textStyle = [newStyle retain]; text = [newText copy]; self.needsDisplayOnBoundsChange = NO; [self sizeToFit]; } return self; } /** @brief Initializes a newly allocated CPTextLayer object with the provided text and the default text style. * @param newText The text to display. * @return The initialized CPTextLayer object. **/ -(id)initWithText:(NSString *)newText { return [self initWithText:newText style:[CPTextStyle textStyle]]; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPTextLayer *theLayer = (CPTextLayer *)layer; textStyle = [theLayer->textStyle retain]; text = [theLayer->text retain]; } return self; } -(void)dealloc { [textStyle release]; [text release]; [super dealloc]; } #pragma mark - #pragma mark Accessors -(void)setText:(NSString *)newValue { if ( text != newValue ) { [text release]; text = [newValue copy]; [self sizeToFit]; } } -(void)setTextStyle:(CPTextStyle *)newStyle { if ( textStyle != newStyle ) { [textStyle release]; textStyle = [newStyle retain]; [self sizeToFit]; } } #pragma mark - #pragma mark Layout /** @brief Determine the minimum size needed to fit the text **/ -(CGSize)sizeThatFits { if ( self.text == nil ) return CGSizeZero; CGSize textSize = [self.text sizeWithTextStyle:textStyle]; // Add small margin textSize.width += 2 * kCPTextLayerMarginWidth; textSize.height += 2 * kCPTextLayerMarginWidth; textSize.width = ceil(textSize.width); textSize.height = ceil(textSize.height); return textSize; } /** @brief Resizes the layer to fit its contents leaving a narrow margin on all four sides. **/ -(void)sizeToFit { if ( self.text == nil ) return; CGSize sizeThatFits = [self sizeThatFits]; CGRect newBounds = self.bounds; newBounds.size = sizeThatFits; self.bounds = newBounds; [self pixelAlign]; [self setNeedsLayout]; [self setNeedsDisplay]; } #pragma mark - #pragma mark Drawing of text -(void)renderAsVectorInContext:(CGContextRef)context { [super renderAsVectorInContext:context]; #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE CGContextSaveGState(context); CGContextTranslateCTM(context, 0.0, self.bounds.size.height); CGContextScaleCTM(context, 1.0, -1.0); #endif [self.text drawAtPoint:CPAlignPointToUserSpace(context, CGPointMake(kCPTextLayerMarginWidth, kCPTextLayerMarginWidth)) withTextStyle:self.textStyle inContext:context]; #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE CGContextRestoreGState(context); #endif } #pragma mark - #pragma mark Text style delegate -(void)textStyleDidChange:(CPTextStyle *)textStyle { [self sizeToFit]; } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"<%@ \"%@\">", [super description], self.text]; }; @end
08iteng-ipad
framework/Source/CPTextLayer.m
Objective-C
bsd
3,788
#import <Foundation/Foundation.h> #import "CPLayer.h" @class CPLineStyle; @interface CPAxisSet : CPLayer { @private NSArray *axes; CPLineStyle *borderLineStyle; } @property (nonatomic, readwrite, retain) NSArray *axes; @property (nonatomic, readwrite, copy) CPLineStyle *borderLineStyle; -(void)relabelAxes; @end
08iteng-ipad
framework/Source/CPAxisSet.h
Objective-C
bsd
324
#import "CPColor.h" #import "CPColorSpace.h" #import "CPPlatformSpecificFunctions.h" /** @brief Wrapper around CGColorRef * * A wrapper class around CGColorRef * * @todo More documentation needed. **/ @implementation CPColor /** @property cgColor * @brief The CGColor to wrap around. **/ @synthesize cgColor; #pragma mark - #pragma mark Factory Methods /** @brief Returns a shared instance of CPColor initialized with a fully transparent color. * * @return A shared CPColor object initialized with a fully transparent color. **/ +(CPColor *)clearColor { static CPColor *color = nil; if ( nil == color ) { CGColorRef clear = NULL; CGFloat values[4] = {0.0, 0.0, 0.0, 0.0}; clear = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values); color = [[CPColor alloc] initWithCGColor:clear]; CGColorRelease(clear); } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque white color. * * @return A shared CPColor object initialized with a fully opaque white color. **/ +(CPColor *)whiteColor { static CPColor *color = nil; if ( nil == color ) { color = [[self colorWithGenericGray:1.0] retain]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque 2/3 gray color. * * @return A shared CPColor object initialized with a fully opaque 2/3 gray color. **/ +(CPColor *)lightGrayColor { static CPColor *color = nil; if ( nil == color ) { color = [[self colorWithGenericGray:2.0/3.0] retain]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque 50% gray color. * * @return A shared CPColor object initialized with a fully opaque 50% gray color. **/ +(CPColor *)grayColor { static CPColor *color = nil; if ( nil == color ) { color = [[self colorWithGenericGray:0.5] retain]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque 1/3 gray color. * * @return A shared CPColor object initialized with a fully opaque 1/3 gray color. **/ +(CPColor *)darkGrayColor { static CPColor *color = nil; if ( nil == color ) { color = [[self colorWithGenericGray:1.0/3.0] retain]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque black color. * * @return A shared CPColor object initialized with a fully opaque black color. **/ +(CPColor *)blackColor { static CPColor *color = nil; if ( nil == color ) { color = [[self colorWithGenericGray:0.0] retain]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque red color. * * @return A shared CPColor object initialized with a fully opaque red color. **/ +(CPColor *)redColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:1.0 green:0.0 blue:0.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque green color. * * @return A shared CPColor object initialized with a fully opaque green color. **/ +(CPColor *)greenColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:0.0 green:1.0 blue:0.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque blue color. * * @return A shared CPColor object initialized with a fully opaque blue color. **/ +(CPColor *)blueColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:0.0 green:0.0 blue:1.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque cyan color. * * @return A shared CPColor object initialized with a fully opaque cyan color. **/ +(CPColor *)cyanColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:0.0 green:1.0 blue:1.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque yellow color. * * @return A shared CPColor object initialized with a fully opaque yellow color. **/ +(CPColor *)yellowColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:1.0 green:1.0 blue:0.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque magenta color. * * @return A shared CPColor object initialized with a fully opaque magenta color. **/ +(CPColor *)magentaColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:1.0 green:0.0 blue:1.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque orange color. * * @return A shared CPColor object initialized with a fully opaque orange color. **/ +(CPColor *)orangeColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:1.0 green:0.5 blue:0.0 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque purple color. * * @return A shared CPColor object initialized with a fully opaque purple color. **/ +(CPColor *)purpleColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:0.5 green:0.0 blue:0.5 alpha:1.0]; } return color; } /** @brief Returns a shared instance of CPColor initialized with a fully opaque brown color. * * @return A shared CPColor object initialized with a fully opaque brown color. **/ +(CPColor *)brownColor { static CPColor *color = nil; if ( nil == color ) { color = [[CPColor alloc] initWithComponentRed:0.6 green:0.4 blue:0.2 alpha:1.0]; } return color; } /** @brief Creates and returns a new CPColor instance initialized with the provided CGColorRef. * @param newCGColor The color to wrap. * @return A new CPColor instance initialized with the provided CGColorRef. **/ +(CPColor *)colorWithCGColor:(CGColorRef)newCGColor { return [[[CPColor alloc] initWithCGColor:newCGColor] autorelease]; } /** @brief Creates and returns a new CPColor instance initialized with the provided RGBA color components. * @param red The red component (0 ≤ red ≤ 1). * @param green The green component (0 ≤ green ≤ 1). * @param blue The blue component (0 ≤ blue ≤ 1). * @param alpha The alpha component (0 ≤ alpha ≤ 1). * @return A new CPColor instance initialized with the provided RGBA color components. **/ +(CPColor *)colorWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha { return [[[CPColor alloc] initWithComponentRed:red green:green blue:blue alpha:alpha] autorelease]; } /** @brief Creates and returns a new CPColor instance initialized with the provided gray level. * @param gray The gray level (0 ≤ gray ≤ 1). * @return A new CPColor instance initialized with the provided gray level. **/ +(CPColor *)colorWithGenericGray:(CGFloat)gray { CGFloat values[4] = {gray, gray, gray, 1.0}; CGColorRef colorRef = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values); CPColor *color = [[CPColor alloc] initWithCGColor:colorRef]; CGColorRelease(colorRef); return [color autorelease]; } #pragma mark - #pragma mark Initialize/Deallocate /** @brief Initializes a newly allocated CPColor object with the provided CGColorRef. * * @param newCGColor The color to wrap. * @return The initialized CPColor object. **/ -(id)initWithCGColor:(CGColorRef)newCGColor { if ( self = [super init] ) { CGColorRetain(newCGColor); cgColor = newCGColor; } return self; } /** @brief Initializes a newly allocated CPColor object with the provided RGBA color components. * * @param red The red component (0 ≤ red ≤ 1). * @param green The green component (0 ≤ green ≤ 1). * @param blue The blue component (0 ≤ blue ≤ 1). * @param alpha The alpha component (0 ≤ alpha ≤ 1). * @return The initialized CPColor object. **/ -(id)initWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha { CGFloat colorComponents[4]; colorComponents[0] = red; colorComponents[1] = green; colorComponents[2] = blue; colorComponents[3] = alpha; CGColorRef color = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, colorComponents); [self initWithCGColor:color]; CGColorRelease(color); return self; } -(void)dealloc { CGColorRelease(cgColor); [super dealloc]; } -(void)finalize { CGColorRelease(cgColor); [super finalize]; } #pragma mark - #pragma mark Creating colors from other colors /** @brief Creates and returns a new CPColor instance having color components identical to the current object * but having the provided alpha component. * @param alpha The alpha component (0 ≤ alpha ≤ 1). * @return A new CPColor instance having the provided alpha component. **/ -(CPColor *)colorWithAlphaComponent:(CGFloat)alpha { CGColorRef newCGColor = CGColorCreateCopyWithAlpha(self.cgColor, alpha); CPColor *newColor = [CPColor colorWithCGColor:newCGColor]; CGColorRelease(newCGColor); return newColor; } #pragma mark - #pragma mark NSCoding methods -(void)encodeWithCoder:(NSCoder *)coder { const CGFloat *colorComponents = CGColorGetComponents(self.cgColor); [coder encodeDouble:colorComponents[0] forKey:@"redComponent"]; [coder encodeDouble:colorComponents[1] forKey:@"greenComponent"]; [coder encodeDouble:colorComponents[2] forKey:@"blueComponent"]; [coder encodeDouble:colorComponents[3] forKey:@"alphaComponent"]; } -(id)initWithCoder:(NSCoder *)coder { self = [super init]; if (self) { CGFloat colorComponents[4]; colorComponents[0] = [coder decodeDoubleForKey:@"redComponent"]; colorComponents[1] = [coder decodeDoubleForKey:@"greenComponent"]; colorComponents[2] = [coder decodeDoubleForKey:@"blueComponent"]; colorComponents[3] = [coder decodeDoubleForKey:@"alphaComponent"]; cgColor = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, colorComponents); } return self; } #pragma mark - #pragma mark NSCopying methods -(id)copyWithZone:(NSZone *)zone { CGColorRef cgColorCopy = NULL; if ( cgColor ) cgColorCopy = CGColorCreateCopy(cgColor); CPColor *colorCopy = [[[self class] allocWithZone:zone] initWithCGColor:cgColorCopy]; CGColorRelease(cgColorCopy); return colorCopy; } #pragma mark - #pragma mark Color comparison -(BOOL)isEqual:(id)object { if ( self == object ) { return YES; } else if ([object isKindOfClass:[self class]]) { return CGColorEqualToColor(self.cgColor, ((CPColor *)object).cgColor); } else { return NO; } } -(NSUInteger)hash { // Equal objects must hash the same. CGFloat theHash = 0.0; CGFloat multiplier = 256.0; CGColorRef theColor = self.cgColor; size_t numberOfComponents = CGColorGetNumberOfComponents(theColor); const CGFloat *colorComponents = CGColorGetComponents(theColor); for (NSUInteger i = 0; i < numberOfComponents; i++) { theHash += multiplier * colorComponents[i]; multiplier *= 256.0; } return (NSUInteger)theHash; } @end
08iteng-ipad
framework/Source/CPColor.m
Objective-C
bsd
11,522
#import "CPRangePlot.h" #import "CPMutableNumericData.h" #import "CPNumericData.h" #import "CPLineStyle.h" #import "CPColor.h" #import "CPPlotArea.h" #import "CPPlotSpace.h" #import "CPPlotSpaceAnnotation.h" #import "CPExceptions.h" #import "CPUtilities.h" #import "CPXYPlotSpace.h" #import "CPPlotSpace.h" #import "CPFill.h" NSString * const CPRangePlotBindingXValues = @"xValues"; ///< X values. NSString * const CPRangePlotBindingYValues = @"yValues"; ///< Y values. NSString * const CPRangePlotBindingHighValues = @"highValues"; ///< high values. NSString * const CPRangePlotBindingLowValues = @"lowValues"; ///< low values. NSString * const CPRangePlotBindingLeftValues = @"leftValues"; ///< left price values. NSString * const CPRangePlotBindingRightValues = @"rightValues";///< right price values. /** @cond */ struct CGPointError { CGFloat x; CGFloat y; CGFloat high; CGFloat low; CGFloat left; CGFloat right; }; typedef struct CGPointError CGPointError; @interface CPRangePlot () @property (nonatomic, readwrite, copy) NSArray *xValues; @property (nonatomic, readwrite, copy) NSArray *yValues; @property (nonatomic, readwrite, copy) CPMutableNumericData *highValues; @property (nonatomic, readwrite, copy) CPMutableNumericData *lowValues; @property (nonatomic, readwrite, copy) CPMutableNumericData *leftValues; @property (nonatomic, readwrite, copy) CPMutableNumericData *rightValues; @end /** @endcond */ /** @brief A plot class representing a range of values in one coordinate, * such as typically used to show errors. * A range plot can show bars (error bars), or an area fill, or both. **/ @implementation CPRangePlot @dynamic xValues; @dynamic yValues; @dynamic highValues; @dynamic lowValues; @dynamic leftValues; @dynamic rightValues; /** @property areaFill * @brief The fill used to render the area. * Set to nil to have no fill. Default is nil. **/ @synthesize areaFill; /** @property barLineStyle * @brief The line style of the range bars. * Set to nil to have no bars. Default is a black line style. **/ @synthesize barLineStyle; /** @property barWidth * @brief Width of the lateral sections of the bars. **/ @synthesize barWidth; /** @property gapHeight * @brief Height of the central gap. * Set to zero to have no gap. **/ @synthesize gapHeight; /** @property gapWidth * @brief Width of the central gap. * Set to zero to have no gap. **/ @synthesize gapWidth; #pragma mark - #pragma mark init/dealloc #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE #else +(void)initialize { if ( self == [CPRangePlot class] ) { [self exposeBinding:CPRangePlotBindingXValues]; [self exposeBinding:CPRangePlotBindingYValues]; [self exposeBinding:CPRangePlotBindingHighValues]; [self exposeBinding:CPRangePlotBindingLowValues]; [self exposeBinding:CPRangePlotBindingLeftValues]; [self exposeBinding:CPRangePlotBindingRightValues]; } } #endif -(id)initWithFrame:(CGRect)newFrame { if ( (self = [super initWithFrame:newFrame]) ) { barLineStyle = [[CPLineStyle alloc] init]; areaFill = nil; } return self; } -(id)initWithLayer:(id)layer { if ( (self = [super initWithLayer:layer]) ) { CPRangePlot *theLayer = (CPRangePlot *)layer; barLineStyle = [theLayer->barLineStyle retain]; areaFill = nil; } return self; } -(void)dealloc { [barLineStyle release]; [areaFill release]; [super dealloc]; } #pragma mark - #pragma mark Determining Which Points to Draw -(void)calculatePointsToDraw:(BOOL *)pointDrawFlags forPlotSpace:(CPXYPlotSpace *)xyPlotSpace includeVisiblePointsOnly:(BOOL)visibleOnly { NSUInteger dataCount = self.cachedDataCount; if ( dataCount == 0 ) return; CPPlotRangeComparisonResult *xRangeFlags = malloc(dataCount * sizeof(CPPlotRangeComparisonResult)); CPPlotRangeComparisonResult *yRangeFlags = malloc(dataCount * sizeof(CPPlotRangeComparisonResult)); BOOL *nanFlags = malloc(dataCount * sizeof(BOOL)); CPPlotRange *xRange = xyPlotSpace.xRange; CPPlotRange *yRange = xyPlotSpace.yRange; // Determine where each point lies in relation to range if ( self.doublePrecisionCache ) { const double *xBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldX].data.bytes; const double *yBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldY].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const double x = *xBytes++; const double y = *yBytes++; xRangeFlags[i] = [xRange compareToDouble:x]; yRangeFlags[i] = [yRange compareToDouble:y]; nanFlags[i] = isnan(x) || isnan(y); } } else { // Determine where each point lies in relation to range const NSDecimal *xBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldX].data.bytes; const NSDecimal *yBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldY].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const NSDecimal *x = xBytes++; const NSDecimal *y = yBytes++; xRangeFlags[i] = [xRange compareToDecimal:*x]; yRangeFlags[i] = [yRange compareToDecimal:*y]; nanFlags[i] = NSDecimalIsNotANumber(x);// || NSDecimalIsNotANumber(high) || NSDecimalIsNotANumber(low); } } // Ensure that whenever the path crosses over a region boundary, both points // are included. This ensures no lines are left out that shouldn't be. pointDrawFlags[0] = (xRangeFlags[0] == CPPlotRangeComparisonResultNumberInRange && yRangeFlags[0] == CPPlotRangeComparisonResultNumberInRange && !nanFlags[0]); for ( NSUInteger i = 1; i < dataCount; i++ ) { pointDrawFlags[i] = NO; if ( !visibleOnly && !nanFlags[i-1] && !nanFlags[i] && ((xRangeFlags[i-1] != xRangeFlags[i]) || (xRangeFlags[i-1] != xRangeFlags[i]))) { pointDrawFlags[i-1] = YES; pointDrawFlags[i] = YES; } else if ( (xRangeFlags[i] == CPPlotRangeComparisonResultNumberInRange) && (yRangeFlags[i] == CPPlotRangeComparisonResultNumberInRange) && !nanFlags[i]) { pointDrawFlags[i] = YES; } } free(xRangeFlags); free(yRangeFlags); free(nanFlags); } -(void)calculateViewPoints:(CGPointError *)viewPoints withDrawPointFlags:(BOOL *)drawPointFlags { NSUInteger dataCount = self.cachedDataCount; CPPlotArea *thePlotArea = self.plotArea; CPPlotSpace *thePlotSpace = self.plotSpace; // Calculate points if ( self.doublePrecisionCache ) { const double *xBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldX].data.bytes; const double *yBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldY].data.bytes; const double *highBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldHigh].data.bytes; const double *lowBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldLow].data.bytes; const double *leftBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldLeft].data.bytes; const double *rightBytes = (const double *)[self cachedNumbersForField:CPRangePlotFieldRight].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const double x = *xBytes++; const double y = *yBytes++; const double high = *highBytes++; const double low = *lowBytes++; const double left = *leftBytes++; const double right = *rightBytes++; if ( !drawPointFlags[i] || isnan(x) || isnan(y)) { viewPoints[i].x = NAN; // depending coordinates viewPoints[i].y = NAN; } else { double plotPoint[2]; plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y; CGPoint pos = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].x = pos.x; viewPoints[i].y = pos.y; plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y + high; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].high = pos.y; plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y - low; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].low = pos.y; plotPoint[CPCoordinateX] = x-left; plotPoint[CPCoordinateY] = y; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].left = pos.x; plotPoint[CPCoordinateX] = x+right; plotPoint[CPCoordinateY] = y; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].right = pos.x; } } } else { const NSDecimal *xBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldX].data.bytes; const NSDecimal *yBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldY].data.bytes; const NSDecimal *highBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldHigh].data.bytes; const NSDecimal *lowBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldLow].data.bytes; const NSDecimal *leftBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldLeft].data.bytes; const NSDecimal *rightBytes = (const NSDecimal *)[self cachedNumbersForField:CPRangePlotFieldRight].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const NSDecimal x = *xBytes++; const NSDecimal y = *yBytes++; const NSDecimal high = *highBytes++; const NSDecimal low = *lowBytes++; const NSDecimal left = *leftBytes++; const NSDecimal right = *rightBytes++; if ( !drawPointFlags[i] || NSDecimalIsNotANumber(&x) || NSDecimalIsNotANumber(&y)) { viewPoints[i].x = NAN; // depending coordinates viewPoints[i].y = NAN; } else { NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y; CGPoint pos = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].x = pos.x; viewPoints[i].y = pos.y; if (!NSDecimalIsNotANumber(&high)) { plotPoint[CPCoordinateX] = x; NSDecimal yh; NSDecimalAdd(&yh, &y, &high, NSRoundPlain); plotPoint[CPCoordinateY] = yh; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].high = pos.y; } else { viewPoints[i].high = NAN; } if (!NSDecimalIsNotANumber(&low)) { plotPoint[CPCoordinateX] = x; NSDecimal yl; NSDecimalSubtract(&yl, &y, &low, NSRoundPlain); plotPoint[CPCoordinateY] = yl; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].low = pos.y; } else { viewPoints[i].low = NAN; } if (!NSDecimalIsNotANumber(&left)) { NSDecimal xl; NSDecimalSubtract(&xl, &x, &left, NSRoundPlain); plotPoint[CPCoordinateX] = xl; plotPoint[CPCoordinateY] = y; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].left = pos.x; } else { viewPoints[i].left = NAN; } if (!NSDecimalIsNotANumber(&right)) { NSDecimal xr; NSDecimalAdd(&xr, &x, &right, NSRoundPlain); plotPoint[CPCoordinateX] = xr; plotPoint[CPCoordinateY] = y; pos = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; viewPoints[i].right = pos.x; } else { viewPoints[i].right = NAN; } } } } } -(void)alignViewPointsToUserSpace:(CGPointError *)viewPoints withContent:(CGContextRef)theContext drawPointFlags:(BOOL *)drawPointFlags { NSUInteger dataCount = self.cachedDataCount; for ( NSUInteger i = 0; i < dataCount; i++ ) { if ( drawPointFlags[i] ) { CGFloat x = viewPoints[i].x; CGFloat y = viewPoints[i].y; CGPoint pos = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x,viewPoints[i].y)); viewPoints[i].x = pos.x; viewPoints[i].y = pos.y; pos = CPAlignPointToUserSpace(theContext, CGPointMake(x,viewPoints[i].high)); viewPoints[i].high = pos.y; pos = CPAlignPointToUserSpace(theContext, CGPointMake(x,viewPoints[i].low)); viewPoints[i].low = pos.y; pos = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].left,y)); viewPoints[i].left = pos.x; pos = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].right,y)); viewPoints[i].right = pos.x; } } } -(NSUInteger)extremeDrawnPointIndexForFlags:(BOOL *)pointDrawFlags extremeNumIsLowerBound:(BOOL)isLowerBound { NSInteger result = NSNotFound; NSInteger delta = (isLowerBound ? 1 : -1); NSUInteger dataCount = self.cachedDataCount; if ( dataCount > 0 ) { NSUInteger initialIndex = (isLowerBound ? 0 : dataCount - 1); for ( NSUInteger i = initialIndex; i < dataCount; i += delta ) { if ( pointDrawFlags[i] ) { result = i; break; } if ( (delta < 0) && (i == 0) ) break; } } return result; } #pragma mark - #pragma mark Data Loading -(void)reloadDataInIndexRange:(NSRange)indexRange { [super reloadDataInIndexRange:indexRange]; if ( self.dataSource ) { id newXValues = [self numbersFromDataSourceForField:CPRangePlotFieldX recordIndexRange:indexRange]; [self cacheNumbers:newXValues forField:CPRangePlotFieldX atRecordIndex:indexRange.location]; id newYValues = [self numbersFromDataSourceForField:CPRangePlotFieldY recordIndexRange:indexRange]; [self cacheNumbers:newYValues forField:CPRangePlotFieldY atRecordIndex:indexRange.location]; id newHighValues = [self numbersFromDataSourceForField:CPRangePlotFieldHigh recordIndexRange:indexRange]; [self cacheNumbers:newHighValues forField:CPRangePlotFieldHigh atRecordIndex:indexRange.location]; id newLowValues = [self numbersFromDataSourceForField:CPRangePlotFieldLow recordIndexRange:indexRange]; [self cacheNumbers:newLowValues forField:CPRangePlotFieldLow atRecordIndex:indexRange.location]; id newLeftValues = [self numbersFromDataSourceForField:CPRangePlotFieldLeft recordIndexRange:indexRange]; [self cacheNumbers:newLeftValues forField:CPRangePlotFieldLeft atRecordIndex:indexRange.location]; id newRightValues = [self numbersFromDataSourceForField:CPRangePlotFieldRight recordIndexRange:indexRange]; [self cacheNumbers:newRightValues forField:CPRangePlotFieldRight atRecordIndex:indexRange.location]; } else { self.xValues = nil; self.yValues = nil; self.highValues = nil; self.lowValues = nil; self.leftValues = nil; self.rightValues = nil; } } -(void)renderAsVectorInContext:(CGContextRef)theContext { CPMutableNumericData *xValueData = [self cachedNumbersForField:CPRangePlotFieldX]; CPMutableNumericData *yValueData = [self cachedNumbersForField:CPRangePlotFieldY]; if ( xValueData == nil || yValueData == nil) return; NSUInteger dataCount = self.cachedDataCount; if ( dataCount == 0 ) return; if (xValueData.numberOfSamples != yValueData.numberOfSamples) { [NSException raise:CPException format:@"Number of x and y values do not match"]; } // Calculate view points, and align to user space CGPointError *viewPoints = malloc(dataCount * sizeof(CGPointError)); BOOL *drawPointFlags = malloc(dataCount * sizeof(BOOL)); CPXYPlotSpace *thePlotSpace = (CPXYPlotSpace *)self.plotSpace; [self calculatePointsToDraw:drawPointFlags forPlotSpace:thePlotSpace includeVisiblePointsOnly:NO]; [self calculateViewPoints:viewPoints withDrawPointFlags:drawPointFlags]; [self alignViewPointsToUserSpace:viewPoints withContent:theContext drawPointFlags:drawPointFlags]; // Get extreme points NSUInteger lastDrawnPointIndex = [self extremeDrawnPointIndexForFlags:drawPointFlags extremeNumIsLowerBound:NO]; NSUInteger firstDrawnPointIndex = [self extremeDrawnPointIndexForFlags:drawPointFlags extremeNumIsLowerBound:YES]; if ( firstDrawnPointIndex != NSNotFound ) { if ( areaFill ) { CGMutablePathRef fillPath = CGPathCreateMutable(); // First do the top points for ( NSUInteger i = firstDrawnPointIndex; i <= lastDrawnPointIndex; i++ ) { CGFloat x = viewPoints[i].x; CGFloat y = viewPoints[i].high; if(isnan(y)) y = viewPoints[i].y; if (!isnan(x) && !isnan(y)) { CGPoint alignedPoint = CPAlignPointToUserSpace(theContext, CGPointMake(x,y)); if (i == firstDrawnPointIndex) { CGPathMoveToPoint(fillPath, NULL, alignedPoint.x, alignedPoint.y); } else { CGPathAddLineToPoint(fillPath, NULL, alignedPoint.x, alignedPoint.y); } } } // Then reverse over bottom points for ( NSUInteger j = lastDrawnPointIndex; j >= firstDrawnPointIndex; j-- ) { CGFloat x = viewPoints[j].x; CGFloat y = viewPoints[j].low; if(isnan(y)) y = viewPoints[j].y; if (!isnan(x) && !isnan(y)) { CGPoint alignedPoint = CPAlignPointToUserSpace(theContext, CGPointMake(x,y)); CGPathAddLineToPoint(fillPath, NULL, alignedPoint.x, alignedPoint.y); } if (j == firstDrawnPointIndex) { // This could be done a bit more elegant break; } } CGContextBeginPath(theContext); CGContextAddPath(theContext, fillPath); // Close the path to have a closed loop CGPathCloseSubpath(fillPath); CGContextSaveGState(theContext); // Pick the current linestyle with a low alpha component [areaFill fillPathInContext:theContext]; CGPathRelease(fillPath); } if ( barLineStyle ) { for ( NSUInteger i = firstDrawnPointIndex; i <= lastDrawnPointIndex; i++ ) { if (!isnan(viewPoints[i].x) && !isnan(viewPoints[i].y)) { //depending coordinates CGMutablePathRef path = CGPathCreateMutable(); // centre-high if (!isnan(viewPoints[i].high)) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x, viewPoints[i].y + 0.5f * self.gapHeight)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x, viewPoints[i].high)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // centre-low if (!isnan(viewPoints[i].low)) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x, viewPoints[i].y - 0.5f * self.gapHeight)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x, viewPoints[i].low)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // top bar if (!isnan(viewPoints[i].high) ) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x - 0.5f * self.barWidth,viewPoints[i].high)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x + 0.5f * self.barWidth, viewPoints[i].high)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // bottom bar if (!isnan(viewPoints[i].low) ) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x - 0.5f * self.barWidth, viewPoints[i].low)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x + 0.5f * self.barWidth, viewPoints[i].low)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // centre-left if (!isnan(viewPoints[i].left)) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x - 0.5f * self.gapWidth, viewPoints[i].y)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].left, viewPoints[i].y)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // centre-right if (!isnan(viewPoints[i].right)) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x + 0.5f * self.gapWidth, viewPoints[i].y)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].right, viewPoints[i].y)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // left bar if (!isnan(viewPoints[i].left) ) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].left, viewPoints[i].y - 0.5f * self.barWidth)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].left, viewPoints[i].y + 0.5f * self.barWidth)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } // right bar if (!isnan(viewPoints[i].right) ) { CGPoint alignedHighPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].right, viewPoints[i].y - 0.5f * self.barWidth)); CGPoint alignedLowPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].right, viewPoints[i].y + 0.5f * self.barWidth)); CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y); CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y); } CGContextBeginPath(theContext); CGContextAddPath(theContext, path); [self.barLineStyle setLineStyleInContext:theContext]; CGContextStrokePath(theContext); CGPathRelease(path); } } } free(viewPoints); free(drawPointFlags); } } #pragma mark - #pragma mark Fields -(NSUInteger)numberOfFields { return 6; } -(NSArray *)fieldIdentifiers { return [NSArray arrayWithObjects: [NSNumber numberWithUnsignedInt:CPRangePlotFieldX], [NSNumber numberWithUnsignedInt:CPRangePlotFieldY], [NSNumber numberWithUnsignedInt:CPRangePlotFieldHigh], [NSNumber numberWithUnsignedInt:CPRangePlotFieldLow], [NSNumber numberWithUnsignedInt:CPRangePlotFieldLeft], [NSNumber numberWithUnsignedInt:CPRangePlotFieldRight], nil]; } -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord { NSArray *result = nil; switch (coord) { case CPCoordinateX: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:CPRangePlotFieldX]]; break; case CPCoordinateY: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:CPRangePlotFieldY]]; break; default: [NSException raise:CPException format:@"Invalid coordinate passed to fieldIdentifiersForCoordinate:"]; break; } return result; } #pragma mark - #pragma mark Data Labels -(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index { NSNumber *xValue = [self cachedNumberForField:CPRangePlotFieldX recordIndex:index]; BOOL positiveDirection = YES; CPPlotRange *yRange = [self.plotSpace plotRangeForCoordinate:CPCoordinateY]; if ( CPDecimalLessThan(yRange.length, CPDecimalFromInteger(0)) ) { positiveDirection = !positiveDirection; } NSNumber *yValue; NSArray *yValues = [NSArray arrayWithObject:[self cachedNumberForField:CPRangePlotFieldY recordIndex:index]]; NSArray *yValuesSorted = [yValues sortedArrayUsingSelector:@selector(compare:)]; if ( positiveDirection ) { yValue = [yValuesSorted lastObject]; } else { yValue = [yValuesSorted objectAtIndex:0]; } label.anchorPlotPoint = [NSArray arrayWithObjects:xValue, yValue, nil]; label.contentLayer.hidden = isnan([xValue doubleValue]) || isnan([yValue doubleValue]); if ( positiveDirection ) { label.displacement = CGPointMake(0.0, self.labelOffset); } else { label.displacement = CGPointMake(0.0, -self.labelOffset); } } #pragma mark - #pragma mark Accessors -(void)setBarLineStyle:(CPLineStyle *)newLineStyle { if ( barLineStyle != newLineStyle ) { [barLineStyle release]; barLineStyle = [newLineStyle copy]; [self setNeedsDisplay]; } } -(void)setAreaFill:(CPFill *)newFill { if ( newFill != areaFill ) { [areaFill release]; areaFill = [newFill copy]; [self setNeedsDisplay]; } } -(void)setXValues:(NSArray *)newValues { [self cacheNumbers:newValues forField:CPRangePlotFieldX]; } -(NSArray *)xValues { return [[self cachedNumbersForField:CPRangePlotFieldX] sampleArray]; } -(void)setYValues:(NSArray *)newValues { [self cacheNumbers:newValues forField:CPRangePlotFieldY]; } -(NSArray *)yValues { return [[self cachedNumbersForField:CPRangePlotFieldY] sampleArray]; } -(CPMutableNumericData *)highValues { return [self cachedNumbersForField:CPRangePlotFieldHigh]; } -(void)setHighValues:(CPMutableNumericData *)newValues { [self cacheNumbers:newValues forField:CPRangePlotFieldHigh]; } -(CPMutableNumericData *)lowValues { return [self cachedNumbersForField:CPRangePlotFieldLow]; } -(void)setLowValues:(CPMutableNumericData *)newValues { [self cacheNumbers:newValues forField:CPRangePlotFieldLow]; } -(CPMutableNumericData *)leftValues { return [self cachedNumbersForField:CPRangePlotFieldLeft]; } -(void)setLeftValues:(CPMutableNumericData *)newValues { [self cacheNumbers:newValues forField:CPRangePlotFieldLeft]; } -(CPMutableNumericData *)rightValues { return [self cachedNumbersForField:CPRangePlotFieldRight]; } -(void)setRightValues:(CPMutableNumericData *)newValues { [self cacheNumbers:newValues forField:CPRangePlotFieldRight]; } @end
08iteng-ipad
framework/Source/CPRangePlot.m
Objective-C
bsd
28,081
#import "CPNumericDataType.h" #import "NSExceptionExtensions.h" #import "complex.h" static CPDataTypeFormat DataTypeForDataTypeString(NSString *dataTypeString); static size_t SampleBytesForDataTypeString(NSString *dataTypeString); static CFByteOrder ByteOrderForDataTypeString(NSString *dataTypeString); #pragma mark - #pragma mark Data type utilities /** @brief Initializes a CPNumericDataType struct with the given parameter values. * @param format The data type format. * @param sampleBytes The number of bytes in each sample. * @param byteOrder The byte order used to store the data samples. * @return The initialized CPNumericDataType struct. **/ CPNumericDataType CPDataType(CPDataTypeFormat format, size_t sampleBytes, CFByteOrder byteOrder) { CPNumericDataType result; result.dataTypeFormat = format; result.sampleBytes = sampleBytes; result.byteOrder = byteOrder; return result; } /** @brief Initializes a CPNumericDataType struct from a data type string. * @param dataTypeString The data type string. * @return The initialized CPNumericDataType struct. **/ CPNumericDataType CPDataTypeWithDataTypeString(NSString *dataTypeString) { CPNumericDataType type; type.dataTypeFormat = DataTypeForDataTypeString(dataTypeString); type.sampleBytes = SampleBytesForDataTypeString(dataTypeString); type.byteOrder = ByteOrderForDataTypeString(dataTypeString); return type; } /** @brief Generates a string representation of the given data type. * @param dataType The data type. * @return The string representation of the given data type. **/ NSString *CPDataTypeStringFromDataType(CPNumericDataType dataType) { NSString *byteOrderString = nil; NSString *typeString = nil; switch ( dataType.byteOrder ) { case CFByteOrderLittleEndian: byteOrderString = @"<"; break; case CFByteOrderBigEndian: byteOrderString = @">"; break; } switch ( dataType.dataTypeFormat ) { case CPFloatingPointDataType: typeString = @"f"; break; case CPIntegerDataType: typeString = @"i"; break; case CPUnsignedIntegerDataType: typeString = @"u"; break; case CPComplexFloatingPointDataType: typeString = @"c"; break; case CPDecimalDataType: typeString = @"d"; break; case CPUndefinedDataType: [NSException raise:NSGenericException format:@"Unsupported data type"]; } return [NSString stringWithFormat:@"%@%@%lu", byteOrderString, typeString, dataType.sampleBytes]; } /** @brief Validates a data type format. * @param format The data type format. * @return Returns YES if the format is supported by CPNumericData, NO otherwise. **/ BOOL CPDataTypeIsSupported(CPNumericDataType format) { BOOL result = YES; switch ( format.byteOrder ) { case CFByteOrderUnknown: case CFByteOrderLittleEndian: case CFByteOrderBigEndian: // valid byte order--continue checking break; default: // invalid byteorder result = NO; break; } if ( result ) { switch ( format.dataTypeFormat ) { case CPUndefinedDataType: // valid; any sampleBytes is ok break; case CPIntegerDataType: switch ( format.sampleBytes ) { case sizeof(int8_t): case sizeof(int16_t): case sizeof(int32_t): case sizeof(int64_t): // valid break; default: result = NO; break; } break; case CPUnsignedIntegerDataType: switch ( format.sampleBytes ) { case sizeof(uint8_t): case sizeof(uint16_t): case sizeof(uint32_t): case sizeof(uint64_t): // valid break; default: result = NO; break; } break; case CPFloatingPointDataType: switch ( format.sampleBytes ) { case sizeof(float): case sizeof(double): // valid break; default: result = NO; break; } break; case CPComplexFloatingPointDataType: switch ( format.sampleBytes ) { case sizeof(float complex): case sizeof(double complex): // only the native byte order is supported result = (format.byteOrder == CFByteOrderGetCurrent()); break; default: result = NO; break; } break; case CPDecimalDataType: // only the native byte order is supported result = (format.sampleBytes == sizeof(NSDecimal)) && (format.byteOrder == CFByteOrderGetCurrent()); break; default: // unrecognized data type format result = NO; break; } } return result; } /** @brief Compares two data types for equality. * @param dataType1 The first data type format. * @param dataType2 The second data type format. * @return Returns YES if the two data types have the same format, size, and byte order. **/ BOOL CPDataTypeEqualToDataType(CPNumericDataType dataType1, CPNumericDataType dataType2) { return (dataType1.dataTypeFormat == dataType2.dataTypeFormat) && (dataType1.sampleBytes == dataType2.sampleBytes) && (dataType1.byteOrder == dataType2.byteOrder); } #pragma mark - #pragma mark Private functions CPDataTypeFormat DataTypeForDataTypeString(NSString *dataTypeString) { CPDataTypeFormat result; NSCAssert([dataTypeString length] >= 3, @"dataTypeString is too short"); switch ( [[dataTypeString lowercaseString] characterAtIndex:1] ) { case 'f': result = CPFloatingPointDataType; break; case 'i': result = CPIntegerDataType; break; case 'u': result = CPUnsignedIntegerDataType; break; case 'c': result = CPComplexFloatingPointDataType; break; case 'd': result = CPDecimalDataType; break; default: [NSException raise:NSGenericException format:@"Unknown type in dataTypeString"]; } return result; } size_t SampleBytesForDataTypeString(NSString *dataTypeString) { NSCAssert([dataTypeString length] >= 3, @"dataTypeString is too short"); NSInteger result = [[dataTypeString substringFromIndex:2] integerValue]; NSCAssert(result > 0, @"sample bytes is negative."); return (size_t)result; } CFByteOrder ByteOrderForDataTypeString(NSString *dataTypeString) { NSCAssert([dataTypeString length] >= 3, @"dataTypeString is too short"); CFByteOrder result; switch ( [[dataTypeString lowercaseString] characterAtIndex:0] ) { case '=': result = CFByteOrderGetCurrent(); break; case '<': result = CFByteOrderLittleEndian; break; case '>': result = CFByteOrderBigEndian; break; default: [NSException raise:NSGenericException format:@"Unknown byte order in dataTypeString"]; } return result; }
08iteng-ipad
framework/Source/CPNumericDataType.m
Objective-C
bsd
7,066
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPPlainBlackTheme : CPXYTheme { } @end
08iteng-ipad
framework/Source/CPPlainBlackTheme.h
Objective-C
bsd
110
#import <Foundation/Foundation.h> #import "CPDefinitions.h" @interface CPConstrainedPosition : NSObject { CGFloat position; CGFloat lowerBound; CGFloat upperBound; CPConstraints constraints; } @property (nonatomic, readwrite, assign) CGFloat position; @property (nonatomic, readwrite, assign) CGFloat lowerBound; @property (nonatomic, readwrite, assign) CGFloat upperBound; @property (nonatomic, readwrite, assign) CPConstraints constraints; -(id)initWithPosition:(CGFloat)newPosition lowerBound:(CGFloat)newLowerBound upperBound:(CGFloat)newUpperBound; -(id)initWithAlignment:(CPAlignment)newAlignment lowerBound:(CGFloat)newLowerBound upperBound:(CGFloat)newUpperBound; -(void)adjustPositionForOldLowerBound:(CGFloat)oldLowerBound oldUpperBound:(CGFloat)oldUpperBound; @end
08iteng-ipad
framework/Source/CPConstrainedPosition.h
Objective-C
bsd
794
#import "CPMutableLineStyle.h" /** @brief Mutable wrapper for various line drawing properties. * * If you need to customize properties of a line, you should use this class rather than the * immutable super class. * **/ @implementation CPMutableLineStyle /** @property lineCap * @brief The style for the endpoints of lines drawn in a graphics context. **/ @dynamic lineCap; /** @property lineJoin * @brief The style for the joins of connected lines in a graphics context. **/ @dynamic lineJoin; /** @property miterLimit * @brief The miter limit for the joins of connected lines in a graphics context. **/ @dynamic miterLimit; /** @property lineWidth * @brief The line width for a graphics context. **/ @dynamic lineWidth; /** @property dashPattern * @brief The dash-and-space pattern for the line. **/ @dynamic dashPattern; /** @property patternPhase * @brief The starting phase of the line dash pattern. **/ @dynamic patternPhase; /** @property lineColor * @brief The current stroke color in a context. **/ @dynamic lineColor; @end
08iteng-ipad
framework/Source/CPMutableLineStyle.m
Objective-C
bsd
1,074
#import "CPTestCase.h" @interface NSExceptionExtensionsTests : CPTestCase { } @end
08iteng-ipad
framework/Source/NSExceptionExtensionsTests.h
Objective-C
bsd
86
#import "CPNumericDataTests.h" #import "CPNumericData.h" #import "CPNumericData+TypeConversion.h" #import "CPExceptions.h" @implementation CPNumericDataTests -(void)testNilShapeGivesSingleDimension { CPNumericData *nd = [[CPNumericData alloc] initWithData:[NSMutableData dataWithLength:1*sizeof(float)] dataTypeString:@"=f4" shape:nil]; NSUInteger actual = nd.numberOfDimensions; NSUInteger expected = 1; STAssertEquals(actual, expected, @"numberOfDimensions == 1"); expected = [nd.shape count]; STAssertEquals(actual, expected, @"numberOfDimensions == 1"); [nd release]; } -(void)testNumberOfDimensionsGivesShapeCount { id shape = [NSArray arrayWithObjects: [NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], (id)nil ]; NSUInteger nElems = 2*2*2; CPNumericData *nd = [[CPNumericData alloc] initWithData:[NSMutableData dataWithLength:nElems*sizeof(float)] dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:shape]; STAssertEquals(nd.numberOfDimensions, nd.shape.count, @"numberOfDimensions == shape.count == 3"); [nd release]; } -(void)testNilShapeCorrectElementCount { NSUInteger nElems = 13; CPNumericData *nd = [[CPNumericData alloc] initWithData:[NSMutableData dataWithLength:nElems*sizeof(float)] dataTypeString:@"=f4" shape:nil]; STAssertEquals(nd.numberOfDimensions, (NSUInteger)1, @"numberOfDimensions == 1"); NSUInteger prod = 1; for ( NSNumber *num in nd.shape ) { prod *= [num unsignedIntValue]; } STAssertEquals(prod, nElems, @"prod == nElems"); [nd release]; } -(void)testIllegalShapeRaisesException { id shape = [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], (id)nil]; NSUInteger nElems = 5; STAssertThrowsSpecificNamed([[CPNumericData alloc] initWithData:[NSMutableData dataWithLength:nElems*sizeof(NSUInteger)] dataType:CPDataType(CPUnsignedIntegerDataType, sizeof(NSUInteger), NSHostByteOrder()) shape:shape], NSException, CPNumericDataException, @"Illegal shape should throw"); } -(void)testReturnsDataLength { CPNumericData *nd = [[CPNumericData alloc] initWithData:[NSMutableData dataWithLength:10*sizeof(float)] dataTypeString:@"=f4" shape:nil]; NSUInteger expected = 10*sizeof(float); NSUInteger actual = [nd.data length]; STAssertEquals(expected, actual, @"data length"); [nd release]; } -(void)testBytesEqualDataBytes { NSUInteger nElements = 10; NSMutableData *data = [NSMutableData dataWithLength:nElements*sizeof(NSInteger)]; NSInteger *intData = (NSInteger *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElements; i++ ) { intData[i] = i; } CPNumericData *nd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPIntegerDataType, sizeof(NSInteger), NSHostByteOrder()) shape:nil]; NSData *expected = data; STAssertEqualObjects(data, nd.data, @"equal objects"); STAssertTrue([expected isEqualToData:nd.data], @"data isEqualToData:"); [nd release]; } -(void)testArchivingRoundTrip { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPNumericData *nd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; CPNumericData *nd2 = [NSUnarchiver unarchiveObjectWithData:[NSArchiver archivedDataWithRootObject:nd]]; STAssertTrue([nd.data isEqualToData:nd2.data], @"equal data"); CPNumericDataType ndType = nd.dataType; CPNumericDataType nd2Type = nd2.dataType; STAssertEquals(ndType.dataTypeFormat, nd2Type.dataTypeFormat, @"dataType.dataTypeFormat equal"); STAssertEquals(ndType.sampleBytes, nd2Type.sampleBytes, @"dataType.sampleBytes equal"); STAssertEquals(ndType.byteOrder, nd2Type.byteOrder, @"dataType.byteOrder equal"); STAssertEqualObjects(nd.shape, nd2.shape, @"shapes equal"); [nd release]; } -(void)testKeyedArchivingRoundTrip { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPNumericData *nd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; CPNumericData *nd2 = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:nd]]; STAssertTrue([nd.data isEqualToData:nd2.data], @"equal data"); CPNumericDataType ndType = nd.dataType; CPNumericDataType nd2Type = nd2.dataType; STAssertEquals(ndType.dataTypeFormat, nd2Type.dataTypeFormat, @"dataType.dataTypeFormat equal"); STAssertEquals(ndType.sampleBytes, nd2Type.sampleBytes, @"dataType.sampleBytes equal"); STAssertEquals(ndType.byteOrder, nd2Type.byteOrder, @"dataType.byteOrder equal"); STAssertEqualObjects(nd.shape, nd2.shape, @"shapes equal"); [nd release]; } -(void)testNumberOfSamplesCorrectForDataType { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPNumericData *nd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEquals([nd numberOfSamples], nElems, @"numberOfSamples == nElems"); [nd release]; nElems = 10; data = [NSMutableData dataWithLength:nElems*sizeof(char)]; char *charSamples = (char *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { charSamples[i] = sin(i); } nd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPIntegerDataType, sizeof(char), NSHostByteOrder()) shape:nil]; STAssertEquals([nd numberOfSamples], nElems, @"numberOfSamples == nElems"); [nd release]; } -(void)testDataTypeAccessorsCorrectForDataType { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPNumericData *nd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEquals([nd dataTypeFormat], CPFloatingPointDataType, @"dataTypeFormat"); STAssertEquals([nd sampleBytes], sizeof(float), @"sampleBytes"); STAssertEquals([nd byteOrder], NSHostByteOrder(), @"byteOrder"); } -(void)testConvertTypeConvertsType { NSUInteger numberOfSamples = 10; NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < numberOfSamples; i++ ) { samples[i] = sinf(i); } CPNumericData *fd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; CPNumericData *dd = [fd dataByConvertingToType:CPFloatingPointDataType sampleBytes:sizeof(double) byteOrder:NSHostByteOrder()]; [fd release]; const double *doubleSamples = (const double *)[dd.data bytes]; for ( NSUInteger i = 0; i < numberOfSamples; i++ ) { STAssertTrue(samples[i] == doubleSamples[i], @"(float)%g != (double)%g", samples[i], doubleSamples[i]); } } -(void)testSamplePointerCorrect { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPNumericData *fd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEquals(((float *)[fd.data bytes])+4, (float *)[fd samplePointer:4], @"%p,%p",samples+4, (float *)[fd samplePointer:4]); STAssertEquals(((float *)[fd.data bytes]), (float *)[fd samplePointer:0], @""); STAssertEquals(((float *)[fd.data bytes])+nElems-1, (float *)[fd samplePointer:nElems-1], @""); STAssertNil([fd samplePointer:nElems], @"too many samples"); [fd release]; } -(void)testSampleValueCorrect { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPNumericData *fd = [[CPNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEqualsWithAccuracy([[fd sampleValue:0] doubleValue], sin(0), 0.01, @"sample value"); STAssertEqualsWithAccuracy([[fd sampleValue:1] doubleValue], sin(1), 0.01, @"sample value"); [fd release]; } @end
08iteng-ipad
framework/Source/CPNumericDataTests.m
Objective-C
bsd
9,419
#import "CPScatterPlotTests.h" @interface CPScatterPlot (Testing) -(void)calculatePointsToDraw:(BOOL *)pointDrawFlags forPlotSpace:(CPXYPlotSpace *)aPlotSpace includeVisiblePointsOnly:(BOOL)visibleOnly; -(void)setXValues:(NSArray *)newValues; -(void)setYValues:(NSArray *)newValues; @end @implementation CPScatterPlotTests @synthesize plot; @synthesize plotSpace; -(void)setUp { double values[5] = {0.5, 0.5, 0.5, 0.5, 0.5}; self.plot = [[CPScatterPlot new] autorelease]; NSMutableArray *yValues = [NSMutableArray array]; for ( NSInteger i = 0; i < 5; i++ ) [yValues addObject:[NSNumber numberWithDouble:values[i]]]; [self.plot setYValues:yValues]; CPPlotRange *xPlotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInteger(0) length:CPDecimalFromInteger(1)]; CPPlotRange *yPlotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInteger(0) length:CPDecimalFromInteger(1)]; self.plotSpace = [[[CPXYPlotSpace alloc] init] autorelease]; self.plotSpace.xRange = xPlotRange; self.plotSpace.yRange = yPlotRange; } -(void)tearDown { self.plot = nil; self.plotSpace = nil; } -(void)testCalculatePointsToDrawAllInRange { BOOL drawFlags[5]; double inRangeValues[5] = {0.1, 0.2, 0.15, 0.6, 0.9}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:NO]; for ( NSUInteger i = 0; i < 5; i++ ) { STAssertTrue(drawFlags[i], @"Test that in range points are drawn (%g).", inRangeValues[i]); } } -(void)testCalculatePointsToDrawAllInRangeVisibleOnly { BOOL drawFlags[5]; double inRangeValues[5] = {0.1, 0.2, 0.15, 0.6, 0.9}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:YES]; for ( NSUInteger i = 0; i < 5; i++ ) { STAssertTrue(drawFlags[i], @"Test that in range points are drawn (%g).", inRangeValues[i]); } } -(void)testCalculatePointsToDrawNoneInRange { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, -0.2, -0.15, -0.6, -0.9}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:NO]; for ( NSUInteger i = 0; i < 5; i++ ) { STAssertFalse(drawFlags[i], @"Test that out of range points are not drawn (%g).", inRangeValues[i]); } } -(void)testCalculatePointsToDrawNoneInRangeVisibleOnly { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, -0.2, -0.15, -0.6, -0.9}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:YES]; for ( NSUInteger i = 0; i < 5; i++ ) { STAssertFalse(drawFlags[i], @"Test that out of range points are not drawn (%g).", inRangeValues[i]); } } -(void)testCalculatePointsToDrawNoneInRangeDifferentRegions { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, 2, -0.15, 3, -0.9}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:NO]; for ( NSUInteger i = 0; i < 5; i++ ) { STAssertTrue(drawFlags[i], @"Test that out of range points in different regions get included (%g).", inRangeValues[i]); } } -(void)testCalculatePointsToDrawNoneInRangeDifferentRegionsVisibleOnly { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, 2, -0.15, 3, -0.9}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:YES]; for ( NSUInteger i = 0; i < 5; i++ ) { STAssertFalse(drawFlags[i], @"Test that out of range points in different regions get included (%g).", inRangeValues[i]); } } -(void)testCalculatePointsToDrawSomeInRange { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, 0.1, 0.2, 1.2, 1.5}; BOOL expected[5] = {YES, YES, YES, YES, NO}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:NO]; for ( NSUInteger i = 0; i < 5; i++ ) { if ( expected[i] ) { STAssertTrue(drawFlags[i], @"Test that correct points included when some are in range, others out (%g).", inRangeValues[i]); } else { STAssertFalse(drawFlags[i], @"Test that correct points included when some are in range, others out (%g).", inRangeValues[i]); } } } -(void)testCalculatePointsToDrawSomeInRangeVisibleOnly { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, 0.1, 0.2, 1.2, 1.5}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:YES]; for ( NSUInteger i = 0; i < 5; i++ ) { if ( [self.plotSpace.xRange compareToNumber:[NSNumber numberWithDouble:inRangeValues[i]]] == CPPlotRangeComparisonResultNumberInRange ) { STAssertTrue(drawFlags[i], @"Test that correct points included when some are in range, others out (%g).", inRangeValues[i]); } else { STAssertFalse(drawFlags[i], @"Test that correct points included when some are in range, others out (%g).", inRangeValues[i]); } } } -(void)testCalculatePointsToDrawSomeInRangeCrossing { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, 1.1, 0.9, -0.1, -0.2}; BOOL expected[5] = {YES, YES, YES, YES, NO}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:NO]; for ( NSUInteger i = 0; i < 5; i++ ) { if ( expected[i] ) { STAssertTrue(drawFlags[i], @"Test that correct points included when some are in range, others out, crossing range (%g).", inRangeValues[i]); } else { STAssertFalse(drawFlags[i], @"Test that correct points included when some are in range, others out, crossing range (%g).", inRangeValues[i]); } } } -(void)testCalculatePointsToDrawSomeInRangeCrossingVisibleOnly { BOOL drawFlags[5]; double inRangeValues[5] = {-0.1, 1.1, 0.9, -0.1, -0.2}; NSMutableArray *values = [NSMutableArray array]; for ( NSUInteger i = 0; i < 5; i++ ) [values addObject:[NSNumber numberWithDouble:inRangeValues[i]]]; [self.plot setXValues:values]; [self.plot calculatePointsToDraw:drawFlags forPlotSpace:self.plotSpace includeVisiblePointsOnly:YES]; for ( NSUInteger i = 0; i < 5; i++ ) { if ( [self.plotSpace.xRange compareToNumber:[NSNumber numberWithDouble:inRangeValues[i]]] == CPPlotRangeComparisonResultNumberInRange ) { STAssertTrue(drawFlags[i], @"Test that correct points included when some are in range, others out, crossing range (%g).", inRangeValues[i]); } else { STAssertFalse(drawFlags[i], @"Test that correct points included when some are in range, others out, crossing range (%g).", inRangeValues[i]); } } } @end
08iteng-ipad
framework/Source/CPScatterPlotTests.m
Objective-C
bsd
8,149
#import "_CPFillImage.h" #import "CPImage.h" /** @cond */ @interface _CPFillImage() @property (nonatomic, readwrite, copy) CPImage *fillImage; @end /** @endcond */ /** @brief Draws CPImage area fills. * * Drawing methods are provided to fill rectangular areas and arbitrary drawing paths. **/ @implementation _CPFillImage /** @property fillImage * @brief The fill image. **/ @synthesize fillImage; #pragma mark - #pragma mark init/dealloc /** @brief Initializes a newly allocated _CPFillImage object with the provided image. * @param anImage The image. * @return The initialized _CPFillImage object. **/ -(id)initWithImage:(CPImage *)anImage { if ( self = [super init] ) { fillImage = [anImage retain]; } return self; } -(void)dealloc { [fillImage release]; [super dealloc]; } #pragma mark - #pragma mark Drawing /** @brief Draws the image into the given graphics context inside the provided rectangle. * @param theRect The rectangle to draw into. * @param theContext The graphics context to draw into. **/ -(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext { [self.fillImage drawInRect:theRect inContext:theContext]; } /** @brief Draws the image into the given graphics context clipped to the current drawing path. * @param theContext The graphics context to draw into. **/ -(void)fillPathInContext:(CGContextRef)theContext { CGContextSaveGState(theContext); CGRect bounds = CGContextGetPathBoundingBox(theContext); CGContextClip(theContext); [self.fillImage drawInRect:bounds inContext:theContext]; CGContextRestoreGState(theContext); } #pragma mark - #pragma mark NSCopying methods -(id)copyWithZone:(NSZone *)zone { _CPFillImage *copy = [[[self class] allocWithZone:zone] init]; copy->fillImage = [self->fillImage copyWithZone:zone]; return copy; } #pragma mark - #pragma mark NSCoding methods -(Class)classForCoder { return [CPFill class]; } -(void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.fillImage forKey:@"fillImage"]; } -(id)initWithCoder:(NSCoder *)coder { if ( self = [super init] ) { fillImage = [[coder decodeObjectForKey:@"fillImage"] retain]; } return self; } @end
08iteng-ipad
framework/Source/_CPFillImage.m
Objective-C
bsd
2,189
#import <QuartzCore/QuartzCore.h> #import <Foundation/Foundation.h> @class CPGradient; @class CPImage; @class CPColor; @interface CPFill : NSObject <NSCopying, NSCoding> { } /// @name Factory Methods /// @{ +(CPFill *)fillWithColor:(CPColor *)aColor; +(CPFill *)fillWithGradient:(CPGradient *)aGradient; +(CPFill *)fillWithImage:(CPImage *)anImage; /// @} /// @name Initialization /// @{ -(id)initWithColor:(CPColor *)aColor; -(id)initWithGradient:(CPGradient *)aGradient; -(id)initWithImage:(CPImage *)anImage; /// @} @end /** @category CPFill(AbstractMethods) * @brief CPFill abstract methods—must be overridden by subclasses **/ @interface CPFill(AbstractMethods) /// @name Drawing /// @{ -(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext; -(void)fillPathInContext:(CGContextRef)theContext; /// @} @end
08iteng-ipad
framework/Source/CPFill.h
Objective-C
bsd
838
#import "CPLimitBand.h" #import "CPFill.h" #import "CPPlotRange.h" /** @brief Defines a range and fill used to highlight a band of data. **/ @implementation CPLimitBand /** @property range * @brief The data range for the band. **/ @synthesize range; /** @property fill * @brief The fill used to draw the band. **/ @synthesize fill; #pragma mark - #pragma mark Init/Dealloc /** @brief Creates and returns a new CPLimitBand instance initialized with the provided range and fill. * @param newRange The range of the band. * @param newFill The fill used to draw the interior of the band. * @return A new CPLimitBand instance initialized with the provided range and fill. **/ +(CPLimitBand *)limitBandWithRange:(CPPlotRange *)newRange fill:(CPFill *)newFill { return [[[CPLimitBand alloc] initWithRange:newRange fill:newFill] autorelease]; } /** @brief Initializes a newly allocated CPLimitBand object with the provided range and fill. * @param newRange The range of the band. * @param newFill The fill used to draw the interior of the band. * @return The initialized CPLimitBand object. **/ -(id)initWithRange:(CPPlotRange *)newRange fill:(CPFill *)newFill { if ( self = [super init] ) { range = [newRange retain]; fill = [newFill retain]; } return self; } -(void)dealloc { [range release]; [fill release]; [super dealloc]; } #pragma mark - #pragma mark NSCopying -(id)copyWithZone:(NSZone *)zone { CPLimitBand *newBand = [[CPLimitBand allocWithZone:zone] init]; if ( newBand ) { newBand->range = [self->range copyWithZone:zone]; newBand->fill = [self->fill copyWithZone:zone]; } return newBand; } #pragma mark - #pragma mark NSCoding - (void)encodeWithCoder:(NSCoder *)encoder { if ( [encoder allowsKeyedCoding] ) { [encoder encodeObject:range forKey:@"range"]; [encoder encodeObject:fill forKey:@"fill"]; } else { [encoder encodeObject:range]; [encoder encodeObject:fill]; } } - (id)initWithCoder:(NSCoder *)decoder { CPPlotRange *newRange; CPFill *newFill; if ( [decoder allowsKeyedCoding] ) { newRange = [decoder decodeObjectForKey:@"range"]; newFill = [decoder decodeObjectForKey:@"fill"]; } else { newRange = [decoder decodeObject]; newFill = [decoder decodeObject]; } return [self initWithRange:newRange fill:newFill]; } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"<%@ with range: %@ and fill: %@>", [super description], self.range, self.fill]; } @end
08iteng-ipad
framework/Source/CPLimitBand.m
Objective-C
bsd
2,526
#import <Foundation/Foundation.h> /// @file /** @brief Enumeration of data formats for numeric data. **/ typedef enum _CPDataTypeFormat { CPUndefinedDataType = 0, ///< Undefined CPIntegerDataType, ///< Integer CPUnsignedIntegerDataType, ///< Unsigned integer CPFloatingPointDataType, ///< Floating point CPComplexFloatingPointDataType, ///< Complex floating point CPDecimalDataType ///< NSDecimal } CPDataTypeFormat; /** @brief Struct that describes the encoding of numeric data samples. **/ typedef struct _CPNumericDataType { CPDataTypeFormat dataTypeFormat; ///< Data type format size_t sampleBytes; ///< Number of bytes in each sample CFByteOrder byteOrder; ///< Byte order } CPNumericDataType; #if __cplusplus extern "C" { #endif /// @name Data Type Utilities /// @{ CPNumericDataType CPDataType(CPDataTypeFormat format, size_t sampleBytes, CFByteOrder byteOrder); CPNumericDataType CPDataTypeWithDataTypeString(NSString *dataTypeString); NSString *CPDataTypeStringFromDataType(CPNumericDataType dataType); BOOL CPDataTypeIsSupported(CPNumericDataType format); BOOL CPDataTypeEqualToDataType(CPNumericDataType dataType1, CPNumericDataType dataType2); /// @} #if __cplusplus } #endif
08iteng-ipad
framework/Source/CPNumericDataType.h
Objective-C
bsd
1,269
#import "CPAxisTitle.h" #import "CPExceptions.h" #import "CPLayer.h" /** @brief An axis title. * * The title can be text-based or can be the content of any CPLayer provided by the user. **/ @implementation CPAxisTitle -(void)positionRelativeToViewPoint:(CGPoint)point forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction { CGPoint newPosition = point; CGFloat *value = (coordinate == CPCoordinateX ? &(newPosition.x) : &(newPosition.y)); self.rotation = (coordinate == CPCoordinateX ? M_PI_2 : 0.0); CGPoint anchor = CGPointZero; // Position the anchor point along the closest edge. switch ( direction ) { case CPSignNone: case CPSignNegative: *value -= self.offset; anchor = (coordinate == CPCoordinateX ? CGPointMake(0.5, 0.0) : CGPointMake(0.5, 1.0)); break; case CPSignPositive: *value += self.offset; anchor = (coordinate == CPCoordinateX ? CGPointMake(0.0, 0.5) : CGPointMake(0.5, 0.0)); break; default: [NSException raise:CPException format:@"Invalid sign in positionRelativeToViewPoint:inDirection:"]; break; } // Pixel-align the title layer to prevent blurriness CPLayer *content = self.contentLayer; CGSize currentSize = content.bounds.size; content.anchorPoint = anchor; if ( self.rotation == 0.0 ) { newPosition.x = round(newPosition.x) - round(currentSize.width * anchor.x) + (currentSize.width * anchor.x); newPosition.y = round(newPosition.y) - round(currentSize.height * anchor.y) + (currentSize.height * anchor.y); } else { newPosition.x = round(newPosition.x); newPosition.y = round(newPosition.y); } content.position = newPosition; content.transform = CATransform3DMakeRotation(self.rotation, 0.0, 0.0, 1.0); [self.contentLayer setNeedsDisplay]; } @end
08iteng-ipad
framework/Source/CPAxisTitle.m
Objective-C
bsd
1,860
#import "CPAxis.h" #import "CPAxisLabelGroup.h" #import "CPAxisSet.h" #import "CPFill.h" #import "CPGridLineGroup.h" #import "CPLineStyle.h" #import "CPPlotGroup.h" #import "CPPlotArea.h" static const int kCPNumberOfLayers = 6; // number of primary layers to arrange /** @cond */ @interface CPPlotArea() @property (nonatomic, readwrite, assign) CPGraphLayerType *bottomUpLayerOrder; @property (nonatomic, readwrite, assign, getter=isUpdatingLayers) BOOL updatingLayers; -(void)updateLayerOrder; -(unsigned)indexForLayerType:(CPGraphLayerType)layerType; @end /** @endcond */ #pragma mark - /** @brief A layer representing the actual plotting area of a graph. * * All plots are drawn inside this area while axes, titles, and borders may fall outside. * The layers are arranged so that the graph elements are drawn in the following order: * -# Background fill * -# Minor grid lines * -# Major grid lines * -# Background border * -# Axis lines with major and minor tick marks * -# Plots * -# Axis labels * -# Axis titles **/ @implementation CPPlotArea /** @property minorGridLineGroup * @brief The parent layer for all minor grid lines. **/ @synthesize minorGridLineGroup; /** @property majorGridLineGroup * @brief The parent layer for all major grid lines. **/ @synthesize majorGridLineGroup; /** @property axisSet * @brief The axis set. **/ @synthesize axisSet; /** @property plotGroup * @brief The plot group. **/ @synthesize plotGroup; /** @property axisLabelGroup * @brief The parent layer for all axis labels. **/ @synthesize axisLabelGroup; /** @property axisTitleGroup * @brief The parent layer for all axis titles. **/ @synthesize axisTitleGroup; /** @property topDownLayerOrder * @brief An array of graph layers to be drawn in an order other than the default. * * The array should reference the layers using the constants defined in #CPGraphLayerType. * Layers should be specified in order starting from the top layer. * Only the layers drawn out of the default order need be specified; all others will * automatically be placed at the bottom of the view in their default order. * * If this property is nil, the layers will be drawn in the default order (bottom to top): * -# Minor grid lines * -# Major grid lines * -# Axis lines, including the tick marks * -# Plots * -# Axis labels * -# Axis titles * * Example usage: * <code>[graph setTopDownLayerOrder:[NSArray arrayWithObjects: * [NSNumber numberWithInt:CPGraphLayerTypePlots], * [NSNumber numberWithInt:CPGraphLayerTypeAxisLabels], * [NSNumber numberWithInt:CPGraphLayerTypeMajorGridLines], * ..., nil]];</code> **/ @synthesize topDownLayerOrder; /** @property borderLineStyle * @brief The line style for the layer border. * If nil, the border is not drawn. **/ @dynamic borderLineStyle; /** @property fill * @brief The fill for the layer background. * If nil, the layer background is not filled. **/ @synthesize fill; // Private properties @synthesize bottomUpLayerOrder; @synthesize updatingLayers; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { minorGridLineGroup = nil; majorGridLineGroup = nil; axisSet = nil; plotGroup = nil; axisLabelGroup = nil; axisTitleGroup = nil; fill = nil; topDownLayerOrder = nil; bottomUpLayerOrder = malloc(kCPNumberOfLayers * sizeof(CPGraphLayerType)); [self updateLayerOrder]; CPPlotGroup *newPlotGroup = [(CPPlotGroup *)[CPPlotGroup alloc] initWithFrame:newFrame]; self.plotGroup = newPlotGroup; [newPlotGroup release]; self.needsDisplayOnBoundsChange = YES; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPPlotArea *theLayer = (CPPlotArea *)layer; minorGridLineGroup = [theLayer->minorGridLineGroup retain]; majorGridLineGroup = [theLayer->majorGridLineGroup retain]; axisSet = [theLayer->axisSet retain]; plotGroup = [theLayer->plotGroup retain]; axisLabelGroup = [theLayer->axisLabelGroup retain]; axisTitleGroup = [theLayer->axisTitleGroup retain]; fill = [theLayer->fill retain]; topDownLayerOrder = [theLayer->topDownLayerOrder retain]; bottomUpLayerOrder = malloc(kCPNumberOfLayers * sizeof(CPGraphLayerType)); memcpy(bottomUpLayerOrder, theLayer->bottomUpLayerOrder, kCPNumberOfLayers * sizeof(CPGraphLayerType)); } return self; } -(void)dealloc { [minorGridLineGroup release]; [majorGridLineGroup release]; [axisSet release]; [plotGroup release]; [axisLabelGroup release]; [axisTitleGroup release]; [fill release]; [topDownLayerOrder release]; free(bottomUpLayerOrder); [super dealloc]; } -(void)finalize { free(bottomUpLayerOrder); [super finalize]; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)context { [super renderAsVectorInContext:context]; [self.fill fillRect:self.bounds inContext:context]; NSArray *theAxes = self.axisSet.axes; for ( CPAxis *axis in theAxes ) { [axis drawBackgroundBandsInContext:context]; } for ( CPAxis *axis in theAxes ) { [axis drawBackgroundLimitsInContext:context]; } } #pragma mark - #pragma mark Layout +(CGFloat)defaultZPosition { return CPDefaultZPositionPlotArea; } -(void)layoutSublayers { [super layoutSublayers]; CALayer *superlayer = self.superlayer; CGRect sublayerBounds = [self convertRect:superlayer.bounds fromLayer:superlayer]; sublayerBounds.origin = CGPointZero; CGPoint sublayerPosition = [self convertPoint:self.bounds.origin toLayer:superlayer]; sublayerPosition = CGPointMake(-sublayerPosition.x, -sublayerPosition.y); NSSet *excludedLayers = [self sublayersExcludedFromAutomaticLayout]; for (CALayer *subLayer in self.sublayers) { if ( [excludedLayers containsObject:subLayer] ) continue; subLayer.frame = CGRectMake(sublayerPosition.x, sublayerPosition.y, sublayerBounds.size.width, sublayerBounds.size.height); } // make the plot group the same size as the plot area to clip the plots CPPlotGroup *thePlotGroup = self.plotGroup; if ( thePlotGroup ) { CGSize selfBoundsSize = self.bounds.size; thePlotGroup.frame = CGRectMake(0.0, 0.0, selfBoundsSize.width, selfBoundsSize.height); } } #pragma mark - #pragma mark Layer ordering -(void)updateLayerOrder { CPGraphLayerType *buLayerOrder = self.bottomUpLayerOrder; for ( int i = 0; i < kCPNumberOfLayers; i++ ) { *(buLayerOrder++) = i; } NSArray *tdLayerOrder = self.topDownLayerOrder; if ( tdLayerOrder ) { buLayerOrder = self.bottomUpLayerOrder; for ( NSUInteger layerIndex = 0; layerIndex < [tdLayerOrder count]; layerIndex++ ) { CPGraphLayerType layerType = [[tdLayerOrder objectAtIndex:layerIndex] intValue]; NSUInteger i = kCPNumberOfLayers - layerIndex - 1; while ( buLayerOrder[i] != layerType ) { if ( i == 0 ) break; i--; } while ( i < kCPNumberOfLayers - layerIndex - 1 ) { buLayerOrder[i] = buLayerOrder[i + 1]; i++; } buLayerOrder[kCPNumberOfLayers - layerIndex - 1] = layerType; } } // force the layer hierarchy to update self.updatingLayers = YES; self.minorGridLineGroup = self.minorGridLineGroup; self.majorGridLineGroup = self.majorGridLineGroup; self.axisSet = self.axisSet; self.plotGroup = self.plotGroup; self.axisLabelGroup = self.axisLabelGroup; self.axisTitleGroup = self.axisTitleGroup; self.updatingLayers = NO; } -(unsigned)indexForLayerType:(CPGraphLayerType)layerType { CPGraphLayerType *buLayerOrder = self.bottomUpLayerOrder; unsigned index = 0; for ( NSInteger i = 0; i < kCPNumberOfLayers; i++ ) { if ( buLayerOrder[i] == layerType ) { break; } switch ( buLayerOrder[i] ) { case CPGraphLayerTypeMinorGridLines: if ( self.minorGridLineGroup ) index++; break; case CPGraphLayerTypeMajorGridLines: if ( self.majorGridLineGroup ) index++; break; case CPGraphLayerTypeAxisLines: if ( self.axisSet ) index++; break; case CPGraphLayerTypePlots: if ( self.plotGroup ) index++; break; case CPGraphLayerTypeAxisLabels: if ( self.axisLabelGroup ) index++; break; case CPGraphLayerTypeAxisTitles: if ( self.axisTitleGroup ) index++; break; } } return index; } #pragma mark - #pragma mark Axis set layer management /** @brief Checks for the presence of the specified layer group and adds or removes it as needed. * @param layerType The layer type being updated. **/ -(void)updateAxisSetLayersForType:(CPGraphLayerType)layerType { BOOL needsLayer = NO; CPAxisSet *theAxisSet = self.axisSet; for ( CPAxis *axis in theAxisSet.axes ) { switch ( layerType ) { case CPGraphLayerTypeMinorGridLines: if ( axis.minorGridLineStyle ) { needsLayer = YES; } break; case CPGraphLayerTypeMajorGridLines: if ( axis.majorGridLineStyle ) { needsLayer = YES; } break; case CPGraphLayerTypeAxisLabels: if ( axis.axisLabels.count > 0 ) { needsLayer = YES; } break; case CPGraphLayerTypeAxisTitles: if ( axis.axisTitle ) { needsLayer = YES; } break; default: break; } } if ( needsLayer ) { [self setAxisSetLayersForType:layerType]; } else { switch ( layerType ) { case CPGraphLayerTypeMinorGridLines: self.minorGridLineGroup = nil; break; case CPGraphLayerTypeMajorGridLines: self.majorGridLineGroup = nil; break; case CPGraphLayerTypeAxisLabels: self.axisLabelGroup = nil; break; case CPGraphLayerTypeAxisTitles: self.axisTitleGroup = nil; break; default: break; } } } /** @brief Ensures that a group layer is set for the given layer type. * @param layerType The layer type being updated. **/ -(void)setAxisSetLayersForType:(CPGraphLayerType)layerType { switch ( layerType ) { case CPGraphLayerTypeMinorGridLines: if ( !self.minorGridLineGroup ) { CPGridLineGroup *newGridLineGroup = [(CPGridLineGroup *)[CPGridLineGroup alloc] initWithFrame:self.bounds]; self.minorGridLineGroup = newGridLineGroup; [newGridLineGroup release]; } break; case CPGraphLayerTypeMajorGridLines: if ( !self.majorGridLineGroup ) { CPGridLineGroup *newGridLineGroup = [(CPGridLineGroup *)[CPGridLineGroup alloc] initWithFrame:self.bounds]; self.majorGridLineGroup = newGridLineGroup; [newGridLineGroup release]; } break; case CPGraphLayerTypeAxisLabels: if ( !self.axisLabelGroup ) { CPAxisLabelGroup *newAxisLabelGroup = [(CPAxisLabelGroup *)[CPAxisLabelGroup alloc] initWithFrame:self.bounds]; self.axisLabelGroup = newAxisLabelGroup; [newAxisLabelGroup release]; } break; case CPGraphLayerTypeAxisTitles: if ( !self.axisTitleGroup ) { CPAxisLabelGroup *newAxisTitleGroup = [(CPAxisLabelGroup *)[CPAxisLabelGroup alloc] initWithFrame:self.bounds]; self.axisTitleGroup = newAxisTitleGroup; [newAxisTitleGroup release]; } break; default: break; } } -(unsigned)sublayerIndexForAxis:(CPAxis *)axis layerType:(CPGraphLayerType)layerType { unsigned index = 0; for ( CPAxis *currentAxis in self.graph.axisSet.axes ) { if ( currentAxis == axis ) break; switch ( layerType ) { case CPGraphLayerTypeMinorGridLines: if ( currentAxis.minorGridLineStyle ) index++; break; case CPGraphLayerTypeMajorGridLines: if ( currentAxis.majorGridLineStyle ) index++; break; case CPGraphLayerTypeAxisLabels: if ( currentAxis.axisLabels.count > 0 ) index++; break; case CPGraphLayerTypeAxisTitles: if ( currentAxis.axisTitle ) index++; break; default: break; } } return index; } #pragma mark - #pragma mark Accessors -(CPLineStyle *)borderLineStyle { return self.axisSet.borderLineStyle; } -(void)setBorderLineStyle:(CPLineStyle *)newLineStyle { self.axisSet.borderLineStyle = newLineStyle; } -(void)setMinorGridLineGroup:(CPGridLineGroup *)newGridLines { if ( (newGridLines != minorGridLineGroup) || self.isUpdatingLayers ) { [minorGridLineGroup removeFromSuperlayer]; [newGridLines retain]; [minorGridLineGroup release]; minorGridLineGroup = newGridLines; if ( minorGridLineGroup ) { minorGridLineGroup.plotArea = self; minorGridLineGroup.major = NO; [self insertSublayer:minorGridLineGroup atIndex:[self indexForLayerType:CPGraphLayerTypeMinorGridLines]]; } [self setNeedsLayout]; } } -(void)setMajorGridLineGroup:(CPGridLineGroup *)newGridLines { if ( (newGridLines != majorGridLineGroup) || self.isUpdatingLayers ) { [majorGridLineGroup removeFromSuperlayer]; [newGridLines retain]; [majorGridLineGroup release]; majorGridLineGroup = newGridLines; if ( majorGridLineGroup ) { majorGridLineGroup.plotArea = self; majorGridLineGroup.major = YES; [self insertSublayer:majorGridLineGroup atIndex:[self indexForLayerType:CPGraphLayerTypeMajorGridLines]]; } [self setNeedsLayout]; } } -(void)setAxisSet:(CPAxisSet *)newAxisSet { if ( (newAxisSet != axisSet) || self.isUpdatingLayers ) { [axisSet removeFromSuperlayer]; for ( CPAxis *axis in axisSet.axes ) { axis.plotArea = nil; } [newAxisSet retain]; [axisSet release]; axisSet = newAxisSet; [self updateAxisSetLayersForType:CPGraphLayerTypeMajorGridLines]; [self updateAxisSetLayersForType:CPGraphLayerTypeMinorGridLines]; [self updateAxisSetLayersForType:CPGraphLayerTypeAxisLabels]; [self updateAxisSetLayersForType:CPGraphLayerTypeAxisTitles]; if ( axisSet ) { [self insertSublayer:axisSet atIndex:[self indexForLayerType:CPGraphLayerTypeAxisLines]]; for ( CPAxis *axis in axisSet.axes ) { axis.plotArea = self; } } [self setNeedsLayout]; } } -(void)setPlotGroup:(CPPlotGroup *)newPlotGroup { if ( (newPlotGroup != plotGroup) || self.isUpdatingLayers ) { [plotGroup removeFromSuperlayer]; [newPlotGroup retain]; [plotGroup release]; plotGroup = newPlotGroup; if ( plotGroup ) { [self insertSublayer:plotGroup atIndex:[self indexForLayerType:CPGraphLayerTypePlots]]; } [self setNeedsLayout]; } } -(void)setAxisLabelGroup:(CPAxisLabelGroup *)newAxisLabelGroup { if ( (newAxisLabelGroup != axisLabelGroup) || self.isUpdatingLayers ) { [axisLabelGroup removeFromSuperlayer]; [newAxisLabelGroup retain]; [axisLabelGroup release]; axisLabelGroup = newAxisLabelGroup; if ( axisLabelGroup ) { [self insertSublayer:axisLabelGroup atIndex:[self indexForLayerType:CPGraphLayerTypeAxisLabels]]; } [self setNeedsLayout]; } } -(void)setAxisTitleGroup:(CPAxisLabelGroup *)newAxisTitleGroup { if ( (newAxisTitleGroup != axisTitleGroup) || self.isUpdatingLayers ) { [axisTitleGroup removeFromSuperlayer]; [newAxisTitleGroup retain]; [axisTitleGroup release]; axisTitleGroup = newAxisTitleGroup; if ( axisTitleGroup ) { [self insertSublayer:axisTitleGroup atIndex:[self indexForLayerType:CPGraphLayerTypeAxisTitles]]; } [self setNeedsLayout]; } } -(void)setTopDownLayerOrder:(NSArray *)newArray { if ( newArray != topDownLayerOrder) { [topDownLayerOrder release]; topDownLayerOrder = [newArray retain]; [self updateLayerOrder]; } } @end
08iteng-ipad
framework/Source/CPPlotArea.m
Objective-C
bsd
15,120
#import <Foundation/Foundation.h> #import "CPDefinitions.h" /// @file #if __cplusplus extern "C" { #endif /// @name Convert NSDecimal to primitive types /// @{ int8_t CPDecimalCharValue(NSDecimal decimalNumber); int16_t CPDecimalShortValue(NSDecimal decimalNumber); int32_t CPDecimalLongValue(NSDecimal decimalNumber); int64_t CPDecimalLongLongValue(NSDecimal decimalNumber); int CPDecimalIntValue(NSDecimal decimalNumber); NSInteger CPDecimalIntegerValue(NSDecimal decimalNumber); uint8_t CPDecimalUnsignedCharValue(NSDecimal decimalNumber); uint16_t CPDecimalUnsignedShortValue(NSDecimal decimalNumber); uint32_t CPDecimalUnsignedLongValue(NSDecimal decimalNumber); uint64_t CPDecimalUnsignedLongLongValue(NSDecimal decimalNumber); unsigned int CPDecimalUnsignedIntValue(NSDecimal decimalNumber); NSUInteger CPDecimalUnsignedIntegerValue(NSDecimal decimalNumber); float CPDecimalFloatValue(NSDecimal decimalNumber); double CPDecimalDoubleValue(NSDecimal decimalNumber); NSString * CPDecimalStringValue(NSDecimal decimalNumber); /// @} /// @name Convert primitive types to NSDecimal /// @{ NSDecimal CPDecimalFromChar(int8_t i); NSDecimal CPDecimalFromShort(int16_t i); NSDecimal CPDecimalFromLong(int32_t i); NSDecimal CPDecimalFromLongLong(int64_t i); NSDecimal CPDecimalFromInt(int i); NSDecimal CPDecimalFromInteger(NSInteger i); NSDecimal CPDecimalFromUnsignedChar(uint8_t i); NSDecimal CPDecimalFromUnsignedShort(uint16_t i); NSDecimal CPDecimalFromUnsignedLong(uint32_t i); NSDecimal CPDecimalFromUnsignedLongLong(uint64_t i); NSDecimal CPDecimalFromUnsignedInt(unsigned int i); NSDecimal CPDecimalFromUnsignedInteger(NSUInteger i); NSDecimal CPDecimalFromFloat(float f); NSDecimal CPDecimalFromDouble(double d); NSDecimal CPDecimalFromString(NSString *stringRepresentation); /// @} /// @name NSDecimal arithmetic /// @{ NSDecimal CPDecimalAdd(NSDecimal leftOperand, NSDecimal rightOperand); NSDecimal CPDecimalSubtract(NSDecimal leftOperand, NSDecimal rightOperand); NSDecimal CPDecimalMultiply(NSDecimal leftOperand, NSDecimal rightOperand); NSDecimal CPDecimalDivide(NSDecimal numerator, NSDecimal denominator); /// @} /// @name NSDecimal comparison /// @{ BOOL CPDecimalGreaterThan(NSDecimal leftOperand, NSDecimal rightOperand); BOOL CPDecimalGreaterThanOrEqualTo(NSDecimal leftOperand, NSDecimal rightOperand); BOOL CPDecimalLessThan(NSDecimal leftOperand, NSDecimal rightOperand); BOOL CPDecimalLessThanOrEqualTo(NSDecimal leftOperand, NSDecimal rightOperand); BOOL CPDecimalEquals(NSDecimal leftOperand, NSDecimal rightOperand); /// @} /// @name NSDecimal utilities /// @{ NSDecimal CPDecimalNaN(void); /// @} /// @name Ranges /// @{ NSRange CPExpandedRange(NSRange range, NSInteger expandBy); /// @} /// @name Coordinates /// @{ CPCoordinate CPOrthogonalCoordinate(CPCoordinate coord); /// @} /// @name Gradient colors /// @{ CPRGBAColor CPRGBAColorFromCGColor(CGColorRef color); /// @} /// @name Quartz Pixel-Alignment Functions /// @{ CGPoint CPAlignPointToUserSpace(CGContextRef context, CGPoint p); CGSize CPAlignSizeToUserSpace(CGContextRef context, CGSize s); CGRect CPAlignRectToUserSpace(CGContextRef context, CGRect r); /// @} /// @name String formatting for Core Graphics structs /// @{ NSString *CPStringFromPoint(CGPoint p); NSString *CPStringFromSize(CGSize s); NSString *CPStringFromRect(CGRect r); /// @} #if __cplusplus } #endif
08iteng-ipad
framework/Source/CPUtilities.h
Objective-C
bsd
3,381
#import "CPAxisSet.h" #import "CPGraph.h" #import "CPLayer.h" #import "CPLayoutManager.h" #import "CPPathExtensions.h" #import "CPPlatformSpecificFunctions.h" #import "CPExceptions.h" #import "CPLineStyle.h" #import "CPUtilities.h" #import "CorePlotProbes.h" #import <objc/runtime.h> /** @cond */ @interface CPLayer() @property (nonatomic, readwrite, getter=isRenderingRecursively) BOOL renderingRecursively; @property (nonatomic, readwrite, assign) BOOL useFastRendering; -(void)applyTransform:(CATransform3D)transform toContext:(CGContextRef)context; @end /** @endcond */ #pragma mark - /** @brief Base class for all Core Animation layers in Core Plot. * * Default animations for changes in position, bounds, and sublayers are turned off. * The default layer is not opaque and does not mask to bounds. * * @todo More documentation needed **/ @implementation CPLayer /** @property graph * @brief The graph for the layer. **/ @synthesize graph; /** @property paddingLeft * @brief Amount to inset the left side of each sublayer. **/ @synthesize paddingLeft; /** @property paddingTop * @brief Amount to inset the top of each sublayer. **/ @synthesize paddingTop; /** @property paddingRight * @brief Amount to inset the right side of each sublayer. **/ @synthesize paddingRight; /** @property paddingBottom * @brief Amount to inset the bottom of each sublayer. **/ @synthesize paddingBottom; /** @property masksToBorder * @brief If YES, a sublayer mask is applied to clip sublayer content to the inside of the border. **/ @synthesize masksToBorder; /** @property outerBorderPath * @brief A drawing path that encompasses the outer boundary of the layer border. **/ @synthesize outerBorderPath; /** @property innerBorderPath * @brief A drawing path that encompasses the inner boundary of the layer border. **/ @synthesize innerBorderPath; /** @property maskingPath * @brief A drawing path that encompasses the layer content including any borders. Set to NULL when no masking is desired. * * This path defines the outline of the layer and is used to mask all drawing. Set to NULL when no masking is desired. * The caller must NOT release the path returned by this property. **/ @dynamic maskingPath; /** @property sublayerMaskingPath * @brief A drawing path that encompasses the layer content excluding any borders. Set to NULL when no masking is desired. * * This path defines the outline of the part of the layer where sublayers should draw and is used to mask all sublayer drawing. * Set to NULL when no masking is desired. * The caller must NOT release the path returned by this property. **/ @dynamic sublayerMaskingPath; /** @property layoutManager * @brief The layout manager for this layer. **/ @synthesize layoutManager; /** @property sublayersExcludedFromAutomaticLayout * @brief A set of sublayers that should be excluded from the automatic sublayer layout. **/ @dynamic sublayersExcludedFromAutomaticLayout; /** @property useFastRendering * @brief If YES, subclasses should optimize their drawing for speed over precision. **/ @synthesize useFastRendering; // Private properties @synthesize renderingRecursively; #pragma mark - #pragma mark Init/Dealloc /** @brief Initializes a newly allocated CPLayer object with the provided frame rectangle. * * This is the designated initializer. The initialized layer will have the following properties that * are different than a CALayer: * - needsDisplayOnBoundsChange = NO * - opaque = NO * - masksToBounds = NO * - zPosition = defaultZPosition * - padding = 0 on all four sides * - Default animations for changes in position, bounds, and sublayers are turned off. * * @param newFrame The frame rectangle. * @return The initialized CPLayer object. **/ -(id)initWithFrame:(CGRect)newFrame { if ( self = [super init] ) { paddingLeft = 0.0; paddingTop = 0.0; paddingRight = 0.0; paddingBottom = 0.0; masksToBorder = NO; layoutManager = nil; renderingRecursively = NO; useFastRendering = NO; graph = nil; outerBorderPath = NULL; innerBorderPath = NULL; self.frame = newFrame; self.needsDisplayOnBoundsChange = NO; self.opaque = NO; self.masksToBounds = NO; self.zPosition = [self.class defaultZPosition]; // Screen scaling if ([self respondsToSelector:@selector(setContentsScale:)]) { Class screenClass = NSClassFromString(@"UIScreen"); if ( screenClass != Nil) { id scale = [[screenClass mainScreen] valueForKey:@"scale"]; [(id)self setValue:scale forKey:@"contentsScale"]; } } } return self; } -(id)init { return [self initWithFrame:CGRectZero]; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPLayer *theLayer = (CPLayer *)layer; paddingLeft = theLayer->paddingLeft; paddingTop = theLayer->paddingTop; paddingRight = theLayer->paddingRight; paddingBottom = theLayer->paddingBottom; masksToBorder = theLayer->masksToBorder; layoutManager = [theLayer->layoutManager retain]; renderingRecursively = theLayer->renderingRecursively; graph = theLayer->graph; outerBorderPath = CGPathRetain(theLayer->outerBorderPath); innerBorderPath = CGPathRetain(theLayer->innerBorderPath); } return self; } -(void)dealloc { graph = nil; [layoutManager release]; CGPathRelease(outerBorderPath); CGPathRelease(innerBorderPath); [super dealloc]; } -(void)finalize { CGPathRelease(outerBorderPath); CGPathRelease(innerBorderPath); [super finalize]; } #pragma mark - #pragma mark Animation -(id <CAAction>)actionForKey:(NSString *)aKey { return nil; } #pragma mark - #pragma mark Drawing -(void)drawInContext:(CGContextRef)context { self.useFastRendering = YES; [self renderAsVectorInContext:context]; self.useFastRendering = NO; } /** @brief Draws layer content into the provided graphics context. * * This method replaces the drawInContext: method to ensure that layer content is always drawn as vectors * and objects rather than as a cached bitmapped image representation. * Subclasses should do all drawing here and must call super to set up the clipping path. * * @param context The graphics context to draw into. **/ -(void)renderAsVectorInContext:(CGContextRef)context; { // This is where subclasses do their drawing [self applyMaskToContext:context]; } /** @brief Draws layer content and the content of all sublayers into the provided graphics context. * @param context The graphics context to draw into. **/ -(void)recursivelyRenderInContext:(CGContextRef)context { // render self CGContextSaveGState(context); [self applyTransform:self.transform toContext:context]; self.renderingRecursively = YES; if ( !self.masksToBounds ) { CGContextSaveGState(context); } [self renderAsVectorInContext:context]; if ( !self.masksToBounds ) { CGContextRestoreGState(context); } self.renderingRecursively = NO; // render sublayers NSArray *sublayersCopy = [self.sublayers copy]; for ( CALayer *currentSublayer in sublayersCopy ) { CGContextSaveGState(context); // Shift origin of context to match starting coordinate of sublayer CGPoint currentSublayerFrameOrigin = currentSublayer.frame.origin; CGRect currentSublayerBounds = currentSublayer.bounds; CGContextTranslateCTM(context, currentSublayerFrameOrigin.x - currentSublayerBounds.origin.x, currentSublayerFrameOrigin.y - currentSublayerBounds.origin.y); [self applyTransform:self.sublayerTransform toContext:context]; if ( [currentSublayer isKindOfClass:[CPLayer class]] ) { [(CPLayer *)currentSublayer recursivelyRenderInContext:context]; } else { if ( self.masksToBounds ) { CGContextClipToRect(context, currentSublayer.bounds); } [currentSublayer drawInContext:context]; } CGContextRestoreGState(context); } [sublayersCopy release]; CGContextRestoreGState(context); } -(void)applyTransform:(CATransform3D)transform3D toContext:(CGContextRef)context { if ( !CATransform3DIsIdentity(transform3D) ) { if ( CATransform3DIsAffine(transform3D) ) { CGRect selfBounds = self.bounds; CGPoint anchorPoint = self.anchorPoint; CGPoint anchorOffset = CGPointMake(anchorOffset.x = selfBounds.origin.x + anchorPoint.x * selfBounds.size.width, anchorOffset.y = selfBounds.origin.y + anchorPoint.y * selfBounds.size.height); CGAffineTransform affineTransform = CGAffineTransformMakeTranslation(-anchorOffset.x, -anchorOffset.y); affineTransform = CGAffineTransformConcat(affineTransform, CATransform3DGetAffineTransform(transform3D)); affineTransform = CGAffineTransformTranslate(affineTransform, anchorOffset.x, anchorOffset.y); CGRect transformedBounds = CGRectApplyAffineTransform(selfBounds, affineTransform); CGContextTranslateCTM(context, -transformedBounds.origin.x, -transformedBounds.origin.y); CGContextConcatCTM(context, affineTransform); } } } /** @brief Updates the layer layout if needed and then draws layer content and the content of all sublayers into the provided graphics context. * @param context The graphics context to draw into. */ -(void)layoutAndRenderInContext:(CGContextRef)context { CPGraph *theGraph = nil; if ( [self isKindOfClass:[CPGraph class]] ) { theGraph = (CPGraph *)self; } else { theGraph = self.graph; } if ( theGraph ) { [theGraph reloadDataIfNeeded]; [theGraph.axisSet.axes makeObjectsPerformSelector:@selector(relabel)]; } [self layoutIfNeeded]; [self recursivelyRenderInContext:context]; } /** @brief Draws layer content and the content of all sublayers into a PDF document. * @return PDF representation of the layer content. **/ -(NSData *)dataForPDFRepresentationOfLayer { NSMutableData *pdfData = [[NSMutableData alloc] init]; CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData); const CGRect mediaBox = CGRectMake(0.0, 0.0, self.bounds.size.width, self.bounds.size.height); CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &mediaBox, NULL); CPPushCGContext(pdfContext); CGContextBeginPage(pdfContext, &mediaBox); [self layoutAndRenderInContext:pdfContext]; CGContextEndPage(pdfContext); CGPDFContextClose(pdfContext); CPPopCGContext(); CGContextRelease(pdfContext); CGDataConsumerRelease(dataConsumer); return [pdfData autorelease]; } #pragma mark - #pragma mark Responder Chain and User interaction /** @brief Informs the receiver that a pinch gesture occurred * @param pinchGestureRecognizer The pinch gesture itself. * @param interactionPoint The coordinates of the gesture's centroid. * @param interactionScale The scale of the pinching gesture. * @return YES should be returned if the gesture was handled (exclusively) by the receiver, NO otherwise. **/ -(BOOL) recognizer:(id)pinchGestureRecognizer atPoint:(CGPoint)interactionPoint withScale:(CGFloat)interactionScale { return NO; } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger down event. * @param event Native event object of device. * @param interactionPoint The coordinates of the event in the host view. * @return Whether the event was handled or not. **/ -(BOOL)pointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint { return NO; } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger up event. * @param event Native event object of device. * @param interactionPoint The coordinates of the event in the host view. * @return Whether the event was handled or not. **/ -(BOOL)pointingDeviceUpEvent:(id)event atPoint:(CGPoint)interactionPoint { return NO; } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger dragged event. * @param event Native event object of device. * @param interactionPoint The coordinates of the event in the host view. * @return Whether the event was handled or not. **/ -(BOOL)pointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)interactionPoint { return NO; } /** @brief Abstraction of Mac and iPhone event handling. Mouse or finger event cancelled. * @param event Native event object of device. * @return Whether the event was handled or not. **/ -(BOOL)pointingDeviceCancelledEvent:(id)event { return NO; } #pragma mark - #pragma mark Layout /** @brief Align the receiver's position with pixel boundaries. **/ -(void)pixelAlign { CGSize currentSize = self.bounds.size; CGPoint currentPosition = self.position; CGPoint anchor = self.anchorPoint; CGPoint newPosition = self.position; newPosition.x = round(currentPosition.x) - round(currentSize.width * anchor.x) + (currentSize.width * anchor.x); newPosition.y = round(currentPosition.y) - round(currentSize.height * anchor.y) + (currentSize.height * anchor.y); self.position = newPosition; } -(void)setPaddingLeft:(CGFloat)newPadding { if ( newPadding != paddingLeft ) { paddingLeft = newPadding; [self setNeedsLayout]; } } -(void)setPaddingRight:(CGFloat)newPadding { if ( newPadding != paddingRight ) { paddingRight = newPadding; [self setNeedsLayout]; } } -(void)setPaddingTop:(CGFloat)newPadding { if ( newPadding != paddingTop ) { paddingTop = newPadding; [self setNeedsLayout]; } } -(void)setPaddingBottom:(CGFloat)newPadding { if ( newPadding != paddingBottom ) { paddingBottom = newPadding; [self setNeedsLayout]; } } /** @brief The default z-position for the layer. * @return The z-position. **/ +(CGFloat)defaultZPosition { return 0.0; } -(void)layoutSublayers { // This is where we do our custom replacement for the Mac-only layout manager and autoresizing mask // Subclasses should override to lay out their own sublayers // Sublayers fill the super layer's bounds minus any padding by default CGFloat leftPadding = self.paddingLeft; CGFloat bottomPadding = self.paddingBottom; CGRect selfBounds = self.bounds; CGSize subLayerSize = selfBounds.size; subLayerSize.width -= leftPadding + self.paddingRight; subLayerSize.width = MAX(subLayerSize.width, 0.0); subLayerSize.height -= self.paddingTop + bottomPadding; subLayerSize.height = MAX(subLayerSize.height, 0.0); NSSet *excludedSublayers = [self sublayersExcludedFromAutomaticLayout]; for (CALayer *subLayer in self.sublayers) { if (![excludedSublayers containsObject:subLayer] && [subLayer isKindOfClass:[CPLayer class]]) { subLayer.frame = CGRectMake(leftPadding, bottomPadding, subLayerSize.width, subLayerSize.height); } } } -(NSSet *)sublayersExcludedFromAutomaticLayout { return [NSSet set]; } #pragma mark - #pragma mark Masking // default path is the rounded rect layer bounds -(CGPathRef)maskingPath { if ( self.masksToBounds ) { CGPathRef path = self.outerBorderPath; if ( path ) return path; CGRect selfBounds = self.bounds; if ( self.cornerRadius > 0.0 ) { CGFloat radius = MIN(MIN(self.cornerRadius, selfBounds.size.width / 2.0), selfBounds.size.height / 2.0); path = CreateRoundedRectPath(selfBounds, radius); self.outerBorderPath = path; CGPathRelease(path); } else { CGMutablePathRef mutablePath = CGPathCreateMutable(); CGPathAddRect(mutablePath, NULL, selfBounds); self.outerBorderPath = mutablePath; CGPathRelease(mutablePath); } return self.outerBorderPath; } else { return NULL; } } -(CGPathRef)sublayerMaskingPath { return self.innerBorderPath; } /** @brief Recursively sets the clipping path of the given graphics context to the sublayer masking paths of its superlayers. * * The clipping path is built by recursively climbing the layer tree and combining the sublayer masks from * each super layer. The tree traversal stops when a layer is encountered that is not a CPLayer. * * @param context The graphics context to clip. * @param sublayer The sublayer that called this method. * @param offset The cumulative position offset between the receiver and the first layer in the recursive calling chain. **/ -(void)applySublayerMaskToContext:(CGContextRef)context forSublayer:(CPLayer *)sublayer withOffset:(CGPoint)offset { CGPoint sublayerBoundsOrigin = sublayer.bounds.origin; CGPoint layerOffset = offset; if ( !self.renderingRecursively ) { CGPoint convertedOffset = [self convertPoint:sublayerBoundsOrigin fromLayer:sublayer]; layerOffset.x += convertedOffset.x; layerOffset.y += convertedOffset.y; } CGAffineTransform sublayerTransform = CATransform3DGetAffineTransform(sublayer.transform); CGContextConcatCTM(context, CGAffineTransformInvert(sublayerTransform)); CALayer *superlayer = self.superlayer; if ( [superlayer isKindOfClass:[CPLayer class]] ) { [(CPLayer *)superlayer applySublayerMaskToContext:context forSublayer:self withOffset:layerOffset]; } CGPathRef maskPath = self.sublayerMaskingPath; if ( maskPath ) { // CGAffineTransform transform = CATransform3DGetAffineTransform(self.transform); // CGAffineTransform sublayerTransform = CATransform3DGetAffineTransform(self.sublayerTransform); CGContextTranslateCTM(context, -layerOffset.x, -layerOffset.y); // CGContextConcatCTM(context, CGAffineTransformInvert(transform)); // CGContextConcatCTM(context, CGAffineTransformInvert(sublayerTransform)); CGContextAddPath(context, maskPath); CGContextClip(context); // CGContextConcatCTM(context, sublayerTransform); // CGContextConcatCTM(context, transform); CGContextTranslateCTM(context, layerOffset.x, layerOffset.y); } CGContextConcatCTM(context, sublayerTransform); } /** @brief Sets the clipping path of the given graphics context to mask the content. * * The clipping path is built by recursively climbing the layer tree and combining the sublayer masks from * each super layer. The tree traversal stops when a layer is encountered that is not a CPLayer. * * @param context The graphics context to clip. **/ -(void)applyMaskToContext:(CGContextRef)context { if ( [self.superlayer isKindOfClass:[CPLayer class]] ) { [(CPLayer *)self.superlayer applySublayerMaskToContext:context forSublayer:self withOffset:CGPointZero]; } CGPathRef maskPath = self.maskingPath; if ( maskPath ) { CGContextAddPath(context, maskPath); CGContextClip(context); } } -(void)setNeedsLayout { [super setNeedsLayout]; if ( self.graph ) [[NSNotificationCenter defaultCenter] postNotificationName:CPGraphNeedsRedrawNotification object:self.graph]; } -(void)setNeedsDisplay { [super setNeedsDisplay]; if ( self.graph ) [[NSNotificationCenter defaultCenter] postNotificationName:CPGraphNeedsRedrawNotification object:self.graph]; } #pragma mark - #pragma mark Line style delegate -(void)lineStyleDidChange:(CPLineStyle *)lineStyle { [self setNeedsDisplay]; } #pragma mark - #pragma mark Accessors - (void)setPosition:(CGPoint)newPosition; { [super setPosition:newPosition]; if ( COREPLOT_LAYER_POSITION_CHANGE_ENABLED() ) { CGRect currentFrame = self.frame; if (!CGRectEqualToRect(currentFrame, CGRectIntegral(self.frame))) COREPLOT_LAYER_POSITION_CHANGE((char *)class_getName([self class]), (int)ceil(currentFrame.origin.x * 1000.0), (int)ceil(currentFrame.origin.y * 1000.0), (int)ceil(currentFrame.size.width * 1000.0), (int)ceil(currentFrame.size.height * 1000.0)); } } -(void)setOuterBorderPath:(CGPathRef)newPath { if ( newPath != outerBorderPath ) { CGPathRelease(outerBorderPath); outerBorderPath = CGPathRetain(newPath); } } -(void)setInnerBorderPath:(CGPathRef)newPath { if ( newPath != innerBorderPath ) { CGPathRelease(innerBorderPath); innerBorderPath = CGPathRetain(newPath); } } -(void)setBounds:(CGRect)newBounds { [super setBounds:newBounds]; self.outerBorderPath = NULL; self.innerBorderPath = NULL; } -(void)setCornerRadius:(CGFloat)newRadius { if ( newRadius != self.cornerRadius ) { super.cornerRadius = newRadius; [self setNeedsDisplay]; self.outerBorderPath = NULL; self.innerBorderPath = NULL; } } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"<%@ bounds: %@>", [super description], CPStringFromRect(self.bounds)]; }; @end
08iteng-ipad
framework/Source/CPLayer.m
Objective-C
bsd
20,349
#import "CPMutableNumericData.h" #import "CPNumericData.h" #import "CPBarPlot.h" #import "CPXYPlotSpace.h" #import "CPColor.h" #import "CPMutableLineStyle.h" #import "CPFill.h" #import "CPPlotArea.h" #import "CPPlotRange.h" #import "CPPlotSpaceAnnotation.h" #import "CPGradient.h" #import "CPUtilities.h" #import "CPExceptions.h" #import "CPTextLayer.h" #import "CPMutableTextStyle.h" NSString * const CPBarPlotBindingBarLocations = @"barLocations"; ///< Bar locations. NSString * const CPBarPlotBindingBarTips = @"barTips"; ///< Bar tips. NSString * const CPBarPlotBindingBarBases = @"barBases"; ///< Bar bases. /** @cond */ @interface CPBarPlot () @property (nonatomic, readwrite, copy) NSArray *barLocations; @property (nonatomic, readwrite, copy) NSArray *barLengths; @property (nonatomic, readwrite, copy) NSArray *barBases; -(CGMutablePathRef)newBarPathWithContext:(CGContextRef)context recordIndex:(NSUInteger)recordIndex; -(CGMutablePathRef)newBarPathWithContext:(CGContextRef)context basePoint:(CGPoint)basePoint tipPoint:(CGPoint)tipPoint; -(void)drawBarInContext:(CGContextRef)context recordIndex:(NSUInteger)index; -(CGFloat)lengthInView:(NSDecimal)plotLength; -(BOOL)barIsVisibleWithBasePoint:(CGPoint)basePoint; @end /** @endcond */ #pragma mark - /** @brief A two-dimensional bar plot. **/ @implementation CPBarPlot @dynamic barLocations; @dynamic barLengths; @dynamic barBases; /** @property barCornerRadius * @brief The corner radius for the end of the bars. **/ @synthesize barCornerRadius; /** @property barOffset * @brief The starting offset of the first bar in location data units. **/ @synthesize barOffset; /** @property barWidthsAreInViewCoordinates * @brief Whether the bar width and bar offset is in view coordinates, or in plot coordinates. * Default is NO, meaning plot coordinates are used. **/ @synthesize barWidthsAreInViewCoordinates; /** @property barWidth * @brief The width of each bar. Either view or plot coordinates can be used. * @see barWidthsAreInViewCoordinates * * With plot coordinates, the bar locations are one data unit apart (e.g., 1, 2, 3, etc.), * a value of 1.0 will result in bars that touch each other; a value of 0.5 will result in bars that are as wide * as the gap between them. **/ @synthesize barWidth; /** @property lineStyle * @brief The line style for the bar outline. * If nil, the outline is not drawn. **/ @synthesize lineStyle; /** @property fill * @brief The fill style for the bars. * If nil, the bars are not filled. **/ @synthesize fill; /** @property barsAreHorizontal * @brief If YES, the bars will have a horizontal orientation, otherwise they will be vertical. **/ @synthesize barsAreHorizontal; /** @property baseValue * @brief The coordinate value of the fixed end of the bars. * This is only used if barsHaveVariableBases is NO. Otherwise, the data source * will be queried for an appropriate value of CPBarPlotFieldBarBase. **/ @synthesize baseValue; /** @property barBasesVary * @brief If YES, a constant base value is used for all bars (baseValue). * If NO, the data source is queried to supply a base value for each bar. **/ @synthesize barBasesVary; /** @property plotRange * @brief Sets the plot range for the independent axis. * * If a plot range is provided, the bars are spaced evenly throughout the plot range. If plotRange is nil, * bar locations are provided by Cocoa bindings or the bar plot datasource. If locations are not provided by * either bindings or the datasource, the first bar will be placed at zero (0) and subsequent bars will be at * successive positive integer coordinates. **/ @synthesize plotRange; /** @property barLabelOffset * @brief Sets the offset of the value label above the bar * @deprecated This property has been replaced by the CPPlot::labelOffset property. **/ @dynamic barLabelOffset; /** @property barLabelTextStyle * @brief Sets the textstyle of the value label above the bar * @deprecated This property has been replaced by the CPPlot::labelTextStyle property. **/ @dynamic barLabelTextStyle; #pragma mark - #pragma mark Convenience Factory Methods /** @brief Creates and returns a new CPBarPlot instance initialized with a bar fill consisting of a linear gradient between black and the given color. * @param color The beginning color. * @param horizontal If YES, the bars will have a horizontal orientation, otherwise they will be vertical. * @return A new CPBarPlot instance initialized with a linear gradient bar fill. **/ +(CPBarPlot *)tubularBarPlotWithColor:(CPColor *)color horizontalBars:(BOOL)horizontal { CPBarPlot *barPlot = [[CPBarPlot alloc] init]; CPMutableLineStyle *barLineStyle = [[CPMutableLineStyle alloc] init]; barLineStyle.lineWidth = 1.0; barLineStyle.lineColor = [CPColor blackColor]; barPlot.lineStyle = barLineStyle; [barLineStyle release]; barPlot.barsAreHorizontal = horizontal; barPlot.barWidth = CPDecimalFromDouble(0.8); barPlot.barWidthsAreInViewCoordinates = NO; barPlot.barCornerRadius = 2.0; CPGradient *fillGradient = [CPGradient gradientWithBeginningColor:color endingColor:[CPColor blackColor]]; fillGradient.angle = (horizontal ? -90.0 : 0.0); barPlot.fill = [CPFill fillWithGradient:fillGradient]; return [barPlot autorelease]; } #pragma mark - #pragma mark Initialization #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE #else +(void)initialize { if ( self == [CPBarPlot class] ) { [self exposeBinding:CPBarPlotBindingBarLocations]; [self exposeBinding:CPBarPlotBindingBarTips]; [self exposeBinding:CPBarPlotBindingBarBases]; } } #endif -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { lineStyle = [[CPLineStyle alloc] init]; fill = [[CPFill fillWithColor:[CPColor blackColor]] retain]; barWidth = CPDecimalFromDouble(0.5); barWidthsAreInViewCoordinates = NO; barOffset = CPDecimalFromDouble(0.0); barCornerRadius = 0.0; baseValue = CPDecimalFromInteger(0); barsAreHorizontal = NO; barBasesVary = NO; plotRange = nil; self.labelOffset = 10.0; self.labelField = CPBarPlotFieldBarTip; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPBarPlot *theLayer = (CPBarPlot *)layer; lineStyle = [theLayer->lineStyle retain]; fill = [theLayer->fill retain]; barWidth = theLayer->barWidth; barWidthsAreInViewCoordinates = theLayer->barWidthsAreInViewCoordinates; barOffset = theLayer->barOffset; barCornerRadius = theLayer->barCornerRadius; baseValue = theLayer->baseValue; barBasesVary = theLayer->barBasesVary; barsAreHorizontal = theLayer->barsAreHorizontal; plotRange = [theLayer->plotRange retain]; } return self; } -(void)dealloc { [lineStyle release]; [fill release]; [plotRange release]; [super dealloc]; } #pragma mark - #pragma mark Data Loading -(void)reloadDataInIndexRange:(NSRange)indexRange { [super reloadDataInIndexRange:indexRange]; // Bar lengths if ( self.dataSource ) { id newBarLengths = [self numbersFromDataSourceForField:CPBarPlotFieldBarTip recordIndexRange:indexRange]; [self cacheNumbers:newBarLengths forField:CPBarPlotFieldBarTip atRecordIndex:indexRange.location]; if ( self.barBasesVary ) { id newBarBases = [self numbersFromDataSourceForField:CPBarPlotFieldBarBase recordIndexRange:indexRange]; [self cacheNumbers:newBarBases forField:CPBarPlotFieldBarBase atRecordIndex:indexRange.location]; } else { self.barBases = nil; } } else { self.barLengths = nil; self.barBases = nil; } // Locations of bars if ( self.plotRange ) { // Spread bars evenly over the plot range CPMutableNumericData *locationData = nil; if ( self.doublePrecisionCache ) { locationData = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:CPDataType(CPFloatingPointDataType, sizeof(double), CFByteOrderGetCurrent()) shape:nil]; ((NSMutableData *)locationData.data).length = indexRange.length * sizeof(double); double doublePrecisionDelta = 1.0; if ( indexRange.length > 1 ) { doublePrecisionDelta = self.plotRange.lengthDouble / (double)(indexRange.length - 1); } double locationDouble = self.plotRange.locationDouble; double *dataBytes = (double *)locationData.mutableBytes; double *dataEnd = dataBytes + indexRange.length; while ( dataBytes < dataEnd ) { *dataBytes++ = locationDouble; locationDouble += doublePrecisionDelta; } } else { locationData = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:CPDataType(CPDecimalDataType, sizeof(NSDecimal), CFByteOrderGetCurrent()) shape:nil]; ((NSMutableData *)locationData.data).length = indexRange.length * sizeof(NSDecimal); NSDecimal delta = CPDecimalFromInteger(1); if ( indexRange.length > 1 ) { delta = CPDecimalDivide(self.plotRange.length, CPDecimalFromUnsignedInteger(indexRange.length - 1)); } NSDecimal locationDecimal = self.plotRange.location; NSDecimal *dataBytes = (NSDecimal *)locationData.mutableBytes; NSDecimal *dataEnd = dataBytes + indexRange.length; while ( dataBytes < dataEnd ) { *dataBytes++ = locationDecimal; locationDecimal = CPDecimalAdd(locationDecimal, delta); } } [self cacheNumbers:locationData forField:CPBarPlotFieldBarLocation atRecordIndex:indexRange.location]; [locationData release]; } else if ( self.dataSource ) { // Get locations from the datasource id newBarLocations = [self numbersFromDataSourceForField:CPBarPlotFieldBarLocation recordIndexRange:indexRange]; [self cacheNumbers:newBarLocations forField:CPBarPlotFieldBarLocation atRecordIndex:indexRange.location]; } else { // Make evenly spaced locations starting at zero CPMutableNumericData *locationData = nil; if ( self.doublePrecisionCache ) { locationData = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:CPDataType(CPFloatingPointDataType, sizeof(double), CFByteOrderGetCurrent()) shape:nil]; ((NSMutableData *)locationData.data).length = indexRange.length * sizeof(double); double locationDouble = 0.0; double *dataBytes = (double *)locationData.mutableBytes; double *dataEnd = dataBytes + indexRange.length; while ( dataBytes < dataEnd ) { *dataBytes++ = locationDouble; locationDouble += 1.0; } } else { locationData = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:CPDataType(CPDecimalDataType, sizeof(NSDecimal), CFByteOrderGetCurrent()) shape:nil]; ((NSMutableData *)locationData.data).length = indexRange.length * sizeof(NSDecimal); NSDecimal locationDecimal = CPDecimalFromInteger(0); NSDecimal *dataBytes = (NSDecimal *)locationData.mutableBytes; NSDecimal *dataEnd = dataBytes + indexRange.length; NSDecimal one = CPDecimalFromInteger(1); while ( dataBytes < dataEnd ) { *dataBytes++ = locationDecimal; locationDecimal = CPDecimalAdd(locationDecimal, one); } } [self cacheNumbers:locationData forField:CPBarPlotFieldBarLocation atRecordIndex:indexRange.location]; [locationData release]; } } #pragma mark - #pragma mark Length Conversions for Independent Coordinate (e.g., widths, offsets) -(CGFloat)lengthInView:(NSDecimal)decimalLength { CPCoordinate coordinate = ( self.barsAreHorizontal ? CPCoordinateY : CPCoordinateX ); CGFloat length; if ( !barWidthsAreInViewCoordinates ) { NSDecimal originPlotPoint[2] = {CPDecimalFromInteger(0), CPDecimalFromInteger(0)}; NSDecimal displacedPlotPoint[2] = {decimalLength, decimalLength}; CGPoint originPoint = [self.plotSpace plotAreaViewPointForPlotPoint:originPlotPoint]; CGPoint displacedPoint = [self.plotSpace plotAreaViewPointForPlotPoint:displacedPlotPoint]; length = ( coordinate == CPCoordinateX ? displacedPoint.x - originPoint.x : displacedPoint.y - originPoint.y ); } else { length = CPDecimalFloatValue(decimalLength); } return length; } -(double)doubleLengthInPlotCoordinates:(NSDecimal)decimalLength { double length; if ( barWidthsAreInViewCoordinates ) { CGFloat floatLength = CPDecimalFloatValue(decimalLength); CGPoint originViewPoint = CGPointZero; CGPoint displacedViewPoint = CGPointMake(floatLength, floatLength); double originPlotPoint[2], displacedPlotPoint[2]; [self.plotSpace doublePrecisionPlotPoint:originPlotPoint forPlotAreaViewPoint:originViewPoint]; [self.plotSpace doublePrecisionPlotPoint:displacedPlotPoint forPlotAreaViewPoint:displacedViewPoint]; length = ( !barsAreHorizontal ? displacedPlotPoint[0] - originPlotPoint[0] : displacedPlotPoint[1] - originPlotPoint[1]); } else { length = CPDecimalDoubleValue(decimalLength); } return length; } -(NSDecimal)lengthInPlotCoordinates:(NSDecimal)decimalLength { NSDecimal length; if ( barWidthsAreInViewCoordinates ) { CGFloat floatLength = CPDecimalFloatValue(decimalLength); CGPoint originViewPoint = CGPointZero; CGPoint displacedViewPoint = CGPointMake(floatLength, floatLength); NSDecimal originPlotPoint[2], displacedPlotPoint[2]; [self.plotSpace plotPoint:originPlotPoint forPlotAreaViewPoint:originViewPoint]; [self.plotSpace plotPoint:displacedPlotPoint forPlotAreaViewPoint:displacedViewPoint]; if ( !barsAreHorizontal ) { length = CPDecimalSubtract(displacedPlotPoint[0], originPlotPoint[0]); } else { length = CPDecimalSubtract(displacedPlotPoint[1], originPlotPoint[1]); } } else { length = decimalLength; } return length; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { CPMutableNumericData *cachedLocations = [self cachedNumbersForField:CPBarPlotFieldBarLocation]; CPMutableNumericData *cachedLengths = [self cachedNumbersForField:CPBarPlotFieldBarTip]; if ( cachedLocations == nil || cachedLengths == nil ) return; BOOL basesVary = self.barBasesVary; CPMutableNumericData *cachedBases = [self cachedNumbersForField:CPBarPlotFieldBarBase]; if ( basesVary && cachedBases == nil ) return; NSUInteger barCount = self.cachedDataCount; if ( barCount == 0 ) return; if ( cachedLocations.numberOfSamples != cachedLengths.numberOfSamples ) { [NSException raise:CPException format:@"Number of bar locations and lengths do not match"]; }; if ( basesVary && cachedLengths.numberOfSamples != cachedBases.numberOfSamples ) { [NSException raise:CPException format:@"Number of bar lengths and bases do not match"]; }; [super renderAsVectorInContext:theContext]; for ( NSUInteger ii = 0; ii < barCount; ii++ ) { // Draw [self drawBarInContext:theContext recordIndex:ii]; } } -(BOOL)barAtRecordIndex:(NSUInteger)index basePoint:(CGPoint *)basePoint tipPoint:(CGPoint *)tipPoint { BOOL horizontalBars = self.barsAreHorizontal; CPCoordinate independentCoord = ( horizontalBars ? CPCoordinateY : CPCoordinateX ); CPCoordinate dependentCoord = ( horizontalBars ? CPCoordinateX : CPCoordinateY ); CPPlotSpace *thePlotSpace = self.plotSpace; CPPlotArea *thePlotArea = self.plotArea; if ( self.doublePrecisionCache ) { double plotPoint[2]; plotPoint[independentCoord] = [self cachedDoubleForField:CPBarPlotFieldBarLocation recordIndex:index]; if ( isnan(plotPoint[independentCoord]) ) return NO; // Tip point plotPoint[dependentCoord] = [self cachedDoubleForField:CPBarPlotFieldBarTip recordIndex:index]; if ( isnan(plotPoint[dependentCoord]) ) return NO; *tipPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; // Base point if ( !self.barBasesVary ) { plotPoint[dependentCoord] = CPDecimalDoubleValue(self.baseValue); } else { plotPoint[dependentCoord] = [self cachedDoubleForField:CPBarPlotFieldBarBase recordIndex:index]; } if ( isnan(plotPoint[dependentCoord]) ) return NO; *basePoint = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; } else { NSDecimal plotPoint[2]; plotPoint[independentCoord] = [self cachedDecimalForField:CPBarPlotFieldBarLocation recordIndex:index]; if ( NSDecimalIsNotANumber(&plotPoint[independentCoord]) ) return NO; // Tip point plotPoint[dependentCoord] = [self cachedDecimalForField:CPBarPlotFieldBarTip recordIndex:index]; if ( NSDecimalIsNotANumber(&plotPoint[dependentCoord]) ) return NO; *tipPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; // Base point if ( !self.barBasesVary ) { plotPoint[dependentCoord] = self.baseValue; } else { plotPoint[dependentCoord] = [self cachedDecimalForField:CPBarPlotFieldBarBase recordIndex:index]; } if ( NSDecimalIsNotANumber(&plotPoint[dependentCoord]) ) return NO; *basePoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; } // Determine bar width and offset. CGFloat barOffsetLength = [self lengthInView:self.barOffset]; // Offset if ( horizontalBars ) { basePoint->y += barOffsetLength; tipPoint->y += barOffsetLength; } else { basePoint->x += barOffsetLength; tipPoint->x += barOffsetLength; } return YES; } -(CGMutablePathRef)newBarPathWithContext:(CGContextRef)context recordIndex:(NSUInteger)recordIndex { // Get base and tip points CGPoint basePoint, tipPoint; BOOL barExists = [self barAtRecordIndex:recordIndex basePoint:&basePoint tipPoint:&tipPoint]; if ( !barExists ) return NULL; CGMutablePathRef path = [self newBarPathWithContext:context basePoint:basePoint tipPoint:tipPoint]; return path; } -(CGMutablePathRef)newBarPathWithContext:(CGContextRef)context basePoint:(CGPoint)basePoint tipPoint:(CGPoint)tipPoint { BOOL horizontalBars = self.barsAreHorizontal; // This function is used to create a path which is used for both // drawing a bar and for doing hit-testing on a click/touch event CPCoordinate widthCoordinate = ( horizontalBars ? CPCoordinateY : CPCoordinateX ); CGFloat barWidthLength = [self lengthInView:self.barWidth]; CGFloat halfBarWidth = 0.5 * barWidthLength; CGFloat point[2]; point[CPCoordinateX] = basePoint.x; point[CPCoordinateY] = basePoint.y; point[widthCoordinate] += halfBarWidth; CGPoint alignedPoint1 = CGPointMake(point[CPCoordinateX], point[CPCoordinateY]); if ( context ) { // may not have a context if doing hit testing alignedPoint1 = CPAlignPointToUserSpace(context, alignedPoint1); } point[CPCoordinateX] = tipPoint.x; point[CPCoordinateY] = tipPoint.y; point[widthCoordinate] += halfBarWidth; CGPoint alignedPoint2 = CGPointMake(point[CPCoordinateX], point[CPCoordinateY]); if ( context ) { alignedPoint2 = CPAlignPointToUserSpace(context, alignedPoint2); } point[CPCoordinateX] = tipPoint.x; point[CPCoordinateY] = tipPoint.y; CGPoint alignedPoint3 = CGPointMake(point[CPCoordinateX], point[CPCoordinateY]); if ( context ) { alignedPoint3 = CPAlignPointToUserSpace(context, alignedPoint3); } point[CPCoordinateX] = tipPoint.x; point[CPCoordinateY] = tipPoint.y; point[widthCoordinate] -= halfBarWidth; CGPoint alignedPoint4 = CGPointMake(point[CPCoordinateX], point[CPCoordinateY]); if ( context ) { alignedPoint4 = CPAlignPointToUserSpace(context, alignedPoint4); } point[CPCoordinateX] = basePoint.x; point[CPCoordinateY] = basePoint.y; point[widthCoordinate] -= halfBarWidth; CGPoint alignedPoint5 = CGPointMake(point[CPCoordinateX], point[CPCoordinateY]); if ( context ) { alignedPoint5 = CPAlignPointToUserSpace(context, alignedPoint5); } CGFloat radius = MIN(self.barCornerRadius, halfBarWidth); if ( horizontalBars ) { radius = MIN(radius, ABS(tipPoint.x - basePoint.x)); } else { radius = MIN(radius, ABS(tipPoint.y - basePoint.y)); } CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, alignedPoint1.x, alignedPoint1.y); CGPathAddArcToPoint(path, NULL, alignedPoint2.x, alignedPoint2.y, alignedPoint3.x, alignedPoint3.y, radius); CGPathAddArcToPoint(path, NULL, alignedPoint4.x, alignedPoint4.y, alignedPoint5.x, alignedPoint5.y, radius); CGPathAddLineToPoint(path, NULL, alignedPoint5.x, alignedPoint5.y); CGPathCloseSubpath(path); return path; } -(BOOL)barIsVisibleWithBasePoint:(CGPoint)basePoint { BOOL horizontalBars = self.barsAreHorizontal; CGFloat barWidthLength = [self lengthInView:self.barWidth]; CGFloat halfBarWidth = 0.5 * barWidthLength; CPPlotArea *thePlotArea = self.plotArea; CGFloat lowerBound = ( horizontalBars ? CGRectGetMinY(thePlotArea.bounds) : CGRectGetMinX(thePlotArea.bounds) ); CGFloat upperBound = ( horizontalBars ? CGRectGetMaxY(thePlotArea.bounds) : CGRectGetMaxX(thePlotArea.bounds) ); CGFloat base = ( horizontalBars ? basePoint.y : basePoint.x ); return ( base + halfBarWidth > lowerBound ) && ( base - halfBarWidth < upperBound ); } -(void)drawBarInContext:(CGContextRef)context recordIndex:(NSUInteger)index { // Get base and tip points CGPoint basePoint, tipPoint; BOOL barExists = [self barAtRecordIndex:index basePoint:&basePoint tipPoint:&tipPoint]; if ( !barExists ) return; // Return if bar is off screen if ( ![self barIsVisibleWithBasePoint:basePoint] ) return; CGMutablePathRef path = [self newBarPathWithContext:context basePoint:basePoint tipPoint:tipPoint]; if ( path ) { CGContextSaveGState(context); // If data source returns nil, default fill is used. // If data source returns NSNull object, no fill is drawn. CPFill *currentBarFill = self.fill; if ( [self.dataSource respondsToSelector:@selector(barFillForBarPlot:recordIndex:)] ) { CPFill *dataSourceFill = [(id <CPBarPlotDataSource>)self.dataSource barFillForBarPlot:self recordIndex:index]; if ( dataSourceFill ) currentBarFill = dataSourceFill; } if ( [currentBarFill isKindOfClass:[CPFill class]] ) { CGContextBeginPath(context); CGContextAddPath(context, path); [currentBarFill fillPathInContext:context]; } CPLineStyle *theLineStyle = self.lineStyle; if ( theLineStyle ) { CGContextBeginPath(context); CGContextAddPath(context, path); [theLineStyle setLineStyleInContext:context]; CGContextStrokePath(context); } CGContextRestoreGState(context); CGPathRelease(path); } } #pragma mark - #pragma mark Data Labels -(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index { NSDecimal theBaseDecimalValue; if ( !self.barBasesVary ) { theBaseDecimalValue = self.baseValue; } else { theBaseDecimalValue = [self cachedDecimalForField:CPBarPlotFieldBarBase recordIndex:index]; } NSNumber *location = [self cachedNumberForField:CPBarPlotFieldBarLocation recordIndex:index]; NSNumber *length = [self cachedNumberForField:CPBarPlotFieldBarTip recordIndex:index]; BOOL positiveDirection = CPDecimalGreaterThanOrEqualTo([length decimalValue], theBaseDecimalValue); BOOL horizontalBars = self.barsAreHorizontal; CPPlotRange *lengthRange = [self.plotSpace plotRangeForCoordinate:horizontalBars ? CPCoordinateX : CPCoordinateY]; if ( CPDecimalLessThan(lengthRange.length, CPDecimalFromInteger(0)) ) { positiveDirection = !positiveDirection; } NSNumber *offsetLocation; if ( self.doublePrecisionCache ) { offsetLocation = [NSNumber numberWithDouble:([location doubleValue] + [self doubleLengthInPlotCoordinates:self.barOffset])]; } else { NSDecimal decimalLocation = [location decimalValue]; NSDecimal offset = [self lengthInPlotCoordinates:self.barOffset]; offsetLocation = [NSDecimalNumber decimalNumberWithDecimal:CPDecimalAdd(decimalLocation, offset)]; } // Offset if ( horizontalBars ) { label.anchorPlotPoint = [NSArray arrayWithObjects:length, offsetLocation, nil]; if ( positiveDirection ) { label.displacement = CGPointMake(self.labelOffset, 0.0); } else { label.displacement = CGPointMake(-self.labelOffset, 0.0); } } else { label.anchorPlotPoint = [NSArray arrayWithObjects:offsetLocation, length, nil]; if ( positiveDirection ) { label.displacement = CGPointMake(0.0, self.labelOffset); } else { label.displacement = CGPointMake(0.0, -self.labelOffset); } } label.contentLayer.hidden = isnan([location doubleValue]) || isnan([length doubleValue]); } #pragma mark - #pragma mark Responder Chain and User interaction -(BOOL)pointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL result = NO; CPGraph *theGraph = self.graph; CPPlotArea *thePlotArea = self.plotArea; if ( !theGraph || !thePlotArea ) return NO; id <CPBarPlotDelegate> theDelegate = self.delegate; if ( [theDelegate respondsToSelector:@selector(barPlot:barWasSelectedAtRecordIndex:)] ) { // Inform delegate if a point was hit CGPoint plotAreaPoint = [theGraph convertPoint:interactionPoint toLayer:thePlotArea]; NSUInteger barCount = self.cachedDataCount; for ( NSUInteger ii = 0; ii < barCount; ii++ ) { CGMutablePathRef path = [self newBarPathWithContext:NULL recordIndex:ii]; if ( CGPathContainsPoint(path, nil, plotAreaPoint, false) ) { [theDelegate barPlot:self barWasSelectedAtRecordIndex:ii]; CGPathRelease(path); return YES; } CGPathRelease(path); } } else { result = [super pointingDeviceDownEvent:event atPoint:interactionPoint]; } return result; } #pragma mark - #pragma mark Accessors -(NSArray *)barLengths { return [[self cachedNumbersForField:CPBarPlotFieldBarTip] sampleArray]; } -(void)setBarLengths:(NSArray *)newLengths { [self cacheNumbers:newLengths forField:CPBarPlotFieldBarTip]; } -(NSArray *)barBases { return [[self cachedNumbersForField:CPBarPlotFieldBarBase] sampleArray]; } -(void)setBarBases:(NSArray *)newBases { [self cacheNumbers:newBases forField:CPBarPlotFieldBarBase]; } -(NSArray *)barLocations { return [[self cachedNumbersForField:CPBarPlotFieldBarLocation] sampleArray]; } -(void)setBarLocations:(NSArray *)newLocations { [self cacheNumbers:newLocations forField:CPBarPlotFieldBarLocation]; } -(void)setLineStyle:(CPLineStyle *)newLineStyle { if (lineStyle != newLineStyle) { [lineStyle release]; lineStyle = [newLineStyle copy]; [self setNeedsDisplay]; } } -(void)setFill:(CPFill *)newFill { if (fill != newFill) { [fill release]; fill = [newFill copy]; [self setNeedsDisplay]; } } -(void)setBarWidth:(NSDecimal)newBarWidth { barWidth = newBarWidth; [self setNeedsDisplay]; } -(void)setBarOffset:(NSDecimal)newBarOffset { barOffset = newBarOffset; [self setNeedsDisplay]; [self setNeedsLayout]; } -(void)setBarCornerRadius:(CGFloat)newCornerRadius { if ( barCornerRadius != newCornerRadius) { barCornerRadius = ABS(newCornerRadius); [self setNeedsDisplay]; } } -(void)setBaseValue:(NSDecimal)newBaseValue { if ( !CPDecimalEquals(baseValue, newBaseValue) ) { baseValue = newBaseValue; [self setNeedsDisplay]; [self setNeedsLayout]; } } -(void)setBarBasesVary:(BOOL)newBasesVary { if ( newBasesVary != barBasesVary ) { barBasesVary = newBasesVary; [self setDataNeedsReloading]; [self setNeedsDisplay]; [self setNeedsLayout]; } } -(void)setBarsAreHorizontal:(BOOL)newBarsAreHorizontal { if (barsAreHorizontal != newBarsAreHorizontal) { barsAreHorizontal = newBarsAreHorizontal; [self setNeedsDisplay]; [self setNeedsLayout]; } } -(CGFloat)barLabelOffset { return self.labelOffset; } -(void)setBarLabelOffset:(CGFloat)newOffset { self.labelOffset = newOffset; } -(CPTextStyle *)barLabelTextStyle { return self.labelTextStyle; } -(void)setBarLabelTextStyle:(CPMutableTextStyle *)newStyle { self.labelTextStyle = newStyle; } #pragma mark - #pragma mark Fields -(NSUInteger)numberOfFields { return 2; } -(NSArray *)fieldIdentifiers { return [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt:CPBarPlotFieldBarLocation], [NSNumber numberWithUnsignedInt:CPBarPlotFieldBarTip], nil]; } -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord { NSArray *result = nil; switch (coord) { case CPCoordinateX: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:(self.barsAreHorizontal ? CPBarPlotFieldBarTip : CPBarPlotFieldBarLocation)]]; break; case CPCoordinateY: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:(self.barsAreHorizontal ? CPBarPlotFieldBarLocation : CPBarPlotFieldBarTip)]]; break; default: [NSException raise:CPException format:@"Invalid coordinate passed to fieldIdentifiersForCoordinate:"]; break; } return result; } @end
08iteng-ipad
framework/Source/CPBarPlot.m
Objective-C
bsd
29,230
#import <Foundation/Foundation.h> #import "CPAnnotation.h" @class CPPlotSpace; @interface CPPlotSpaceAnnotation : CPAnnotation { NSArray *anchorPlotPoint; CPPlotSpace *plotSpace; } @property (nonatomic, readwrite, copy) NSArray *anchorPlotPoint; @property (nonatomic, readonly, retain) CPPlotSpace *plotSpace; -(id)initWithPlotSpace:(CPPlotSpace *)space anchorPlotPoint:(NSArray *)plotPoint; @end
08iteng-ipad
framework/Source/CPPlotSpaceAnnotation.h
Objective-C
bsd
407
#import "CPAxis.h" #import "CPGridLines.h" /** @brief An abstract class that draws grid lines for an axis. **/ @implementation CPGridLines /** @property axis * @brief The axis. **/ @synthesize axis; /** @property major * @brief If YES, draw the major grid lines, else draw the minor grid lines. **/ @synthesize major; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { axis = nil; major = NO; self.needsDisplayOnBoundsChange = YES; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPGridLines *theLayer = (CPGridLines *)layer; axis = theLayer->axis; major = theLayer->major; } return self; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { [self.axis drawGridLinesInContext:theContext isMajor:self.major]; } #pragma mark - #pragma mark Accessors -(void)setAxis:(CPAxis *)newAxis { if ( newAxis != axis ) { axis = newAxis; [self setNeedsDisplay]; } } @end
08iteng-ipad
framework/Source/CPGridLines.m
Objective-C
bsd
1,078
#import "CPAxisLabel.h" #import "CPLayer.h" #import "CPTextLayer.h" #import "CPMutableTextStyle.h" #import "CPExceptions.h" #import "CPUtilities.h" /** @brief An axis label. * * The label can be text-based or can be the content of any CPLayer provided by the user. **/ @implementation CPAxisLabel /** @property contentLayer * @brief The label content. **/ @synthesize contentLayer; /** @property offset * @brief The offset distance between the axis and label. **/ @synthesize offset; /** @property rotation * @brief The rotation of the label in radians. **/ @synthesize rotation; /** @property alignment * @brief The alignment of the axis label with respect to the tick mark. **/ @synthesize alignment; /** @property tickLocation * @brief The data coordinate of the ticklocation. **/ @synthesize tickLocation; #pragma mark - #pragma mark Init/Dealloc /** @brief Initializes a newly allocated text-based CPAxisLabel object with the provided text and style. * * @param newText The label text. * @param newStyle The text style for the label. * @return The initialized CPAxisLabel object. **/ -(id)initWithText:(NSString *)newText textStyle:(CPMutableTextStyle *)newStyle { CPTextLayer *newLayer = [[CPTextLayer alloc] initWithText:newText]; newLayer.textStyle = newStyle; [newLayer sizeToFit]; self = [self initWithContentLayer:newLayer]; [newLayer release]; return self; } /** @brief Initializes a newly allocated CPAxisLabel object with the provided layer. This is the designated initializer. * * @param layer The label content. * @return The initialized CPAxisLabel object. **/ -(id)initWithContentLayer:(CPLayer *)layer { if ( layer ) { if ( self = [super init] ) { contentLayer = [layer retain]; offset = 20.0; rotation = 0.0; alignment = CPAlignmentCenter; tickLocation = CPDecimalFromInteger(0); } } else { [self release]; self = nil; } return self; } -(void)dealloc { [contentLayer release]; [super dealloc]; } #pragma mark - #pragma mark Layout /** @brief Positions the axis label relative to the given point. * The algorithm for positioning is different when the rotation property is non-zero. * When zero, the anchor point is positioned along the closest side of the label. * When non-zero, the anchor point is left at the center. This has consequences for * the value taken by the offset. * @param point The view point. * @param coordinate The coordinate in which the label is being position. Orthogonal to the axis coordinate. * @param direction The offset direction. **/ -(void)positionRelativeToViewPoint:(CGPoint)point forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction { CPLayer *content = self.contentLayer; if ( !content ) return; CGPoint newPosition = point; CGFloat *value = (coordinate == CPCoordinateX ? &(newPosition.x) : &(newPosition.y)); double angle = 0.0; CGFloat myRotation = self.rotation; content.transform = CATransform3DMakeRotation(myRotation, 0.0, 0.0, 1.0); CGRect contentFrame = content.frame; // Position the anchor point along the closest edge. switch ( direction ) { case CPSignNone: case CPSignNegative: *value -= self.offset; switch ( coordinate ) { case CPCoordinateX: angle = M_PI; switch ( self.alignment ) { case CPAlignmentBottom: newPosition.y += contentFrame.size.height / 2.0; break; case CPAlignmentTop: newPosition.y -= contentFrame.size.height / 2.0; break; default: // middle // no adjustment break; } break; case CPCoordinateY: angle = -M_PI_2; switch ( self.alignment ) { case CPAlignmentLeft: newPosition.x += contentFrame.size.width / 2.0; break; case CPAlignmentRight: newPosition.x -= contentFrame.size.width / 2.0; break; default: // center // no adjustment break; } break; default: [NSException raise:NSInvalidArgumentException format:@"Invalid coordinate in positionRelativeToViewPoint:forCoordinate:inDirection:"]; break; } break; case CPSignPositive: *value += self.offset; switch ( coordinate ) { case CPCoordinateX: // angle = 0.0; switch ( self.alignment ) { case CPAlignmentBottom: newPosition.y += contentFrame.size.height / 2.0; break; case CPAlignmentTop: newPosition.y -= contentFrame.size.height / 2.0; break; default: // middle // no adjustment break; } break; case CPCoordinateY: angle = M_PI_2; switch ( self.alignment ) { case CPAlignmentLeft: newPosition.x += contentFrame.size.width / 2.0; break; case CPAlignmentRight: newPosition.x -= contentFrame.size.width / 2.0; break; default: // center // no adjustment break; } break; default: [NSException raise:NSInvalidArgumentException format:@"Invalid coordinate in positionRelativeToViewPoint:forCoordinate:inDirection:"]; break; } break; default: [NSException raise:NSInvalidArgumentException format:@"Invalid direction in positionRelativeToViewPoint:forCoordinate:inDirection:"]; break; } angle += M_PI; angle -= myRotation; double newAnchorX = cos(angle); double newAnchorY = sin(angle); if ( ABS(newAnchorX) <= ABS(newAnchorY) ) { newAnchorX /= ABS(newAnchorY); newAnchorY = signbit(newAnchorY) ? -1.0 : 1.0; } else { newAnchorY /= ABS(newAnchorX); newAnchorX = signbit(newAnchorX) ? -1.0 : 1.0; } CGPoint anchor = CGPointMake((newAnchorX + 1.0) / 2.0, (newAnchorY + 1.0) / 2.0); content.anchorPoint = anchor; // Pixel-align the label layer to prevent blurriness CGSize currentSize = content.bounds.size; if ( myRotation == 0.0 ) { newPosition.x = round(newPosition.x) - round(currentSize.width * anchor.x) + (currentSize.width * anchor.x); newPosition.y = round(newPosition.y) - round(currentSize.height * anchor.y) + (currentSize.height * anchor.y); } else { newPosition.x = round(newPosition.x); newPosition.y = round(newPosition.y); } content.position = newPosition; [content setNeedsDisplay]; } /** @brief Positions the axis label between two given points. * @param firstPoint The first view point. * @param secondPoint The second view point. * @param coordinate The axis coordinate. * @param direction The offset direction. * @note Not implemented. * @todo Write implementation for positioning label between ticks. **/ -(void)positionBetweenViewPoint:(CGPoint)firstPoint andViewPoint:(CGPoint)secondPoint forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction { // TODO: Write implementation for positioning label between ticks [NSException raise:CPException format:@"positionBetweenViewPoint:andViewPoint:forCoordinate:inDirection: not implemented"]; } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"<%@ {%@}>", [super description], self.contentLayer]; } #pragma mark - #pragma mark Label comparison // Axis labels are equal if they have the same location -(BOOL)isEqual:(id)object { if ( self == object ) { return YES; } else if ( [object isKindOfClass:[self class]] ) { return CPDecimalEquals(self.tickLocation, ((CPAxisLabel *)object).tickLocation); } else { return NO; } } -(NSUInteger)hash { NSUInteger hashValue = 0; // Equal objects must hash the same. double tickLocationAsDouble = CPDecimalDoubleValue(self.tickLocation); if ( !isnan(tickLocationAsDouble) ) { hashValue = (NSUInteger)fmod(ABS(tickLocationAsDouble), (double)NSUIntegerMax); } return hashValue; } @end
08iteng-ipad
framework/Source/CPAxisLabel.m
Objective-C
bsd
7,799
#import <Foundation/Foundation.h> #import "CPLayer.h" @interface CPAxisLabelGroup : CPLayer { } @end
08iteng-ipad
framework/Source/CPAxisLabelGroup.h
Objective-C
bsd
104
#import <Foundation/Foundation.h> #import "CPMutableNumericData.h" #import "CPNumericDataType.h" /** @category CPMutableNumericData(TypeConversion) * @brief Type conversion methods for CPMutableNumericData. **/ @interface CPMutableNumericData(TypeConversion) /// @name Data Format /// @{ @property (assign, readwrite) CPNumericDataType dataType; @property (assign, readwrite) CPDataTypeFormat dataTypeFormat; @property (assign, readwrite) size_t sampleBytes; @property (assign, readwrite) CFByteOrder byteOrder; /// @} /// @name Type Conversion /// @{ -(void)convertToType:(CPDataTypeFormat)newDataType sampleBytes:(size_t)newSampleBytes byteOrder:(CFByteOrder)newByteOrder; /// @} @end
08iteng-ipad
framework/Source/CPMutableNumericData+TypeConversion.h
Objective-C
bsd
701
#import "CPPlotRange.h" #import "CPPlatformSpecificCategories.h" #import "NSDecimalNumberExtensions.h" #import "CPUtilities.h" #import "CPDefinitions.h" /** @brief Defines a range of plot data **/ @implementation CPPlotRange /** @property location * @brief The starting value of the range. **/ @synthesize location; /** @property length * @brief The length of the range. **/ @synthesize length; /** @property locationDouble * @brief The starting value of the range as a <code>double</code>. **/ @synthesize locationDouble; /** @property lengthDouble * @brief The length of the range as a <code>double</code>. **/ @synthesize lengthDouble; /** @property end * @brief The ending value of the range. **/ @dynamic end; /** @property endDouble * @brief The ending value of the range as a <code>double</code>. **/ @dynamic endDouble; /** @property minLimit * @brief The minimum extreme value of the range. **/ @dynamic minLimit; /** @property minLimitDouble * @brief The minimum extreme value of the range as a <code>double</code>. **/ @dynamic minLimitDouble; /** @property midPoint * @brief The middle value of the range. **/ @dynamic midPoint; /** @property midPointDouble * @brief The middle value of the range as a <code>double</code>. **/ @dynamic midPointDouble; /** @property maxLimit * @brief The maximum extreme value of the range. **/ @dynamic maxLimit; /** @property maxLimitDouble * @brief The maximum extreme value of the range as a <code>double</code>. **/ @dynamic maxLimitDouble; #pragma mark - #pragma mark Init/Dealloc /** @brief Creates and returns a new CPPlotRange instance initialized with the provided location and length. * @param loc The starting location of the range. * @param len The length of the range. * @return A new CPPlotRange instance initialized with the provided location and length. **/ +(CPPlotRange *)plotRangeWithLocation:(NSDecimal)loc length:(NSDecimal)len { return [[[CPPlotRange alloc] initWithLocation:loc length:len] autorelease]; } /** @brief Initializes a newly allocated CPPlotRange object with the provided location and length. * @param loc The starting location of the range. * @param len The length of the range. * @return The initialized CPPlotRange object. **/ -(id)initWithLocation:(NSDecimal)loc length:(NSDecimal)len { if ( self = [super init] ) { self.location = loc; self.length = len; } return self; } -(id)init { NSDecimal zero = CPDecimalFromInteger(0); return [self initWithLocation:zero length:zero]; } #pragma mark - #pragma mark Accessors -(void)setLocation:(NSDecimal)newLocation { if ( !CPDecimalEquals(location, newLocation) ) { location = newLocation; locationDouble = [[NSDecimalNumber decimalNumberWithDecimal:newLocation] doubleValue]; } } -(void)setLength:(NSDecimal)newLength { if ( !CPDecimalEquals(length, newLength) ) { length = newLength; lengthDouble = [[NSDecimalNumber decimalNumberWithDecimal:newLength] doubleValue]; } } -(NSDecimal)end { return CPDecimalAdd(self.location, self.length); } -(double)endDouble { return (self.locationDouble + self.lengthDouble); } -(NSDecimal)minLimit { NSDecimal loc = self.location; NSDecimal len = self.length; if ( CPDecimalLessThan(len, CPDecimalFromInteger(0)) ) { return CPDecimalAdd(loc, len); } else { return loc; } } -(double)minLimitDouble { double doubleLoc = self.locationDouble; double doubleLen = self.lengthDouble; if ( doubleLen < 0.0 ) { return doubleLoc + doubleLen; } else { return doubleLoc; } } -(NSDecimal)midPoint { return CPDecimalAdd(self.location, CPDecimalDivide(self.length, CPDecimalFromInteger(2))); } -(double)midPointDouble { return fma(self.lengthDouble, 0.5, self.locationDouble); } -(NSDecimal)maxLimit { NSDecimal loc = self.location; NSDecimal len = self.length; if ( CPDecimalGreaterThan(len, CPDecimalFromInteger(0)) ) { return CPDecimalAdd(loc, len); } else { return loc; } } -(double)maxLimitDouble { double doubleLoc = self.locationDouble; double doubleLen = self.lengthDouble; if ( doubleLen > 0.0 ) { return doubleLoc + doubleLen; } else { return doubleLoc; } } #pragma mark - #pragma mark NSCopying -(id)copyWithZone:(NSZone *)zone { CPPlotRange *newRange = [[CPPlotRange allocWithZone:zone] init]; if ( newRange ) { newRange->location = self->location; newRange->length = self->length; newRange->locationDouble = self->locationDouble; newRange->lengthDouble = self->lengthDouble; } return newRange; } #pragma mark - #pragma mark NSCoding - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:[NSDecimalNumber decimalNumberWithDecimal:self.location]]; [encoder encodeObject:[NSDecimalNumber decimalNumberWithDecimal:self.length]]; } - (id)initWithCoder:(NSCoder *)decoder { if ( self = [super init] ) { self.location = [[decoder decodeObject] decimalValue]; self.length = [[decoder decodeObject] decimalValue]; } return self; } #pragma mark - #pragma mark Checking Containership /** @brief Determines whether a given number is inside the range. * @param number The number to check. * @return True if <code>location</code> ≤ <code>number</code> ≤ <code>end</code>. **/ -(BOOL)contains:(NSDecimal)number { return (CPDecimalGreaterThanOrEqualTo(number, self.minLimit) && CPDecimalLessThanOrEqualTo(number, self.maxLimit)); } /** @brief Determines whether a given number is inside the range. * @param number The number to check. * @return True if <code>location</code> ≤ <code>number</code> ≤ <code>end</code>. **/ -(BOOL)containsDouble:(double)number { return ((number >= self.minLimitDouble) && (number <= self.maxLimitDouble)); } /** @brief Determines whether a given range is equal to the range of the receiver. * @param otherRange The range to check. * @return True if the ranges both have the same location and length. **/ -(BOOL)isEqualToRange:(CPPlotRange *)otherRange { return (CPDecimalEquals(self.location, otherRange.location) && CPDecimalEquals(self.length, otherRange.length)); } /** @brief Compares a number to the range, determining if it is in the range, or above or below it. * @param number The number to check. * @return The comparison result. **/ -(CPPlotRangeComparisonResult)compareToNumber:(NSNumber *)number { CPPlotRangeComparisonResult result; if ( [number isKindOfClass:[NSDecimalNumber class]] ) { result = [self compareToDecimal:number.decimalValue]; } else { result = [self compareToDouble:number.doubleValue]; } return result; } /** @brief Compares a number to the range, determining if it is in the range, or above or below it. * @param number The number to check. * @return The comparison result. **/ -(CPPlotRangeComparisonResult)compareToDecimal:(NSDecimal)number { CPPlotRangeComparisonResult result; if ( [self contains:number] ) { result = CPPlotRangeComparisonResultNumberInRange; } else if ( CPDecimalLessThan(number, self.minLimit) ) { result = CPPlotRangeComparisonResultNumberBelowRange; } else { result = CPPlotRangeComparisonResultNumberAboveRange; } return result; } /** @brief Compares a number to the range, determining if it is in the range, or above or below it. * @param number The number to check. * @return The comparison result. **/ -(CPPlotRangeComparisonResult)compareToDouble:(double)number { CPPlotRangeComparisonResult result; if ( number < self.minLimitDouble ) { result = CPPlotRangeComparisonResultNumberBelowRange; } else if ( number > self.maxLimitDouble ) { result = CPPlotRangeComparisonResultNumberAboveRange; } else { result = CPPlotRangeComparisonResultNumberInRange; } return result; } #pragma mark - #pragma mark Combining ranges /** @brief Extends the range to include another range. The sign of <code>length</code> is unchanged. * @param other The other plot range. **/ -(void)unionPlotRange:(CPPlotRange *)other { if ( !other ) return; NSDecimal min1 = self.minLimit; NSDecimal min2 = other.minLimit; NSDecimal minimum = CPDecimalLessThan(min1, min2) ? min1 : min2; NSDecimal max1 = self.maxLimit; NSDecimal max2 = other.maxLimit; NSDecimal maximum = CPDecimalGreaterThan(max1, max2) ? max1 : max2; NSDecimal newLocation, newLength; if ( CPDecimalGreaterThanOrEqualTo(self.length, CPDecimalFromInteger(0)) ) { newLocation = minimum; newLength = CPDecimalSubtract(maximum, minimum); } else { newLocation = maximum; newLength = CPDecimalSubtract(minimum, maximum); } self.location = newLocation; self.length = newLength; } /** @brief Sets the messaged object to the intersection with another range. The sign of <code>length</code> is unchanged. * @param other The other plot range. **/ -(void)intersectionPlotRange:(CPPlotRange *)other { if ( !other ) return; NSDecimal min1 = self.minLimit; NSDecimal min2 = other.minLimit; NSDecimal minimum = CPDecimalGreaterThan(min1, min2) ? min1 : min2; NSDecimal max1 = self.maxLimit; NSDecimal max2 = other.maxLimit; NSDecimal maximum = CPDecimalLessThan(max1, max2) ? max1 : max2; if ( CPDecimalGreaterThanOrEqualTo(maximum, minimum) ) { NSDecimal newLocation, newLength; if ( CPDecimalGreaterThanOrEqualTo(self.length, CPDecimalFromInteger(0)) ) { newLocation = minimum; newLength = CPDecimalSubtract(maximum, minimum); } else { newLocation = maximum; newLength = CPDecimalSubtract(minimum, maximum); } self.location = newLocation; self.length = newLength; } else { self.length = CPDecimalFromInteger(0); } } #pragma mark - #pragma mark Expanding/Contracting ranges /** @brief Extends/contracts the range by a factor. * @param factor Factor used. A value of 1.0 gives no change. * Less than 1.0 is a contraction, and greater than 1.0 is expansion. **/ -(void)expandRangeByFactor:(NSDecimal)factor { NSDecimal oldLength = self.length; NSDecimal newLength = CPDecimalMultiply(oldLength, factor); NSDecimal locationOffset = CPDecimalDivide(CPDecimalSubtract(oldLength, newLength), CPDecimalFromInteger(2)); NSDecimal newLocation = CPDecimalAdd(self.location, locationOffset); self.location = newLocation; self.length = newLength; } #pragma mark - #pragma mark Shifting Range /** @brief Moves the whole range so that the location fits in other range. * @param otherRange Other range. * The minimum possible shift is made. The range length is unchanged. **/ -(void)shiftLocationToFitInRange:(CPPlotRange *)otherRange { NSParameterAssert(otherRange); switch ( [otherRange compareToNumber:[NSDecimalNumber decimalNumberWithDecimal:self.location]] ) { case CPPlotRangeComparisonResultNumberBelowRange: self.location = otherRange.minLimit; break; case CPPlotRangeComparisonResultNumberAboveRange: self.location = otherRange.maxLimit; break; default: // in range--do nothing break; } } /** @brief Moves the whole range so that the end point fits in other range. * @param otherRange Other range. * The minimum possible shift is made. The range length is unchanged. **/ -(void)shiftEndToFitInRange:(CPPlotRange *)otherRange { NSParameterAssert(otherRange); switch ( [otherRange compareToNumber:[NSDecimalNumber decimalNumberWithDecimal:self.end]] ) { case CPPlotRangeComparisonResultNumberBelowRange: self.location = CPDecimalSubtract(otherRange.minLimit, self.length); break; case CPPlotRangeComparisonResultNumberAboveRange: self.location = CPDecimalSubtract(otherRange.maxLimit, self.length); break; default: // in range--do nothing break; } } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"<%@ {%@, %@}>", [super description], NSDecimalString(&location, [NSLocale currentLocale]), NSDecimalString(&length, [NSLocale currentLocale])]; } @end
08iteng-ipad
framework/Source/CPPlotRange.m
Objective-C
bsd
11,914
#import "CPBorderedLayer.h" #import "CPPathExtensions.h" #import "CPLineStyle.h" #import "CPFill.h" /** @brief A layer with rounded corners. **/ @implementation CPBorderedLayer /** @property borderLineStyle * @brief The line style for the layer border. * * If nil, the border is not drawn. **/ @synthesize borderLineStyle; /** @property fill * @brief The fill for the layer background. * * If nil, the layer background is not filled. **/ @synthesize fill; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { borderLineStyle = nil; fill = nil; self.masksToBorder = YES; self.needsDisplayOnBoundsChange = YES; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPBorderedLayer *theLayer = (CPBorderedLayer *)layer; borderLineStyle = [theLayer->borderLineStyle retain]; fill = [theLayer->fill retain]; } return self; } -(void)dealloc { [borderLineStyle release]; [fill release]; [super dealloc]; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)context { [super renderAsVectorInContext:context]; BOOL useMask = self.masksToBounds; self.masksToBounds = YES; CGContextBeginPath(context); CGContextAddPath(context, self.maskingPath); [self.fill fillPathInContext:context]; self.masksToBounds = useMask; if ( self.borderLineStyle ) { CGFloat inset = self.borderLineStyle.lineWidth / 2.0; CGRect selfBounds = CGRectInset(self.bounds, inset, inset); [self.borderLineStyle setLineStyleInContext:context]; if ( self.cornerRadius > 0.0 ) { CGFloat radius = MIN(MIN(self.cornerRadius, selfBounds.size.width / 2.0), selfBounds.size.height / 2.0); CGContextBeginPath(context); AddRoundedRectPath(context, selfBounds, radius); CGContextStrokePath(context); } else { CGContextStrokeRect(context, selfBounds); } } } #pragma mark - #pragma mark Masking -(CGPathRef)maskingPath { if ( self.masksToBounds ) { CGPathRef path = self.outerBorderPath; if ( path ) return path; CGFloat lineWidth = self.borderLineStyle.lineWidth; CGRect selfBounds = self.bounds; if ( self.cornerRadius > 0.0 ) { CGFloat radius = MIN(MIN(self.cornerRadius + lineWidth / 2.0, selfBounds.size.width / 2.0), selfBounds.size.height / 2.0); path = CreateRoundedRectPath(selfBounds, radius); self.outerBorderPath = path; CGPathRelease(path); } else { CGMutablePathRef mutablePath = CGPathCreateMutable(); CGPathAddRect(mutablePath, NULL, selfBounds); self.outerBorderPath = mutablePath; CGPathRelease(mutablePath); } return self.outerBorderPath; } else { return NULL; } } -(CGPathRef)sublayerMaskingPath { if ( self.masksToBorder ) { CGPathRef path = self.innerBorderPath; if ( path ) return path; CGFloat lineWidth = self.borderLineStyle.lineWidth; CGRect selfBounds = CGRectInset(self.bounds, lineWidth, lineWidth); if ( self.cornerRadius > 0.0 ) { CGFloat radius = MIN(MIN(self.cornerRadius - lineWidth / 2.0, selfBounds.size.width / 2.0), selfBounds.size.height / 2.0); path = CreateRoundedRectPath(selfBounds, radius); self.innerBorderPath = path; CGPathRelease(path); } else { CGMutablePathRef mutablePath = CGPathCreateMutable(); CGPathAddRect(mutablePath, NULL, selfBounds); self.innerBorderPath = mutablePath; CGPathRelease(mutablePath); } return self.innerBorderPath; } else { return NULL; } } #pragma mark - #pragma mark Accessors -(void)setBorderLineStyle:(CPLineStyle *)newLineStyle { if ( newLineStyle != borderLineStyle ) { if ( newLineStyle.lineWidth != borderLineStyle.lineWidth ) { self.outerBorderPath = NULL; self.innerBorderPath = NULL; } [borderLineStyle release]; borderLineStyle = [newLineStyle copy]; [self setNeedsDisplay]; } } -(void)setFill:(CPFill *)newFill { if ( newFill != fill ) { [fill release]; fill = [newFill copy]; [self setNeedsDisplay]; } } @end
08iteng-ipad
framework/Source/CPBorderedLayer.m
Objective-C
bsd
4,047
#import <Foundation/Foundation.h> /// @file @interface CPTimeFormatter : NSNumberFormatter { @private NSDateFormatter *dateFormatter; NSDate *referenceDate; } @property (nonatomic, readwrite, retain) NSDateFormatter *dateFormatter; @property (nonatomic, readwrite, copy) NSDate *referenceDate; -(id)initWithDateFormatter:(NSDateFormatter *)aDateFormatter; @end
08iteng-ipad
framework/Source/CPTimeFormatter.h
Objective-C
bsd
372
#import "CPDefinitions.h" #import "CPPlotRange.h" #import "CPNumericDataType.h" #import "CPAnnotationHostLayer.h" #import "CPMutableTextStyle.h" @class CPMutableNumericData; @class CPNumericData; @class CPPlot; @class CPPlotArea; @class CPPlotSpace; @class CPPlotSpaceAnnotation; @class CPPlotRange; /// @file /** @brief Enumeration of cache precisions. **/ typedef enum _CPPlotCachePrecision { CPPlotCachePrecisionAuto, ///< Cache precision is determined automatically from the data. All cached data will be converted to match the last data loaded. CPPlotCachePrecisionDouble, ///< All cached data will be converted to double precision. CPPlotCachePrecisionDecimal ///< All cached data will be converted to NSDecimal. } CPPlotCachePrecision; #pragma mark - /** @brief A plot data source. **/ @protocol CPPlotDataSource <NSObject> /** @brief The number of data points for the plot. * @param plot The plot. * @return The number of data points for the plot. **/ -(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot; @optional /// @name Implement one of the following /// @{ /** @brief Gets a range of plot data for the given plot and field. * @param plot The plot. * @param fieldEnum The field index. * @param indexRange The range of the data indexes of interest. * @return An array of data points. **/ -(NSArray *)numbersForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange; /** @brief Gets a plot data value for the given plot and field. * @param plot The plot. * @param fieldEnum The field index. * @param index The data index of interest. * @return A data point. **/ -(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index; /** @brief Gets a range of plot data for the given plot and field. * @param plot The plot. * @param fieldEnum The field index. * @param indexRange The range of the data indexes of interest. * @return A retained C array of data points. **/ -(double *)doublesForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange; /** @brief Gets a plot data value for the given plot and field. * @param plot The plot. * @param fieldEnum The field index. * @param index The data index of interest. * @return A data point. **/ -(double)doubleForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index; /** @brief Gets a range of plot data for the given plot and field. * @param plot The plot. * @param fieldEnum The field index. * @param indexRange The range of the data indexes of interest. * @return A one-dimensional array of data points. **/ -(CPNumericData *)dataForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange; /// @} /// @name Data Range /// @{ /** @brief Determines the record index range corresponding to a given range of data. * This method is optional. If the method is implemented, it could improve performance * in data sets that are only partially displayed. * @param plot The plot. * @param plotRange The range expressed in data values. * @return The range of record indexes. * @deprecated This method is no longer used and will be removed from a later release. **/ -(NSRange)recordIndexRangeForPlot:(CPPlot *)plot plotRange:(CPPlotRange *)plotRange; /// @} /// @name Data Labels /// @{ /** @brief Gets a data label for the given plot. This method is optional. * @param plot The plot. * @param index The data index of interest. * @return The data label for the point with the given index. * If you return nil, the default data label will be used. If you return an instance of NSNull, * no label will be shown for the index in question. **/ -(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index; /// @} @end #pragma mark - @interface CPPlot : CPAnnotationHostLayer { @private id <CPPlotDataSource> dataSource; id <NSCopying, NSObject> identifier; CPPlotSpace *plotSpace; BOOL dataNeedsReloading; NSMutableDictionary *cachedData; NSUInteger cachedDataCount; CPPlotCachePrecision cachePrecision; BOOL needsRelabel; CGFloat labelOffset; CGFloat labelRotation; NSUInteger labelField; CPMutableTextStyle *labelTextStyle; NSNumberFormatter *labelFormatter; BOOL labelFormatterChanged; NSRange labelIndexRange; NSMutableArray *labelAnnotations; } /// @name Data Source /// @{ @property (nonatomic, readwrite, assign) id <CPPlotDataSource> dataSource; /// @} /// @name Identification /// @{ @property (nonatomic, readwrite, copy) id <NSCopying, NSObject> identifier; /// @} /// @name Plot Space /// @{ @property (nonatomic, readwrite, retain) CPPlotSpace *plotSpace; /// @} /// @name Plot Area /// @{ @property (nonatomic, readonly, retain) CPPlotArea *plotArea; /// @} /// @name Data Loading /// @{ @property (nonatomic, readonly, assign) BOOL dataNeedsReloading; /// @} /// @name Data Cache /// @{ @property (nonatomic, readonly, assign) NSUInteger cachedDataCount; @property (nonatomic, readonly, assign) BOOL doublePrecisionCache; @property (nonatomic, readwrite, assign) CPPlotCachePrecision cachePrecision; @property (nonatomic, readonly, assign) CPNumericDataType doubleDataType; @property (nonatomic, readonly, assign) CPNumericDataType decimalDataType; /// @} /// @name Data Labels /// @{ @property (nonatomic, readonly, assign) BOOL needsRelabel; @property (nonatomic, readwrite, assign) CGFloat labelOffset; @property (nonatomic, readwrite, assign) CGFloat labelRotation; @property (nonatomic, readwrite, assign) NSUInteger labelField; @property (nonatomic, readwrite, copy) CPMutableTextStyle *labelTextStyle; @property (nonatomic, readwrite, retain) NSNumberFormatter *labelFormatter; /// @} /// @name Data Labels /// @{ -(void)setNeedsRelabel; -(void)relabel; -(void)relabelIndexRange:(NSRange)indexRange; /// @} /// @name Data Loading /// @{ -(void)setDataNeedsReloading; -(void)reloadData; -(void)reloadDataIfNeeded; -(void)reloadDataInIndexRange:(NSRange)indexRange; -(void)insertDataAtIndex:(NSUInteger)index numberOfRecords:(NSUInteger)numberOfRecords; -(void)deleteDataInIndexRange:(NSRange)indexRange; /// @} /// @name Plot Data /// @{ -(id)numbersFromDataSourceForField:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange; /// @} /// @name Data Cache /// @{ -(CPMutableNumericData *)cachedNumbersForField:(NSUInteger)fieldEnum; -(NSNumber *)cachedNumberForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index; -(double)cachedDoubleForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index; -(NSDecimal)cachedDecimalForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index; -(void)cacheNumbers:(id)numbers forField:(NSUInteger)fieldEnum; -(void)cacheNumbers:(id)numbers forField:(NSUInteger)fieldEnum atRecordIndex:(NSUInteger)index; /// @} /// @name Plot Data Ranges /// @{ -(CPPlotRange *)plotRangeForField:(NSUInteger)fieldEnum; -(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coord; /// @} @end #pragma mark - /** @category CPPlot(AbstractMethods) * @brief CPPlot abstract methods—must be overridden by subclasses **/ @interface CPPlot(AbstractMethods) /// @name Fields /// @{ -(NSUInteger)numberOfFields; -(NSArray *)fieldIdentifiers; -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord; /// @} /// @name Data Labels /// @{ -(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index; /// @} @end
08iteng-ipad
framework/Source/CPPlot.h
Objective-C
bsd
7,440
#import <Foundation/Foundation.h> #import "CPPlot.h" #import "CPDefinitions.h" @class CPLineStyle; @class CPFill; extern NSString * const CPRangePlotBindingXValues; extern NSString * const CPRangePlotBindingYValues; extern NSString * const CPRangePlotBindingHighValues; extern NSString * const CPRangePlotBindingLowValues; extern NSString * const CPRangePlotBindingLeftValues; extern NSString * const CPRangePlotBindingRightValues; /** @brief Enumeration of range plot data source field types **/ typedef enum _CPRangePlotField { CPRangePlotFieldX, ///< X values. CPRangePlotFieldY, ///< Y values. CPRangePlotFieldHigh, ///< relative High values. CPRangePlotFieldLow , ///< relative Low values. CPRangePlotFieldLeft, ///< relative Left values. CPRangePlotFieldRight, ///< relative Right values. } CPRangePlotField; @interface CPRangePlot : CPPlot { CPLineStyle *barLineStyle; CGFloat barWidth; CGFloat gapHeight; CGFloat gapWidth; CPFill *areaFill; } /// @name Bar Appearance /// @{ @property (nonatomic, readwrite, copy) CPLineStyle *barLineStyle; @property (nonatomic, readwrite) CGFloat barWidth, gapHeight, gapWidth; /// @} /// @name Area Fill /// @{ @property (nonatomic, copy) CPFill *areaFill; /// @} @end
08iteng-ipad
framework/Source/CPRangePlot.h
Objective-C
bsd
1,249
#import <Foundation/Foundation.h> #import "CPLayer.h" #import "CPGraph.h" #import "CPAnnotationHostLayer.h" @class CPAxis; @class CPAxisLabelGroup; @class CPAxisSet; @class CPGridLineGroup; @class CPPlotGroup; @class CPLineStyle; @class CPFill; @interface CPPlotArea : CPAnnotationHostLayer { @private CPGridLineGroup *minorGridLineGroup; CPGridLineGroup *majorGridLineGroup; CPAxisSet *axisSet; CPPlotGroup *plotGroup; CPAxisLabelGroup *axisLabelGroup; CPAxisLabelGroup *axisTitleGroup; CPFill *fill; NSArray *topDownLayerOrder; CPGraphLayerType *bottomUpLayerOrder; BOOL updatingLayers; } /// @name Layers /// @{ @property (nonatomic, readwrite, retain) CPGridLineGroup *minorGridLineGroup; @property (nonatomic, readwrite, retain) CPGridLineGroup *majorGridLineGroup; @property (nonatomic, readwrite, retain) CPAxisSet *axisSet; @property (nonatomic, readwrite, retain) CPPlotGroup *plotGroup; @property (nonatomic, readwrite, retain) CPAxisLabelGroup *axisLabelGroup; @property (nonatomic, readwrite, retain) CPAxisLabelGroup *axisTitleGroup; /// @} /// @name Layer ordering /// @{ @property (nonatomic, readwrite, retain) NSArray *topDownLayerOrder; /// @} /// @name Decorations /// @{ @property (nonatomic, readwrite, copy) CPLineStyle *borderLineStyle; @property (nonatomic, readwrite, copy) CPFill *fill; /// @} /// @name Axis set layer management /// @{ -(void)updateAxisSetLayersForType:(CPGraphLayerType)layerType; -(void)setAxisSetLayersForType:(CPGraphLayerType)layerType; -(unsigned)sublayerIndexForAxis:(CPAxis *)axis layerType:(CPGraphLayerType)layerType; /// @} @end
08iteng-ipad
framework/Source/CPPlotArea.h
Objective-C
bsd
1,601
#import <Foundation/Foundation.h> #import "CPLayer.h" #import "CPDefinitions.h" #import "CPTextStyle.h" /// @file @class CPAxis; @class CPAxisSet; @class CPAxisTitle; @class CPGridLines; @class CPLimitBand; @class CPLineStyle; @class CPPlotSpace; @class CPPlotRange; @class CPPlotArea; /** @brief Enumeration of labeling policies **/ typedef enum _CPAxisLabelingPolicy { CPAxisLabelingPolicyNone, ///< No labels provided; user sets labels and locations. CPAxisLabelingPolicyLocationsProvided, ///< User sets locations; class makes labels. CPAxisLabelingPolicyFixedInterval, ///< Fixed interval labeling policy. CPAxisLabelingPolicyAutomatic, ///< Automatic labeling policy. // TODO: Implement logarithmic labeling CPAxisLabelingPolicyLogarithmic ///< logarithmic labeling policy (not implemented). } CPAxisLabelingPolicy; #pragma mark - /** @brief Axis labeling delegate. **/ @protocol CPAxisDelegate <NSObject> /// @name Labels /// @{ /** @brief Determines if the axis should relabel itself now. * @param axis The axis. * @return YES if the axis should relabel now. **/ -(BOOL)axisShouldRelabel:(CPAxis *)axis; /** @brief The method is called after the axis is relabeled to allow the delegate to perform any * necessary cleanup or further labeling actions. * @param axis The axis. **/ -(void)axisDidRelabel:(CPAxis *)axis; @optional /** @brief This method gives the delegate a chance to create custom labels for each tick. * It can be used with any relabeling policy. Returning NO will cause the axis not * to update the labels. It is then the delegates responsiblity to do this. * @param axis The axis. * @param locations The locations of the major ticks. * @return YES if the axis class should proceed with automatic relabeling. **/ -(BOOL)axis:(CPAxis *)axis shouldUpdateAxisLabelsAtLocations:(NSSet *)locations; /// @} @end #pragma mark - @interface CPAxis : CPLayer { @private CPCoordinate coordinate; CPPlotSpace *plotSpace; NSSet *majorTickLocations; NSSet *minorTickLocations; CGFloat majorTickLength; CGFloat minorTickLength; CGFloat labelOffset; CGFloat minorTickLabelOffset; CGFloat labelRotation; CGFloat minorTickLabelRotation; CPAlignment labelAlignment; CPAlignment minorTickLabelAlignment; CPLineStyle *axisLineStyle; CPLineStyle *majorTickLineStyle; CPLineStyle *minorTickLineStyle; CPLineStyle *majorGridLineStyle; CPLineStyle *minorGridLineStyle; NSDecimal labelingOrigin; NSDecimal majorIntervalLength; NSUInteger minorTicksPerInterval; NSUInteger preferredNumberOfMajorTicks; CPAxisLabelingPolicy labelingPolicy; CPTextStyle *labelTextStyle; CPTextStyle *minorTickLabelTextStyle; CPTextStyle *titleTextStyle; NSNumberFormatter *labelFormatter; NSNumberFormatter *minorTickLabelFormatter; BOOL labelFormatterChanged; NSSet *axisLabels; NSSet *minorTickAxisLabels; CPAxisTitle *axisTitle; NSString *title; CGFloat titleOffset; NSDecimal titleLocation; CPSign tickDirection; BOOL needsRelabel; NSArray *labelExclusionRanges; CPPlotRange *visibleRange; CPPlotRange *gridLinesRange; NSArray *alternatingBandFills; NSMutableArray *mutableBackgroundLimitBands; BOOL separateLayers; __weak CPPlotArea *plotArea; __weak CPGridLines *minorGridLines; __weak CPGridLines *majorGridLines; } /// @name Axis /// @{ @property (nonatomic, readwrite, copy) CPLineStyle *axisLineStyle; @property (nonatomic, readwrite, assign) CPCoordinate coordinate; @property (nonatomic, readwrite, assign) NSDecimal labelingOrigin; @property (nonatomic, readwrite, assign) CPSign tickDirection; @property (nonatomic, readwrite, copy) CPPlotRange *visibleRange; /// @} /// @name Title /// @{ @property (nonatomic, readwrite, copy) CPTextStyle *titleTextStyle; @property (nonatomic, readwrite, retain) CPAxisTitle *axisTitle; @property (nonatomic, readwrite, assign) CGFloat titleOffset; @property (nonatomic, readwrite, copy) NSString *title; @property (nonatomic, readwrite, assign) NSDecimal titleLocation; @property (nonatomic, readonly, assign) NSDecimal defaultTitleLocation; /// @} /// @name Labels /// @{ @property (nonatomic, readwrite, assign) CPAxisLabelingPolicy labelingPolicy; @property (nonatomic, readwrite, assign) CGFloat labelOffset; @property (nonatomic, readwrite, assign) CGFloat minorTickLabelOffset; @property (nonatomic, readwrite, assign) CGFloat labelRotation; @property (nonatomic, readwrite, assign) CGFloat minorTickLabelRotation; @property (nonatomic, readwrite, assign) CPAlignment labelAlignment; @property (nonatomic, readwrite, assign) CPAlignment minorTickLabelAlignment; @property (nonatomic, readwrite, copy) CPTextStyle *labelTextStyle; @property (nonatomic, readwrite, copy) CPTextStyle *minorTickLabelTextStyle; @property (nonatomic, readwrite, retain) NSNumberFormatter *labelFormatter; @property (nonatomic, readwrite, retain) NSNumberFormatter *minorTickLabelFormatter; @property (nonatomic, readwrite, retain) NSSet *axisLabels; @property (nonatomic, readwrite, retain) NSSet *minorTickAxisLabels; @property (nonatomic, readonly, assign) BOOL needsRelabel; @property (nonatomic, readwrite, retain) NSArray *labelExclusionRanges; /// @} /// @name Major Ticks /// @{ @property (nonatomic, readwrite, assign) NSDecimal majorIntervalLength; @property (nonatomic, readwrite, assign) CGFloat majorTickLength; @property (nonatomic, readwrite, copy) CPLineStyle *majorTickLineStyle; @property (nonatomic, readwrite, retain) NSSet *majorTickLocations; @property (nonatomic, readwrite, assign) NSUInteger preferredNumberOfMajorTicks; /// @} /// @name Minor Ticks /// @{ @property (nonatomic, readwrite, assign) NSUInteger minorTicksPerInterval; @property (nonatomic, readwrite, assign) CGFloat minorTickLength; @property (nonatomic, readwrite, copy) CPLineStyle *minorTickLineStyle; @property (nonatomic, readwrite, retain) NSSet *minorTickLocations; /// @} /// @name Grid Lines /// @{ @property (nonatomic, readwrite, copy) CPLineStyle *majorGridLineStyle; @property (nonatomic, readwrite, copy) CPLineStyle *minorGridLineStyle; @property (nonatomic, readwrite, copy) CPPlotRange *gridLinesRange; /// @} /// @name Background Bands /// @{ @property (nonatomic, readwrite, copy) NSArray *alternatingBandFills; @property (nonatomic, readonly, retain) NSArray *backgroundLimitBands; /// @} /// @name Plot Space /// @{ @property (nonatomic, readwrite, retain) CPPlotSpace *plotSpace; /// @} /// @name Layers /// @{ @property (nonatomic, readwrite, assign) BOOL separateLayers; @property (nonatomic, readwrite, assign) __weak CPPlotArea *plotArea; @property (nonatomic, readonly, assign) __weak CPGridLines *minorGridLines; @property (nonatomic, readonly, assign) __weak CPGridLines *majorGridLines; @property (nonatomic, readonly, retain) CPAxisSet *axisSet; /// @} /// @name Labels /// @{ -(void)relabel; -(void)setNeedsRelabel; /// @} /// @name Ticks /// @{ -(NSSet *)filteredMajorTickLocations:(NSSet *)allLocations; -(NSSet *)filteredMinorTickLocations:(NSSet *)allLocations; /// @} /// @name Background Bands /// @{ -(void)addBackgroundLimitBand:(CPLimitBand *)limitBand; -(void)removeBackgroundLimitBand:(CPLimitBand *)limitBand; /// @} @end #pragma mark - /** @category CPAxis(AbstractMethods) * @brief CPAxis abstract methods—must be overridden by subclasses **/ @interface CPAxis(AbstractMethods) /// @name Coordinate Space Conversions /// @{ -(CGPoint)viewPointForCoordinateDecimalNumber:(NSDecimal)coordinateDecimalNumber; /// @} /// @name Grid Lines /// @{ -(void)drawGridLinesInContext:(CGContextRef)context isMajor:(BOOL)major; /// @} /// @name Background Bands /// @{ -(void)drawBackgroundBandsInContext:(CGContextRef)context; -(void)drawBackgroundLimitsInContext:(CGContextRef)context; /// @} @end
08iteng-ipad
framework/Source/CPAxis.h
Objective-C
bsd
7,838
#import "CPTestCase.h" #import <CorePlot/CorePlot.h> @interface CPScatterPlotTests : CPTestCase { CPScatterPlot *plot; CPXYPlotSpace *plotSpace; } @property (retain) CPScatterPlot *plot; @property (retain) CPXYPlotSpace *plotSpace; @end
08iteng-ipad
framework/Source/CPScatterPlotTests.h
Objective-C
bsd
246
#import "CPXYPlotSpaceTests.h" #import "CPXYGraph.h" #import "CPXYPlotSpace.h" #import "CPExceptions.h" #import "CPPlotRange.h" #import "CPUtilities.h" @interface CPXYPlotSpace(testingAdditions) -(CPPlotRange *)constrainRange:(CPPlotRange *)existingRange toGlobalRange:(CPPlotRange *)globalRange; @end #pragma mark - @implementation CPXYPlotSpaceTests @synthesize graph; -(void)setUp { self.graph = [[(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 50.0)] autorelease]; self.graph.paddingLeft = 0.0; self.graph.paddingRight = 0.0; self.graph.paddingTop = 0.0; self.graph.paddingBottom = 0.0; [self.graph layoutIfNeeded]; } -(void)tearDown { self.graph = nil; } -(void)testViewPointForPlotPoint { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = CPDecimalFromDouble(5.0); plotPoint[CPCoordinateY] = CPDecimalFromDouble(5.0); CGPoint viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint]; STAssertEqualsWithAccuracy(viewPoint.x, (CGFloat)50.0, (CGFloat)0.01, @""); STAssertEqualsWithAccuracy(viewPoint.y, (CGFloat)25.0, (CGFloat)0.01, @""); plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(5.0)]; viewPoint = [plotSpace plotAreaViewPointForPlotPoint:plotPoint]; STAssertEqualsWithAccuracy(viewPoint.x, (CGFloat)50.0, (CGFloat)0.01, @""); STAssertEqualsWithAccuracy(viewPoint.y, (CGFloat)50.0, (CGFloat)0.01, @""); } -(void)testPlotPointForViewPoint { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; NSDecimal plotPoint[2]; CGPoint viewPoint = CGPointMake(50.0, 25.0); NSString *errMessage; [plotSpace plotPoint:plotPoint forPlotAreaViewPoint:viewPoint]; errMessage = [NSString stringWithFormat:@"plotPoint[CPCoordinateX] was %@", NSDecimalString(&plotPoint[CPCoordinateX], nil)]; STAssertTrue(CPDecimalEquals(plotPoint[CPCoordinateX], CPDecimalFromDouble(5.0)), errMessage); errMessage = [NSString stringWithFormat:@"plotPoint[CPCoordinateY] was %@", NSDecimalString(&plotPoint[CPCoordinateY], nil)]; STAssertTrue(CPDecimalEquals(plotPoint[CPCoordinateY], CPDecimalFromDouble(5.0)), errMessage); } -(void)testConstrainNilRanges { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; STAssertEqualObjects([plotSpace constrainRange:plotSpace.xRange toGlobalRange:nil], plotSpace.xRange, @"Constrain to nil global range should return original range."); STAssertNil([plotSpace constrainRange:nil toGlobalRange:plotSpace.xRange], @"Constrain nil range should return nil."); } -(void)testConstrainRanges1 { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; CPPlotRange *existingRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(2.0) length:CPDecimalFromDouble(5.0)]; CPPlotRange *globalRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; CPPlotRange *expectedRange = existingRange; CPPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange]; NSString *errMessage = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange, nil]; STAssertTrue([constrainedRange isEqualToRange:expectedRange], errMessage); } -(void)testConstrainRanges2 { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; CPPlotRange *existingRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; CPPlotRange *globalRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(5.0)]; CPPlotRange *expectedRange = globalRange; CPPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange]; NSString *errMessage = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange, nil]; STAssertTrue([constrainedRange isEqualToRange:expectedRange], errMessage); } -(void)testConstrainRanges3 { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; CPPlotRange *existingRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(8.0)]; CPPlotRange *globalRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; CPPlotRange *expectedRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(8.0)]; CPPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange]; NSString *errMessage = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange, nil]; STAssertTrue([constrainedRange isEqualToRange:expectedRange], errMessage); } -(void)testConstrainRanges4 { CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace; CPPlotRange *existingRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(3.0) length:CPDecimalFromDouble(8.0)]; CPPlotRange *globalRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(10.0)]; CPPlotRange *expectedRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(2.0) length:CPDecimalFromDouble(8.0)]; CPPlotRange *constrainedRange = [plotSpace constrainRange:existingRange toGlobalRange:globalRange]; NSString *errMessage = [NSString stringWithFormat:@"constrainedRange was %@, expected %@", constrainedRange, expectedRange, nil]; STAssertTrue([constrainedRange isEqualToRange:expectedRange], errMessage); } @end
08iteng-ipad
framework/Source/CPXYPlotSpaceTests.m
Objective-C
bsd
6,824
#import "CPAnnotation.h" #import "CPLayer.h" #import "CPAnnotationHostLayer.h" /** @brief An annotation positions a content layer relative to some anchor point. * * Annotations can be used to add text or images that are anchored to a feature * of a graph. For example, the graph title is an annotation anchored to the * plot area frame. * * @todo More documentation needed. **/ @implementation CPAnnotation /** @property contentLayer * @brief The annotation content. **/ @synthesize contentLayer; /** @property annotationHostLayer * @brief The host layer for the annotation content. **/ @synthesize annotationHostLayer; /** @property displacement * @brief The displacement from the layer anchor point. **/ @synthesize displacement; /** @property contentAnchorPoint * @brief The anchor point for the content layer. **/ @synthesize contentAnchorPoint; /** @property rotation * @brief The rotation of the label in radians. **/ @synthesize rotation; #pragma mark - #pragma mark Init/Dealloc -(id)init { if ( self = [super init] ) { annotationHostLayer = nil; contentLayer = nil; displacement = CGPointZero; contentAnchorPoint = CGPointMake(0.5, 0.5); rotation = 0.0; } return self; } -(void)dealloc { [contentLayer release]; [super dealloc]; } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"<%@ {%@}>", [super description], self.contentLayer]; } #pragma mark - #pragma mark Accessors -(void)setContentLayer:(CPLayer *)newLayer { if ( newLayer != contentLayer ) { [contentLayer removeFromSuperlayer]; [contentLayer release]; contentLayer = [newLayer retain]; if ( contentLayer ) { [annotationHostLayer addSublayer:contentLayer]; } } } -(void)setAnnotationHostLayer:(CPAnnotationHostLayer *)newLayer { if ( newLayer != annotationHostLayer ) { [contentLayer removeFromSuperlayer]; annotationHostLayer = newLayer; if ( contentLayer ) { [annotationHostLayer addSublayer:contentLayer]; } } } -(void)setDisplacement:(CGPoint)newDisplacement { if ( !CGPointEqualToPoint(newDisplacement, displacement) ) { displacement = newDisplacement; [self.contentLayer setNeedsLayout]; } } -(void)setContentAnchorPoint:(CGPoint)newAnchorPoint { if ( !CGPointEqualToPoint(newAnchorPoint, contentAnchorPoint) ) { contentAnchorPoint = newAnchorPoint; [self.contentLayer setNeedsLayout]; } } -(void)setRotation:(CGFloat)newRotation { if ( newRotation != rotation ) { rotation = newRotation; [self.contentLayer setNeedsLayout]; } } @end #pragma mark - #pragma mark Layout @implementation CPAnnotation(AbstractMethods) /** @brief Positions the content layer relative to its reference anchor. * * This method must be overridden by subclasses. The default implementation * does nothing. **/ -(void)positionContentLayer { // Do nothing--implementation provided by subclasses } @end
08iteng-ipad
framework/Source/CPAnnotation.m
Objective-C
bsd
3,021
#import <Foundation/Foundation.h> @class CPGraph; @class CPPlotAreaFrame; @class CPAxisSet; @class CPMutableTextStyle; /// @file /// @name Theme Names /// @{ extern NSString * const kCPDarkGradientTheme; extern NSString * const kCPPlainWhiteTheme; extern NSString * const kCPPlainBlackTheme; extern NSString * const kCPSlateTheme; extern NSString * const kCPStocksTheme; /// @} @interface CPTheme : NSObject { @private NSString *name; Class graphClass; } @property (nonatomic, readwrite, copy) NSString *name; @property (nonatomic, readwrite, retain) Class graphClass; /// @name Theme Management /// @{ +(NSArray *)themeClasses; +(CPTheme *)themeNamed:(NSString *)theme; +(void)addTheme:(CPTheme *)newTheme; +(NSString *)defaultName; /// @} /// @name Theme Usage /// @{ -(void)applyThemeToGraph:(CPGraph *)graph; /// @} @end /** @category CPTheme(AbstractMethods) * @brief CPTheme abstract methods—must be overridden by subclasses **/ @interface CPTheme(AbstractMethods) /// @name Theme Usage /// @{ -(id)newGraph; -(void)applyThemeToBackground:(CPGraph *)graph; -(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame; -(void)applyThemeToAxisSet:(CPAxisSet *)axisSet; /// @} @end
08iteng-ipad
framework/Source/CPTheme.h
Objective-C
bsd
1,207
#import "CPMutableNumericData.h" #import "CPNumericData.h" #import "CPPieChart.h" #import "CPPlotArea.h" #import "CPPlotSpace.h" #import "CPPlotSpaceAnnotation.h" #import "CPColor.h" #import "CPFill.h" #import "CPUtilities.h" #import "CPTextLayer.h" #import "CPLineStyle.h" NSString * const CPPieChartBindingPieSliceWidthValues = @"sliceWidths"; ///< Pie slice widths. /** @cond */ @interface CPPieChart () @property (nonatomic, readwrite, copy) NSArray *sliceWidths; -(void)updateNormalizedData; -(CGFloat)radiansForPieSliceValue:(CGFloat)pieSliceValue; -(CGFloat)normalizedPosition:(CGFloat)rawPosition; -(BOOL)angle:(CGFloat)touchedAngle betweenStartAngle:(CGFloat)startingAngle endAngle:(CGFloat)endingAngle; -(void)addSliceToPath:(CGMutablePathRef)slicePath centerPoint:(CGPoint)center startingAngle:(CGFloat)startingAngle finishingAngle:(CGFloat)finishingAngle; -(void)drawSliceInContext:(CGContextRef)context centerPoint:(CGPoint)centerPoint radialOffset:(CGFloat)radialOffset startingValue:(CGFloat)startingValue width:(CGFloat)sliceWidth fill:(CPFill *)sliceFill; -(void)drawOverlayInContext:(CGContextRef)context centerPoint:(CGPoint)centerPoint; @end /** @endcond */ #pragma mark - /** @brief A pie chart. **/ @implementation CPPieChart @dynamic sliceWidths; /** @property pieRadius * @brief The radius of the overall pie chart. Defaults to 80% of the initial frame size. **/ @synthesize pieRadius; /** @property pieInnerRadius * @brief The inner radius of the pie chart, used to create a "donut hole". Defaults to 0. **/ @synthesize pieInnerRadius; /** @property sliceLabelOffset * @brief The radial offset of the slice labels from the edge of each slice. Defaults to 10.0 * @deprecated This property has been replaced by the CPPlot::labelOffset property. **/ @dynamic sliceLabelOffset; /** @property startAngle * @brief The starting angle for the first slice in radians. Defaults to pi/2. **/ @synthesize startAngle; /** @property sliceDirection * @brief Determines whether the pie slices are drawn in a clockwise or counter-clockwise * direction from the starting point. Defaults to clockwise. **/ @synthesize sliceDirection; /** @property centerAnchor * @brief The position of the center of the pie chart with the x and y coordinates * given as a fraction of the width and height, respectively. Defaults to (0.5, 0.5). **/ @synthesize centerAnchor; /** @property borderLineStyle * @brief The line style used to outline the pie slices. If nil, no border is drawn. Defaults to nil. **/ @synthesize borderLineStyle; /** @property overlayFill * @brief A fill drawn on top of the pie chart. * Can be used to add shading/gloss effects. Defaults to nil. **/ @synthesize overlayFill; #pragma mark - #pragma mark Convenience Factory Methods static CGFloat colorLookupTable[10][3] = { {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}, {1.0, 1.0, 0.0}, {0.25, 0.5, 0.25}, {1.0, 0.0, 1.0}, {0.5, 0.5, 0.5}, {0.25, 0.5, 0.0}, {0.25, 0.25, 0.25}, {0.0, 1.0, 1.0} }; /** @brief Creates and returns a CPColor that acts as the default color for that pie chart index. * @param pieSliceIndex The pie slice index to return a color for. * @return A new CPColor instance corresponding to the default value for this pie slice index. **/ +(CPColor *)defaultPieSliceColorForIndex:(NSUInteger)pieSliceIndex; { return [CPColor colorWithComponentRed:(colorLookupTable[pieSliceIndex % 10][0] + (CGFloat)(pieSliceIndex / 10) * 0.1) green:(colorLookupTable[pieSliceIndex % 10][1] + (CGFloat)(pieSliceIndex / 10) * 0.1) blue:(colorLookupTable[pieSliceIndex % 10][2] + (CGFloat)(pieSliceIndex / 10) * 0.1) alpha:1.0]; } #pragma mark - #pragma mark Initialization #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE #else +(void)initialize { if ( self == [CPPieChart class] ) { [self exposeBinding:CPPieChartBindingPieSliceWidthValues]; } } #endif -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { pieRadius = 0.8 * (MIN(newFrame.size.width, newFrame.size.height) / 2.0); pieInnerRadius = 0.0; startAngle = M_PI_2; // pi/2 sliceDirection = CPPieDirectionClockwise; centerAnchor = CGPointMake(0.5, 0.5); borderLineStyle = nil; self.labelOffset = 10.0; self.labelField = CPPieChartFieldSliceWidth; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPPieChart *theLayer = (CPPieChart *)layer; pieRadius = theLayer->pieRadius; pieInnerRadius = theLayer->pieInnerRadius; startAngle = theLayer->startAngle; sliceDirection = theLayer->sliceDirection; centerAnchor = theLayer->centerAnchor; borderLineStyle = [theLayer->borderLineStyle retain]; } return self; } -(void)dealloc { [borderLineStyle release]; [super dealloc]; } #pragma mark - #pragma mark Data Loading -(void)reloadDataInIndexRange:(NSRange)indexRange { [super reloadDataInIndexRange:indexRange]; // Pie slice widths if ( self.dataSource ) { // Grab all values from the data source id rawSliceValues = [self numbersFromDataSourceForField:CPPieChartFieldSliceWidth recordIndexRange:indexRange]; [self cacheNumbers:rawSliceValues forField:CPPieChartFieldSliceWidth atRecordIndex:indexRange.location]; } else { [self cacheNumbers:nil forField:CPPieChartFieldSliceWidth]; } [self updateNormalizedData]; } -(void)deleteDataInIndexRange:(NSRange)indexRange { [super deleteDataInIndexRange:indexRange]; [self updateNormalizedData]; } -(void)updateNormalizedData { // Normalize these widths to 1.0 for the whole pie NSUInteger sampleCount = self.cachedDataCount; if ( sampleCount > 0 ) { CPMutableNumericData *rawSliceValues = [self cachedNumbersForField:CPPieChartFieldSliceWidth]; if ( self.doublePrecisionCache ) { double valueSum = 0.0; const double *dataBytes = (const double *)rawSliceValues.bytes; const double *dataEnd = dataBytes + sampleCount; while ( dataBytes < dataEnd ) { double currentWidth = *dataBytes++; if ( !isnan(currentWidth) ) { valueSum += currentWidth; } } CPNumericDataType dataType = CPDataType(CPFloatingPointDataType, sizeof(double), CFByteOrderGetCurrent()); CPMutableNumericData *normalizedSliceValues = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:dataType shape:nil]; ((NSMutableData *)normalizedSliceValues.data).length = sampleCount * sizeof(double); CPMutableNumericData *cumulativeSliceValues = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:dataType shape:nil]; ((NSMutableData *)cumulativeSliceValues.data).length = sampleCount * sizeof(double); double cumulativeSum = 0.0; dataBytes = (const double *)rawSliceValues.bytes; double *normalizedBytes = normalizedSliceValues.mutableBytes; double *cumulativeBytes = cumulativeSliceValues.mutableBytes; while ( dataBytes < dataEnd ) { double currentWidth = *dataBytes++; if ( isnan(currentWidth) ) { *normalizedBytes++ = NAN; } else { *normalizedBytes++ = currentWidth / valueSum; cumulativeSum += currentWidth; } *cumulativeBytes++ = cumulativeSum / valueSum; } [self cacheNumbers:normalizedSliceValues forField:CPPieChartFieldSliceWidthNormalized]; [self cacheNumbers:cumulativeSliceValues forField:CPPieChartFieldSliceWidthSum]; [normalizedSliceValues release]; [cumulativeSliceValues release]; } else { NSDecimal valueSum = CPDecimalFromInteger(0); const NSDecimal *dataBytes = (const NSDecimal *)rawSliceValues.bytes; const NSDecimal *dataEnd = dataBytes + sampleCount; while ( dataBytes < dataEnd ) { NSDecimal currentWidth = *dataBytes++; if ( !NSDecimalIsNotANumber(&currentWidth) ) { valueSum = CPDecimalAdd(valueSum, *dataBytes++); } } CPNumericDataType dataType = CPDataType(CPDecimalDataType, sizeof(NSDecimal), CFByteOrderGetCurrent()); CPMutableNumericData *normalizedSliceValues = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:dataType shape:nil]; ((NSMutableData *)normalizedSliceValues.data).length = sampleCount * sizeof(NSDecimal); CPMutableNumericData *cumulativeSliceValues = [[CPMutableNumericData alloc] initWithData:[NSData data] dataType:dataType shape:nil]; ((NSMutableData *)cumulativeSliceValues.data).length = sampleCount * sizeof(NSDecimal); NSDecimal cumulativeSum = CPDecimalFromInteger(0); NSDecimal decimalNAN = CPDecimalNaN(); dataBytes = (const NSDecimal *)rawSliceValues.bytes; NSDecimal *normalizedBytes = normalizedSliceValues.mutableBytes; NSDecimal *cumulativeBytes = cumulativeSliceValues.mutableBytes; while ( dataBytes < dataEnd ) { NSDecimal currentWidth = *dataBytes++; if ( NSDecimalIsNotANumber(&currentWidth) ) { *normalizedBytes++ = decimalNAN; } else { *normalizedBytes++ = CPDecimalDivide(currentWidth, valueSum); cumulativeSum = CPDecimalAdd(cumulativeSum, currentWidth); } *cumulativeBytes++ = CPDecimalDivide(cumulativeSum, valueSum); } [self cacheNumbers:normalizedSliceValues forField:CPPieChartFieldSliceWidthNormalized]; [self cacheNumbers:cumulativeSliceValues forField:CPPieChartFieldSliceWidthSum]; [normalizedSliceValues release]; [cumulativeSliceValues release]; } } else { [self cacheNumbers:nil forField:CPPieChartFieldSliceWidthNormalized]; [self cacheNumbers:nil forField:CPPieChartFieldSliceWidthSum]; } // Labels [self relabelIndexRange:NSMakeRange(0, [self.dataSource numberOfRecordsForPlot:self])]; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)context { NSUInteger sampleCount = self.cachedDataCount; if ( sampleCount == 0 ) return; [super renderAsVectorInContext:context]; CGRect plotAreaBounds = self.plotArea.bounds; CGPoint anchor = self.centerAnchor; CGPoint centerPoint = CGPointMake(plotAreaBounds.origin.x + plotAreaBounds.size.width * anchor.x, plotAreaBounds.origin.y + plotAreaBounds.size.height * anchor.y); centerPoint = [self convertPoint:centerPoint fromLayer:self.plotArea]; centerPoint = CPAlignPointToUserSpace(context, centerPoint); // TODO: Add NSDecimal rendering path NSUInteger currentIndex = 0; CGFloat startingWidth = 0.0; id <CPPieChartDataSource> theDataSource = (id <CPPieChartDataSource>)self.dataSource; BOOL dataSourceProvidesFills = [theDataSource respondsToSelector:@selector(sliceFillForPieChart:recordIndex:)]; BOOL dataSourceProvidesRadialOffsets = [theDataSource respondsToSelector:@selector(radialOffsetForPieChart:recordIndex:)]; while ( currentIndex < sampleCount ) { CGFloat currentWidth = [self cachedDoubleForField:CPPieChartFieldSliceWidthNormalized recordIndex:currentIndex]; if ( !isnan(currentWidth) ) { CPFill *currentFill = nil; if ( dataSourceProvidesFills ) { CPFill *dataSourceFill = [theDataSource sliceFillForPieChart:self recordIndex:currentIndex]; if ( nil != dataSourceFill ) currentFill = dataSourceFill; } else { currentFill = [CPFill fillWithColor:[CPPieChart defaultPieSliceColorForIndex:currentIndex]]; } CGFloat radialOffset = 0.0; if ( dataSourceProvidesRadialOffsets ) { radialOffset = [theDataSource radialOffsetForPieChart:self recordIndex:currentIndex]; } [self drawSliceInContext:context centerPoint:centerPoint radialOffset:radialOffset startingValue:startingWidth width:currentWidth fill:currentFill]; startingWidth += currentWidth; } currentIndex++; } [self drawOverlayInContext:context centerPoint:centerPoint]; } -(CGFloat)radiansForPieSliceValue:(CGFloat)pieSliceValue { CGFloat angle = self.startAngle; switch ( self.sliceDirection ) { case CPPieDirectionClockwise: angle -= pieSliceValue * M_PI * 2.0; break; case CPPieDirectionCounterClockwise: angle += pieSliceValue * M_PI * 2.0; break; } return angle; } -(void)addSliceToPath:(CGMutablePathRef)slicePath centerPoint:(CGPoint)center startingAngle:(CGFloat)startingAngle finishingAngle:(CGFloat)finishingAngle { bool direction = (self.sliceDirection == CPPieDirectionClockwise) ? true : false; CGFloat innerRadius = self.pieInnerRadius; if ( innerRadius > 0.0 ) { CGPathAddArc(slicePath, NULL, center.x, center.y, self.pieRadius, startingAngle, finishingAngle, direction); CGPathAddArc(slicePath, NULL, center.x, center.y, innerRadius, finishingAngle, startingAngle, !direction); } else { CGPathMoveToPoint(slicePath, NULL, center.x, center.y); CGPathAddArc(slicePath, NULL, center.x, center.y, self.pieRadius, startingAngle, finishingAngle, direction); } } -(void)drawSliceInContext:(CGContextRef)context centerPoint:(CGPoint)centerPoint radialOffset:(CGFloat)radialOffset startingValue:(CGFloat)startingValue width:(CGFloat)sliceWidth fill:(CPFill *)sliceFill; { CGContextSaveGState(context); CGFloat startingAngle = [self radiansForPieSliceValue:startingValue]; CGFloat finishingAngle = [self radiansForPieSliceValue:startingValue + sliceWidth]; CGFloat xOffset = 0.0; CGFloat yOffset = 0.0; if ( radialOffset != 0.0 ) { CGFloat medianAngle = 0.5 * (startingAngle + finishingAngle); #if CGFLOAT_IS_DOUBLE xOffset = round(cos(medianAngle) * radialOffset); yOffset = round(sin(medianAngle) * radialOffset); #else xOffset = roundf(cosf(medianAngle) * radialOffset); yOffset = roundf(sinf(medianAngle) * radialOffset); #endif } CGFloat centerX = centerPoint.x + xOffset; CGFloat centerY = centerPoint.y + yOffset; CGMutablePathRef slicePath = CGPathCreateMutable(); [self addSliceToPath:slicePath centerPoint:CGPointMake(centerX, centerY) startingAngle:startingAngle finishingAngle:finishingAngle]; CGPathCloseSubpath(slicePath); if ( sliceFill ) { CGContextBeginPath(context); CGContextAddPath(context, slicePath); [sliceFill fillPathInContext:context]; } // Draw the border line around the slice CPLineStyle *borderStyle = self.borderLineStyle; if ( borderStyle ) { CGContextBeginPath(context); CGContextAddPath(context, slicePath); [borderStyle setLineStyleInContext:context]; CGContextStrokePath(context); } CGPathRelease(slicePath); CGContextRestoreGState(context); } -(void)drawOverlayInContext:(CGContextRef)context centerPoint:(CGPoint)centerPoint { if ( !overlayFill ) return; CGContextSaveGState(context); CGMutablePathRef fillPath = CGPathCreateMutable(); [self addSliceToPath:fillPath centerPoint:CGPointMake(centerPoint.x, centerPoint.y) startingAngle:0.0f finishingAngle:2*M_PI]; CGPathCloseSubpath(fillPath); CGContextBeginPath(context); CGContextAddPath(context, fillPath); [overlayFill fillPathInContext:context]; CGPathRelease(fillPath); CGContextRestoreGState(context); } #pragma mark - #pragma mark Fields -(NSUInteger)numberOfFields { return 1; } -(NSArray *)fieldIdentifiers { return [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:CPPieChartFieldSliceWidth]]; } -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord { return nil; } #pragma mark - #pragma mark Data Labels -(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index { if ( label.contentLayer ) { CGRect plotAreaBounds = self.plotArea.bounds; CGPoint anchor = self.centerAnchor; CGPoint centerPoint = CGPointMake(plotAreaBounds.origin.x + plotAreaBounds.size.width * anchor.x, plotAreaBounds.origin.y + plotAreaBounds.size.height * anchor.y); NSDecimal plotPoint[2]; [self.plotSpace plotPoint:plotPoint forPlotAreaViewPoint:centerPoint]; NSDecimalNumber *xValue = [[NSDecimalNumber alloc] initWithDecimal:plotPoint[CPCoordinateX]]; NSDecimalNumber *yValue = [[NSDecimalNumber alloc] initWithDecimal:plotPoint[CPCoordinateY]]; label.anchorPlotPoint = [NSArray arrayWithObjects:xValue, yValue, nil]; [xValue release]; [yValue release]; id <CPPieChartDataSource> theDataSource = (id <CPPieChartDataSource>)self.dataSource; BOOL dataSourceProvidesRadialOffsets = [theDataSource respondsToSelector:@selector(radialOffsetForPieChart:recordIndex:)]; CGFloat radialOffset = 0.0; if ( dataSourceProvidesRadialOffsets ) { radialOffset = [theDataSource radialOffsetForPieChart:self recordIndex:index]; } CGFloat labelRadius = self.pieRadius + self.labelOffset + radialOffset; double startingWidth = 0.0; if ( index > 0 ) { startingWidth = [self cachedDoubleForField:CPPieChartFieldSliceWidthSum recordIndex:index - 1]; } double currentWidth = [self cachedDoubleForField:CPPieChartFieldSliceWidthNormalized recordIndex:index]; double labelAngle = [self radiansForPieSliceValue:startingWidth + currentWidth / 2.0]; #if CGFLOAT_IS_DOUBLE label.displacement = CGPointMake(labelRadius * cos(labelAngle), labelRadius * sin(labelAngle)); #else label.displacement = CGPointMake(labelRadius * cosf(labelAngle), labelRadius * sinf(labelAngle)); #endif label.contentLayer.hidden = isnan(currentWidth); } else { label.anchorPlotPoint = nil; label.displacement = CGPointZero; } } #pragma mark - #pragma mark Responder Chain and User interaction -(CGFloat)normalizedPosition:(CGFloat)rawPosition { CGFloat result = rawPosition; #if CGFLOAT_IS_DOUBLE result /= 2.0 * M_PI; if ( result < 0.0 ) { result += 1.0; } result = fmod(result, 1.0); #else result /= 2.0f * (float)M_PI; if ( result < 0.0f ) { result += 1.0f; } result = fmodf(result, 1.0f); #endif return result; } -(BOOL)angle:(CGFloat)touchedAngle betweenStartAngle:(CGFloat)startingAngle endAngle:(CGFloat)endingAngle { switch ( self.sliceDirection ) { case CPPieDirectionClockwise: if ( (touchedAngle <= startingAngle) && (touchedAngle >= endingAngle) ) { return YES; } else if ( (endingAngle < 0.0) && (touchedAngle - 1.0 >= endingAngle) ) { return YES; } break; case CPPieDirectionCounterClockwise: if ( (touchedAngle >= startingAngle) && (touchedAngle <= endingAngle) ) { return YES; } else if ( (endingAngle > 1.0) && (touchedAngle + 1.0 <= endingAngle) ) { return YES; } break; } return NO; } -(BOOL)pointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL result = NO; CPGraph *theGraph = self.graph; CPPlotArea *thePlotArea = self.plotArea; if ( !theGraph || !thePlotArea ) return NO; id <CPPieChartDelegate> theDelegate = self.delegate; if ( [theDelegate respondsToSelector:@selector(pieChart:sliceWasSelectedAtRecordIndex:)] ) { // Inform delegate if a slice was hit CGPoint plotAreaPoint = [theGraph convertPoint:interactionPoint toLayer:thePlotArea]; NSUInteger sampleCount = self.cachedDataCount; if ( sampleCount == 0 ) return NO; CGRect plotAreaBounds = thePlotArea.bounds; CGPoint anchor = self.centerAnchor; CGPoint centerPoint = CGPointMake(plotAreaBounds.origin.x + plotAreaBounds.size.width * anchor.x, plotAreaBounds.origin.y + plotAreaBounds.size.height * anchor.y); centerPoint = [self convertPoint:centerPoint fromLayer:thePlotArea]; id <CPPieChartDataSource> theDataSource = (id <CPPieChartDataSource>)self.dataSource; BOOL dataSourceProvidesRadialOffsets = [theDataSource respondsToSelector:@selector(radialOffsetForPieChart:recordIndex:)]; CGFloat chartRadius = self.pieRadius; CGFloat chartRadiusSquared = chartRadius * chartRadius; CGFloat chartInnerRadius = self.pieInnerRadius; CGFloat chartInnerRadiusSquared = chartInnerRadius * chartInnerRadius; CGFloat dx = plotAreaPoint.x - centerPoint.x; CGFloat dy = plotAreaPoint.y - centerPoint.y; CGFloat distanceSquared = dx * dx + dy * dy; #if CGFLOAT_IS_DOUBLE CGFloat touchedAngle = [self normalizedPosition:atan2(dy, dx)]; #else CGFloat touchedAngle = [self normalizedPosition:atan2f(dy, dx)]; #endif CGFloat startingAngle = [self normalizedPosition:self.startAngle]; switch ( self.sliceDirection ) { case CPPieDirectionClockwise: for ( NSUInteger currentIndex = 0; currentIndex < sampleCount; currentIndex++ ) { // calculate angles for this slice CGFloat width = [self cachedDoubleForField:CPPieChartFieldSliceWidthNormalized recordIndex:currentIndex]; if ( isnan(width) ) continue; CGFloat endingAngle = startingAngle - width; // offset the center point of the slice if needed CGFloat offsetTouchedAngle = touchedAngle; CGFloat offsetDistanceSquared = distanceSquared; CGFloat radialOffset = 0.0; if ( dataSourceProvidesRadialOffsets ) { radialOffset = [theDataSource radialOffsetForPieChart:self recordIndex:currentIndex]; if ( radialOffset != 0.0 ) { CGPoint offsetCenter; CGFloat medianAngle = M_PI * (startingAngle + endingAngle); #if CGFLOAT_IS_DOUBLE offsetCenter = CGPointMake(centerPoint.x + cos(medianAngle) * radialOffset, centerPoint.y + sin(medianAngle) * radialOffset); #else offsetCenter = CGPointMake(centerPoint.x + cosf(medianAngle) * radialOffset, centerPoint.y + sinf(medianAngle) * radialOffset); #endif dx = plotAreaPoint.x - offsetCenter.x; dy = plotAreaPoint.y - offsetCenter.y; #if CGFLOAT_IS_DOUBLE offsetTouchedAngle = [self normalizedPosition:atan2(dy, dx)]; #else offsetTouchedAngle = [self normalizedPosition:atan2f(dy, dx)]; #endif offsetDistanceSquared = dx * dx + dy * dy; } } // check angles BOOL angleInSlice = NO; if ( [self angle:touchedAngle betweenStartAngle:startingAngle endAngle:endingAngle] ) { if ( [self angle:offsetTouchedAngle betweenStartAngle:startingAngle endAngle:endingAngle] ) { angleInSlice = YES; } else { return NO; } } // check distance if ( angleInSlice && (offsetDistanceSquared >= chartInnerRadiusSquared) && (offsetDistanceSquared <= chartRadiusSquared) ) { [theDelegate pieChart:self sliceWasSelectedAtRecordIndex:currentIndex]; return YES; } // save angle for the next slice startingAngle = endingAngle; } break; case CPPieDirectionCounterClockwise: for ( NSUInteger currentIndex = 0; currentIndex < sampleCount; currentIndex++ ) { // calculate angles for this slice CGFloat width = [self cachedDoubleForField:CPPieChartFieldSliceWidthNormalized recordIndex:currentIndex]; if ( isnan(width) ) continue; CGFloat endingAngle = startingAngle + width; // offset the center point of the slice if needed CGFloat offsetTouchedAngle = touchedAngle; CGFloat offsetDistanceSquared = distanceSquared; CGFloat radialOffset = 0.0; if ( dataSourceProvidesRadialOffsets ) { radialOffset = [theDataSource radialOffsetForPieChart:self recordIndex:currentIndex]; if ( radialOffset != 0.0 ) { CGPoint offsetCenter; CGFloat medianAngle = M_PI * (startingAngle + endingAngle); #if CGFLOAT_IS_DOUBLE offsetCenter = CGPointMake(centerPoint.x + cos(medianAngle) * radialOffset, centerPoint.y + sin(medianAngle) * radialOffset); #else offsetCenter = CGPointMake(centerPoint.x + cosf(medianAngle) * radialOffset, centerPoint.y + sinf(medianAngle) * radialOffset); #endif dx = plotAreaPoint.x - offsetCenter.x; dy = plotAreaPoint.y - offsetCenter.y; #if CGFLOAT_IS_DOUBLE offsetTouchedAngle = [self normalizedPosition:atan2(dy, dx)]; #else offsetTouchedAngle = [self normalizedPosition:atan2f(dy, dx)]; #endif offsetDistanceSquared = dx * dx + dy * dy; } } // check angles BOOL angleInSlice = NO; if ( [self angle:touchedAngle betweenStartAngle:startingAngle endAngle:endingAngle] ) { if ( [self angle:offsetTouchedAngle betweenStartAngle:startingAngle endAngle:endingAngle] ) { angleInSlice = YES; } else { return NO; } } // check distance if ( angleInSlice && (offsetDistanceSquared >= chartInnerRadiusSquared) && (offsetDistanceSquared <= chartRadiusSquared) ) { [theDelegate pieChart:self sliceWasSelectedAtRecordIndex:currentIndex]; return YES; } // save angle for the next slice startingAngle = endingAngle; } break; default: break; } } else { result = [super pointingDeviceDownEvent:event atPoint:interactionPoint]; } return result; } #pragma mark - #pragma mark Accessors -(NSArray *)sliceWidths { return [[self cachedNumbersForField:CPPieChartFieldSliceWidthNormalized] sampleArray]; } -(void)setSliceWidths:(NSArray *)newSliceWidths { [self cacheNumbers:newSliceWidths forField:CPPieChartFieldSliceWidthNormalized]; [self updateNormalizedData]; } -(void)setPieRadius:(CGFloat)newPieRadius { if ( pieRadius != newPieRadius ) { pieRadius = ABS(newPieRadius); [self setNeedsDisplay]; [self setNeedsRelabel]; } } -(void)setPieInnerRadius:(CGFloat)newPieRadius { if ( pieInnerRadius != newPieRadius ) { pieInnerRadius = ABS(newPieRadius); [self setNeedsDisplay]; } } -(void)setStartAngle:(CGFloat)newAngle { if ( newAngle != startAngle ) { startAngle = newAngle; [self setNeedsDisplay]; [self setNeedsRelabel]; } } -(void)setSliceDirection:(CPPieDirection)newDirection { if ( newDirection != sliceDirection ) { sliceDirection = newDirection; [self setNeedsDisplay]; [self setNeedsRelabel]; } } -(void)setBorderLineStyle:(CPLineStyle *)newStyle { if ( borderLineStyle != newStyle ) { [borderLineStyle release]; borderLineStyle = [newStyle copy]; [self setNeedsDisplay]; } } -(void)setCenterAnchor:(CGPoint)newCenterAnchor { if ( !CGPointEqualToPoint(centerAnchor, newCenterAnchor) ) { centerAnchor = newCenterAnchor; [self setNeedsDisplay]; [self setNeedsRelabel]; } } -(CGFloat)sliceLabelOffset { return self.labelOffset; } -(void)setSliceLabelOffset:(CGFloat)newOffset { self.labelOffset = newOffset; } @end
08iteng-ipad
framework/Source/CPPieChart.m
Objective-C
bsd
26,218
#import "CPTestCase.h" @interface CPMutableNumericDataTypeConversionTests : CPTestCase { } @end
08iteng-ipad
framework/Source/CPMutableNumericDataTypeConversionTests.h
Objective-C
bsd
100
#import <Foundation/Foundation.h> #import "CPDefinitions.h" @class CPLayer; @class CPTextStyle; @interface CPAxisLabel : NSObject { @private CPLayer *contentLayer; CGFloat offset; CGFloat rotation; CPAlignment alignment; NSDecimal tickLocation; } @property (nonatomic, readwrite, retain) CPLayer *contentLayer; @property (nonatomic, readwrite, assign) CGFloat offset; @property (nonatomic, readwrite, assign) CGFloat rotation; @property (nonatomic, readwrite, assign) CPAlignment alignment; @property (nonatomic, readwrite) NSDecimal tickLocation; /// @name Initialization /// @{ -(id)initWithText:(NSString *)newText textStyle:(CPTextStyle *)style; -(id)initWithContentLayer:(CPLayer *)layer; /// @} /// @name Layout /// @{ -(void)positionRelativeToViewPoint:(CGPoint)point forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction; -(void)positionBetweenViewPoint:(CGPoint)firstPoint andViewPoint:(CGPoint)secondPoint forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction; /// @} @end
08iteng-ipad
framework/Source/CPAxisLabel.h
Objective-C
bsd
1,037
#import "CPThemeTests.h" #import "CPTheme.h" #import "CPXYGraph.h" #import "CPGraph.h" #import "CPExceptions.h" #import "CPDarkGradientTheme.h" #import "CPPlainBlackTheme.h" #import "CPPlainWhiteTheme.h" #import "CPStocksTheme.h" #import "CPDerivedXYGraph.h" @implementation CPThemeTests -(void)testSetGraphClassUsingCPXYGraphShouldWork { CPTheme *theme = [[CPTheme alloc] init]; [theme setGraphClass:[CPXYGraph class]]; STAssertEquals([CPXYGraph class], theme.graphClass, @"graphClass should be CPXYGraph"); [theme release]; } -(void)testSetGraphUsingDerivedClassShouldWork { CPTheme *theme = [[CPTheme alloc] init]; [theme setGraphClass:[CPDerivedXYGraph class]]; STAssertEquals([CPDerivedXYGraph class], theme.graphClass, @"graphClass should be CPDerivedXYGraph"); [theme release]; } -(void)testSetGraphUsingCPGraphShouldThrowException { CPTheme *theme = [[CPTheme alloc] init]; @try { STAssertThrowsSpecificNamed([theme setGraphClass:[CPGraph class]], NSException, CPException, @"Should raise CPException for wrong kind of class"); } @finally { STAssertNil(theme.graphClass, @"graphClass should be nil."); [theme release]; } } -(void)testThemeNamedRandomNameShouldReturnNil { CPTheme *theme = [CPTheme themeNamed:@"not a theme"]; STAssertNil(theme, @"Should be nil"); } -(void)testThemeNamedDarkGradientShouldReturnCPDarkGradientTheme { CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme]; STAssertTrue([theme isKindOfClass:[CPDarkGradientTheme class]], @"Should be CPDarkGradientTheme"); } -(void)testThemeNamedPlainBlackShouldReturnCPPlainBlackTheme { CPTheme *theme = [CPTheme themeNamed:kCPPlainBlackTheme]; STAssertTrue([theme isKindOfClass:[CPPlainBlackTheme class]], @"Should be CPPlainBlackTheme"); } -(void)testThemeNamedPlainWhiteShouldReturnCPPlainWhiteTheme { CPTheme *theme = [CPTheme themeNamed:kCPPlainWhiteTheme]; STAssertTrue([theme isKindOfClass:[CPPlainWhiteTheme class]], @"Should be CPPlainWhiteTheme"); } -(void)testThemeNamedStocksShouldReturnCPStocksTheme { CPTheme *theme = [CPTheme themeNamed:kCPStocksTheme]; STAssertTrue([theme isKindOfClass:[CPStocksTheme class]], @"Should be CPStocksTheme"); } @end
08iteng-ipad
framework/Source/CPThemeTests.m
Objective-C
bsd
2,185
#import "CPPlotGroup.h" #import "CPPlot.h" /** @brief Defines the coordinate system of a plot. **/ @implementation CPPlotGroup /** @property identifier * @brief An object used to identify the plot group in collections. **/ @synthesize identifier; #pragma mark - #pragma mark Initialize/Deallocate -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { identifier = nil; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPPlotGroup *theLayer = (CPPlotGroup *)layer; identifier = [theLayer->identifier retain]; } return self; } -(void)dealloc { [identifier release]; [super dealloc]; } #pragma mark - #pragma mark Organizing Plots /** @brief Add a plot to the default plot space. * @param plot The plot. **/ -(void)addPlot:(CPPlot *)plot { [self addSublayer:plot]; } -(void)removePlot:(CPPlot *)plot { if ( self == [plot superlayer] ) { [plot removeFromSuperlayer]; } } #pragma mark - #pragma mark Layout +(CGFloat)defaultZPosition { return CPDefaultZPositionPlotGroup; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { // nothing to draw } @end
08iteng-ipad
framework/Source/CPPlotGroup.m
Objective-C
bsd
1,207
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPStocksTheme : CPXYTheme { } @end
08iteng-ipad
framework/Source/CPStocksTheme.h
Objective-C
bsd
106
#import "CPMutableNumericData.h" #import "CPMutableNumericDataTests.h" #import "CPNumericData+TypeConversion.h" #import "CPExceptions.h" @implementation CPMutableNumericDataTests -(void)testNilShapeGivesSingleDimension { CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:[NSMutableData dataWithLength:1*sizeof(float)] dataTypeString:@"=f4" shape:nil]; NSUInteger actual = nd.numberOfDimensions; NSUInteger expected = 1; STAssertEquals(actual, expected, @"numberOfDimensions == 1"); expected = [nd.shape count]; STAssertEquals(actual, expected, @"numberOfDimensions == 1"); [nd release]; } -(void)testNumberOfDimensionsGivesShapeCount { id shape = [NSArray arrayWithObjects: [NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], (id)nil ]; NSUInteger nElems = 2*2*2; CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:[NSMutableData dataWithLength:nElems*sizeof(float)] dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:shape]; STAssertEquals(nd.numberOfDimensions, nd.shape.count, @"numberOfDimensions == shape.count == 3"); [nd release]; } -(void)testNilShapeCorrectElementCount { NSUInteger nElems = 13; CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:[NSMutableData dataWithLength:nElems*sizeof(float)] dataTypeString:@"=f4" shape:nil]; STAssertEquals(nd.numberOfDimensions, (NSUInteger)1, @"numberOfDimensions == 1"); NSUInteger prod = 1; for ( NSNumber *num in nd.shape ) { prod *= [num unsignedIntValue]; } STAssertEquals(prod, nElems, @"prod == nElems"); [nd release]; } -(void)testIllegalShapeRaisesException { id shape = [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], [NSNumber numberWithUnsignedInt:2], (id)nil]; NSUInteger nElems = 5; STAssertThrowsSpecificNamed([[CPMutableNumericData alloc] initWithData:[NSMutableData dataWithLength:nElems*sizeof(NSUInteger)] dataType:CPDataType(CPUnsignedIntegerDataType, sizeof(NSUInteger), NSHostByteOrder()) shape:shape], NSException, CPNumericDataException, @"Illegal shape should throw"); } -(void)testReturnsDataLength { CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:[NSMutableData dataWithLength:10*sizeof(float)] dataTypeString:@"=f4" shape:nil]; NSUInteger expected = 10*sizeof(float); NSUInteger actual = [nd length]; STAssertEquals(expected, actual, @"data length"); [nd release]; } -(void)testBytesEqualDataBytes { NSUInteger nElements = 10; NSMutableData *data = [NSMutableData dataWithLength:nElements*sizeof(NSInteger)]; NSInteger *intData = (NSInteger *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElements; i++ ) { intData[i] = i; } CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPIntegerDataType, sizeof(NSInteger), NSHostByteOrder()) shape:nil]; NSMutableData *expected = data; STAssertTrue([expected isEqualToData:nd.data], @"data isEqualToData:"); [nd release]; } -(void)testArchivingRoundTrip { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; CPMutableNumericData *nd2 = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:nd]]; STAssertTrue([nd.data isEqualToData:nd2.data], @"equal data"); CPNumericDataType ndType = nd.dataType; CPNumericDataType nd2Type = nd2.dataType; STAssertEquals(ndType.dataTypeFormat, nd2Type.dataTypeFormat, @"dataType.dataTypeFormat equal"); STAssertEquals(ndType.sampleBytes, nd2Type.sampleBytes, @"dataType.sampleBytes equal"); STAssertEquals(ndType.byteOrder, nd2Type.byteOrder, @"dataType.byteOrder equal"); STAssertEqualObjects(nd.shape, nd2.shape, @"shapes equal"); [nd release]; } -(void)testNumberOfSamplesCorrectForDataType { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEquals([nd numberOfSamples], nElems, @"numberOfSamples == nElems"); [nd release]; nElems = 10; data = [NSMutableData dataWithLength:nElems*sizeof(char)]; char *charSamples = (char *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { charSamples[i] = sin(i); } nd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPIntegerDataType, sizeof(char), NSHostByteOrder()) shape:nil]; STAssertEquals([nd numberOfSamples], nElems, @"numberOfSamples == nElems"); [nd release]; } -(void)testDataTypeAccessorsCorrectForDataType { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPMutableNumericData *nd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEquals([nd dataTypeFormat], CPFloatingPointDataType, @"dataTypeFormat"); STAssertEquals([nd sampleBytes], sizeof(float), @"sampleBytes"); STAssertEquals([nd byteOrder], NSHostByteOrder(), @"byteOrder"); [nd release]; } -(void)testConvertTypeConvertsType { NSUInteger numberOfSamples = 10; NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < numberOfSamples; i++ ) { samples[i] = sin(i); } CPMutableNumericData *fd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; CPNumericData *dd = [fd dataByConvertingToType:CPFloatingPointDataType sampleBytes:sizeof(double) byteOrder:NSHostByteOrder()]; [fd release]; const double *doubleSamples = (const double *)[dd.data bytes]; for ( NSUInteger i = 0; i < numberOfSamples; i++ ) { STAssertTrue(samples[i] == doubleSamples[i], @"(float)%g != (double)%g", samples[i], doubleSamples[i]); } } -(void)testSamplePointerCorrect { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sinf(i); } CPMutableNumericData *fd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEquals(((float *)[fd mutableBytes])+4, (float *)[fd samplePointer:4], @"%p,%p",samples+4, (float *)[fd samplePointer:4]); STAssertEquals(((float *)[fd mutableBytes]), (float *)[fd samplePointer:0], @""); STAssertEquals(((float *)[fd mutableBytes])+nElems-1, (float *)[fd samplePointer:nElems-1], @""); STAssertNil([fd samplePointer:nElems], @"too many samples"); [fd release]; } -(void)testSampleValueCorrect { NSUInteger nElems = 10; NSMutableData *data = [NSMutableData dataWithLength:nElems*sizeof(float)]; float *samples = (float *)[data mutableBytes]; for ( NSUInteger i = 0; i < nElems; i++ ) { samples[i] = sin(i); } CPMutableNumericData *fd = [[CPMutableNumericData alloc] initWithData:data dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder()) shape:nil]; STAssertEqualsWithAccuracy([[fd sampleValue:0] doubleValue], sin(0), 0.01, @"sample value"); STAssertEqualsWithAccuracy([[fd sampleValue:1] doubleValue], sin(1), 0.01, @"sample value"); [fd release]; } @end
08iteng-ipad
framework/Source/CPMutableNumericDataTests.m
Objective-C
bsd
8,593
#import "CPLineStyle.h" #import "CPLayer.h" #import "CPColor.h" #import "CPMutableLineStyle.h" /** @cond */ @interface CPLineStyle () @property (nonatomic, readwrite, assign) CGLineCap lineCap; @property (nonatomic, readwrite, assign) CGLineJoin lineJoin; @property (nonatomic, readwrite, assign) CGFloat miterLimit; @property (nonatomic, readwrite, assign) CGFloat lineWidth; @property (nonatomic, readwrite, retain) NSArray *dashPattern; @property (nonatomic, readwrite, assign) CGFloat patternPhase; @property (nonatomic, readwrite, retain) CPColor *lineColor; @end /** @endcond */ /** @brief Immutable wrapper for various line drawing properties. * * @see See Apple's <a href="http://developer.apple.com/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_paths/dq_paths.html#//apple_ref/doc/uid/TP30001066-CH211-TPXREF105">Quartz 2D</a> * and <a href="http://developer.apple.com/documentation/GraphicsImaging/Reference/CGContext/Reference/reference.html">CGContext</a> * documentation for more information about each of these properties. * * In general, you will want to create a CPMutableLineStyle if you want to customize properties. **/ @implementation CPLineStyle /** @property lineCap * @brief The style for the endpoints of lines drawn in a graphics context. **/ @synthesize lineCap; /** @property lineJoin * @brief The style for the joins of connected lines in a graphics context. **/ @synthesize lineJoin; /** @property miterLimit * @brief The miter limit for the joins of connected lines in a graphics context. **/ @synthesize miterLimit; /** @property lineWidth * @brief The line width for a graphics context. **/ @synthesize lineWidth; /** @property dashPattern * @brief The dash-and-space pattern for the line. **/ @synthesize dashPattern; /** @property patternPhase * @brief The starting phase of the line dash pattern. **/ @synthesize patternPhase; /** @property lineColor * @brief The current stroke color in a context. **/ @synthesize lineColor; #pragma mark - #pragma mark init/dealloc /** @brief Creates and returns a new CPLineStyle instance. * @return A new CPLineStyle instance. **/ +(id)lineStyle { return [[[self alloc] init] autorelease]; } -(id)init { if ( self = [super init] ) { lineCap = kCGLineCapButt; lineJoin = kCGLineJoinMiter; miterLimit = 10.0; lineWidth = 1.0; dashPattern = nil; patternPhase = 0.0; lineColor = [[CPColor blackColor] retain]; } return self; } -(void)dealloc { [lineColor release]; [dashPattern release]; [super dealloc]; } #pragma mark - #pragma mark Drawing /** @brief Sets all of the line drawing properties in the given graphics context. * @param theContext The graphics context. **/ -(void)setLineStyleInContext:(CGContextRef)theContext { CGContextSetLineCap(theContext, lineCap); CGContextSetLineJoin(theContext, lineJoin); CGContextSetMiterLimit(theContext, miterLimit); CGContextSetLineWidth(theContext, lineWidth); if ( dashPattern.count > 0 ) { CGFloat *dashLengths = (CGFloat *)calloc(dashPattern.count, sizeof(CGFloat)); NSUInteger dashCounter = 0; for ( NSNumber *currentDashLength in dashPattern ) { dashLengths[dashCounter++] = [currentDashLength doubleValue]; } CGContextSetLineDash(theContext, patternPhase, dashLengths, dashPattern.count); free(dashLengths); } CGContextSetStrokeColorWithColor(theContext, lineColor.cgColor); } #pragma mark - #pragma mark NSCopying methods -(id)copyWithZone:(NSZone *)zone { CPLineStyle *styleCopy = [[CPLineStyle allocWithZone:zone] init]; styleCopy->lineCap = self->lineCap; styleCopy->lineJoin = self->lineJoin; styleCopy->miterLimit = self->miterLimit; styleCopy->lineWidth = self->lineWidth; styleCopy->dashPattern = [self->dashPattern copy]; styleCopy->patternPhase = self->patternPhase; styleCopy->lineColor = [self->lineColor copy]; return styleCopy; } -(id)mutableCopyWithZone:(NSZone *)zone { CPLineStyle *styleCopy = [[CPMutableLineStyle allocWithZone:zone] init]; styleCopy->lineCap = self->lineCap; styleCopy->lineJoin = self->lineJoin; styleCopy->miterLimit = self->miterLimit; styleCopy->lineWidth = self->lineWidth; styleCopy->dashPattern = [self->dashPattern copy]; styleCopy->patternPhase = self->patternPhase; styleCopy->lineColor = [self->lineColor copy]; return styleCopy; } @end
08iteng-ipad
framework/Source/CPLineStyle.m
Objective-C
bsd
4,385
#import "CPTestCase.h" @interface CPNumericDataTypeConversionTests : CPTestCase { } @end
08iteng-ipad
framework/Source/CPNumericDataTypeConversionTests.h
Objective-C
bsd
93
#import <Foundation/Foundation.h> /** @category NSException(CPExtensions) * @brief Core Plot extensions to NSException. **/ @interface NSException(CPExtensions) +(void)raiseGenericFormat:(NSString*)fmt,...; @end
08iteng-ipad
framework/Source/NSExceptionExtensions.h
Objective-C
bsd
217
// Abstract class #import "CPBorderedLayer.h" #import "CPDefinitions.h" /// @file @class CPAxisSet; @class CPPlot; @class CPPlotAreaFrame; @class CPPlotSpace; @class CPTheme; @class CPMutableTextStyle; @class CPLayerAnnotation; /** * @brief Graph notifications **/ extern NSString * const CPGraphNeedsRedrawNotification; /** * @brief Enumeration of graph layers. **/ typedef enum _CPGraphLayerType { CPGraphLayerTypeMinorGridLines, ///< Minor grid lines. CPGraphLayerTypeMajorGridLines, ///< Major grid lines. CPGraphLayerTypeAxisLines, ///< Axis lines. CPGraphLayerTypePlots, ///< Plots. CPGraphLayerTypeAxisLabels, ///< Axis labels. CPGraphLayerTypeAxisTitles ///< Axis titles. } CPGraphLayerType; #pragma mark - @interface CPGraph : CPBorderedLayer { @private CPPlotAreaFrame *plotAreaFrame; NSMutableArray *plots; NSMutableArray *plotSpaces; NSString *title; CPMutableTextStyle *titleTextStyle; CPRectAnchor titlePlotAreaFrameAnchor; CGPoint titleDisplacement; CPLayerAnnotation *titleAnnotation; } /// @name Title /// @{ @property (nonatomic, readwrite, copy) NSString *title; @property (nonatomic, readwrite, copy) CPMutableTextStyle *titleTextStyle; @property (nonatomic, readwrite, assign) CGPoint titleDisplacement; @property (nonatomic, readwrite, assign) CPRectAnchor titlePlotAreaFrameAnchor; /// @} /// @name Layers /// @{ @property (nonatomic, readwrite, retain) CPAxisSet *axisSet; @property (nonatomic, readwrite, retain) CPPlotAreaFrame *plotAreaFrame; @property (nonatomic, readonly, retain) CPPlotSpace *defaultPlotSpace; @property (nonatomic, readwrite, retain) NSArray *topDownLayerOrder; /// @} /// @name Data Source /// @{ -(void)reloadData; -(void)reloadDataIfNeeded; /// @} /// @name Retrieving Plots /// @{ -(NSArray *)allPlots; -(CPPlot *)plotAtIndex:(NSUInteger)index; -(CPPlot *)plotWithIdentifier:(id <NSCopying>)identifier; /// @} /// @name Adding and Removing Plots /// @{ -(void)addPlot:(CPPlot *)plot; -(void)addPlot:(CPPlot *)plot toPlotSpace:(CPPlotSpace *)space; -(void)removePlot:(CPPlot *)plot; -(void)insertPlot:(CPPlot *)plot atIndex:(NSUInteger)index; -(void)insertPlot:(CPPlot *)plot atIndex:(NSUInteger)index intoPlotSpace:(CPPlotSpace *)space; /// @} /// @name Retrieving Plot Spaces /// @{ -(NSArray *)allPlotSpaces; -(CPPlotSpace *)plotSpaceAtIndex:(NSUInteger)index; -(CPPlotSpace *)plotSpaceWithIdentifier:(id <NSCopying>)identifier; /// @} /// @name Adding and Removing Plot Spaces /// @{ -(void)addPlotSpace:(CPPlotSpace *)space; -(void)removePlotSpace:(CPPlotSpace *)plotSpace; /// @} /// @name Themes /// @{ -(void)applyTheme:(CPTheme *)theme; /// @} @end #pragma mark - /** @category CPGraph(AbstractFactoryMethods) * @brief CPGraph abstract methods—must be overridden by subclasses **/ @interface CPGraph(AbstractFactoryMethods) /// @name Factory Methods /// @{ -(CPPlotSpace *)newPlotSpace; -(CPAxisSet *)newAxisSet; /// @} @end
08iteng-ipad
framework/Source/CPGraph.h
Objective-C
bsd
2,966
#import "CPAxis.h" #import "CPAxisSet.h" #import "CPGridLineGroup.h" #import "CPGridLines.h" #import "CPPlotArea.h" /** @brief A group of grid line layers. * * When using separate axis layers, this layer serves as the common superlayer for the grid line layers. * Otherwise, this layer handles the drawing for the grid lines. It supports mixing the two modes; * some axes can use separate grid line layers while others are handled by the grid line group. **/ @implementation CPGridLineGroup /** @property plotArea * @brief The plot area that this grid line group belongs to. **/ @synthesize plotArea; /** @property major * @brief If YES, draw the major grid lines, else draw the minor grid lines. **/ @synthesize major; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { plotArea = nil; major = NO; self.needsDisplayOnBoundsChange = YES; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPGridLineGroup *theLayer = (CPGridLineGroup *)layer; plotArea = theLayer->plotArea; major = theLayer->major; } return self; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { for ( CPAxis *axis in self.plotArea.axisSet.axes ) { if ( !axis.separateLayers ) { [axis drawGridLinesInContext:theContext isMajor:self.major]; } } } #pragma mark - #pragma mark Accessors -(void)setPlotArea:(CPPlotArea *)newPlotArea { if ( newPlotArea != plotArea ) { plotArea = newPlotArea; if ( plotArea ) { [self setNeedsDisplay]; } } } @end
08iteng-ipad
framework/Source/CPGridLineGroup.m
Objective-C
bsd
1,638
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPPlainWhiteTheme : CPXYTheme { } @end
08iteng-ipad
framework/Source/CPPlainWhiteTheme.h
Objective-C
bsd
110
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPDarkGradientTheme : CPXYTheme { } @end
08iteng-ipad
framework/Source/CPDarkGradientTheme.h
Objective-C
bsd
111
#import "CPPlainWhiteTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotAreaFrame.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPMutableLineStyle.h" #import "CPMutableTextStyle.h" #import "CPBorderedLayer.h" /** @brief Creates a CPXYGraph instance formatted with white backgrounds and black lines. **/ @implementation CPPlainWhiteTheme +(NSString *)defaultName { return kCPPlainWhiteTheme; } -(void)applyThemeToBackground:(CPXYGraph *)graph { graph.fill = [CPFill fillWithColor:[CPColor whiteColor]]; } -(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame { plotAreaFrame.fill = [CPFill fillWithColor:[CPColor whiteColor]]; CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor blackColor]; borderLineStyle.lineWidth = 1.0; plotAreaFrame.borderLineStyle = borderLineStyle; plotAreaFrame.cornerRadius = 0.0; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPMutableLineStyle *majorLineStyle = [CPMutableLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapButt; majorLineStyle.lineColor = [CPColor colorWithGenericGray:0.5]; majorLineStyle.lineWidth = 1.0; CPMutableLineStyle *minorLineStyle = [CPMutableLineStyle lineStyle]; minorLineStyle.lineCap = kCGLineCapButt; minorLineStyle.lineColor = [CPColor blackColor]; minorLineStyle.lineWidth = 1.0; CPXYAxis *x = axisSet.xAxis; CPMutableTextStyle *blackTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; blackTextStyle.color = [CPColor blackColor]; blackTextStyle.fontSize = 14.0; CPMutableTextStyle *minorTickBlackTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; minorTickBlackTextStyle.color = [CPColor blackColor]; minorTickBlackTextStyle.fontSize = 12.0; x.labelingPolicy = CPAxisLabelingPolicyFixedInterval; x.majorIntervalLength = CPDecimalFromDouble(0.5); x.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0); x.tickDirection = CPSignNone; x.minorTicksPerInterval = 4; x.majorTickLineStyle = majorLineStyle; x.minorTickLineStyle = minorLineStyle; x.axisLineStyle = majorLineStyle; x.majorTickLength = 7.0; x.minorTickLength = 5.0; x.labelTextStyle = blackTextStyle; x.minorTickLabelTextStyle = blackTextStyle; x.titleTextStyle = blackTextStyle; CPXYAxis *y = axisSet.yAxis; y.labelingPolicy = CPAxisLabelingPolicyFixedInterval; y.majorIntervalLength = CPDecimalFromDouble(0.5); y.minorTicksPerInterval = 4; y.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0); y.tickDirection = CPSignNone; y.majorTickLineStyle = majorLineStyle; y.minorTickLineStyle = minorLineStyle; y.axisLineStyle = majorLineStyle; y.majorTickLength = 7.0; y.minorTickLength = 5.0; y.labelTextStyle = blackTextStyle; y.minorTickLabelTextStyle = minorTickBlackTextStyle; y.titleTextStyle = blackTextStyle; } @end
08iteng-ipad
framework/Source/CPPlainWhiteTheme.m
Objective-C
bsd
3,022
// Based on CTGradient (http://blog.oofn.net/2006/01/15/gradients-in-cocoa/) // CTGradient is in public domain (Thanks Chad Weider!) /// @file #import <Foundation/Foundation.h> #import "CPDefinitions.h" /** * @brief A structure representing one node in a linked list of RGBA colors. **/ typedef struct _CPGradientElement { CPRGBAColor color; ///< Color CGFloat position; ///< Gradient position (0 ≤ position ≤ 1) struct _CPGradientElement *nextElement; ///< Pointer to the next CPGradientElement in the list (last element == NULL) } CPGradientElement; /** * @brief Enumeration of blending modes **/ typedef enum _CPBlendingMode { CPLinearBlendingMode, ///< Linear blending mode CPChromaticBlendingMode, ///< Chromatic blending mode CPInverseChromaticBlendingMode ///< Inverse chromatic blending mode } CPGradientBlendingMode; /** * @brief Enumeration of gradient types **/ typedef enum _CPGradientType { CPGradientTypeAxial, ///< Axial gradient CPGradientTypeRadial ///< Radial gradient } CPGradientType; @class CPColorSpace; @class CPColor; @interface CPGradient : NSObject <NSCopying, NSCoding> { @private CPColorSpace *colorspace; CPGradientElement *elementList; CPGradientBlendingMode blendingMode; CGFunctionRef gradientFunction; CGFloat angle; // angle in degrees CPGradientType gradientType; } @property (assign, readonly) CPGradientBlendingMode blendingMode; @property (assign) CGFloat angle; @property (assign) CPGradientType gradientType; /// @name Factory Methods /// @{ +(CPGradient *)gradientWithBeginningColor:(CPColor *)begin endingColor:(CPColor *)end; +(CPGradient *)gradientWithBeginningColor:(CPColor *)begin endingColor:(CPColor *)end beginningPosition:(CGFloat)beginningPosition endingPosition:(CGFloat)endingPosition; +(CPGradient *)aquaSelectedGradient; +(CPGradient *)aquaNormalGradient; +(CPGradient *)aquaPressedGradient; +(CPGradient *)unifiedSelectedGradient; +(CPGradient *)unifiedNormalGradient; +(CPGradient *)unifiedPressedGradient; +(CPGradient *)unifiedDarkGradient; +(CPGradient *)sourceListSelectedGradient; +(CPGradient *)sourceListUnselectedGradient; +(CPGradient *)rainbowGradient; +(CPGradient *)hydrogenSpectrumGradient; /// @} /// @name Modification /// @{ -(CPGradient *)gradientWithAlphaComponent:(CGFloat)alpha; -(CPGradient *)gradientWithBlendingMode:(CPGradientBlendingMode)mode; -(CPGradient *)addColorStop:(CPColor *)color atPosition:(CGFloat)position; // positions given relative to [0,1] -(CPGradient *)removeColorStopAtIndex:(NSUInteger)index; -(CPGradient *)removeColorStopAtPosition:(CGFloat)position; /// @} /// @name Information /// @{ -(CGColorRef)newColorStopAtIndex:(NSUInteger)index; -(CGColorRef)newColorAtPosition:(CGFloat)position; /// @} /// @name Drawing /// @{ -(void)drawSwatchInRect:(CGRect)rect inContext:(CGContextRef)context; -(void)fillRect:(CGRect)rect inContext:(CGContextRef)context; -(void)fillPathInContext:(CGContextRef)context; /// @} @end
08iteng-ipad
framework/Source/CPGradient.h
Objective-C
bsd
2,967
#import <Foundation/Foundation.h> /// @file @class CPLineStyle; @class CPFill; /** @brief Plot symbol types. **/ typedef enum _CPPlotSymbolType { CPPlotSymbolTypeNone, ///< No symbol. CPPlotSymbolTypeRectangle, ///< Rectangle symbol. CPPlotSymbolTypeEllipse, ///< Elliptical symbol. CPPlotSymbolTypeDiamond, ///< Diamond symbol. CPPlotSymbolTypeTriangle, ///< Triangle symbol. CPPlotSymbolTypeStar, ///< 5-point star symbol. CPPlotSymbolTypePentagon, ///< Pentagon symbol. CPPlotSymbolTypeHexagon, ///< Hexagon symbol. CPPlotSymbolTypeCross, ///< X symbol. CPPlotSymbolTypePlus, ///< Plus symbol. CPPlotSymbolTypeDash, ///< Dash symbol. CPPlotSymbolTypeSnow, ///< Snowflake symbol. CPPlotSymbolTypeCustom ///< Custom symbol. } CPPlotSymbolType; @interface CPPlotSymbol : NSObject <NSCopying> { @private CGSize size; CPPlotSymbolType symbolType; CPLineStyle *lineStyle; CPFill *fill; CGPathRef cachedSymbolPath; CGPathRef customSymbolPath; BOOL usesEvenOddClipRule; CGLayerRef cachedLayer; } @property (nonatomic, readwrite, assign) CGSize size; @property (nonatomic, readwrite, assign) CPPlotSymbolType symbolType; @property (nonatomic, readwrite, retain) CPLineStyle *lineStyle; @property (nonatomic, readwrite, retain) CPFill *fill; @property (nonatomic, readwrite, assign) CGPathRef customSymbolPath; @property (nonatomic, readwrite, assign) BOOL usesEvenOddClipRule; /// @name Factory Methods /// @{ +(CPPlotSymbol *)plotSymbol; +(CPPlotSymbol *)crossPlotSymbol; +(CPPlotSymbol *)ellipsePlotSymbol; +(CPPlotSymbol *)rectanglePlotSymbol; +(CPPlotSymbol *)plusPlotSymbol; +(CPPlotSymbol *)starPlotSymbol; +(CPPlotSymbol *)diamondPlotSymbol; +(CPPlotSymbol *)trianglePlotSymbol; +(CPPlotSymbol *)pentagonPlotSymbol; +(CPPlotSymbol *)hexagonPlotSymbol; +(CPPlotSymbol *)dashPlotSymbol; +(CPPlotSymbol *)snowPlotSymbol; +(CPPlotSymbol *)customPlotSymbolWithPath:(CGPathRef)aPath; /// @} /// @name Drawing /// @{ -(void)renderInContext:(CGContextRef)theContext atPoint:(CGPoint)center; -(void)renderAsVectorInContext:(CGContextRef)theContext atPoint:(CGPoint)center; /// @} @end
08iteng-ipad
framework/Source/CPPlotSymbol.h
Objective-C
bsd
2,126
#import <Foundation/Foundation.h> #import "CPFill.h" @interface _CPFillColor : CPFill <NSCopying, NSCoding> { @private CPColor *fillColor; } /// @name Initialization /// @{ -(id)initWithColor:(CPColor *)aCcolor; /// @} /// @name Drawing /// @{ -(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext; -(void)fillPathInContext:(CGContextRef)theContext; /// @} @end
08iteng-ipad
framework/Source/_CPFillColor.h
Objective-C
bsd
383
#import "CPAnnotationHostLayer.h" #import "CPAnnotation.h" #import "CPExceptions.h" /** @cond */ @interface CPAnnotationHostLayer() @property (nonatomic, readwrite, retain) NSMutableArray *mutableAnnotations; @end /** @endcond */ #pragma mark - /** @brief An annotation host layer is a container layer for annotations. * * Annotations can be added to and removed from an annotation layer. * * @todo More documentation needed. **/ @implementation CPAnnotationHostLayer /** @property annotations * @brief An array of annotations attached to this layer. **/ @dynamic annotations; @synthesize mutableAnnotations; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { mutableAnnotations = [[NSMutableArray alloc] init]; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPAnnotationHostLayer *theLayer = (CPAnnotationHostLayer *)layer; mutableAnnotations = [theLayer->mutableAnnotations retain]; } return self; } -(void)dealloc { [mutableAnnotations release]; [super dealloc]; } #pragma mark - #pragma mark Annotations -(NSArray *)annotations { return [[self.mutableAnnotations copy] autorelease]; } /** @brief Adds an annotation to the receiver. **/ -(void)addAnnotation:(CPAnnotation *)annotation { if ( annotation ) { [self.mutableAnnotations addObject:annotation]; annotation.annotationHostLayer = self; [annotation positionContentLayer]; } } /** @brief Removes an annotation from the receiver. **/ -(void)removeAnnotation:(CPAnnotation *)annotation { if ( [self.mutableAnnotations containsObject:annotation] ) { annotation.annotationHostLayer = nil; [self.mutableAnnotations removeObject:annotation]; } else { [NSException raise:CPException format:@"Tried to remove CPAnnotation from %@. Host layer was %@.", self, annotation.annotationHostLayer]; } } /** @brief Removes all annotations from the receiver. **/ -(void)removeAllAnnotations { NSMutableArray *allAnnotations = self.mutableAnnotations; for ( CPAnnotation *annotation in allAnnotations ) { annotation.annotationHostLayer = nil; } [allAnnotations removeAllObjects]; } #pragma mark - #pragma mark Layout -(NSSet *)sublayersExcludedFromAutomaticLayout { NSMutableSet *layers = [NSMutableSet set]; for ( CPAnnotation *annotation in self.mutableAnnotations ) { CALayer *content = annotation.contentLayer; if ( content ) { [layers addObject:content]; } } return layers; } -(void)layoutSublayers { [super layoutSublayers]; [self.mutableAnnotations makeObjectsPerformSelector:@selector(positionContentLayer)]; } @end
08iteng-ipad
framework/Source/CPAnnotationHostLayer.m
Objective-C
bsd
2,733
#import <Foundation/Foundation.h> /// @file /// @name Custom Exception Identifiers /// @{ extern NSString * const CPException; extern NSString * const CPDataException; extern NSString * const CPNumericDataException; /// @}
08iteng-ipad
framework/Source/CPExceptions.h
Objective-C
bsd
225
#import "_CPFillGradient.h" #import "CPGradient.h" /** @cond */ @interface _CPFillGradient() @property (nonatomic, readwrite, copy) CPGradient *fillGradient; @end /** @endcond */ /** @brief Draws CPGradient area fills. * * Drawing methods are provided to fill rectangular areas and arbitrary drawing paths. **/ @implementation _CPFillGradient /** @property fillGradient * @brief The fill gradient. **/ @synthesize fillGradient; #pragma mark - #pragma mark init/dealloc /** @brief Initializes a newly allocated _CPFillGradient object with the provided gradient. * @param aGradient The gradient. * @return The initialized _CPFillGradient object. **/ -(id)initWithGradient:(CPGradient *)aGradient { if ( self = [super init] ) { fillGradient = [aGradient retain]; } return self; } -(void)dealloc { [fillGradient release]; [super dealloc]; } #pragma mark - #pragma mark Drawing /** @brief Draws the gradient into the given graphics context inside the provided rectangle. * @param theRect The rectangle to draw into. * @param theContext The graphics context to draw into. **/ -(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext { [self.fillGradient fillRect:theRect inContext:theContext]; } /** @brief Draws the gradient into the given graphics context clipped to the current drawing path. * @param theContext The graphics context to draw into. **/ -(void)fillPathInContext:(CGContextRef)theContext { [self.fillGradient fillPathInContext:theContext]; } #pragma mark - #pragma mark NSCopying methods -(id)copyWithZone:(NSZone *)zone { _CPFillGradient *copy = [[[self class] allocWithZone:zone] init]; copy->fillGradient = [self->fillGradient copyWithZone:zone]; return copy; } #pragma mark - #pragma mark NSCoding methods -(Class)classForCoder { return [CPFill class]; } -(void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.fillGradient forKey:@"fillGradient"]; } -(id)initWithCoder:(NSCoder *)coder { if ( self = [super init] ) { fillGradient = [[coder decodeObjectForKey:@"fillGradient"] retain]; } return self; } @end
08iteng-ipad
framework/Source/_CPFillGradient.m
Objective-C
bsd
2,104
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> @interface CPColor : NSObject <NSCopying, NSCoding> { @private CGColorRef cgColor; } @property (nonatomic, readonly, assign) CGColorRef cgColor; /// @name Factory Methods /// @{ +(CPColor *)clearColor; +(CPColor *)whiteColor; +(CPColor *)lightGrayColor; +(CPColor *)grayColor; +(CPColor *)darkGrayColor; +(CPColor *)blackColor; +(CPColor *)redColor; +(CPColor *)greenColor; +(CPColor *)blueColor; +(CPColor *)cyanColor; +(CPColor *)yellowColor; +(CPColor *)magentaColor; +(CPColor *)orangeColor; +(CPColor *)purpleColor; +(CPColor *)brownColor; +(CPColor *)colorWithCGColor:(CGColorRef)newCGColor; +(CPColor *)colorWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha; +(CPColor *)colorWithGenericGray:(CGFloat)gray; /// @} /// @name Initialization /// @{ -(id)initWithCGColor:(CGColorRef)cgColor; -(id)initWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha; -(CPColor *)colorWithAlphaComponent:(CGFloat)alpha; /// @} @end
08iteng-ipad
framework/Source/CPColor.h
Objective-C
bsd
1,081
#import "NSExceptionExtensionsTests.h" #import "NSExceptionExtensions.h" @implementation NSExceptionExtensionsTests - (void)testRaiseGenericFormatRaisesExceptionWithFormat { NSString *expectedReason = @"reason %d"; STAssertThrowsSpecificNamed([NSException raiseGenericFormat:@""], NSException, NSGenericException, @""); @try { [NSException raiseGenericFormat:expectedReason, 2]; } @catch (NSException * e) { STAssertEqualObjects([e reason], @"reason 2", @""); } } @end
08iteng-ipad
framework/Source/NSExceptionExtensionsTests.m
Objective-C
bsd
511
#import <Foundation/Foundation.h> #import "CPTextStyle.h" @class CPColor; @interface CPMutableTextStyle : CPTextStyle { } @property(readwrite, copy, nonatomic) NSString *fontName; @property(readwrite, assign, nonatomic) CGFloat fontSize; @property(readwrite, copy, nonatomic) CPColor *color; @end
08iteng-ipad
framework/Source/CPMutableTextStyle.h
Objective-C
bsd
304
#import <Foundation/Foundation.h> #import "CPNumericDataType.h" #import "CPNumericData.h" @interface CPMutableNumericData : CPNumericData { } /// @name Data Buffer /// @{ @property (readonly) void *mutableBytes; /// @} /// @name Dimensions /// @{ @property (copy, readwrite) NSArray *shape; /// @} /// @name Factory Methods /// @{ +(CPMutableNumericData *)numericDataWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; +(CPMutableNumericData *)numericDataWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray; /// @} /// @name Initialization /// @{ -(id)initWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; /// @} @end
08iteng-ipad
framework/Source/CPMutableNumericData.h
Objective-C
bsd
822
#import <Foundation/Foundation.h> #import "CPNumericDataType.h" @interface CPNumericData : NSObject <NSCopying, NSMutableCopying, NSCoding> { @protected NSData *data; CPNumericDataType dataType; NSArray *shape; // array of dimension shapes (NSNumber<unsigned>) } /// @name Data Buffer /// @{ @property (copy, readonly) NSData *data; @property (readonly) const void *bytes; @property (readonly) NSUInteger length; /// @} /// @name Data Format /// @{ @property (assign, readonly) CPNumericDataType dataType; @property (readonly) CPDataTypeFormat dataTypeFormat; @property (readonly) size_t sampleBytes; @property (readonly) CFByteOrder byteOrder; /// @} /// @name Dimensions /// @{ @property (copy, readonly) NSArray *shape; @property (readonly) NSUInteger numberOfDimensions; @property (readonly) NSUInteger numberOfSamples; /// @} /// @name Factory Methods /// @{ +(CPNumericData *)numericDataWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; +(CPNumericData *)numericDataWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray; +(CPNumericData *)numericDataWithArray:(NSArray *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; +(CPNumericData *)numericDataWithArray:(NSArray *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray; /// @} /// @name Initialization /// @{ -(id)initWithData:(NSData *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; -(id)initWithData:(NSData *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray; -(id)initWithArray:(NSArray *)newData dataType:(CPNumericDataType)newDataType shape:(NSArray *)shapeArray; -(id)initWithArray:(NSArray *)newData dataTypeString:(NSString *)newDataTypeString shape:(NSArray *)shapeArray; /// @} /// @name Samples /// @{ -(void *)samplePointer:(NSUInteger)sample; -(NSNumber *)sampleValue:(NSUInteger)sample; -(NSArray *)sampleArray; /// @} @end
08iteng-ipad
framework/Source/CPNumericData.h
Objective-C
bsd
2,190
#import "CPGradient.h" #import "CPUtilities.h" #import "CPLayer.h" #import "CPColorSpace.h" #import "CPColor.h" #import <tgmath.h> /** @cond */ @interface CPGradient() @property (retain, readwrite) CPColorSpace *colorspace; @property (assign, readwrite) CPGradientBlendingMode blendingMode; -(void)commonInit; -(void)addElement:(CPGradientElement*)newElement; -(CGShadingRef)newAxialGradientInRect:(CGRect)rect; -(CGShadingRef)newRadialGradientInRect:(CGRect)rect context:(CGContextRef)context; -(CPGradientElement *)elementAtIndex:(NSUInteger)index; -(CPGradientElement)removeElementAtIndex:(NSUInteger)index; -(CPGradientElement)removeElementAtPosition:(CGFloat)position; -(void)removeAllElements; @end /** @endcond */ // C Fuctions for color blending static void linearEvaluation(void *info, const CGFloat *in, CGFloat *out); static void chromaticEvaluation(void *info, const CGFloat *in, CGFloat *out); static void inverseChromaticEvaluation(void *info, const CGFloat *in, CGFloat *out); static void transformRGB_HSV(CGFloat *components); static void transformHSV_RGB(CGFloat *components); static void resolveHSV(CGFloat *color1, CGFloat *color2); #pragma mark - /** @brief Draws color gradient fills. * * Based on CTGradient (http://blog.oofn.net/2006/01/15/gradients-in-cocoa/). * CTGradient is in public domain (Thanks Chad Weider!) * * @todo More documentation needed **/ @implementation CPGradient /** @property colorspace * @brief The colorspace for the gradient colors. **/ @synthesize colorspace; /** @property blendingMode * @brief The color blending mode used to create the gradient. **/ @synthesize blendingMode; /** @property angle * @brief The axis angle of an axial gradient, expressed in degrees. **/ @synthesize angle; /** @property gradientType * @brief The gradient type. **/ @synthesize gradientType; #pragma mark - #pragma mark Initialization -(id)init { if ( self = [super init] ) { [self commonInit]; self.blendingMode = CPLinearBlendingMode; angle = 0.0; gradientType = CPGradientTypeAxial; } return self; } -(void)commonInit { colorspace = [[CPColorSpace genericRGBSpace] retain]; elementList = NULL; } -(void)dealloc { [colorspace release]; CGFunctionRelease(gradientFunction); [self removeAllElements]; [super dealloc]; } -(void)finalize { CGFunctionRelease(gradientFunction); [self removeAllElements]; [super finalize]; } -(id)copyWithZone:(NSZone *)zone { CPGradient *copy = [[[self class] allocWithZone:zone] init]; CPGradientElement *currentElement = elementList; while (currentElement != NULL) { [copy addElement:currentElement]; currentElement = currentElement->nextElement; } copy.blendingMode = self.blendingMode; copy->angle = self->angle; copy->gradientType = self->gradientType; return copy; } -(void)encodeWithCoder:(NSCoder *)coder { if ( [coder allowsKeyedCoding] ) { NSUInteger count = 0; CPGradientElement *currentElement = elementList; while (currentElement != NULL) { [coder encodeValueOfObjCType:@encode(double) at:&(currentElement->color.red)]; [coder encodeValueOfObjCType:@encode(double) at:&(currentElement->color.green)]; [coder encodeValueOfObjCType:@encode(double) at:&(currentElement->color.blue)]; [coder encodeValueOfObjCType:@encode(double) at:&(currentElement->color.alpha)]; [coder encodeValueOfObjCType:@encode(double) at:&(currentElement->position)]; count++; currentElement = currentElement->nextElement; } [coder encodeInteger:count forKey:@"CPGradientElementCount"]; [coder encodeInt:blendingMode forKey:@"CPGradientBlendingMode"]; [coder encodeDouble:angle forKey:@"CPGradientAngle"]; [coder encodeInt:gradientType forKey:@"CPGradientType"]; } else { [NSException raise:NSInvalidArchiveOperationException format:@"Only supports NSKeyedArchiver coders"]; } } -(id)initWithCoder:(NSCoder *)coder { if ( self = [super init] ) { [self commonInit]; gradientType = [coder decodeIntForKey:@"CPGradientType"]; angle = [coder decodeDoubleForKey:@"CPGradientAngle"]; self.blendingMode = [coder decodeIntForKey:@"CPGradientBlendingMode"]; NSUInteger count = [coder decodeIntegerForKey:@"CPGradientElementCount"]; while (count != 0) { CPGradientElement newElement; [coder decodeValueOfObjCType:@encode(double) at:&(newElement.color.red)]; [coder decodeValueOfObjCType:@encode(double) at:&(newElement.color.green)]; [coder decodeValueOfObjCType:@encode(double) at:&(newElement.color.blue)]; [coder decodeValueOfObjCType:@encode(double) at:&(newElement.color.alpha)]; [coder decodeValueOfObjCType:@encode(double) at:&(newElement.position)]; count--; [self addElement:&newElement]; } } return self; } #pragma mark - #pragma mark Factory Methods /** @brief Creates and returns a new CPGradient instance initialized with an axial linear gradient between two given colors. * @param begin The beginning color. * @param end The ending color. * @return A new CPGradient instance initialized with an axial linear gradient between the two given colors. **/ +(CPGradient *)gradientWithBeginningColor:(CPColor *)begin endingColor:(CPColor *)end { return [self gradientWithBeginningColor:begin endingColor:end beginningPosition:0.0 endingPosition:1.0]; } /** @brief Creates and returns a new CPGradient instance initialized with an axial linear gradient between two given colors, at two given normalized positions. * @param begin The beginning color. * @param end The ending color. * @param beginningPosition The beginning position (0 ≤ beginningPosition ≤ 1). * @param endingPosition The ending position (0 ≤ endingPosition ≤ 1). * @return A new CPGradient instance initialized with an axial linear gradient between the two given colors, at two given normalized positions. **/ +(CPGradient *)gradientWithBeginningColor:(CPColor *)begin endingColor:(CPColor *)end beginningPosition:(CGFloat)beginningPosition endingPosition:(CGFloat)endingPosition { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; CPGradientElement color2; color1.color = CPRGBAColorFromCGColor(begin.cgColor); color2.color = CPRGBAColorFromCGColor(end.cgColor); color1.position = beginningPosition; color2.position = endingPosition; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the Aqua selected gradient. * @return A new CPGradient instance initialized with the Aqua selected gradient. **/ +(CPGradient *)aquaSelectedGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = 0.58; color1.color.green = 0.86; color1.color.blue = 0.98; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = 0.42; color2.color.green = 0.68; color2.color.blue = 0.90; color2.color.alpha = 1.00; color2.position = 0.5; CPGradientElement color3; color3.color.red = 0.64; color3.color.green = 0.80; color3.color.blue = 0.94; color3.color.alpha = 1.00; color3.position = 0.5; CPGradientElement color4; color4.color.red = 0.56; color4.color.green = 0.70; color4.color.blue = 0.90; color4.color.alpha = 1.00; color4.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; [newInstance addElement:&color3]; [newInstance addElement:&color4]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the Aqua normal gradient. * @return A new CPGradient instance initialized with the Aqua normal gradient. **/ +(CPGradient *)aquaNormalGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = color1.color.green = color1.color.blue = 0.95; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.83; color2.color.alpha = 1.00; color2.position = 0.5; CPGradientElement color3; color3.color.red = color3.color.green = color3.color.blue = 0.95; color3.color.alpha = 1.00; color3.position = 0.5; CPGradientElement color4; color4.color.red = color4.color.green = color4.color.blue = 0.92; color4.color.alpha = 1.00; color4.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; [newInstance addElement:&color3]; [newInstance addElement:&color4]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the Aqua pressed gradient. * @return A new CPGradient instance initialized with the Aqua pressed gradient. **/ +(CPGradient *)aquaPressedGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = color1.color.green = color1.color.blue = 0.80; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.64; color2.color.alpha = 1.00; color2.position = 0.5; CPGradientElement color3; color3.color.red = color3.color.green = color3.color.blue = 0.80; color3.color.alpha = 1.00; color3.position = 0.5; CPGradientElement color4; color4.color.red = color4.color.green = color4.color.blue = 0.77; color4.color.alpha = 1.00; color4.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; [newInstance addElement:&color3]; [newInstance addElement:&color4]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the unified selected gradient. * @return A new CPGradient instance initialized with the unified selected gradient. **/ +(CPGradient *)unifiedSelectedGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = color1.color.green = color1.color.blue = 0.85; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.95; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the unified normal gradient. * @return A new CPGradient instance initialized with the unified normal gradient. **/ +(CPGradient *)unifiedNormalGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = color1.color.green = color1.color.blue = 0.75; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.90; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the unified pressed gradient. * @return A new CPGradient instance initialized with the unified pressed gradient. **/ +(CPGradient *)unifiedPressedGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = color1.color.green = color1.color.blue = 0.60; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.75; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the unified dark gradient. * @return A new CPGradient instance initialized with the unified dark gradient. **/ +(CPGradient *)unifiedDarkGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = color1.color.green = color1.color.blue = 0.68; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.83; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the source list selected gradient. * @return A new CPGradient instance initialized with the source list selected gradient. **/ +(CPGradient *)sourceListSelectedGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = 0.06; color1.color.green = 0.37; color1.color.blue = 0.85; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = 0.30; color2.color.green = 0.60; color2.color.blue = 0.92; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with the source list unselected gradient. * @return A new CPGradient instance initialized with the source list unselected gradient. **/ +(CPGradient *)sourceListUnselectedGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = 0.43; color1.color.green = 0.43; color1.color.blue = 0.43; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = 0.60; color2.color.green = 0.60; color2.color.blue = 0.60; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with a rainbow gradient. * @return A new CPGradient instance initialized with a rainbow gradient. **/ +(CPGradient *)rainbowGradient { CPGradient *newInstance = [[self alloc] init]; CPGradientElement color1; color1.color.red = 1.00; color1.color.green = 0.00; color1.color.blue = 0.00; color1.color.alpha = 1.00; color1.position = 0.0; CPGradientElement color2; color2.color.red = 0.54; color2.color.green = 0.00; color2.color.blue = 1.00; color2.color.alpha = 1.00; color2.position = 1.0; [newInstance addElement:&color1]; [newInstance addElement:&color2]; newInstance.blendingMode = CPChromaticBlendingMode; return [newInstance autorelease]; } /** @brief Creates and returns a new CPGradient instance initialized with a hydrogen spectrum gradient. * @return A new CPGradient instance initialized with a hydrogen spectrum gradient. **/ +(CPGradient *)hydrogenSpectrumGradient { CPGradient *newInstance = [[self alloc] init]; struct {CGFloat hue; CGFloat position; CGFloat width;} colorBands[4]; colorBands[0].hue = 22; colorBands[0].position = 0.145; colorBands[0].width = 0.01; colorBands[1].hue = 200; colorBands[1].position = 0.71; colorBands[1].width = 0.008; colorBands[2].hue = 253; colorBands[2].position = 0.885; colorBands[2].width = 0.005; colorBands[3].hue = 275; colorBands[3].position = 0.965; colorBands[3].width = 0.003; for( NSUInteger i = 0; i < 4; i++ ) { CGFloat color[4]; color[0] = colorBands[i].hue - 180.0 * colorBands[i].width; color[1] = 1.0; color[2] = 0.001; color[3] = 1.0; transformHSV_RGB(color); CPGradientElement fadeIn; fadeIn.color.red = color[0]; fadeIn.color.green = color[1]; fadeIn.color.blue = color[2]; fadeIn.color.alpha = color[3]; fadeIn.position = colorBands[i].position - colorBands[i].width; color[0] = colorBands[i].hue; color[1] = 1.0; color[2] = 1.0; color[3] = 1.0; transformHSV_RGB(color); CPGradientElement band; band.color.red = color[0]; band.color.green = color[1]; band.color.blue = color[2]; band.color.alpha = color[3]; band.position = colorBands[i].position; color[0] = colorBands[i].hue + 180.0 * colorBands[i].width; color[1] = 1.0; color[2] = 0.001; color[3] = 1.0; transformHSV_RGB(color); CPGradientElement fadeOut; fadeOut.color.red = color[0]; fadeOut.color.green = color[1]; fadeOut.color.blue = color[2]; fadeOut.color.alpha = color[3]; fadeOut.position = colorBands[i].position + colorBands[i].width; [newInstance addElement:&fadeIn]; [newInstance addElement:&band]; [newInstance addElement:&fadeOut]; } newInstance.blendingMode = CPChromaticBlendingMode; return [newInstance autorelease]; } #pragma mark - #pragma mark Modification /** @brief Copies the current gradient and sets a new alpha value. * @param alpha The alpha component (0 ≤ alpha ≤ 1). * @return A copy of the current gradient with the new alpha value. **/ -(CPGradient *)gradientWithAlphaComponent:(CGFloat)alpha { CPGradient *newGradient = [[[self class] alloc] init]; CPGradientElement *curElement = elementList; CPGradientElement tempElement; while (curElement != NULL) { tempElement = *curElement; tempElement.color.alpha = alpha; [newGradient addElement:&tempElement]; curElement = curElement->nextElement; } newGradient.blendingMode = self.blendingMode; newGradient.angle = self.angle; newGradient.gradientType = self.gradientType; return [newGradient autorelease]; } /** @brief Copies the current gradient and sets a new blending mode. * @param mode The blending mode. * @return A copy of the current gradient with the new blending mode. **/ -(CPGradient *)gradientWithBlendingMode:(CPGradientBlendingMode)mode { CPGradient *newGradient = [self copy]; newGradient.blendingMode = mode; return [newGradient autorelease]; } /** @brief Copies the current gradient and adds a color stop. * * Adds a color stop with <tt>color</tt> at <tt>position</tt> in elementList. * If two elements are at the same position then it is added immediately after the one that was there already. * * @param color The color. * @param position The color stop position (0 ≤ position ≤ 1). * @return A copy of the current gradient with the new color stop. **/ -(CPGradient *)addColorStop:(CPColor *)color atPosition:(CGFloat)position { CPGradient *newGradient = [self copy]; CPGradientElement newGradientElement; //put the components of color into the newGradientElement - must make sure it is a RGB color (not Gray or CMYK) newGradientElement.color = CPRGBAColorFromCGColor(color.cgColor); newGradientElement.position = position; //Pass it off to addElement to take care of adding it to the elementList [newGradient addElement:&newGradientElement]; return [newGradient autorelease]; } /** @brief Copies the current gradient and removes the color stop at <tt>position</tt> from elementList. * @param position The color stop position (0 ≤ position ≤ 1). * @return A copy of the current gradient with the color stop removed. **/ -(CPGradient *)removeColorStopAtPosition:(CGFloat)position { CPGradient *newGradient = [self copy]; CPGradientElement removedElement = [newGradient removeElementAtPosition:position]; if ( isnan(removedElement.position) ) { [NSException raise:NSRangeException format:@"-[%@ removeColorStopAtPosition:]: no such colorStop at position (%g)", [self class], position]; } return [newGradient autorelease]; } /** @brief Copies the current gradient and removes the color stop at <tt>index</tt> from elementList. * @param index The color stop index. * @return A copy of the current gradient with the color stop removed. **/ -(CPGradient *)removeColorStopAtIndex:(NSUInteger)index { CPGradient *newGradient = [self copy]; CPGradientElement removedElement = [newGradient removeElementAtIndex:index]; if ( isnan(removedElement.position) ) { [NSException raise:NSRangeException format:@"-[%@ removeColorStopAtIndex:]: index (%i) beyond bounds", [self class], index]; } return [newGradient autorelease]; } #pragma mark - #pragma mark Information /** @brief Gets the color at color stop <tt>index</tt> from elementList. * @param index The color stop index. * @return The color at color stop <tt>index</tt>. **/ -(CGColorRef)newColorStopAtIndex:(NSUInteger)index { CPGradientElement *element = [self elementAtIndex:index]; if (element != NULL) { #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE CGFloat colorComponents[4] = {element->color.red, element->color.green, element->color.blue, element->color.alpha}; return CGColorCreate(self.colorspace.cgColorSpace, colorComponents); #else return CGColorCreateGenericRGB(element->color.red, element->color.green, element->color.blue, element->color.alpha); #endif } [NSException raise:NSRangeException format:@"-[%@ colorStopAtIndex:]: index (%i) beyond bounds", [self class], index]; return NULL; } /** @brief Gets the color at an arbitrary position in the gradient. * @param position The color stop position (0 ≤ position ≤ 1). * @return The color at <tt>position</tt> in gradient. **/ -(CGColorRef)newColorAtPosition:(CGFloat)position { CGFloat components[4] = {0.0, 0.0, 0.0, 0.0}; CGColorRef gradientColor; switch ( self.blendingMode ) { case CPLinearBlendingMode: linearEvaluation(&elementList, &position, components); break; case CPChromaticBlendingMode: chromaticEvaluation(&elementList, &position, components); break; case CPInverseChromaticBlendingMode: inverseChromaticEvaluation(&elementList, &position, components); break; } if ( 0.0 != components[3] ) { //undo premultiplication that CG requires #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE CGFloat colorComponents[4] = {components[0] / components[3], components[1] / components[3], components[2] / components[3], components[3]}; gradientColor = CGColorCreate(self.colorspace.cgColorSpace, colorComponents); #else gradientColor = CGColorCreateGenericRGB(components[0] / components[3], components[1] / components[3], components[2] / components[3], components[3]); #endif } else { #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE CGFloat colorComponents[4] = {components[0], components[1], components[2], components[3]}; gradientColor = CGColorCreate(self.colorspace.cgColorSpace, colorComponents); #else gradientColor = CGColorCreateGenericRGB(components[0], components[1], components[2], components[3]); #endif } return gradientColor; } #pragma mark - #pragma mark Drawing /** @brief Draws the gradient into the given graphics context inside the provided rectangle. * @param rect The rectangle to draw into. * @param context The graphics context to draw into. **/ -(void)drawSwatchInRect:(CGRect)rect inContext:(CGContextRef)context { [self fillRect:rect inContext:context]; } /** @brief Draws the gradient into the given graphics context inside the provided rectangle. * @param rect The rectangle to draw into. * @param context The graphics context to draw into. **/ -(void)fillRect:(CGRect)rect inContext:(CGContextRef)context { CGShadingRef myCGShading = NULL; CGContextSaveGState(context); CGContextClipToRect(context, *(CGRect *)&rect); switch ( self.gradientType ) { case CPGradientTypeAxial: myCGShading = [self newAxialGradientInRect:rect]; break; case CPGradientTypeRadial: myCGShading = [self newRadialGradientInRect:rect context:context]; break; } CGContextDrawShading(context, myCGShading); CGShadingRelease(myCGShading); CGContextRestoreGState(context); } /** @brief Draws the gradient into the given graphics context clipped to the current drawing path. * @param context The graphics context to draw into. **/ -(void)fillPathInContext:(CGContextRef)context { if ( !CGContextIsPathEmpty(context) ) { CGShadingRef myCGShading = NULL; CGContextSaveGState(context); CGRect bounds = CGContextGetPathBoundingBox(context); CGContextClip(context); switch ( self.gradientType ) { case CPGradientTypeAxial: myCGShading = [self newAxialGradientInRect:bounds]; break; case CPGradientTypeRadial: myCGShading = [self newRadialGradientInRect:bounds context:context]; break; } CGContextDrawShading(context, myCGShading); CGShadingRelease(myCGShading); CGContextRestoreGState(context); } } #pragma mark - #pragma mark Private Methods -(CGShadingRef)newAxialGradientInRect:(CGRect)rect { // First Calculate where the beginning and ending points should be CGPoint startPoint, endPoint; if ( self.angle == 0.0 ) { startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)); // right of rect endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect)); // left of rect } else if ( self.angle == 90.0 ) { startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)); // bottom of rect endPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect)); // top of rect } else { // ok, we'll do the calculations now CGFloat x, y; CGFloat sina, cosa, tana; CGFloat length; CGFloat deltax, deltay; CGFloat rangle = self.angle * M_PI / 180.0; //convert the angle to radians if ( fabs(tan(rangle)) <= 1.0 ) { //for range [-45,45], [135,225] x = CGRectGetWidth(rect); y = CGRectGetHeight(rect); sina = sin(rangle); cosa = cos(rangle); tana = tan(rangle); length = x / fabs(cosa) + (y - x * fabs(tana)) * fabs(sina); deltax = length * cosa / 2.0; deltay = length * sina / 2.0; } else { //for range [45,135], [225,315] x = CGRectGetHeight(rect); y = CGRectGetWidth(rect); rangle -= M_PI_2; sina = sin(rangle); cosa = cos(rangle); tana = tan(rangle); length = x / fabs(cosa) + (y - x * fabs(tana)) * fabs(sina); deltax = -length * sina / 2.0; deltay = length * cosa / 2.0; } startPoint = CGPointMake(CGRectGetMidX(rect) - deltax, CGRectGetMidY(rect) - deltay); endPoint = CGPointMake(CGRectGetMidX(rect) + deltax, CGRectGetMidY(rect) + deltay); } // Calls to CoreGraphics CGShadingRef myCGShading = CGShadingCreateAxial(self.colorspace.cgColorSpace, startPoint, endPoint, gradientFunction, false, false); return myCGShading; } -(CGShadingRef)newRadialGradientInRect:(CGRect)rect context:(CGContextRef)context { CGPoint startPoint, endPoint; CGFloat startRadius, endRadius; CGFloat scalex, scaley; startPoint = endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)); startRadius = -1.0; if ( CGRectGetHeight(rect)>CGRectGetWidth(rect) ) { scalex = CGRectGetWidth(rect)/CGRectGetHeight(rect); startPoint.x /= scalex; endPoint.x /= scalex; scaley = 1.0; endRadius = CGRectGetHeight(rect) / 2.0; } else { scalex = 1.0; scaley = CGRectGetHeight(rect) / CGRectGetWidth(rect); startPoint.y /= scaley; endPoint.y /= scaley; endRadius = CGRectGetWidth(rect) / 2.0; } CGContextScaleCTM(context, scalex, scaley); CGShadingRef myCGShading = CGShadingCreateRadial(self.colorspace.cgColorSpace, startPoint, startRadius, endPoint, endRadius, gradientFunction, true, true); return myCGShading; } -(void)setBlendingMode:(CPGradientBlendingMode)mode; { blendingMode = mode; // Choose what blending function to use void *evaluationFunction = NULL; switch ( blendingMode ) { case CPLinearBlendingMode: evaluationFunction = &linearEvaluation; break; case CPChromaticBlendingMode: evaluationFunction = &chromaticEvaluation; break; case CPInverseChromaticBlendingMode: evaluationFunction = &inverseChromaticEvaluation; break; } // replace the current CoreGraphics Function with new one if ( gradientFunction != NULL ) { CGFunctionRelease(gradientFunction); } CGFunctionCallbacks evaluationCallbackInfo = {0 , evaluationFunction, NULL}; // Version, evaluator function, cleanup function static const CGFloat input_value_range [2] = { 0, 1 }; // range for the evaluator input static const CGFloat output_value_ranges [8] = { 0, 1, 0, 1, 0, 1, 0, 1 }; // ranges for the evaluator output (4 returned values) gradientFunction = CGFunctionCreate(&elementList, //the two transition colors 1, input_value_range , //number of inputs (just fraction of progression) 4, output_value_ranges, //number of outputs (4 - RGBa) &evaluationCallbackInfo); //info for using the evaluator function } -(void)addElement:(CPGradientElement *)newElement { if ( elementList == NULL || newElement->position < elementList->position ) { CPGradientElement *tmpNext = elementList; elementList = malloc(sizeof(CPGradientElement)); if ( elementList ) { *elementList = *newElement; elementList->nextElement = tmpNext; } } else { CPGradientElement *curElement = elementList; while ( curElement->nextElement != NULL && !((curElement->position <= newElement->position) && (newElement->position < curElement->nextElement->position)) ) { curElement = curElement->nextElement; } CPGradientElement *tmpNext = curElement->nextElement; curElement->nextElement = malloc(sizeof(CPGradientElement)); *(curElement->nextElement) = *newElement; curElement->nextElement->nextElement = tmpNext; } } -(CPGradientElement)removeElementAtIndex:(NSUInteger)index { CPGradientElement removedElement; if ( elementList != NULL ) { if ( index == 0 ) { CPGradientElement *tmpNext = elementList; elementList = elementList->nextElement; removedElement = *tmpNext; free(tmpNext); return removedElement; } NSUInteger count = 1; //we want to start one ahead CPGradientElement *currentElement = elementList; while ( currentElement->nextElement != NULL ) { if ( count == index ) { CPGradientElement *tmpNext = currentElement->nextElement; currentElement->nextElement = currentElement->nextElement->nextElement; removedElement = *tmpNext; free(tmpNext); return removedElement; } count++; currentElement = currentElement->nextElement; } } // element is not found, return empty element removedElement.color.red = 0.0; removedElement.color.green = 0.0; removedElement.color.blue = 0.0; removedElement.color.alpha = 0.0; removedElement.position = NAN; removedElement.nextElement = NULL; return removedElement; } -(CPGradientElement)removeElementAtPosition:(CGFloat)position { CPGradientElement removedElement; if ( elementList != NULL ) { if ( elementList->position == position ) { CPGradientElement *tmpNext = elementList; elementList = elementList->nextElement; removedElement = *tmpNext; free(tmpNext); return removedElement; } else { CPGradientElement *curElement = elementList; while ( curElement->nextElement != NULL ) { if ( curElement->nextElement->position == position ) { CPGradientElement *tmpNext = curElement->nextElement; curElement->nextElement = curElement->nextElement->nextElement; removedElement = *tmpNext; free(tmpNext); return removedElement; } } } } // element is not found, return empty element removedElement.color.red = 0.0; removedElement.color.green = 0.0; removedElement.color.blue = 0.0; removedElement.color.alpha = 0.0; removedElement.position = NAN; removedElement.nextElement = NULL; return removedElement; } -(void)removeAllElements { while (elementList != NULL) { CPGradientElement *elementToRemove = elementList; elementList = elementList->nextElement; free(elementToRemove); } } -(CPGradientElement *)elementAtIndex:(NSUInteger)index { NSUInteger count = 0; CPGradientElement *currentElement = elementList; while ( currentElement != NULL ) { if ( count == index ) { return currentElement; } count++; currentElement = currentElement->nextElement; } return NULL; } #pragma mark - #pragma mark Core Graphics void linearEvaluation (void *info, const CGFloat *in, CGFloat *out) { CGFloat position = *in; if ( *(CPGradientElement **)info == NULL ) { out[0] = out[1] = out[2] = out[3] = 1.0; return; } //This grabs the first two colors in the sequence CPGradientElement *color1 = *(CPGradientElement **)info; CPGradientElement *color2 = color1->nextElement; //make sure first color and second color are on other sides of position while ( color2 != NULL && color2->position < position ) { color1 = color2; color2 = color1->nextElement; } //if we don't have another color then make next color the same color if ( color2 == NULL ) { color2 = color1; } //----------FailSafe settings---------- //color1->red = 1; color2->red = 0; //color1->green = 1; color2->green = 0; //color1->blue = 1; color2->blue = 0; //color1->alpha = 1; color2->alpha = 1; //color1->position = 0.5; //color2->position = 0.5; //------------------------------------- if ( position <= color1->position ) { out[0] = color1->color.red; out[1] = color1->color.green; out[2] = color1->color.blue; out[3] = color1->color.alpha; } else if ( position >= color2->position ) { out[0] = color2->color.red; out[1] = color2->color.green; out[2] = color2->color.blue; out[3] = color2->color.alpha; } else { //adjust position so that it goes from 0 to 1 in the range from color 1 & 2's position position = (position-color1->position)/(color2->position - color1->position); out[0] = (color2->color.red - color1->color.red )*position + color1->color.red; out[1] = (color2->color.green - color1->color.green)*position + color1->color.green; out[2] = (color2->color.blue - color1->color.blue )*position + color1->color.blue; out[3] = (color2->color.alpha - color1->color.alpha)*position + color1->color.alpha; } //Premultiply the color by the alpha. out[0] *= out[3]; out[1] *= out[3]; out[2] *= out[3]; } //Chromatic Evaluation - // This blends colors by their Hue, Saturation, and Value(Brightness) right now I just // transform the RGB values stored in the CPGradientElements to HSB, in the future I may // streamline it to avoid transforming in and out of HSB colorspace *for later* // // For the chromatic blend we shift the hue of color1 to meet the hue of color2. To do // this we will add to the hue's angle (if we subtract we'll be doing the inverse // chromatic...scroll down more for that). All we need to do is keep adding to the hue // until we wrap around the colorwheel and get to color2. void chromaticEvaluation(void *info, const CGFloat *in, CGFloat *out) { CGFloat position = *in; if ( *(CPGradientElement **)info == NULL ) { out[0] = out[1] = out[2] = out[3] = 1.0; return; } // This grabs the first two colors in the sequence CPGradientElement *color1 = *(CPGradientElement **)info; CPGradientElement *color2 = color1->nextElement; CGFloat c1[4]; CGFloat c2[4]; // make sure first color and second color are on other sides of position while ( color2 != NULL && color2->position < position ) { color1 = color2; color2 = color1->nextElement; } // if we don't have another color then make next color the same color if ( color2 == NULL ) { color2 = color1; } c1[0] = color1->color.red; c1[1] = color1->color.green; c1[2] = color1->color.blue; c1[3] = color1->color.alpha; c2[0] = color2->color.red; c2[1] = color2->color.green; c2[2] = color2->color.blue; c2[3] = color2->color.alpha; transformRGB_HSV(c1); transformRGB_HSV(c2); resolveHSV(c1,c2); if ( c1[0] > c2[0] ) { // if color1's hue is higher than color2's hue then c2[0] += 360.0; // we need to move c2 one revolution around the wheel } if ( position <= color1->position ) { out[0] = c1[0]; out[1] = c1[1]; out[2] = c1[2]; out[3] = c1[3]; } else if ( position >= color2->position ) { out[0] = c2[0]; out[1] = c2[1]; out[2] = c2[2]; out[3] = c2[3]; } else { //adjust position so that it goes from 0 to 1 in the range from color 1 & 2's position position = (position-color1->position)/(color2->position - color1->position); out[0] = (c2[0] - c1[0])*position + c1[0]; out[1] = (c2[1] - c1[1])*position + c1[1]; out[2] = (c2[2] - c1[2])*position + c1[2]; out[3] = (c2[3] - c1[3])*position + c1[3]; } transformHSV_RGB(out); //Premultiply the color by the alpha. out[0] *= out[3]; out[1] *= out[3]; out[2] *= out[3]; } // Inverse Chromatic Evaluation - // Inverse Chromatic is about the same story as Chromatic Blend, but here the Hue // is strictly decreasing, that is we need to get from color1 to color2 by decreasing // the 'angle' (i.e. 90º -> 180º would be done by subtracting 270º and getting -180º... // which is equivalent to 180º mod 360º void inverseChromaticEvaluation(void *info, const CGFloat *in, CGFloat *out) { CGFloat position = *in; if (*(CPGradientElement **)info == NULL) { out[0] = out[1] = out[2] = out[3] = 1; return; } // This grabs the first two colors in the sequence CPGradientElement *color1 = *(CPGradientElement **)info; CPGradientElement *color2 = color1->nextElement; CGFloat c1[4]; CGFloat c2[4]; //make sure first color and second color are on other sides of position while ( color2 != NULL && color2->position < position ) { color1 = color2; color2 = color1->nextElement; } // if we don't have another color then make next color the same color if ( color2 == NULL ) { color2 = color1; } c1[0] = color1->color.red; c1[1] = color1->color.green; c1[2] = color1->color.blue; c1[3] = color1->color.alpha; c2[0] = color2->color.red; c2[1] = color2->color.green; c2[2] = color2->color.blue; c2[3] = color2->color.alpha; transformRGB_HSV(c1); transformRGB_HSV(c2); resolveHSV(c1,c2); if ( c1[0] < c2[0] ) //if color1's hue is higher than color2's hue then c1[0] += 360.0; // we need to move c2 one revolution back on the wheel if ( position <= color1->position ) { out[0] = c1[0]; out[1] = c1[1]; out[2] = c1[2]; out[3] = c1[3]; } else if ( position >= color2->position ) { out[0] = c2[0]; out[1] = c2[1]; out[2] = c2[2]; out[3] = c2[3]; } else { //adjust position so that it goes from 0 to 1 in the range from color 1 & 2's position position = (position-color1->position)/(color2->position - color1->position); out[0] = (c2[0] - c1[0])*position + c1[0]; out[1] = (c2[1] - c1[1])*position + c1[1]; out[2] = (c2[2] - c1[2])*position + c1[2]; out[3] = (c2[3] - c1[3])*position + c1[3]; } transformHSV_RGB(out); // Premultiply the color by the alpha. out[0] *= out[3]; out[1] *= out[3]; out[2] *= out[3]; } void transformRGB_HSV(CGFloat *components) //H,S,B -> R,G,B { CGFloat H = NAN, S, V; CGFloat R = components[0]; CGFloat G = components[1]; CGFloat B = components[2]; CGFloat MAX = R > G ? (R > B ? R : B) : (G > B ? G : B); CGFloat MIN = R < G ? (R < B ? R : B) : (G < B ? G : B); if ( MAX == R ) { if ( G >= B ) { H = 60.0 * (G - B) / (MAX - MIN) + 0.0; } else { H = 60.0 * (G - B) / (MAX - MIN) + 360.0; } } else if ( MAX == G ) { H = 60 * (B - R) / (MAX - MIN) + 120.0; } else if ( MAX == B ) { H = 60 * (R - G) / (MAX - MIN) + 240.0; } S = MAX == 0 ? 0 : 1 - MIN/MAX; V = MAX; components[0] = H; components[1] = S; components[2] = V; } void transformHSV_RGB(CGFloat *components) //H,S,B -> R,G,B { CGFloat R = 0.0, G = 0.0, B = 0.0; CGFloat H = fmod(components[0], 360.0); //map to [0,360) CGFloat S = components[1]; CGFloat V = components[2]; int Hi = (int)floor(H / 60.0) % 6; CGFloat f = H / 60.0 - Hi; CGFloat p = V * (1.0 - S); CGFloat q = V * (1.0 - f * S); CGFloat t = V * (1.0 - (1.0 - f) * S); switch ( Hi) { case 0: R = V; G = t; B = p; break; case 1: R = q; G = V; B = p; break; case 2: R = p; G = V; B = t; break; case 3: R = p; G = q; B = V; break; case 4: R = t; G = p; B = V; break; case 5: R = V; G = p; B = q; break; } components[0] = R; components[1] = G; components[2] = B; } void resolveHSV(CGFloat *color1, CGFloat *color2) // H value may be undefined (i.e. graycale color) { // we want to fill it with a sensible value if ( isnan(color1[0]) && isnan(color2[0]) ) { color1[0] = color2[0] = 0; } else if ( isnan(color1[0]) ) { color1[0] = color2[0]; } else if ( isnan(color2[0]) ) { color2[0] = color1[0]; } } @end
08iteng-ipad
framework/Source/CPGradient.m
Objective-C
bsd
43,201
#import "CPExceptions.h" NSString * const CPException = @"CPException"; ///< General Core Plot exceptions. NSString * const CPDataException = @"CPDataException"; ///< Core Plot data exceptions. NSString * const CPNumericDataException = @"CPNumericDataException"; ///< Core Plot numeric data exceptions.
08iteng-ipad
framework/Source/CPExceptions.m
Objective-C
bsd
312
#import <Foundation/Foundation.h> #import "CPAxisSet.h" @class CPXYAxis; @interface CPXYAxisSet : CPAxisSet { } @property (nonatomic, readonly, retain) CPXYAxis *xAxis; @property (nonatomic, readonly, retain) CPXYAxis *yAxis; @end
08iteng-ipad
framework/Source/CPXYAxisSet.h
Objective-C
bsd
235
#import <stdlib.h> #import "CPMutableNumericData.h" #import "CPNumericData.h" #import "CPScatterPlot.h" #import "CPLineStyle.h" #import "CPPlotArea.h" #import "CPPlotSpace.h" #import "CPPlotSpaceAnnotation.h" #import "CPExceptions.h" #import "CPUtilities.h" #import "CPXYPlotSpace.h" #import "CPPlotSymbol.h" #import "CPFill.h" /// @name Binding Identifiers /// @{ NSString * const CPScatterPlotBindingXValues = @"xValues"; ///< X values. NSString * const CPScatterPlotBindingYValues = @"yValues"; ///< Y values. NSString * const CPScatterPlotBindingPlotSymbols = @"plotSymbols"; ///< Plot symbols. /// @} /** @cond */ @interface CPScatterPlot () @property (nonatomic, readwrite, copy) NSArray *xValues; @property (nonatomic, readwrite, copy) NSArray *yValues; @property (nonatomic, readwrite, retain) NSArray *plotSymbols; -(void)calculatePointsToDraw:(BOOL *)pointDrawFlags forPlotSpace:(CPXYPlotSpace *)plotSpace includeVisiblePointsOnly:(BOOL)visibleOnly; -(void)calculateViewPoints:(CGPoint *)viewPoints withDrawPointFlags:(BOOL *)drawPointFlags; -(void)alignViewPointsToUserSpace:(CGPoint *)viewPoints withContent:(CGContextRef)theContext drawPointFlags:(BOOL *)drawPointFlags; -(NSUInteger)extremeDrawnPointIndexForFlags:(BOOL *)pointDrawFlags extremeNumIsLowerBound:(BOOL)isLowerBound; -(CGPathRef)newDataLinePathForViewPoints:(CGPoint *)viewPoints indexRange:(NSRange)indexRange baselineYValue:(CGFloat)baselineYValue; CGFloat squareOfDistanceBetweenPoints(CGPoint point1, CGPoint point2); @end /** @endcond */ #pragma mark - /** @brief A two-dimensional scatter plot. **/ @implementation CPScatterPlot @dynamic xValues; @dynamic yValues; @synthesize plotSymbols; /** @property interpolation * @brief The interpolation algorithm used for lines between data points. * Default is CPScatterPlotInterpolationLinear **/ @synthesize interpolation; /** @property dataLineStyle * @brief The line style for the data line. * If nil, the line is not drawn. **/ @synthesize dataLineStyle; /** @property plotSymbol * @brief The plot symbol drawn at each point if the data source does not provide symbols. * If nil, no symbol is drawn. **/ @synthesize plotSymbol; /** @property areaFill * @brief The fill style for the area underneath the data line. * If nil, the area is not filled. **/ @synthesize areaFill; /** @property areaFill2 * @brief The fill style for the area above the data line. * If nil, the area is not filled. **/ @synthesize areaFill2; /** @property areaBaseValue * @brief The Y coordinate of the straight boundary of the area fill. * If not a number, the area is not filled. * * Typically set to the minimum value of the Y range, but it can be any value that gives the desired appearance. **/ @synthesize areaBaseValue; /** @property areaBaseValue2 * @brief The Y coordinate of the straight boundary of the secondary area fill. * If not a number, the area is not filled. * * Typically set to the maximum value of the Y range, but it can be any value that gives the desired appearance. **/ @synthesize areaBaseValue2; /** @property plotSymbolMarginForHitDetection * @brief A margin added to each side of a symbol when determining whether it has been hit. * * Default is zero. The margin is set in plot area view coordinates. **/ @synthesize plotSymbolMarginForHitDetection; #pragma mark - #pragma mark init/dealloc #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE #else +(void)initialize { if ( self == [CPScatterPlot class] ) { [self exposeBinding:CPScatterPlotBindingXValues]; [self exposeBinding:CPScatterPlotBindingYValues]; [self exposeBinding:CPScatterPlotBindingPlotSymbols]; } } #endif -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { dataLineStyle = [[CPLineStyle alloc] init]; plotSymbol = nil; areaFill = nil; areaFill2 = nil; areaBaseValue = [[NSDecimalNumber notANumber] decimalValue]; areaBaseValue = [[NSDecimalNumber notANumber] decimalValue]; plotSymbols = nil; plotSymbolMarginForHitDetection = 0.0f; interpolation = CPScatterPlotInterpolationLinear; self.labelField = CPScatterPlotFieldY; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPScatterPlot *theLayer = (CPScatterPlot *)layer; dataLineStyle = [theLayer->dataLineStyle retain]; plotSymbol = [theLayer->plotSymbol retain]; areaFill = [theLayer->areaFill retain]; areaFill2 = [theLayer->areaFill2 retain]; areaBaseValue = theLayer->areaBaseValue; areaBaseValue2 = theLayer->areaBaseValue2; plotSymbols = [theLayer->plotSymbols retain]; plotSymbolMarginForHitDetection = theLayer->plotSymbolMarginForHitDetection; interpolation = theLayer->interpolation; } return self; } -(void)dealloc { [dataLineStyle release]; [plotSymbol release]; [areaFill release]; [areaFill2 release]; [plotSymbols release]; [super dealloc]; } #pragma mark - #pragma mark Data Loading -(void)reloadDataInIndexRange:(NSRange)indexRange { [super reloadDataInIndexRange:indexRange]; if ( self.dataSource ) { id <CPScatterPlotDataSource> theDataSource = (id <CPScatterPlotDataSource>)self.dataSource; id newXValues = [self numbersFromDataSourceForField:CPScatterPlotFieldX recordIndexRange:indexRange]; [self cacheNumbers:newXValues forField:CPScatterPlotFieldX atRecordIndex:indexRange.location]; id newYValues = [self numbersFromDataSourceForField:CPScatterPlotFieldY recordIndexRange:indexRange]; [self cacheNumbers:newYValues forField:CPScatterPlotFieldY atRecordIndex:indexRange.location]; BOOL datasourceProvidesSymbolArray = [theDataSource respondsToSelector:@selector(symbolsForScatterPlot:recordIndexRange:)]; BOOL datasourceProvidesSymbols = [theDataSource respondsToSelector:@selector(symbolForScatterPlot:recordIndex:)]; if ( datasourceProvidesSymbolArray || datasourceProvidesSymbols ) { // Ensure the plot symbol array exists and is the right size NSMutableArray *symbols = (NSMutableArray *)self.plotSymbols; NSUInteger numberOfRecords = [theDataSource numberOfRecordsForPlot:self]; if ( !symbols ) { self.plotSymbols = [NSMutableArray array]; symbols = (NSMutableArray *)self.plotSymbols; } NSNull *nullObject = [NSNull null]; NSUInteger i = symbols.count; while ( i < numberOfRecords ) { [symbols addObject:nullObject]; i++; } // Update plot symbols if ( datasourceProvidesSymbolArray ) { [symbols replaceObjectsInRange:indexRange withObjectsFromArray:[theDataSource symbolsForScatterPlot:self recordIndexRange:indexRange]]; } else if ( datasourceProvidesSymbols ) { NSUInteger indexRangeEnd = indexRange.location + indexRange.length; for ( NSUInteger recordIndex = indexRange.location; recordIndex < indexRangeEnd; recordIndex++ ) { CPPlotSymbol *theSymbol = [theDataSource symbolForScatterPlot:self recordIndex:recordIndex]; if ( theSymbol ) { [symbols replaceObjectAtIndex:recordIndex withObject:theSymbol]; } else { [symbols replaceObjectAtIndex:recordIndex withObject:nullObject]; } } } } else { self.plotSymbols = nil; } } else { self.xValues = nil; self.yValues = nil; self.plotSymbols = nil; } } -(void)insertDataAtIndex:(NSUInteger)index numberOfRecords:(NSUInteger)numberOfRecords { NSMutableArray *symbols = (NSMutableArray *)self.plotSymbols; if ( index < symbols.count ) { NSNull *nullObject = [NSNull null]; NSUInteger endIndex = index + numberOfRecords; for ( NSUInteger i = index; i < endIndex; i++ ) { [symbols insertObject:nullObject atIndex:i]; } } [super insertDataAtIndex:index numberOfRecords:numberOfRecords]; } -(void)deleteDataInIndexRange:(NSRange)indexRange { [super deleteDataInIndexRange:indexRange]; NSMutableArray *symbols = (NSMutableArray *)self.plotSymbols; [symbols removeObjectsInRange:indexRange]; } #pragma mark - #pragma mark Symbols /** @brief Returns the plot symbol to use for a given index. * @param index The index of the record. * @return The plot symbol to use, or nil if no plot symbol should be drawn. **/ -(CPPlotSymbol *)plotSymbolForRecordIndex:(NSUInteger)index { CPPlotSymbol *symbol = self.plotSymbol; if ( index < self.plotSymbols.count ) symbol = [self.plotSymbols objectAtIndex:index]; if ( ![symbol isKindOfClass:[CPPlotSymbol class]] ) symbol = nil; // Account for NSNull values return symbol; } #pragma mark - #pragma mark Determining Which Points to Draw -(void)calculatePointsToDraw:(BOOL *)pointDrawFlags forPlotSpace:(CPXYPlotSpace *)xyPlotSpace includeVisiblePointsOnly:(BOOL)visibleOnly { NSUInteger dataCount = self.cachedDataCount; if ( dataCount == 0 ) return; if ( self.areaFill || self.areaFill2 || self.dataLineStyle.dashPattern ) { // show all points to preserve the line dash and area fills for ( NSUInteger i = 0; i < dataCount; i++ ) { pointDrawFlags[i] = YES; } } else { CPPlotRangeComparisonResult *xRangeFlags = malloc(dataCount * sizeof(CPPlotRangeComparisonResult)); CPPlotRangeComparisonResult *yRangeFlags = malloc(dataCount * sizeof(CPPlotRangeComparisonResult)); BOOL *nanFlags = malloc(dataCount * sizeof(BOOL)); CPPlotRange *xRange = xyPlotSpace.xRange; CPPlotRange *yRange = xyPlotSpace.yRange; // Determine where each point lies in relation to range if ( self.doublePrecisionCache ) { const double *xBytes = (const double *)[self cachedNumbersForField:CPScatterPlotFieldX].data.bytes; const double *yBytes = (const double *)[self cachedNumbersForField:CPScatterPlotFieldY].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const double x = *xBytes++; const double y = *yBytes++; xRangeFlags[i] = [xRange compareToDouble:x]; yRangeFlags[i] = [yRange compareToDouble:y]; nanFlags[i] = isnan(x) || isnan(y); } } else { // Determine where each point lies in relation to range const NSDecimal *xBytes = (const NSDecimal *)[self cachedNumbersForField:CPScatterPlotFieldX].data.bytes; const NSDecimal *yBytes = (const NSDecimal *)[self cachedNumbersForField:CPScatterPlotFieldY].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const NSDecimal *x = xBytes++; const NSDecimal *y = yBytes++; xRangeFlags[i] = [xRange compareToDecimal:*x]; yRangeFlags[i] = [yRange compareToDecimal:*y]; nanFlags[i] = NSDecimalIsNotANumber(x) || NSDecimalIsNotANumber(y); } } // Ensure that whenever the path crosses over a region boundary, both points // are included. This ensures no lines are left out that shouldn't be. pointDrawFlags[0] = (xRangeFlags[0] == CPPlotRangeComparisonResultNumberInRange && yRangeFlags[0] == CPPlotRangeComparisonResultNumberInRange && !nanFlags[0]); for ( NSUInteger i = 1; i < dataCount; i++ ) { pointDrawFlags[i] = NO; if ( !visibleOnly && !nanFlags[i-1] && !nanFlags[i] && ((xRangeFlags[i-1] != xRangeFlags[i]) || (yRangeFlags[i-1] != yRangeFlags[i])) ) { pointDrawFlags[i-1] = YES; pointDrawFlags[i] = YES; } else if ( (xRangeFlags[i] == CPPlotRangeComparisonResultNumberInRange) && (yRangeFlags[i] == CPPlotRangeComparisonResultNumberInRange) && !nanFlags[i]) { pointDrawFlags[i] = YES; } } free(xRangeFlags); free(yRangeFlags); free(nanFlags); } } -(void)calculateViewPoints:(CGPoint *)viewPoints withDrawPointFlags:(BOOL *)drawPointFlags { NSUInteger dataCount = self.cachedDataCount; CPPlotArea *thePlotArea = self.plotArea; CPPlotSpace *thePlotSpace = self.plotSpace; // Calculate points if ( self.doublePrecisionCache ) { const double *xBytes = (const double *)[self cachedNumbersForField:CPScatterPlotFieldX].data.bytes; const double *yBytes = (const double *)[self cachedNumbersForField:CPScatterPlotFieldY].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const double x = *xBytes++; const double y = *yBytes++; if ( !drawPointFlags[i] || isnan(x) || isnan(y) ) { viewPoints[i] = CGPointMake(NAN, NAN); } else { double plotPoint[2]; plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y; viewPoints[i] = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea]; } } } else { const NSDecimal *xBytes = (const NSDecimal *)[self cachedNumbersForField:CPScatterPlotFieldX].data.bytes; const NSDecimal *yBytes = (const NSDecimal *)[self cachedNumbersForField:CPScatterPlotFieldY].data.bytes; for ( NSUInteger i = 0; i < dataCount; i++ ) { const NSDecimal x = *xBytes++; const NSDecimal y = *yBytes++; if ( !drawPointFlags[i] || NSDecimalIsNotANumber(&x) || NSDecimalIsNotANumber(&y) ) { viewPoints[i] = CGPointMake(NAN, NAN); } else { NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y; viewPoints[i] = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea]; } } } } -(void)alignViewPointsToUserSpace:(CGPoint *)viewPoints withContent:(CGContextRef)theContext drawPointFlags:(BOOL *)drawPointFlags { NSUInteger dataCount = self.cachedDataCount; for ( NSUInteger i = 0; i < dataCount; i++ ) { if ( drawPointFlags[i] ) { viewPoints[i] = CPAlignPointToUserSpace(theContext, viewPoints[i]); } } } -(NSUInteger)extremeDrawnPointIndexForFlags:(BOOL *)pointDrawFlags extremeNumIsLowerBound:(BOOL)isLowerBound { NSInteger result = NSNotFound; NSInteger delta = (isLowerBound ? 1 : -1); NSUInteger dataCount = self.cachedDataCount; if ( dataCount > 0 ) { NSUInteger initialIndex = (isLowerBound ? 0 : dataCount - 1); for ( NSUInteger i = initialIndex; i < dataCount; i += delta ) { if ( pointDrawFlags[i] ) { result = i; break; } if ( (delta < 0) && (i == 0) ) break; } } return result; } #pragma mark - #pragma mark View Points CGFloat squareOfDistanceBetweenPoints(CGPoint point1, CGPoint point2) { CGFloat deltaX = point1.x - point2.x; CGFloat deltaY = point1.y - point2.y; CGFloat distanceSquared = deltaX * deltaX + deltaY * deltaY; return distanceSquared; } /** @brief Returns the index of the closest visible point to the point passed in. * @param viewPoint The reference point. * @return The index of the closest point, or NSNotFound if there is no visible point. **/ -(NSUInteger)indexOfVisiblePointClosestToPlotAreaPoint:(CGPoint)viewPoint { NSUInteger dataCount = self.cachedDataCount; CGPoint *viewPoints = malloc(dataCount * sizeof(CGPoint)); BOOL *drawPointFlags = malloc(dataCount * sizeof(BOOL)); [self calculatePointsToDraw:drawPointFlags forPlotSpace:(id)self.plotSpace includeVisiblePointsOnly:YES]; [self calculateViewPoints:viewPoints withDrawPointFlags:drawPointFlags]; NSUInteger result = [self extremeDrawnPointIndexForFlags:drawPointFlags extremeNumIsLowerBound:YES]; if ( result != NSNotFound ) { CGFloat minimumDistanceSquared = squareOfDistanceBetweenPoints(viewPoint, viewPoints[result]); for ( NSUInteger i = result + 1; i < dataCount; ++i ) { CGFloat distanceSquared = squareOfDistanceBetweenPoints(viewPoint, viewPoints[i]); if ( distanceSquared < minimumDistanceSquared ) { minimumDistanceSquared = distanceSquared; result = i; } } } free(viewPoints); free(drawPointFlags); return result; } /** @brief Returns the plot area view point of a visible point. * @param index The index of the point. * @return The view point of the visible point at the index passed. **/ -(CGPoint)plotAreaPointOfVisiblePointAtIndex:(NSUInteger)index { NSUInteger dataCount = self.cachedDataCount; CGPoint *viewPoints = malloc(dataCount * sizeof(CGPoint)); BOOL *drawPointFlags = malloc(dataCount * sizeof(BOOL)); [self calculatePointsToDraw:drawPointFlags forPlotSpace:(id)self.plotSpace includeVisiblePointsOnly:YES]; [self calculateViewPoints:viewPoints withDrawPointFlags:drawPointFlags]; CGPoint result = viewPoints[index]; free(viewPoints); free(drawPointFlags); return result; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { CPMutableNumericData *xValueData = [self cachedNumbersForField:CPScatterPlotFieldX]; CPMutableNumericData *yValueData = [self cachedNumbersForField:CPScatterPlotFieldY]; if ( xValueData == nil || yValueData == nil ) return; NSUInteger dataCount = self.cachedDataCount; if ( dataCount == 0 ) return; if ( !(self.dataLineStyle || self.areaFill || self.areaFill2 || self.plotSymbol || self.plotSymbols.count) ) return; if ( xValueData.numberOfSamples != yValueData.numberOfSamples ) { [NSException raise:CPException format:@"Number of x and y values do not match"]; } [super renderAsVectorInContext:theContext]; // Calculate view points, and align to user space CGPoint *viewPoints = malloc(dataCount * sizeof(CGPoint)); BOOL *drawPointFlags = malloc(dataCount * sizeof(BOOL)); CPXYPlotSpace *thePlotSpace = (CPXYPlotSpace *)self.plotSpace; [self calculatePointsToDraw:drawPointFlags forPlotSpace:thePlotSpace includeVisiblePointsOnly:NO]; [self calculateViewPoints:viewPoints withDrawPointFlags:drawPointFlags]; [self alignViewPointsToUserSpace:viewPoints withContent:theContext drawPointFlags:drawPointFlags]; // Get extreme points NSUInteger lastDrawnPointIndex = [self extremeDrawnPointIndexForFlags:drawPointFlags extremeNumIsLowerBound:NO]; NSUInteger firstDrawnPointIndex = [self extremeDrawnPointIndexForFlags:drawPointFlags extremeNumIsLowerBound:YES]; if ( firstDrawnPointIndex != NSNotFound ) { NSRange viewIndexRange = NSMakeRange(firstDrawnPointIndex, lastDrawnPointIndex - firstDrawnPointIndex); // Draw fills NSDecimal theAreaBaseValue; CPFill *theFill; for ( NSUInteger i = 0; i < 2; i++ ) { switch ( i ) { case 0: theAreaBaseValue = self.areaBaseValue; theFill = self.areaFill; break; case 1: theAreaBaseValue = self.areaBaseValue2; theFill = self.areaFill2; break; default: break; } if ( theFill && (!NSDecimalIsNotANumber(&theAreaBaseValue)) ) { NSNumber *xValue = [xValueData sampleValue:firstDrawnPointIndex]; NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = [xValue decimalValue]; plotPoint[CPCoordinateY] = theAreaBaseValue; CGPoint baseLinePoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:self.plotArea]; CGPathRef dataLinePath = [self newDataLinePathForViewPoints:viewPoints indexRange:viewIndexRange baselineYValue:baseLinePoint.y]; CGContextBeginPath(theContext); CGContextAddPath(theContext, dataLinePath); [theFill fillPathInContext:theContext]; CGPathRelease(dataLinePath); } } // Draw line if ( self.dataLineStyle ) { CGPathRef dataLinePath = [self newDataLinePathForViewPoints:viewPoints indexRange:viewIndexRange baselineYValue:NAN]; CGContextBeginPath(theContext); CGContextAddPath(theContext, dataLinePath); [self.dataLineStyle setLineStyleInContext:theContext]; CGContextStrokePath(theContext); CGPathRelease(dataLinePath); } // Draw plot symbols if ( self.plotSymbol || self.plotSymbols.count ) { if ( self.useFastRendering ) { for ( NSUInteger i = firstDrawnPointIndex; i <= lastDrawnPointIndex; i++ ) { if ( drawPointFlags[i] ) { CPPlotSymbol *currentSymbol = [self plotSymbolForRecordIndex:i]; [currentSymbol renderInContext:theContext atPoint:viewPoints[i]]; } } } else { for ( NSUInteger i = firstDrawnPointIndex; i <= lastDrawnPointIndex; i++ ) { if ( drawPointFlags[i] ) { CPPlotSymbol *currentSymbol = [self plotSymbolForRecordIndex:i]; [currentSymbol renderAsVectorInContext:theContext atPoint:viewPoints[i]]; } } } } } free(viewPoints); free(drawPointFlags); } -(CGPathRef)newDataLinePathForViewPoints:(CGPoint *)viewPoints indexRange:(NSRange)indexRange baselineYValue:(CGFloat)baselineYValue { CGMutablePathRef dataLinePath = CGPathCreateMutable(); CPScatterPlotInterpolation theInterpolation = self.interpolation; BOOL lastPointSkipped = YES; CGFloat firstXValue = 0.0; CGFloat lastXValue = 0.0; NSUInteger lastDrawnPointIndex = NSMaxRange(indexRange); for ( NSUInteger i = indexRange.location; i <= lastDrawnPointIndex; i++ ) { CGPoint viewPoint = viewPoints[i]; if ( isnan(viewPoint.x) || isnan(viewPoint.y) ) { if ( !lastPointSkipped ) { if ( !isnan(baselineYValue) ) { CGPathAddLineToPoint(dataLinePath, NULL, lastXValue, baselineYValue); CGPathAddLineToPoint(dataLinePath, NULL, firstXValue, baselineYValue); CGPathCloseSubpath(dataLinePath); } lastPointSkipped = YES; } } else { if ( lastPointSkipped ) { CGPathMoveToPoint(dataLinePath, NULL, viewPoint.x, viewPoint.y); lastPointSkipped = NO; firstXValue = viewPoint.x; } else { switch ( theInterpolation ) { case CPScatterPlotInterpolationLinear: CGPathAddLineToPoint(dataLinePath, NULL, viewPoint.x, viewPoint.y); break; case CPScatterPlotInterpolationStepped: CGPathAddLineToPoint(dataLinePath, NULL, viewPoint.x, viewPoints[i-1].y); CGPathAddLineToPoint(dataLinePath, NULL, viewPoint.x, viewPoint.y); break; case CPScatterPlotInterpolationHistogram: { CGFloat x = (viewPoints[i-1].x + viewPoints[i].x) / 2.0; CGPathAddLineToPoint(dataLinePath, NULL, x, viewPoints[i-1].y); CGPathAddLineToPoint(dataLinePath, NULL, x, viewPoint.y); CGPathAddLineToPoint(dataLinePath, NULL, viewPoint.x, viewPoint.y); } break; default: [NSException raise:CPException format:@"Interpolation method not supported in scatter plot."]; break; } } lastXValue = viewPoint.x; } } if ( !lastPointSkipped && !isnan(baselineYValue) ) { CGPathAddLineToPoint(dataLinePath, NULL, lastXValue, baselineYValue); CGPathAddLineToPoint(dataLinePath, NULL, firstXValue, baselineYValue); CGPathCloseSubpath(dataLinePath); } return dataLinePath; } #pragma mark - #pragma mark Fields -(NSUInteger)numberOfFields { return 2; } -(NSArray *)fieldIdentifiers { return [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt:CPScatterPlotFieldX], [NSNumber numberWithUnsignedInt:CPScatterPlotFieldY], nil]; } -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord { NSArray *result = nil; switch (coord) { case CPCoordinateX: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:CPScatterPlotFieldX]]; break; case CPCoordinateY: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:CPScatterPlotFieldY]]; break; default: [NSException raise:CPException format:@"Invalid coordinate passed to fieldIdentifiersForCoordinate:"]; break; } return result; } #pragma mark - #pragma mark Data Labels -(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index { NSNumber *xValue = [self cachedNumberForField:CPScatterPlotFieldX recordIndex:index]; NSNumber *yValue = [self cachedNumberForField:CPScatterPlotFieldY recordIndex:index]; BOOL positiveDirection = YES; CPPlotRange *yRange = [self.plotSpace plotRangeForCoordinate:CPCoordinateY]; if ( CPDecimalLessThan(yRange.length, CPDecimalFromInteger(0)) ) { positiveDirection = !positiveDirection; } label.anchorPlotPoint = [NSArray arrayWithObjects:xValue, yValue, nil]; label.contentLayer.hidden = isnan([xValue doubleValue]) || isnan([yValue doubleValue]); if ( positiveDirection ) { label.displacement = CGPointMake(0.0, self.labelOffset); } else { label.displacement = CGPointMake(0.0, -self.labelOffset); } } #pragma mark - #pragma mark Responder Chain and User interaction -(BOOL)pointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL result = NO; if ( !self.graph || !self.plotArea ) return NO; id <CPScatterPlotDelegate> theDelegate = self.delegate; if ( [theDelegate respondsToSelector:@selector(scatterPlot:plotSymbolWasSelectedAtRecordIndex:)] ) { // Inform delegate if a point was hit CGPoint plotAreaPoint = [self.graph convertPoint:interactionPoint toLayer:self.plotArea]; NSUInteger index = [self indexOfVisiblePointClosestToPlotAreaPoint:plotAreaPoint]; CGPoint center = [self plotAreaPointOfVisiblePointAtIndex:index]; CPPlotSymbol *symbol = [self plotSymbolForRecordIndex:index]; CGRect symbolRect = CGRectZero; symbolRect.size = symbol.size; symbolRect.size.width += 2.0 * plotSymbolMarginForHitDetection; symbolRect.size.height += 2.0 * plotSymbolMarginForHitDetection; symbolRect.origin = CGPointMake(center.x - 0.5 * CGRectGetWidth(symbolRect), center.y - 0.5 * CGRectGetHeight(symbolRect)); if ( CGRectContainsPoint(symbolRect, plotAreaPoint) ) { [theDelegate scatterPlot:self plotSymbolWasSelectedAtRecordIndex:index]; result = YES; } } else { result = [super pointingDeviceDownEvent:event atPoint:interactionPoint]; } return result; } #pragma mark - #pragma mark Accessors -(void)setInterpolation:(CPScatterPlotInterpolation)newInterpolation { if ( newInterpolation != interpolation ) { interpolation = newInterpolation; [self setNeedsDisplay]; } } -(void)setPlotSymbol:(CPPlotSymbol *)aSymbol { if ( aSymbol != plotSymbol ) { [plotSymbol release]; plotSymbol = [aSymbol copy]; [self setNeedsDisplay]; } } -(void)setDataLineStyle:(CPLineStyle *)newLineStyle { if ( dataLineStyle != newLineStyle ) { [dataLineStyle release]; dataLineStyle = [newLineStyle copy]; [self setNeedsDisplay]; } } -(void)setAreaFill:(CPFill *)newFill { if ( newFill != areaFill ) { [areaFill release]; areaFill = [newFill copy]; [self setNeedsDisplay]; } } -(void)setAreaFill2:(CPFill *)newFill { if ( newFill != areaFill2 ) { [areaFill2 release]; areaFill2 = [newFill copy]; [self setNeedsDisplay]; } } -(void)setAreaBaseValue:(NSDecimal)newAreaBaseValue { if ( CPDecimalEquals(areaBaseValue, newAreaBaseValue) ) { return; } areaBaseValue = newAreaBaseValue; [self setNeedsDisplay]; } -(void)setAreaBaseValue2:(NSDecimal)newAreaBaseValue { if ( CPDecimalEquals(areaBaseValue2, newAreaBaseValue) ) { return; } areaBaseValue2 = newAreaBaseValue; [self setNeedsDisplay]; } -(void)setXValues:(NSArray *)newValues { [self cacheNumbers:newValues forField:CPScatterPlotFieldX]; } -(NSArray *)xValues { return [[self cachedNumbersForField:CPScatterPlotFieldX] sampleArray]; } -(void)setYValues:(NSArray *)newValues { [self cacheNumbers:newValues forField:CPScatterPlotFieldY]; } -(NSArray *)yValues { return [[self cachedNumbersForField:CPScatterPlotFieldY] sampleArray]; } -(void)setPlotSymbols:(NSArray *)newSymbols { if ( newSymbols != plotSymbols ) { [plotSymbols release]; plotSymbols = [newSymbols mutableCopy]; [self setNeedsDisplay]; } } @end
08iteng-ipad
framework/Source/CPScatterPlot.m
Objective-C
bsd
27,251
#import "CPTestCase.h" #import "CPPlot.h" @class CPPlotRange; @class CPPlot; @interface CPDataSourceTestCase : CPTestCase <CPPlotDataSource> { @private NSArray *xData, *yData; CPPlotRange *xRange, *yRange; NSMutableArray *plots; NSUInteger nRecords; } @property (copy,readwrite) NSArray *xData; @property (copy,readwrite) NSArray *yData; @property (assign,readwrite) NSUInteger nRecords; @property (retain,readonly) CPPlotRange * xRange; @property (retain,readonly) CPPlotRange * yRange; @property (retain,readwrite) NSMutableArray *plots; -(void)buildData; -(void)addPlot:(CPPlot*)newPlot; @end
08iteng-ipad
framework/Source/CPDataSourceTestCase.h
Objective-C
bsd
628
#import "NSNumberExtensions.h" @implementation NSNumber(CPExtensions) /** @brief Returns the value of the receiver as an NSDecimalNumber. * @return The value of the receiver as an NSDecimalNumber. **/ -(NSDecimalNumber *)decimalNumber { if ([self isMemberOfClass:[NSDecimalNumber class]]) { return (NSDecimalNumber *)self; } return [NSDecimalNumber decimalNumberWithDecimal:[self decimalValue]]; } @end
08iteng-ipad
framework/Source/NSNumberExtensions.m
Objective-C
bsd
428
#import "CPLayer.h" @class CPPlot; @interface CPPlotGroup : CPLayer { @private id <NSCopying, NSObject> identifier; } @property (nonatomic, readwrite, copy) id <NSCopying, NSObject> identifier; /// @name Adding and Removing Plots /// @{ -(void)addPlot:(CPPlot *)plot; -(void)removePlot:(CPPlot *)plot; /// @} @end
08iteng-ipad
framework/Source/CPPlotGroup.h
Objective-C
bsd
322
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPSlateTheme : CPXYTheme { } @end
08iteng-ipad
framework/Source/CPSlateTheme.h
Objective-C
bsd
104
#import "CPPolarPlotSpace.h" /** @brief A plot space using a two-dimensional polar coordinate system. * @note Not implemented. * @todo Implement CPPolarPlotSpace. **/ @implementation CPPolarPlotSpace @end
08iteng-ipad
framework/Source/CPPolarPlotSpace.m
Objective-C
bsd
211
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> @class CPAnnotationHostLayer; @class CPLayer; @interface CPAnnotation : NSObject { @private __weak CPAnnotationHostLayer *annotationHostLayer; CPLayer *contentLayer; CGPoint contentAnchorPoint; CGPoint displacement; CGFloat rotation; } @property (nonatomic, readwrite, retain) CPLayer *contentLayer; @property (nonatomic, readwrite, assign) __weak CPAnnotationHostLayer *annotationHostLayer; @property (nonatomic, readwrite, assign) CGPoint contentAnchorPoint; @property (nonatomic, readwrite, assign) CGPoint displacement; @property (nonatomic, readwrite, assign) CGFloat rotation; @end #pragma mark - /** @category CPAnnotation(AbstractMethods) * @brief CPAnnotation abstract methods—must be overridden by subclasses. **/ @interface CPAnnotation(AbstractMethods) -(void)positionContentLayer; @end
08iteng-ipad
framework/Source/CPAnnotation.h
Objective-C
bsd
884
#import <Foundation/Foundation.h> #import "CPTheme.h" @interface CPXYTheme : CPTheme { } @end
08iteng-ipad
framework/Source/CPXYTheme.h
Objective-C
bsd
98
#import "CPTheme.h" #import "CPExceptions.h" #import "CPDarkGradientTheme.h" #import "CPPlainBlackTheme.h" #import "CPPlainWhiteTheme.h" #import "CPStocksTheme.h" #import "CPSlateTheme.h" #import "CPGraph.h" // theme names NSString * const kCPDarkGradientTheme = @"Dark Gradients"; ///< Dark gradient theme. NSString * const kCPPlainWhiteTheme = @"Plain White"; ///< Plain white theme. NSString * const kCPPlainBlackTheme = @"Plain Black"; ///< Plain black theme. NSString * const kCPSlateTheme = @"Slate"; ///< Slate theme. NSString * const kCPStocksTheme = @"Stocks"; ///< Stocks theme. // Registered themes static NSMutableDictionary *themes = nil; /** @brief Creates a CPGraph instance formatted with predefined themes. * * @todo More documentation needed **/ @implementation CPTheme /** @property name * @brief The name of the theme. **/ @synthesize name; #pragma mark - #pragma mark Init/dealloc /** @property graphClass * @brief The class used to create new graphs. Must be a subclass of CPGraph. **/ @synthesize graphClass; -(id)init { if ( self = [super init] ) { name = nil; graphClass = Nil; } return self; } -(void)dealloc { [name release]; [graphClass release]; [super dealloc]; } #pragma mark - #pragma mark Accessors -(void)setGraphClass:(Class)newGraphClass { if ( graphClass != newGraphClass ) { if ( [newGraphClass isEqual:[CPGraph class]] ) { [NSException raise:CPException format:@"Invalid graph class for theme; must be a subclass of CPGraph"]; } else { [graphClass release]; graphClass = [newGraphClass retain]; } } } /** @brief List of the available themes. * @return An NSArray with all available themes. **/ +(NSArray *)themeClasses { static NSArray *themeClasses = nil; if ( themeClasses == nil ) { themeClasses = [[NSArray alloc] initWithObjects:[CPDarkGradientTheme class], [CPPlainBlackTheme class], [CPPlainWhiteTheme class], [CPSlateTheme class], [CPStocksTheme class], nil]; } return themeClasses; } /** @brief Gets a named theme. * @param themeName The name of the desired theme. * @return A CPTheme instance with name matching themeName or nil if no themes with a matching name were found. **/ +(CPTheme *)themeNamed:(NSString *)themeName { if ( themes == nil ) themes = [[NSMutableDictionary alloc] init]; CPTheme *theme = [themes objectForKey:themeName]; if ( theme ) return theme; for ( Class themeClass in [CPTheme themeClasses] ) { if ( [themeName isEqualToString:[themeClass defaultName]] ) { theme = [[themeClass alloc] init]; [themes setObject:theme forKey:themeName]; break; } } return [theme autorelease]; } /** @brief Register a theme for a given name. * @param newTheme Theme to register. **/ +(void)addTheme:(CPTheme *)newTheme { CPTheme *existingTheme = [self themeNamed:newTheme.name]; if ( existingTheme ) { [NSException raise:CPException format:@"Theme already exists with name %@", newTheme.name]; } [themes setObject:newTheme forKey:newTheme.name]; } /** @brief The name used by default for this theme class. * @return The name. **/ +(NSString *)defaultName { return NSStringFromClass(self); } -(NSString *)name { return [[(name ? name : [[self class] defaultName]) copy] autorelease] ; } /** @brief Applies the theme to the provided graph. * @param graph The graph to style. **/ -(void)applyThemeToGraph:(CPGraph *)graph { [self applyThemeToBackground:graph]; [self applyThemeToPlotArea:graph.plotAreaFrame]; [self applyThemeToAxisSet:graph.axisSet]; } @end #pragma mark - @implementation CPTheme(AbstractMethods) /** @brief Creates a new graph styled with the theme. * @return The new graph. **/ -(id)newGraph { return nil; } /** @brief Applies the background theme to the provided graph. * @param graph The graph to style. **/ -(void)applyThemeToBackground:(CPGraph *)graph { } /** @brief Applies the theme to the provided plot area. * @param plotAreaFrame The plot area to style. **/ -(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame { } /** @brief Applies the theme to the provided axis set. * @param axisSet The axis set to style. **/ -(void)applyThemeToAxisSet:(CPAxisSet *)axisSet { } @end
08iteng-ipad
framework/Source/CPTheme.m
Objective-C
bsd
4,230
#import <Foundation/Foundation.h> #import "CPNumericData.h" #import "CPNumericDataType.h" /** @category CPNumericData(TypeConversion) * @brief Type conversion methods for CPNumericData. **/ @interface CPNumericData(TypeConversion) /// @name Type Conversion /// @{ -(CPNumericData *)dataByConvertingToDataType:(CPNumericDataType)newDataType; -(CPNumericData *)dataByConvertingToType:(CPDataTypeFormat)newDataType sampleBytes:(size_t)newSampleBytes byteOrder:(CFByteOrder)newByteOrder; /// @} /// @name Data Conversion Utilities /// @{ -(void)convertData:(NSData *)sourceData dataType:(CPNumericDataType *)sourceDataType toData:(NSMutableData *)destData dataType:(CPNumericDataType *)destDataType; -(void)swapByteOrderForData:(NSMutableData *)sourceData sampleSize:(size_t)sampleSize; /// @} @end
08iteng-ipad
framework/Source/CPNumericData+TypeConversion.h
Objective-C
bsd
873
#import "CPPlotSpace.h" #import "CPLayer.h" #import "CPAxisSet.h" /** @brief Plot space coordinate change notification. * * This notification is posted to the default notification center whenever the mapping between * the plot space coordinate system and drawing coordinates changes. **/ NSString * const CPPlotSpaceCoordinateMappingDidChangeNotification = @"CPPlotSpaceCoordinateMappingDidChangeNotification"; /** @brief Defines the coordinate system of a plot. **/ @implementation CPPlotSpace /** @property identifier * @brief An object used to identify the plot in collections. **/ @synthesize identifier; /** @property allowsUserInteraction * @brief Determines whether user can interactively change plot range and/or zoom. **/ @synthesize allowsUserInteraction; /** @property graph * @brief The graph of the space. **/ @synthesize graph; /** @property delegate * @brief The plot space delegate. **/ @synthesize delegate; #pragma mark - #pragma mark Initialize/Deallocate -(id)init { if ( self = [super init] ) { identifier = nil; allowsUserInteraction = NO; graph = nil; delegate = nil; } return self; } -(void)dealloc { delegate = nil; graph = nil; [identifier release]; [super dealloc]; } #pragma mark - #pragma mark Responder Chain and User interaction /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger down event. * @param interactionPoint The coordinates of the event in the host view. * @return Whether the plot space handled the event or not. **/ -(BOOL)pointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL handledByDelegate = NO; if ( [delegate respondsToSelector:@selector(plotSpace:shouldHandlePointingDeviceDownEvent:atPoint:)] ) { handledByDelegate = ![delegate plotSpace:self shouldHandlePointingDeviceDownEvent:event atPoint:interactionPoint]; } return handledByDelegate; } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger up event. * @param interactionPoint The coordinates of the event in the host view. * @return Whether the plot space handled the event or not. **/ -(BOOL)pointingDeviceUpEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL handledByDelegate = NO; if ( [delegate respondsToSelector:@selector(plotSpace:shouldHandlePointingDeviceUpEvent:atPoint:)] ) { handledByDelegate = ![delegate plotSpace:self shouldHandlePointingDeviceUpEvent:event atPoint:interactionPoint]; } return handledByDelegate; } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger dragged event. * @param interactionPoint The coordinates of the event in the host view. * @return Whether the plot space handled the event or not. **/ -(BOOL)pointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL handledByDelegate = NO; if ( [delegate respondsToSelector:@selector(plotSpace:shouldHandlePointingDeviceDraggedEvent:atPoint:)] ) { handledByDelegate = ![delegate plotSpace:self shouldHandlePointingDeviceDraggedEvent:event atPoint:interactionPoint]; } return handledByDelegate; } /** @brief Abstraction of Mac and iPhone event handling. Mouse or finger event cancelled. * @return Whether the plot space handled the event or not. **/ -(BOOL)pointingDeviceCancelledEvent:(id)event { BOOL handledByDelegate = NO; if ( [delegate respondsToSelector:@selector(plotSpace:shouldHandlePointingDeviceCancelledEvent:)] ) { handledByDelegate = ![delegate plotSpace:self shouldHandlePointingDeviceCancelledEvent:event]; } return handledByDelegate; } @end #pragma mark - @implementation CPPlotSpace(AbstractMethods) /** @brief Converts a data point to plot area drawing coordinates. * @param plotPoint A c-style array of data point coordinates (as NSDecimals). * @return The drawing coordinates of the data point. **/ -(CGPoint)plotAreaViewPointForPlotPoint:(NSDecimal *)plotPoint { return CGPointZero; } /** @brief Converts a data point to plot area drawing coordinates. * @param plotPoint A c-style array of data point coordinates (as doubles). * @return The drawing coordinates of the data point. **/ -(CGPoint)plotAreaViewPointForDoublePrecisionPlotPoint:(double *)plotPoint; { return CGPointZero; } /** @brief Converts a point given in plot area drawing coordinates to the data coordinate space. * @param plotPoint A c-style array of data point coordinates (as NSDecimals). * @param point The drawing coordinates of the data point. **/ -(void)plotPoint:(NSDecimal *)plotPoint forPlotAreaViewPoint:(CGPoint)point { } /** @brief Converts a point given in drawing coordinates to the data coordinate space. * @param plotPoint A c-style array of data point coordinates (as doubles). * @param point The drawing coordinates of the data point. **/ -(void)doublePrecisionPlotPoint:(double *)plotPoint forPlotAreaViewPoint:(CGPoint)point { } /** @brief Sets the range of values for a given coordinate. * @param newRange The new plot range. * @param coordinate The axis coordinate. **/ -(void)setPlotRange:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate { } /** @brief Gets the range of values for a given coordinate. * @param coordinate The axis coordinate. * @return The range of values. **/ -(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coordinate { return nil; } /** @brief Scales the plot ranges so that the plots just fit in the visible space. * @param plots An array of the plots that have to fit in the visible area. **/ -(void)scaleToFitPlots:(NSArray *)plots { } /** @brief Zooms the plot space equally in each dimension. * @param interactionScale The scaling factor. One gives no scaling. * @param interactionPoint The plot area view point about which the scaling occurs. **/ -(void)scaleBy:(CGFloat)interactionScale aboutPoint:(CGPoint)interactionPoint { } @end
08iteng-ipad
framework/Source/CPPlotSpace.m
Objective-C
bsd
5,889
#import <Foundation/Foundation.h> #import "CPLayer.h" @class CPAxis; @interface CPGridLines : CPLayer { @private __weak CPAxis *axis; BOOL major; } @property (nonatomic, readwrite, assign) __weak CPAxis *axis; @property (nonatomic, readwrite) BOOL major; @end
08iteng-ipad
framework/Source/CPGridLines.h
Objective-C
bsd
266
#import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPExceptions.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPAxisSet.h" #import "CPPlot.h" #import "CPPlotAreaFrame.h" #import "CPPlotRange.h" #import "CPPlotArea.h" #import "CPGraph.h" /** @cond */ @interface CPXYPlotSpace () -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range plotCoordinateValue:(NSDecimal)plotCoord; -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range doublePrecisionPlotCoordinateValue:(double)plotCoord; -(CPPlotRange *)constrainRange:(CPPlotRange *)existingRange toGlobalRange:(CPPlotRange *)globalRange; @end /** @endcond */ #pragma mark - /** @brief A plot space using a two-dimensional cartesian coordinate system. **/ @implementation CPXYPlotSpace /** @property xRange * @brief The range of the x coordinate. **/ @synthesize xRange; /** @property yRange * @brief The range of the y coordinate. **/ @synthesize yRange; /** @property globalXRange * @brief The global range of the x coordinate to which the plot range is constrained. * If nil, there is no constraint on x. **/ @synthesize globalXRange; /** @property globalYRange * @brief The global range of the y coordinate to which the plot range is constrained. * If nil, there is no constraint on y. **/ @synthesize globalYRange; /** @property xScaleType * @brief The scale type of the x coordinate. **/ @synthesize xScaleType; /** @property yScaleType * @brief The scale type of the y coordinate. **/ @synthesize yScaleType; #pragma mark - #pragma mark Initialize/Deallocate -(id)init { if ( self = [super init] ) { xRange = [[CPPlotRange alloc] initWithLocation:CPDecimalFromInteger(0) length:CPDecimalFromInteger(1)]; yRange = [[CPPlotRange alloc] initWithLocation:CPDecimalFromInteger(0) length:CPDecimalFromInteger(1)];; globalXRange = nil; globalYRange = nil; xScaleType = CPScaleTypeLinear; yScaleType = CPScaleTypeLinear; } return self; } -(void)dealloc { [xRange release]; [yRange release]; [globalXRange release]; [globalYRange release]; [super dealloc]; } #pragma mark - #pragma mark Ranges -(void)setPlotRange:(CPPlotRange *)newRange forCoordinate:(CPCoordinate)coordinate { if ( coordinate == CPCoordinateX ) { self.xRange = newRange; } else { self.yRange = newRange; } } -(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coordinate { return ( coordinate == CPCoordinateX ? self.xRange : self.yRange ); } -(void)setXRange:(CPPlotRange *)range { NSParameterAssert(range); if ( ![range isEqualToRange:xRange] ) { CPPlotRange *constrainedRange = [self constrainRange:range toGlobalRange:self.globalXRange]; [xRange release]; xRange = [constrainedRange copy]; [[NSNotificationCenter defaultCenter] postNotificationName:CPPlotSpaceCoordinateMappingDidChangeNotification object:self]; if ( [self.delegate respondsToSelector:@selector(plotSpace:didChangePlotRangeForCoordinate:)] ) { [self.delegate plotSpace:self didChangePlotRangeForCoordinate:CPCoordinateX]; } if ( self.graph ) [[NSNotificationCenter defaultCenter] postNotificationName:CPGraphNeedsRedrawNotification object:self.graph]; } } -(void)setYRange:(CPPlotRange *)range { NSParameterAssert(range); if ( ![range isEqualToRange:yRange] ) { CPPlotRange *constrainedRange = [self constrainRange:range toGlobalRange:self.globalYRange]; [yRange release]; yRange = [constrainedRange copy]; [[NSNotificationCenter defaultCenter] postNotificationName:CPPlotSpaceCoordinateMappingDidChangeNotification object:self]; if ( [self.delegate respondsToSelector:@selector(plotSpace:didChangePlotRangeForCoordinate:)] ) { [self.delegate plotSpace:self didChangePlotRangeForCoordinate:CPCoordinateY]; } if ( self.graph ) [[NSNotificationCenter defaultCenter] postNotificationName:CPGraphNeedsRedrawNotification object:self.graph]; } } -(CPPlotRange *)constrainRange:(CPPlotRange *)existingRange toGlobalRange:(CPPlotRange *)globalRange { if ( !globalRange ) return existingRange; if ( !existingRange ) return nil; if ( CPDecimalGreaterThanOrEqualTo(existingRange.length, globalRange.length) ) { return [[globalRange copy] autorelease]; } else { CPPlotRange *newRange = [[existingRange copy] autorelease]; [newRange shiftEndToFitInRange:globalRange]; [newRange shiftLocationToFitInRange:globalRange]; return newRange; } } -(void)setGlobalXRange:(CPPlotRange *)newRange { if ( ![newRange isEqualToRange:globalXRange] ) { [globalXRange release]; globalXRange = [newRange copy]; self.xRange = [self constrainRange:self.xRange toGlobalRange:globalXRange]; } } -(void)setGlobalYRange:(CPPlotRange *)newRange { if ( ![newRange isEqualToRange:globalYRange] ) { [globalYRange release]; globalYRange = [newRange copy]; self.yRange = [self constrainRange:self.yRange toGlobalRange:globalYRange]; } } -(void)scaleToFitPlots:(NSArray *)plots { if ( plots.count == 0 ) return; // Determine union of ranges CPPlotRange *unionXRange = nil; CPPlotRange *unionYRange = nil; for ( CPPlot *plot in plots ) { CPPlotRange *currentXRange = [plot plotRangeForCoordinate:CPCoordinateX]; CPPlotRange *currentYRange = [plot plotRangeForCoordinate:CPCoordinateY]; if ( !unionXRange ) unionXRange = currentXRange; if ( !unionYRange ) unionYRange = currentYRange; [unionXRange unionPlotRange:currentXRange]; [unionYRange unionPlotRange:currentYRange]; } // Set range NSDecimal zero = CPDecimalFromInteger(0); if ( unionXRange && !CPDecimalEquals(unionXRange.length, zero) ) self.xRange = unionXRange; if ( unionYRange && !CPDecimalEquals(unionYRange.length, zero) ) self.yRange = unionYRange; } #pragma mark - #pragma mark Point Conversion -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range plotCoordinateValue:(NSDecimal)plotCoord { if ( !range ) return 0.0; NSDecimal factor = CPDecimalDivide(CPDecimalSubtract(plotCoord, range.location), range.length); if ( NSDecimalIsNotANumber(&factor) ) { factor = CPDecimalFromInteger(0); } CGFloat viewCoordinate = viewLength * [[NSDecimalNumber decimalNumberWithDecimal:factor] doubleValue]; return viewCoordinate; } -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range doublePrecisionPlotCoordinateValue:(double)plotCoord; { if ( !range || range.lengthDouble == 0.0 ) return 0.0; return viewLength * ((plotCoord - range.locationDouble) / range.lengthDouble); } -(CGPoint)plotAreaViewPointForPlotPoint:(NSDecimal *)plotPoint { CGFloat viewX = 0.0, viewY = 0.0; CGSize layerSize = self.graph.plotAreaFrame.plotArea.bounds.size; switch ( self.xScaleType ) { case CPScaleTypeLinear: viewX = [self viewCoordinateForViewLength:layerSize.width linearPlotRange:self.xRange plotCoordinateValue:plotPoint[CPCoordinateX]]; break; default: [NSException raise:CPException format:@"Scale type not supported in CPXYPlotSpace"]; } switch ( self.yScaleType ) { case CPScaleTypeLinear: viewY = [self viewCoordinateForViewLength:layerSize.height linearPlotRange:self.yRange plotCoordinateValue:plotPoint[CPCoordinateY]]; break; default: [NSException raise:CPException format:@"Scale type not supported in CPXYPlotSpace"]; } return CGPointMake(viewX, viewY); } -(CGPoint)plotAreaViewPointForDoublePrecisionPlotPoint:(double *)plotPoint { CGFloat viewX = 0.0, viewY = 0.0; CGSize layerSize = self.graph.plotAreaFrame.plotArea.bounds.size; switch ( self.xScaleType ) { case CPScaleTypeLinear: viewX = [self viewCoordinateForViewLength:layerSize.width linearPlotRange:self.xRange doublePrecisionPlotCoordinateValue:plotPoint[CPCoordinateX]]; break; default: [NSException raise:CPException format:@"Scale type not supported in CPXYPlotSpace"]; } switch ( self.yScaleType ) { case CPScaleTypeLinear: viewY = [self viewCoordinateForViewLength:layerSize.height linearPlotRange:self.yRange doublePrecisionPlotCoordinateValue:plotPoint[CPCoordinateY]]; break; default: [NSException raise:CPException format:@"Scale type not supported in CPXYPlotSpace"]; } return CGPointMake(viewX, viewY); } -(void)plotPoint:(NSDecimal *)plotPoint forPlotAreaViewPoint:(CGPoint)point { NSDecimal pointx = CPDecimalFromDouble(point.x); NSDecimal pointy = CPDecimalFromDouble(point.y); CGSize boundsSize = self.graph.plotAreaFrame.plotArea.bounds.size; NSDecimal boundsw = CPDecimalFromDouble(boundsSize.width); NSDecimal boundsh = CPDecimalFromDouble(boundsSize.height); // get the xRange's location and length NSDecimal xLocation = xRange.location; NSDecimal xLength = xRange.length; NSDecimal x; NSDecimalDivide(&x, &pointx, &boundsw, NSRoundPlain); NSDecimalMultiply(&x, &x, &(xLength), NSRoundPlain); NSDecimalAdd(&x, &x, &(xLocation), NSRoundPlain); // get the yRange's location and length NSDecimal yLocation = yRange.location; NSDecimal yLength = yRange.length; NSDecimal y; NSDecimalDivide(&y, &pointy, &boundsh, NSRoundPlain); NSDecimalMultiply(&y, &y, &(yLength), NSRoundPlain); NSDecimalAdd(&y, &y, &(yLocation), NSRoundPlain); plotPoint[CPCoordinateX] = x; plotPoint[CPCoordinateY] = y; } -(void)doublePrecisionPlotPoint:(double *)plotPoint forPlotAreaViewPoint:(CGPoint)point { // TODO: implement doublePrecisionPlotPoint:forViewPoint: } #pragma mark - #pragma mark Scaling -(void)scaleBy:(CGFloat)interactionScale aboutPoint:(CGPoint)plotAreaPoint { if ( !self.allowsUserInteraction || !self.graph.plotAreaFrame || interactionScale <= 1.e-6 ) return; if ( ![self.graph.plotAreaFrame.plotArea containsPoint:plotAreaPoint] ) return; // Ask the delegate if it is OK BOOL shouldScale = YES; if ( [self.delegate respondsToSelector:@selector(plotSpace:shouldScaleBy:aboutPoint:)] ) { shouldScale = [self.delegate plotSpace:self shouldScaleBy:interactionScale aboutPoint:plotAreaPoint]; } if ( !shouldScale ) return; // Determine point in plot coordinates NSDecimal const decimalScale = CPDecimalFromFloat(interactionScale); NSDecimal plotInteractionPoint[2]; [self plotPoint:plotInteractionPoint forPlotAreaViewPoint:plotAreaPoint]; // Original Lengths NSDecimal oldFirstLengthX = CPDecimalSubtract(plotInteractionPoint[0], self.xRange.minLimit); NSDecimal oldSecondLengthX = CPDecimalSubtract(self.xRange.maxLimit, plotInteractionPoint[0]); NSDecimal oldFirstLengthY = CPDecimalSubtract(plotInteractionPoint[1], self.yRange.minLimit); NSDecimal oldSecondLengthY = CPDecimalSubtract(self.yRange.maxLimit, plotInteractionPoint[1]); // Lengths are scaled by the pinch gesture inverse proportional NSDecimal newFirstLengthX = CPDecimalDivide(oldFirstLengthX, decimalScale); NSDecimal newSecondLengthX = CPDecimalDivide(oldSecondLengthX, decimalScale); NSDecimal newFirstLengthY = CPDecimalDivide(oldFirstLengthY, decimalScale); NSDecimal newSecondLengthY = CPDecimalDivide(oldSecondLengthY, decimalScale); // New ranges CPPlotRange *newRangeX = [[[CPPlotRange alloc] initWithLocation:CPDecimalSubtract(plotInteractionPoint[0],newFirstLengthX) length:CPDecimalAdd(newFirstLengthX,newSecondLengthX)] autorelease]; CPPlotRange *newRangeY = [[[CPPlotRange alloc] initWithLocation:CPDecimalSubtract(plotInteractionPoint[1],newFirstLengthY) length:CPDecimalAdd(newFirstLengthY,newSecondLengthY)] autorelease]; // delegate may still veto/modify the range if ( [self.delegate respondsToSelector:@selector(plotSpace:willChangePlotRangeTo:forCoordinate:)] ) { newRangeX = [self.delegate plotSpace:self willChangePlotRangeTo:newRangeX forCoordinate:CPCoordinateX]; newRangeY = [self.delegate plotSpace:self willChangePlotRangeTo:newRangeY forCoordinate:CPCoordinateY]; } self.xRange = newRangeX; self.yRange = newRangeY; } #pragma mark - #pragma mark Interaction -(BOOL)pointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL handledByDelegate = [super pointingDeviceDownEvent:event atPoint:interactionPoint]; if ( handledByDelegate ) return YES; if ( !self.allowsUserInteraction || !self.graph.plotAreaFrame ) { return NO; } CGPoint pointInPlotArea = [self.graph convertPoint:interactionPoint toLayer:self.graph.plotAreaFrame]; if ( [self.graph.plotAreaFrame containsPoint:pointInPlotArea] ) { // Handle event lastDragPoint = pointInPlotArea; isDragging = YES; return YES; } return NO; } -(BOOL)pointingDeviceUpEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL handledByDelegate = [super pointingDeviceUpEvent:event atPoint:interactionPoint]; if ( handledByDelegate ) return YES; if ( !self.allowsUserInteraction || !self.graph.plotAreaFrame ) { return NO; } if ( isDragging ) { isDragging = NO; return YES; } return NO; } -(BOOL)pointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)interactionPoint { BOOL handledByDelegate = [super pointingDeviceDraggedEvent:event atPoint:interactionPoint]; if ( handledByDelegate ) return YES; if ( !self.allowsUserInteraction || !self.graph.plotAreaFrame ) { return NO; } CGPoint pointInPlotArea = [self.graph convertPoint:interactionPoint toLayer:self.graph.plotAreaFrame]; if ( isDragging ) { CGPoint displacement = CGPointMake(pointInPlotArea.x-lastDragPoint.x, pointInPlotArea.y-lastDragPoint.y); CGPoint pointToUse = pointInPlotArea; // Allow delegate to override if ( [self.delegate respondsToSelector:@selector(plotSpace:willDisplaceBy:)] ) { displacement = [self.delegate plotSpace:self willDisplaceBy:displacement]; pointToUse = CGPointMake(lastDragPoint.x+displacement.x, lastDragPoint.y+displacement.y); } NSDecimal lastPoint[2], newPoint[2]; [self plotPoint:lastPoint forPlotAreaViewPoint:lastDragPoint]; [self plotPoint:newPoint forPlotAreaViewPoint:pointToUse]; CPPlotRange *newRangeX = [[self.xRange copy] autorelease]; CPPlotRange *newRangeY = [[self.yRange copy] autorelease]; NSDecimal shiftX = CPDecimalSubtract(lastPoint[0], newPoint[0]); NSDecimal shiftY = CPDecimalSubtract(lastPoint[1], newPoint[1]); newRangeX.location = CPDecimalAdd(newRangeX.location, shiftX); newRangeY.location = CPDecimalAdd(newRangeY.location, shiftY); // Delegate override if ( [self.delegate respondsToSelector:@selector(plotSpace:willChangePlotRangeTo:forCoordinate:)] ) { newRangeX = [self.delegate plotSpace:self willChangePlotRangeTo:newRangeX forCoordinate:CPCoordinateX]; newRangeY = [self.delegate plotSpace:self willChangePlotRangeTo:newRangeY forCoordinate:CPCoordinateY]; } self.xRange = newRangeX; self.yRange = newRangeY; lastDragPoint = pointInPlotArea; return YES; } return NO; } @end
08iteng-ipad
framework/Source/CPXYPlotSpace.m
Objective-C
bsd
15,299
#import "CPXYTheme.h" #import "CPPlotRange.h" #import "CPXYGraph.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" /** @brief Creates a CPXYGraph instance formatted with padding of 60 on each side and X and Y plot ranges of +/- 1. **/ @implementation CPXYTheme -(id)init { if ( self = [super init] ) { self.graphClass = [CPXYGraph class]; } return self; } -(id)newGraph { CPXYGraph *graph; if (self.graphClass) { graph = [(CPXYGraph *)[self.graphClass alloc] initWithFrame:CGRectMake(0.0, 0.0, 200.0, 200.0)]; } else { graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectMake(0.0, 0.0, 200.0, 200.0)]; } graph.paddingLeft = 60.0; graph.paddingTop = 60.0; graph.paddingRight = 60.0; graph.paddingBottom = 60.0; CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace; plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]; plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]; [self applyThemeToGraph:graph]; return graph; } @end
08iteng-ipad
framework/Source/CPXYTheme.m
Objective-C
bsd
1,131
#import "CPConstrainedPosition.h" #import "CPExceptions.h" /** @brief Implements a spring and strut positioning algorithm for one dimension. **/ @implementation CPConstrainedPosition /** @property lowerBound * @brief The lower bound. **/ @synthesize lowerBound; /** @property upperBound * @brief The upper bound. **/ @synthesize upperBound; /** @property constraints * @brief The positioning constraints. **/ @synthesize constraints; /** @property position * @brief The current position. **/ @synthesize position; #pragma mark - #pragma mark Init/Dealloc /** @brief Initializes a newly allocated CPConstrainedPosition object with the provided position and bounds. This is the designated initializer. * @param newPosition The position. * @param newLowerBound The lower bound. * @param newUpperBound The upper bound. * @return A CPConstrainedPosition instance initialized with the provided position and bounds. **/ -(id)initWithPosition:(CGFloat)newPosition lowerBound:(CGFloat)newLowerBound upperBound:(CGFloat)newUpperBound { if ( self = [super init] ) { position = newPosition; lowerBound = newLowerBound; upperBound = newUpperBound; constraints.lower = CPConstraintNone; constraints.upper = CPConstraintNone; } return self; } /** @brief Initializes a newly allocated CPConstrainedPosition object with the provided alignment and bounds. * @param newAlignment The alignment. * @param newLowerBound The lower bound. * @param newUpperBound The upper bound. * @return A CPConstrainedPosition instance initialized with the provided alignment and bounds. **/ -(id)initWithAlignment:(CPAlignment)newAlignment lowerBound:(CGFloat)newLowerBound upperBound:(CGFloat)newUpperBound { CGFloat newPosition; CPConstraint lowerConstraint; CPConstraint upperConstraint; switch ( newAlignment ) { case CPAlignmentLeft: case CPAlignmentBottom: newPosition = newLowerBound; lowerConstraint = CPConstraintFixed; upperConstraint = CPConstraintNone; break; case CPAlignmentRight: case CPAlignmentTop: newPosition = newUpperBound; lowerConstraint = CPConstraintNone; upperConstraint = CPConstraintFixed; break; case CPAlignmentCenter: case CPAlignmentMiddle: newPosition = (newUpperBound - newLowerBound) * 0.5 + newLowerBound; lowerConstraint = CPConstraintNone; upperConstraint = CPConstraintNone; break; default: [NSException raise:CPException format:@"Invalid alignment in initWithAlignment..."]; break; } if ( self = [self initWithPosition:newPosition lowerBound:newLowerBound upperBound:newUpperBound] ) { constraints.lower = lowerConstraint; constraints.upper = upperConstraint; } return self; } #pragma mark - #pragma mark Positioning /** @brief Adjust the position given the previous bounds. * @param oldLowerBound The old lower bound. * @param oldUpperBound The old upper bound. **/ -(void)adjustPositionForOldLowerBound:(CGFloat)oldLowerBound oldUpperBound:(CGFloat)oldUpperBound { if ( self.constraints.lower == self.constraints.upper ) { CGFloat lowerRatio = 0.0; if ( (oldUpperBound - oldLowerBound) != 0.0 ) { lowerRatio = (self.position - oldLowerBound) / (oldUpperBound - oldLowerBound); } self.position = self.lowerBound + lowerRatio * (self.upperBound - self.lowerBound); } else if ( self.constraints.lower == CPConstraintFixed ) { self.position = self.lowerBound + (self.position - oldLowerBound); } else { self.position = self.upperBound - (oldUpperBound - self.position); } } #pragma mark - #pragma mark Accessors -(void)setLowerBound:(CGFloat)newLowerBound { if ( newLowerBound != lowerBound ) { CGFloat oldLowerBound = lowerBound; lowerBound = newLowerBound; [self adjustPositionForOldLowerBound:oldLowerBound oldUpperBound:self.upperBound]; } } -(void)setUpperBound:(CGFloat)newUpperBound { if ( newUpperBound != upperBound ) { CGFloat oldUpperBound = upperBound; upperBound = newUpperBound; [self adjustPositionForOldLowerBound:self.lowerBound oldUpperBound:oldUpperBound]; } } @end
08iteng-ipad
framework/Source/CPConstrainedPosition.m
Objective-C
bsd
4,391
#import "CPDarkGradientTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotAreaFrame.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPMutableLineStyle.h" #import "CPMutableTextStyle.h" #import "CPBorderedLayer.h" #import "CPExceptions.h" /** @cond */ @interface CPDarkGradientTheme () -(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle minorLineStyle:(CPLineStyle *)minorLineStyle textStyle:(CPMutableTextStyle *)textStyle minorTickTextStyle:(CPMutableTextStyle *)minorTickTextStyle; @end /** @endcond */ #pragma mark - /** @brief Creates a CPXYGraph instance formatted with dark gray gradient backgrounds and light gray lines. **/ @implementation CPDarkGradientTheme +(NSString *)defaultName { return kCPDarkGradientTheme; } -(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle minorLineStyle:(CPLineStyle *)minorLineStyle textStyle:(CPMutableTextStyle *)textStyle minorTickTextStyle:(CPMutableTextStyle *)minorTickTextStyle { axis.labelingPolicy = CPAxisLabelingPolicyFixedInterval; axis.majorIntervalLength = CPDecimalFromDouble(0.5); axis.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0); axis.tickDirection = CPSignNone; axis.minorTicksPerInterval = 4; axis.majorTickLineStyle = majorLineStyle; axis.minorTickLineStyle = minorLineStyle; axis.axisLineStyle = majorLineStyle; axis.majorTickLength = 7.0; axis.minorTickLength = 5.0; axis.labelTextStyle = textStyle; axis.minorTickLabelTextStyle = minorTickTextStyle; axis.titleTextStyle = textStyle; } -(void)applyThemeToBackground:(CPXYGraph *)graph { CPColor *endColor = [CPColor colorWithGenericGray:0.1]; CPGradient *graphGradient = [CPGradient gradientWithBeginningColor:endColor endingColor:endColor]; graphGradient = [graphGradient addColorStop:[CPColor colorWithGenericGray:0.2] atPosition:0.3]; graphGradient = [graphGradient addColorStop:[CPColor colorWithGenericGray:0.3] atPosition:0.5]; graphGradient = [graphGradient addColorStop:[CPColor colorWithGenericGray:0.2] atPosition:0.6]; graphGradient.angle = 90.0; graph.fill = [CPFill fillWithGradient:graphGradient]; } -(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame { CPGradient *gradient = [CPGradient gradientWithBeginningColor:[CPColor colorWithGenericGray:0.1] endingColor:[CPColor colorWithGenericGray:0.3]]; gradient.angle = 90.0; plotAreaFrame.fill = [CPFill fillWithGradient:gradient]; CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor colorWithGenericGray:0.2]; borderLineStyle.lineWidth = 4.0; plotAreaFrame.borderLineStyle = borderLineStyle; plotAreaFrame.cornerRadius = 10.0; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPMutableLineStyle *majorLineStyle = [CPMutableLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapSquare; majorLineStyle.lineColor = [CPColor colorWithGenericGray:0.5]; majorLineStyle.lineWidth = 2.0; CPMutableLineStyle *minorLineStyle = [CPMutableLineStyle lineStyle]; minorLineStyle.lineCap = kCGLineCapSquare; minorLineStyle.lineColor = [CPColor darkGrayColor]; minorLineStyle.lineWidth = 1.0; CPMutableTextStyle *whiteTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; whiteTextStyle.color = [CPColor whiteColor]; whiteTextStyle.fontSize = 14.0; CPMutableTextStyle *whiteMinorTickTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; whiteMinorTickTextStyle.color = [CPColor whiteColor]; whiteMinorTickTextStyle.fontSize = 12.0; for (CPXYAxis *axis in axisSet.axes) { [self applyThemeToAxis:axis usingMajorLineStyle:majorLineStyle minorLineStyle:minorLineStyle textStyle:whiteTextStyle minorTickTextStyle:whiteMinorTickTextStyle]; } } @end
08iteng-ipad
framework/Source/CPDarkGradientTheme.m
Objective-C
bsd
3,934
#import "CPPlotSpace.h" #import "CPDefinitions.h" @class CPPlotRange; @interface CPXYPlotSpace : CPPlotSpace { @private CPPlotRange *xRange; CPPlotRange *yRange; CPPlotRange *globalXRange; CPPlotRange *globalYRange; CPScaleType xScaleType; // TODO: Implement scale types CPScaleType yScaleType; // TODO: Implement scale types CGPoint lastDragPoint; BOOL isDragging; } @property (nonatomic, readwrite, copy) CPPlotRange *xRange; @property (nonatomic, readwrite, copy) CPPlotRange *yRange; @property (nonatomic, readwrite, copy) CPPlotRange *globalXRange; @property (nonatomic, readwrite, copy) CPPlotRange *globalYRange; @property (nonatomic, readwrite, assign) CPScaleType xScaleType; @property (nonatomic, readwrite, assign) CPScaleType yScaleType; @end
08iteng-ipad
framework/Source/CPXYPlotSpace.h
Objective-C
bsd
783
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> @interface CPImage : NSObject <NSCopying> { @private CGImageRef image; BOOL tiled; BOOL tileAnchoredToContext; } @property (assign) CGImageRef image; @property (assign, getter=isTiled) BOOL tiled; @property (assign) BOOL tileAnchoredToContext; /// @name Factory Methods /// @{ +(CPImage *)imageWithCGImage:(CGImageRef)anImage; +(CPImage *)imageForPNGFile:(NSString *)path; /// @} /// @name Initialization /// @{ -(id)initWithCGImage:(CGImageRef)anImage; -(id)initForPNGFile:(NSString *)path; /// @} /// @name Drawing /// @{ -(void)drawInRect:(CGRect)rect inContext:(CGContextRef)context; /// @} @end
08iteng-ipad
framework/Source/CPImage.h
Objective-C
bsd
682
#import <Foundation/Foundation.h> #import "CPPlot.h" #import "CPDefinitions.h" /// @file @class CPColor; @class CPFill; @class CPMutableNumericData; @class CPNumericData; @class CPPieChart; @class CPTextLayer; @class CPLineStyle; /// @name Binding Identifiers /// @{ extern NSString * const CPPieChartBindingPieSliceWidthValues; /// @} /** @brief Enumeration of pie chart data source field types. **/ typedef enum _CPPieChartField { CPPieChartFieldSliceWidth, ///< Pie slice width. CPPieChartFieldSliceWidthNormalized, ///< Pie slice width normalized [0, 1]. CPPieChartFieldSliceWidthSum ///< Cumulative sum of pie slice widths. } CPPieChartField; /** @brief Enumeration of pie slice drawing directions. **/ typedef enum _CPPieDirection { CPPieDirectionClockwise, ///< Pie slices are drawn in a clockwise direction. CPPieDirectionCounterClockwise ///< Pie slices are drawn in a counter-clockwise direction. } CPPieDirection; #pragma mark - /** @brief A pie chart data source. **/ @protocol CPPieChartDataSource <CPPlotDataSource> @optional /** @brief Gets a fill for the given pie chart slice. This method is optional. * @param pieChart The pie chart. * @param index The data index of interest. * @return The pie slice fill for the slice with the given index. **/ -(CPFill *)sliceFillForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index; /** @brief Gets a label for the given pie chart slice. This method is no longer used. * @param pieChart The pie chart. * @param index The data index of interest. * @return The pie slice label for the slice with the given index. * If you return nil, the default pie slice label will be used. If you return an instance of NSNull, * no label will be shown for the index in question. * @deprecated This method has been replaced by the CPPlotDataSource::dataLabelForPlot:recordIndex: method and is no longer used. **/ -(CPTextLayer *)sliceLabelForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index; /** @brief Offsets the slice radially from the center point. Can be used to "explode" the chart. * @param pieChart The pie chart. * @param index The data index of interest. * @return The radial offset in view coordinates. Zero is no offset. **/ -(CGFloat)radialOffsetForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index; @end #pragma mark - /** @brief Pie chart delegate. **/ @protocol CPPieChartDelegate <NSObject> @optional // @name Point selection /// @{ /** @brief Informs the delegate that a pie slice was touched or clicked. * @param plot The pie chart. * @param index The index of the slice that was touched or clicked. **/ -(void)pieChart:(CPPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)index; /// @} @end #pragma mark - @interface CPPieChart : CPPlot { @private CGFloat pieRadius; CGFloat pieInnerRadius; CGFloat startAngle; CPPieDirection sliceDirection; CGPoint centerAnchor; CPLineStyle *borderLineStyle; CPFill *overlayFill; } @property (nonatomic, readwrite) CGFloat pieRadius; @property (nonatomic, readwrite) CGFloat pieInnerRadius; @property (nonatomic, readwrite) CGFloat sliceLabelOffset; @property (nonatomic, readwrite) CGFloat startAngle; @property (nonatomic, readwrite) CPPieDirection sliceDirection; @property (nonatomic, readwrite) CGPoint centerAnchor; @property (nonatomic, readwrite, copy) CPLineStyle *borderLineStyle; @property (nonatomic, readwrite, copy) CPFill *overlayFill; /// @name Factory Methods /// @{ +(CPColor *)defaultPieSliceColorForIndex:(NSUInteger)pieSliceIndex; /// @} @end
08iteng-ipad
framework/Source/CPPieChart.h
Objective-C
bsd
3,587
#import "CPUtilities.h" #import "CPUtilitiesTests.h" #import "CPDefinitions.h" #import "CPUtilities.h" @implementation CPUtilitiesTests -(void)testCPDecimalIntegerValue { NSDecimalNumber *d = [NSDecimalNumber decimalNumberWithString:@"42"]; STAssertEquals(CPDecimalIntegerValue([d decimalValue]), (NSInteger)42, @"Result incorrect"); d = [NSDecimalNumber decimalNumberWithString:@"42.1"]; STAssertEquals((NSInteger)CPDecimalIntegerValue([d decimalValue]), (NSInteger)42, @"Result incorrect"); } -(void)testCPDecimalFloatValue { NSDecimalNumber *d = [NSDecimalNumber decimalNumberWithString:@"42"]; STAssertEquals((float)CPDecimalFloatValue([d decimalValue]), (float)42.0, @"Result incorrect"); d = [NSDecimalNumber decimalNumberWithString:@"42.1"]; STAssertEquals((float)CPDecimalFloatValue([d decimalValue]), (float)42.1, @"Result incorrect"); } -(void)testCPDecimalDoubleValue { NSDecimalNumber *d = [NSDecimalNumber decimalNumberWithString:@"42"]; STAssertEquals((double)CPDecimalDoubleValue([d decimalValue]), (double)42.0, @"Result incorrect"); d = [NSDecimalNumber decimalNumberWithString:@"42.1"]; STAssertEquals((double)CPDecimalDoubleValue([d decimalValue]), (double)42.1, @"Result incorrect"); } -(void)testToDecimalConversion { NSInteger i = 100; NSUInteger unsignedI = 100; float f = 3.141f; double d = 42.1; STAssertEqualObjects([NSDecimalNumber decimalNumberWithString:@"100"], [NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromInteger(i)], @"NSInteger to NSDecimal conversion failed"); STAssertEqualObjects([NSDecimalNumber decimalNumberWithString:@"100"], [NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromUnsignedInteger(unsignedI)], @"NSUInteger to NSDecimal conversion failed"); STAssertEqualsWithAccuracy([[NSDecimalNumber numberWithFloat:f] floatValue], [[NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromFloat(f)] floatValue], 1.0e-7, @"float to NSDecimal conversion failed"); STAssertEqualObjects([NSDecimalNumber numberWithDouble:d], [NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromDouble(d)], @"double to NSDecimal conversion failed."); } -(void)testCachedZero { NSDecimal zero = [[NSDecimalNumber zero] decimalValue]; NSDecimal testValue; NSString *errMessage; // signed conversions testValue = CPDecimalFromChar(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromShort(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromLong(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromLongLong(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromInt(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromInteger(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); // unsigned conversions testValue = CPDecimalFromUnsignedChar(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedShort(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedLong(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedLongLong(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedInt(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedInteger(0); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&zero, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &zero) == NSOrderedSame, errMessage); } -(void)testCachedOne { NSDecimal one = [[NSDecimalNumber one] decimalValue]; NSDecimal testValue; NSString *errMessage; // signed conversions testValue = CPDecimalFromChar(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromShort(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromLong(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromLongLong(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromInt(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromInteger(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); // unsigned conversions testValue = CPDecimalFromUnsignedChar(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedShort(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedLong(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedLongLong(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedInt(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); testValue = CPDecimalFromUnsignedInteger(1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&one, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &one) == NSOrderedSame, errMessage); } -(void)testConvertNegativeOne { NSDecimal zero = [[NSDecimalNumber zero] decimalValue]; NSDecimal one = [[NSDecimalNumber one] decimalValue]; NSDecimal negativeOne; NSDecimalSubtract(&negativeOne, &zero, &one, NSRoundPlain); NSDecimal testValue; NSString *errMessage; // signed conversions testValue = CPDecimalFromChar(-1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&negativeOne, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &negativeOne) == NSOrderedSame, errMessage); testValue = CPDecimalFromShort(-1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&negativeOne, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &negativeOne) == NSOrderedSame, errMessage); testValue = CPDecimalFromLong(-1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&negativeOne, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &negativeOne) == NSOrderedSame, errMessage); testValue = CPDecimalFromLongLong(-1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&negativeOne, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &negativeOne) == NSOrderedSame, errMessage); testValue = CPDecimalFromInt(-1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&negativeOne, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &negativeOne) == NSOrderedSame, errMessage); testValue = CPDecimalFromInteger(-1); errMessage = [NSString stringWithFormat:@"test value was %@, expected %@", NSDecimalString(&testValue, nil), NSDecimalString(&negativeOne, nil), nil]; STAssertTrue(NSDecimalCompare(&testValue, &negativeOne) == NSOrderedSame, errMessage); } @end
08iteng-ipad
framework/Source/CPUtilitiesTests.m
Objective-C
bsd
10,936
#import <Foundation/Foundation.h> #import "CPPlot.h" #import "CPDefinitions.h" /// @file @class CPLineStyle; @class CPMutableNumericData; @class CPNumericData; @class CPPlotSymbol; @class CPScatterPlot; @class CPFill; /// @name Binding Identifiers /// @{ extern NSString * const CPScatterPlotBindingXValues; extern NSString * const CPScatterPlotBindingYValues; extern NSString * const CPScatterPlotBindingPlotSymbols; /// @} /** @brief Enumeration of scatter plot data source field types **/ typedef enum _CPScatterPlotField { CPScatterPlotFieldX, ///< X values. CPScatterPlotFieldY ///< Y values. } CPScatterPlotField; /** @brief Enumeration of scatter plot interpolation algorithms **/ typedef enum _CPScatterPlotInterpolation { CPScatterPlotInterpolationLinear, ///< Linear interpolation. CPScatterPlotInterpolationStepped, ///< Steps beginnning at data point. CPScatterPlotInterpolationHistogram ///< Steps centered at data point. } CPScatterPlotInterpolation; #pragma mark - /** @brief A scatter plot data source. **/ @protocol CPScatterPlotDataSource <CPPlotDataSource> @optional /// @name Implement one of the following to add plot symbols /// @{ /** @brief Gets a range of plot symbols for the given scatter plot. * @param plot The scatter plot. * @param indexRange The range of the data indexes of interest. * @return An array of plot symbols. **/ -(NSArray *)symbolsForScatterPlot:(CPScatterPlot *)plot recordIndexRange:(NSRange)indexRange; /** @brief Gets a plot symbol for the given scatter plot. * @param plot The scatter plot. * @param index The data index of interest. * @return The plot symbol to show for the point with the given index. **/ -(CPPlotSymbol *)symbolForScatterPlot:(CPScatterPlot *)plot recordIndex:(NSUInteger)index; /// @} @end #pragma mark - /** @brief Scatter plot delegate. **/ @protocol CPScatterPlotDelegate <NSObject> @optional // @name Point selection /// @{ /** @brief Informs delegate that a point was touched. * @param plot The scatter plot. * @param index Index of touched point **/ -(void)scatterPlot:(CPScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index; /// @} @end #pragma mark - @interface CPScatterPlot : CPPlot { @private CPScatterPlotInterpolation interpolation; CPLineStyle *dataLineStyle; CPPlotSymbol *plotSymbol; CPFill *areaFill; CPFill *areaFill2; NSDecimal areaBaseValue; NSDecimal areaBaseValue2; CGFloat plotSymbolMarginForHitDetection; NSArray *plotSymbols; } @property (nonatomic, readwrite, copy) CPLineStyle *dataLineStyle; @property (nonatomic, readwrite, copy) CPPlotSymbol *plotSymbol; @property (nonatomic, readwrite, copy) CPFill *areaFill; @property (nonatomic, readwrite, copy) CPFill *areaFill2; @property (nonatomic, readwrite) NSDecimal areaBaseValue; @property (nonatomic, readwrite) NSDecimal areaBaseValue2; @property (nonatomic, readwrite, assign) CPScatterPlotInterpolation interpolation; @property (nonatomic, readwrite, assign) CGFloat plotSymbolMarginForHitDetection; -(NSUInteger)indexOfVisiblePointClosestToPlotAreaPoint:(CGPoint)viewPoint; -(CGPoint)plotAreaPointOfVisiblePointAtIndex:(NSUInteger)index; -(CPPlotSymbol *)plotSymbolForRecordIndex:(NSUInteger)index; @end
08iteng-ipad
framework/Source/CPScatterPlot.h
Objective-C
bsd
3,299
#import "CPPlotRangeTests.h" #import "CPExceptions.h" #import "CPPlotRange.h" #import "CPUtilities.h" @interface CPPlotRangeTests() -(void)checkRangeWithLocation:(double)loc length:(double)len; @end #pragma mark - @implementation CPPlotRangeTests @synthesize plotRange; -(void)setUp { self.plotRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(1.0) length:CPDecimalFromDouble(2.0)]; } -(void)tearDown { self.plotRange = nil; } #pragma mark - #pragma mark Checking Ranges -(void)testContains { STAssertFalse([self.plotRange contains:CPDecimalFromDouble(0.999)], @"Test contains:0.999"); STAssertTrue([self.plotRange contains:CPDecimalFromDouble(1.0)], @"Test contains:1.0"); STAssertTrue([self.plotRange contains:CPDecimalFromDouble(2.0)], @"Test contains:2.0"); STAssertTrue([self.plotRange contains:CPDecimalFromDouble(3.0)], @"Test contains:3.0"); STAssertFalse([self.plotRange contains:CPDecimalFromDouble(3.001)], @"Test contains:3.001"); } -(void)testContainsNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); STAssertFalse([self.plotRange contains:CPDecimalFromDouble(-1.001)], @"Test contains:-1.001"); STAssertTrue([self.plotRange contains:CPDecimalFromDouble(-1.0)], @"Test contains:-1.0"); STAssertTrue([self.plotRange contains:CPDecimalFromDouble(0.0)], @"Test contains:0.0"); STAssertTrue([self.plotRange contains:CPDecimalFromDouble(1.0)], @"Test contains:1.0"); STAssertFalse([self.plotRange contains:CPDecimalFromDouble(1.001)], @"Test contains:1.001"); } -(void)testContainsDouble { STAssertFalse([self.plotRange containsDouble:0.999], @"Test contains:0.999"); STAssertTrue([self.plotRange containsDouble:1.0], @"Test contains:1.0"); STAssertTrue([self.plotRange containsDouble:2.0], @"Test contains:2.0"); STAssertTrue([self.plotRange containsDouble:3.0], @"Test contains:3.0"); STAssertFalse([self.plotRange containsDouble:3.001], @"Test contains:3.001"); } -(void)testContainsDoubleNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); STAssertFalse([self.plotRange containsDouble:-1.001], @"Test contains:-1.001"); STAssertTrue([self.plotRange containsDouble:-1.0], @"Test contains:-1.0"); STAssertTrue([self.plotRange containsDouble:0.0], @"Test contains:0.0"); STAssertTrue([self.plotRange containsDouble:1.0], @"Test contains:1.0"); STAssertFalse([self.plotRange containsDouble:1.001], @"Test contains:1.001"); } #pragma mark - #pragma mark Union -(void)testUnionRange { [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:0.0 length:4.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:-1.0 length:5.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:-1.0 length:8.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-4.0 length:11.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-5.0 length:12.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-5.0 length:12.0]; } -(void)testUnionRangeNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:4.0 length:-5.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:4.0 length:-5.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:7.0 length:-8.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:7.0 length:-11.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:7.0 length:-12.0]; [self.plotRange unionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:7.0 length:-12.0]; } #pragma mark - #pragma mark Intersection -(void)testIntersectRange { [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:1.0 length:2.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:1.0 length:1.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:1.0 length:0.0]; } -(void)testIntersectRange2 { [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(4.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:1.0 length:2.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(2.0) length:CPDecimalFromDouble(-1.0)]]; [self checkRangeWithLocation:1.0 length:1.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:1.0 length:0.0]; } -(void)testIntersectRangeNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:1.0 length:-1.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:1.0 length:-1.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:1.0 length:0.0]; } -(void)testIntersectRangeNegative2 { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:0.0 length:-1.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(2.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:0.0 length:-1.0]; [self.plotRange intersectionPlotRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:0.0 length:0.0]; } #pragma mark - #pragma mark Shifting Ranges -(void)testShiftLocation { [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:1.0 length:2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:0.0 length:2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:5.0 length:2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:0.0 length:2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-1.0 length:2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:1.0 length:2.0]; } -(void)testShiftLocationNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:1.0 length:-2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:0.0 length:-2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:5.0 length:-2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:0.0 length:-2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-1.0 length:-2.0]; [self.plotRange shiftLocationToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:1.0 length:-2.0]; } -(void)testShiftEnd { [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:1.0 length:2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:-2.0 length:2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:3.0 length:2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-2.0 length:2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-3.0 length:2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:-1.0 length:2.0]; } -(void)testShiftEndNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(4.0)]]; [self checkRangeWithLocation:2.0 length:-2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(1.0)]]; [self checkRangeWithLocation:2.0 length:-2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(2.0)]]; [self checkRangeWithLocation:7.0 length:-2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(0.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:2.0 length:-2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(-1.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:1.0 length:-2.0]; [self.plotRange shiftEndToFitInRange:[CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(5.0) length:CPDecimalFromDouble(-4.0)]]; [self checkRangeWithLocation:3.0 length:-2.0]; } #pragma mark - #pragma mark Expand Range -(void)testExpandRangeHalf { [self.plotRange expandRangeByFactor:CPDecimalFromDouble(0.5)]; [self checkRangeWithLocation:1.5 length:1.0]; } -(void)testExpandRangeSame { [self.plotRange expandRangeByFactor:CPDecimalFromDouble(1.0)]; [self checkRangeWithLocation:1.0 length:2.0]; } -(void)testExpandRangeDouble { [self.plotRange expandRangeByFactor:CPDecimalFromDouble(2.0)]; [self checkRangeWithLocation:0.0 length:4.0]; } -(void)testExpandRangeHalfNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange expandRangeByFactor:CPDecimalFromDouble(0.5)]; [self checkRangeWithLocation:0.5 length:-1.0]; } -(void)testExpandRangeSameNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange expandRangeByFactor:CPDecimalFromDouble(1.0)]; [self checkRangeWithLocation:1.0 length:-2.0]; } -(void)testExpandRangeDoubleNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); [self.plotRange expandRangeByFactor:CPDecimalFromDouble(2.0)]; [self checkRangeWithLocation:2.0 length:-4.0]; } #pragma mark - #pragma mark Comparing Ranges -(void)testCompareToDecimal { STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(0.999)], CPPlotRangeComparisonResultNumberBelowRange, @"Test compareTo:0.999"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(1.0)], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:1.0"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(2.0)], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:2.0"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(3.0)], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:3.0"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(3.001)], CPPlotRangeComparisonResultNumberAboveRange, @"Test compareTo:3.001"); } -(void)testCompareToDecimalNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(-1.001)], CPPlotRangeComparisonResultNumberBelowRange, @"Test compareTo:-1.001"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(-1.0)], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:-1.0"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(0.0)], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:0.0"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(1.0)], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:1.0"); STAssertEquals([self.plotRange compareToDecimal:CPDecimalFromDouble(1.001)], CPPlotRangeComparisonResultNumberAboveRange, @"Test compareTo:1.001"); } -(void)testCompareToDouble { STAssertEquals([self.plotRange compareToDouble:0.999], CPPlotRangeComparisonResultNumberBelowRange, @"Test compareTo:0.999"); STAssertEquals([self.plotRange compareToDouble:1.0], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:1.0"); STAssertEquals([self.plotRange compareToDouble:2.0], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:2.0"); STAssertEquals([self.plotRange compareToDouble:3.0], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:3.0"); STAssertEquals([self.plotRange compareToDouble:3.001], CPPlotRangeComparisonResultNumberAboveRange, @"Test compareTo:3.001"); } -(void)testCompareToDoubleNegative { self.plotRange.length = CPDecimalFromDouble(-2.0); STAssertEquals([self.plotRange compareToDouble:-1.001], CPPlotRangeComparisonResultNumberBelowRange, @"Test compareTo:-1.001"); STAssertEquals([self.plotRange compareToDouble:-1.0], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:-1.0"); STAssertEquals([self.plotRange compareToDouble:0.0], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:0.0"); STAssertEquals([self.plotRange compareToDouble:1.0], CPPlotRangeComparisonResultNumberInRange, @"Test compareTo:1.0"); STAssertEquals([self.plotRange compareToDouble:1.001], CPPlotRangeComparisonResultNumberAboveRange, @"Test compareTo:1.001"); } #pragma mark - #pragma mark Private Methods -(void)checkRangeWithLocation:(double)loc length:(double)len { NSDecimal newLocation = self.plotRange.location; STAssertTrue(CPDecimalEquals(newLocation, CPDecimalFromDouble(loc)), [NSString stringWithFormat:@"expected location = %g, was %@", loc, NSDecimalString(&newLocation, nil)]); NSDecimal newLength = self.plotRange.length; STAssertTrue(CPDecimalEquals(newLength, CPDecimalFromDouble(len)), [NSString stringWithFormat:@"expected length = %g, was %@", len, NSDecimalString(&newLength, nil)]); } @end
08iteng-ipad
framework/Source/CPPlotRangeTests.m
Objective-C
bsd
16,558
#import "CPXYGraph.h" #import "CPXYPlotSpace.h" #import "CPExceptions.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" /** @cond */ @interface CPXYGraph() @property (nonatomic, readwrite, assign) CPScaleType xScaleType; @property (nonatomic, readwrite, assign) CPScaleType yScaleType; @end /** @endcond */ /** @brief A graph using a cartesian (X-Y) plot space. **/ @implementation CPXYGraph /** @property xScaleType * @brief The scale type for the x-axis. **/ @synthesize xScaleType; /** @property yScaleType * @brief The scale type for the y-axis. **/ @synthesize yScaleType; #pragma mark - #pragma mark Init/Dealloc /** @brief Initializes a newly allocated CPXYGraph object with the provided frame rectangle and scale types. * * This is the designated initializer. * * @param newFrame The frame rectangle. * @param newXScaleType The scale type for the x-axis. * @param newYScaleType The scale type for the y-axis. * @return The initialized CPXYGraph object. **/ -(id)initWithFrame:(CGRect)newFrame xScaleType:(CPScaleType)newXScaleType yScaleType:(CPScaleType)newYScaleType; { if ( self = [super initWithFrame:newFrame] ) { xScaleType = newXScaleType; yScaleType = newYScaleType; } return self; } -(id)initWithFrame:(CGRect)newFrame { return [self initWithFrame:newFrame xScaleType:CPScaleTypeLinear yScaleType:CPScaleTypeLinear]; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPXYGraph *theLayer = (CPXYGraph *)layer; xScaleType = theLayer->xScaleType; yScaleType = theLayer->yScaleType; } return self; } #pragma mark - #pragma mark Factory Methods -(CPPlotSpace *)newPlotSpace { CPXYPlotSpace *space = [[CPXYPlotSpace alloc] init]; space.xScaleType = self.xScaleType; space.yScaleType = self.yScaleType; return space; } -(CPAxisSet *)newAxisSet { CPXYAxisSet *newAxisSet = [(CPXYAxisSet *)[CPXYAxisSet alloc] initWithFrame:self.bounds]; newAxisSet.xAxis.plotSpace = self.defaultPlotSpace; newAxisSet.yAxis.plotSpace = self.defaultPlotSpace; return newAxisSet; } @end
08iteng-ipad
framework/Source/CPXYGraph.m
Objective-C
bsd
2,094
#import "CPPlainBlackTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotAreaFrame.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPMutableLineStyle.h" #import "CPMutableTextStyle.h" #import "CPBorderedLayer.h" #import "CPExceptions.h" /** @brief Creates a CPXYGraph instance formatted with black backgrounds and white lines. **/ @implementation CPPlainBlackTheme +(NSString *)defaultName { return kCPPlainBlackTheme; } -(void)applyThemeToBackground:(CPXYGraph *)graph { graph.fill = [CPFill fillWithColor:[CPColor blackColor]]; } -(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame { plotAreaFrame.fill = [CPFill fillWithColor:[CPColor blackColor]]; CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor whiteColor]; borderLineStyle.lineWidth = 1.0; plotAreaFrame.borderLineStyle = borderLineStyle; plotAreaFrame.cornerRadius = 0.0; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPMutableLineStyle *majorLineStyle = [CPMutableLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapRound; majorLineStyle.lineColor = [CPColor whiteColor]; majorLineStyle.lineWidth = 3.0; CPMutableLineStyle *minorLineStyle = [CPMutableLineStyle lineStyle]; minorLineStyle.lineColor = [CPColor whiteColor]; minorLineStyle.lineWidth = 3.0; CPXYAxis *x = axisSet.xAxis; CPMutableTextStyle *whiteTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; whiteTextStyle.color = [CPColor whiteColor]; whiteTextStyle.fontSize = 14.0; CPMutableTextStyle *minorTickWhiteTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; minorTickWhiteTextStyle.color = [CPColor whiteColor]; minorTickWhiteTextStyle.fontSize = 12.0; x.labelingPolicy = CPAxisLabelingPolicyFixedInterval; x.majorIntervalLength = CPDecimalFromDouble(0.5); x.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0); x.tickDirection = CPSignNone; x.minorTicksPerInterval = 4; x.majorTickLineStyle = majorLineStyle; x.minorTickLineStyle = minorLineStyle; x.axisLineStyle = majorLineStyle; x.majorTickLength = 7.0; x.minorTickLength = 5.0; x.labelTextStyle = whiteTextStyle; x.minorTickLabelTextStyle = whiteTextStyle; x.titleTextStyle = whiteTextStyle; CPXYAxis *y = axisSet.yAxis; y.labelingPolicy = CPAxisLabelingPolicyFixedInterval; y.majorIntervalLength = CPDecimalFromDouble(0.5); y.minorTicksPerInterval = 4; y.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0); y.tickDirection = CPSignNone; y.majorTickLineStyle = majorLineStyle; y.minorTickLineStyle = minorLineStyle; y.axisLineStyle = majorLineStyle; y.majorTickLength = 7.0; y.minorTickLength = 5.0; y.labelTextStyle = whiteTextStyle; y.minorTickLabelTextStyle = minorTickWhiteTextStyle; y.titleTextStyle = whiteTextStyle; } @end
08iteng-ipad
framework/Source/CPPlainBlackTheme.m
Objective-C
bsd
2,994
#import "_CPFillColor.h" #import "CPColor.h" /** @cond */ @interface _CPFillColor() @property (nonatomic, readwrite, copy) CPColor *fillColor; @end /** @endcond */ /** @brief Draws CPColor area fills. * * Drawing methods are provided to fill rectangular areas and arbitrary drawing paths. **/ @implementation _CPFillColor /** @property fillColor * @brief The fill color. **/ @synthesize fillColor; #pragma mark - #pragma mark init/dealloc /** @brief Initializes a newly allocated _CPFillColor object with the provided color. * @param aColor The color. * @return The initialized _CPFillColor object. **/ -(id)initWithColor:(CPColor *)aColor { if ( self = [super init] ) { fillColor = [aColor retain]; } return self; } -(void)dealloc { [fillColor release]; [super dealloc]; } #pragma mark - #pragma mark Drawing /** @brief Draws the color into the given graphics context inside the provided rectangle. * @param theRect The rectangle to draw into. * @param theContext The graphics context to draw into. **/ -(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext { CGContextSaveGState(theContext); CGContextSetFillColorWithColor(theContext, self.fillColor.cgColor); CGContextFillRect(theContext, theRect); CGContextRestoreGState(theContext); } /** @brief Draws the color into the given graphics context clipped to the current drawing path. * @param theContext The graphics context to draw into. **/ -(void)fillPathInContext:(CGContextRef)theContext { CGContextSaveGState(theContext); CGContextSetFillColorWithColor(theContext, self.fillColor.cgColor); CGContextFillPath(theContext); CGContextRestoreGState(theContext); } #pragma mark - #pragma mark NSCopying methods -(id)copyWithZone:(NSZone *)zone { _CPFillColor *copy = [[[self class] allocWithZone:zone] init]; copy->fillColor = [self->fillColor copyWithZone:zone]; return copy; } #pragma mark - #pragma mark NSCoding methods -(Class)classForCoder { return [CPFill class]; } -(void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.fillColor forKey:@"fillColor"]; } -(id)initWithCoder:(NSCoder *)coder { if ( self = [super init] ) { fillColor = [[coder decodeObjectForKey:@"fillColor"] retain]; } return self; } @end
08iteng-ipad
framework/Source/_CPFillColor.m
Objective-C
bsd
2,270
#import <Foundation/Foundation.h> #import "CPGraph.h" #import "CPDefinitions.h" @interface CPXYGraph : CPGraph { @private CPScaleType xScaleType; CPScaleType yScaleType; } /// @name Initialization /// @{ -(id)initWithFrame:(CGRect)newFrame xScaleType:(CPScaleType)newXScaleType yScaleType:(CPScaleType)newYScaleType; /// @} @end
08iteng-ipad
framework/Source/CPXYGraph.h
Objective-C
bsd
340
#import "CPSlateTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotAreaFrame.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPMutableLineStyle.h" #import "CPMutableTextStyle.h" #import "CPBorderedLayer.h" #import "CPExceptions.h" /** @cond */ @interface CPSlateTheme () -(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle minorLineStyle:(CPLineStyle *)minorLineStyle textStyle:(CPMutableTextStyle *)textStyle minorTickTextStyle:(CPMutableTextStyle *)minorTickTextStyle; @end /** @endcond */ #pragma mark - /** @brief Creates a CPXYGraph instance with colors that match the default iPhone navigation bar, toolbar buttons, and table views. **/ @implementation CPSlateTheme +(NSString *)defaultName { return kCPSlateTheme; } -(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle minorLineStyle:(CPLineStyle *)minorLineStyle textStyle:(CPMutableTextStyle *)textStyle minorTickTextStyle:(CPMutableTextStyle *)minorTickTextStyle { axis.labelingPolicy = CPAxisLabelingPolicyFixedInterval; axis.majorIntervalLength = CPDecimalFromDouble(0.5); axis.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0); axis.tickDirection = CPSignNone; axis.minorTicksPerInterval = 4; axis.majorTickLineStyle = majorLineStyle; axis.minorTickLineStyle = minorLineStyle; axis.axisLineStyle = majorLineStyle; axis.majorTickLength = 7.0; axis.minorTickLength = 5.0; axis.labelTextStyle = textStyle; axis.minorTickLabelTextStyle = minorTickTextStyle; axis.titleTextStyle = textStyle; } -(void)applyThemeToBackground:(CPXYGraph *)graph { // No background fill has been implemented } -(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame { CPGradient *gradient = [CPGradient gradientWithBeginningColor:[CPColor colorWithComponentRed:0.43f green:0.51f blue:0.63f alpha:1.0f] endingColor:[CPColor colorWithComponentRed:0.70f green:0.73f blue:0.80f alpha:1.0f]]; gradient.angle = 90.0; plotAreaFrame.fill = [CPFill fillWithGradient:gradient]; CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor colorWithGenericGray:0.2]; borderLineStyle.lineWidth = 1.0; plotAreaFrame.borderLineStyle = borderLineStyle; plotAreaFrame.cornerRadius = 5.0; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPMutableLineStyle *majorLineStyle = [CPMutableLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapSquare; majorLineStyle.lineColor = [CPColor colorWithComponentRed:0.0f green:0.25f blue:0.50f alpha:1.0f]; majorLineStyle.lineWidth = 2.0; CPMutableLineStyle *minorLineStyle = [CPMutableLineStyle lineStyle]; minorLineStyle.lineCap = kCGLineCapSquare; minorLineStyle.lineColor = [CPColor blackColor]; minorLineStyle.lineWidth = 1.0; CPMutableTextStyle *blackTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; blackTextStyle.color = [CPColor blackColor]; blackTextStyle.fontSize = 14.0; CPMutableTextStyle *minorTickBlackTextStyle = [[[CPMutableTextStyle alloc] init] autorelease]; minorTickBlackTextStyle.color = [CPColor blackColor]; minorTickBlackTextStyle.fontSize = 12.0; for (CPXYAxis *axis in axisSet.axes) { [self applyThemeToAxis:axis usingMajorLineStyle:majorLineStyle minorLineStyle:minorLineStyle textStyle:blackTextStyle minorTickTextStyle:minorTickBlackTextStyle]; } } @end
08iteng-ipad
framework/Source/CPSlateTheme.m
Objective-C
bsd
3,549
#import "CPPlotAreaFrame.h" #import "CPAxisSet.h" #import "CPPlotGroup.h" #import "CPDefinitions.h" #import "CPLineStyle.h" #import "CPPlotArea.h" /** @cond */ @interface CPPlotAreaFrame() @property (nonatomic, readwrite, retain) CPPlotArea *plotArea; @end /** @endcond */ #pragma mark - /** @brief A layer drawn on top of the graph layer and behind all plot elements. **/ @implementation CPPlotAreaFrame /** @property plotArea * @brief The plot area. **/ @synthesize plotArea; /** @property axisSet * @brief The axis set. **/ @dynamic axisSet; /** @property plotGroup * @brief The plot group. **/ @dynamic plotGroup; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { plotArea = nil; CPPlotArea *newPlotArea = [(CPPlotArea *)[CPPlotArea alloc] initWithFrame:newFrame]; self.plotArea = newPlotArea; [newPlotArea release]; self.needsDisplayOnBoundsChange = YES; } return self; } -(id)initWithLayer:(id)layer { if ( self = [super initWithLayer:layer] ) { CPPlotAreaFrame *theLayer = (CPPlotAreaFrame *)layer; plotArea = [theLayer->plotArea retain]; } return self; } -(void)dealloc { [plotArea release]; [super dealloc]; } #pragma mark - #pragma mark Layout +(CGFloat)defaultZPosition { return CPDefaultZPositionPlotAreaFrame; } -(void)layoutSublayers { CPPlotArea *thePlotArea = self.plotArea; if ( thePlotArea ) { CGFloat leftPadding = self.paddingLeft; CGFloat bottomPadding = self.paddingBottom; CGRect selfBounds = self.bounds; CGSize subLayerSize = selfBounds.size; CGFloat lineWidth = self.borderLineStyle.lineWidth; subLayerSize.width -= leftPadding + self.paddingRight + lineWidth; subLayerSize.width = MAX(subLayerSize.width, 0.0); subLayerSize.height -= self.paddingTop + bottomPadding + lineWidth; subLayerSize.height = MAX(subLayerSize.height, 0.0); thePlotArea.frame = CGRectMake(leftPadding, bottomPadding, subLayerSize.width, subLayerSize.height); } } #pragma mark - #pragma mark Accessors -(void)setPlotArea:(CPPlotArea *)newPlotArea { if ( newPlotArea != plotArea ) { [plotArea removeFromSuperlayer]; [plotArea release]; plotArea = [newPlotArea retain]; if ( plotArea ) { [self insertSublayer:plotArea atIndex:0]; } [self setNeedsLayout]; } } -(CPAxisSet *)axisSet { return self.plotArea.axisSet; } -(void)setAxisSet:(CPAxisSet *)newAxisSet { self.plotArea.axisSet = newAxisSet; } -(CPPlotGroup *)plotGroup { return self.plotArea.plotGroup; } -(void)setPlotGroup:(CPPlotGroup *)newPlotGroup { self.plotArea.plotGroup = newPlotGroup; } @end
08iteng-ipad
framework/Source/CPPlotAreaFrame.m
Objective-C
bsd
2,648
#import "CPBorderedLayer.h" @class CPAxisSet; @class CPPlotGroup; @class CPPlotArea; @interface CPPlotAreaFrame : CPBorderedLayer { @private CPPlotArea *plotArea; } @property (nonatomic, readonly, retain) CPPlotArea *plotArea; @property (nonatomic, readwrite, retain) CPAxisSet *axisSet; @property (nonatomic, readwrite, retain) CPPlotGroup *plotGroup; @end
08iteng-ipad
framework/Source/CPPlotAreaFrame.h
Objective-C
bsd
367