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 "CPPlotArea.h" #import "CPAxisSet.h" #import "CPPlotGroup.h" #import "CPDefinitions.h" #import "CPLineStyle.h" /** @brief A layer drawn on top of the graph layer and behind all plot elements. **/ @implementation CPPlotArea /** @property axisSet * @brief The axis set. **/ @synthesize axisSet; /** @property plotGroup * @brief The plot group. **/ @synthesize plotGroup; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { axisSet = nil; plotGroup = nil; CPPlotGroup *newPlotGroup = [[CPPlotGroup alloc] init]; self.plotGroup = newPlotGroup; [newPlotGroup release]; self.needsDisplayOnBoundsChange = YES; } return self; } -(void)dealloc { [axisSet release]; [plotGroup release]; [super dealloc]; } #pragma mark - #pragma mark Layout +(CGFloat)defaultZPosition { return CPDefaultZPositionPlotArea; } -(void)layoutSublayers { [super layoutSublayers]; CGFloat inset = self.borderLineStyle.lineWidth; CGRect sublayerBounds = CGRectInset(self.bounds, inset, inset); CPAxisSet *theAxisSet = self.axisSet; if ( theAxisSet ) { // Set the bounds so that the axis set coordinates coincide with the // plot area drawing coordinates. theAxisSet.bounds = sublayerBounds; theAxisSet.anchorPoint = CGPointZero; theAxisSet.position = sublayerBounds.origin; } CPPlotGroup *thePlotGroup = self.plotGroup; if ( thePlotGroup ) { // Set the bounds so that the plot group coordinates coincide with the // plot area drawing coordinates. thePlotGroup.bounds = sublayerBounds; thePlotGroup.anchorPoint = CGPointZero; thePlotGroup.position = sublayerBounds.origin; } } #pragma mark - #pragma mark Accessors -(void)setAxisSet:(CPAxisSet *)newAxisSet { if ( newAxisSet != axisSet ) { [axisSet removeFromSuperlayer]; [axisSet release]; axisSet = [newAxisSet retain]; if ( axisSet ) { [self insertSublayer:axisSet atIndex:0]; } [self setNeedsLayout]; } } -(void)setPlotGroup:(CPPlotGroup *)newPlotGroup { if ( newPlotGroup != plotGroup ) { [plotGroup removeFromSuperlayer]; [plotGroup release]; plotGroup = [newPlotGroup retain]; if ( plotGroup ) { [self insertSublayer:plotGroup below:self.axisSet]; } [self setNeedsLayout]; } } @end
08iteng-ipad
systemtests/tests/Source/CPPlotArea.m
Objective-C
bsd
2,312
#import <Foundation/Foundation.h> #import "CPDefinitions.h" /// @file /// @name NSDecimal Utilities /// @{ NSInteger CPDecimalIntegerValue(NSDecimal decimalNumber); float CPDecimalFloatValue(NSDecimal decimalNumber); double CPDecimalDoubleValue(NSDecimal decimalNumber); NSDecimal CPDecimalFromInt(NSInteger i); NSDecimal CPDecimalFromFloat(float f); NSDecimal CPDecimalFromDouble(double d); NSDecimal CPDecimalAdd(NSDecimal leftOperand, NSDecimal rightOperand); NSDecimal CPDecimalSubtract(NSDecimal leftOperand, NSDecimal rightOperand); NSDecimal CPDecimalMultiply(NSDecimal leftOperand, NSDecimal rightOperand); NSDecimal CPDecimalDivide(NSDecimal numerator, NSDecimal denominator); 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); NSDecimal CPDecimalFromString(NSString *stringRepresentation); /// @} NSRange CPExpandedRange(NSRange range, NSInteger expandBy); CPCoordinate CPOrthogonalCoordinate(CPCoordinate coord); 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); /// @}
08iteng-ipad
systemtests/tests/Source/CPUtilities.h
Objective-C
bsd
1,567
#import "CPLayer.h" #import "CPLayoutManager.h" #import "CPPlatformSpecificFunctions.h" #import "CPExceptions.h" #import "CorePlotProbes.h" #import <objc/runtime.h> /// @cond @interface CPLayer() @property (nonatomic, readwrite, getter=isRenderingRecursively) BOOL renderingRecursively; @end /// @endcond /** @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 /// @defgroup CPLayer CPLayer /// @{ /** @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 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; // 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.0f; paddingTop = 0.0f; paddingRight = 0.0f; paddingBottom = 0.0f; layoutManager = nil; renderingRecursively = NO; self.frame = newFrame; self.needsDisplayOnBoundsChange = NO; self.opaque = NO; self.masksToBounds = NO; self.zPosition = [self.class defaultZPosition]; NSDictionary *actionsDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNull null], @"position", [NSNull null], @"bounds", [NSNull null], @"sublayers", nil]; self.actions = actionsDict; [actionsDict release]; } return self; } -(id)init { return [self initWithFrame:CGRectZero]; } -(void)dealloc { [layoutManager release]; [super dealloc]; } #pragma mark - #pragma mark Drawing -(void)drawInContext:(CGContextRef)context { [self renderAsVectorInContext:context]; } /** @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 { self.renderingRecursively = YES; [self renderAsVectorInContext:context]; self.renderingRecursively = NO; for ( CALayer *currentSublayer in self.sublayers ) { CGContextSaveGState(context); // Shift origin of context to match starting coordinate of sublayer CGPoint currentSublayerFrameOrigin = currentSublayer.frame.origin; CGPoint currentSublayerBoundsOrigin = currentSublayer.bounds.origin; CGContextTranslateCTM(context, currentSublayerFrameOrigin.x - currentSublayerBoundsOrigin.x, currentSublayerFrameOrigin.y - currentSublayerBoundsOrigin.y); if ( [currentSublayer isKindOfClass:[CPLayer class]] ) { [(CPLayer *)currentSublayer recursivelyRenderInContext:context]; } else { if ( self.masksToBounds ) { CGContextClipToRect(context, currentSublayer.bounds); } [currentSublayer drawInContext:context]; } CGContextRestoreGState(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.0f, 0.0f, self.bounds.size.width, self.bounds.size.height); CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &mediaBox, NULL); CPPushCGContext(pdfContext); CGContextBeginPage(pdfContext, &mediaBox); [self recursivelyRenderInContext:pdfContext]; CGContextEndPage(pdfContext); CGPDFContextClose(pdfContext); CPPopCGContext(); CGContextRelease(pdfContext); CGDataConsumerRelease(dataConsumer); return [pdfData autorelease]; } #pragma mark - #pragma mark User interaction -(BOOL)containsPoint:(CGPoint)thePoint { // By default, don't respond to touch or mouse events return NO; } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger down event. * @param interactionPoint The coordinates of the event. **/ -(void)mouseOrFingerDownAtPoint:(CGPoint)interactionPoint { // Subclasses should handle mouse or touch interactions here } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger up event. * @param interactionPoint The coordinates of the event. **/ -(void)mouseOrFingerUpAtPoint:(CGPoint)interactionPoint { // Subclasses should handle mouse or touch interactions here } /** @brief Abstraction of Mac and iPhone event handling. Handles mouse or finger dragged event. * @param interactionPoint The coordinates of the event. **/ -(void)mouseOrFingerDraggedAtPoint:(CGPoint)interactionPoint { // Subclasses should handle mouse or touch interactions here } /** @brief Abstraction of Mac and iPhone event handling. Mouse or finger event cancelled. **/ -(void)mouseOrFingerCancelled { // Subclasses should handle mouse or touch interactions here } #pragma mark - #pragma mark Layout -(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.0f; } -(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 // TODO: create a generic layout manager akin to CAConstraintLayoutManager ("struts and springs" is not flexible enough) // Sublayers fill the super layer's bounds minus any padding by default CGRect selfBounds = self.bounds; CGSize subLayerSize = selfBounds.size; subLayerSize.width -= self.paddingLeft + self.paddingRight; subLayerSize.width = MAX(subLayerSize.width, 0.0f); subLayerSize.height -= self.paddingTop + self.paddingBottom; subLayerSize.height = MAX(subLayerSize.height, 0.0f); for (CALayer *subLayer in self.sublayers) { if ([subLayer isKindOfClass:[CPLayer class]]) { CGRect subLayerBounds = subLayer.bounds; subLayerBounds.size = subLayerSize; subLayer.bounds = subLayerBounds; subLayer.anchorPoint = CGPointZero; subLayer.position = CGPointMake(selfBounds.origin.x + self.paddingLeft, selfBounds.origin.y + self.paddingBottom); } } } #pragma mark - #pragma mark Masking -(CGPathRef)maskingPath { return NULL; } -(CGPathRef)sublayerMaskingPath { return NULL; } /** @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 sublayerFrameOrigin = sublayer.frame.origin; CGPoint sublayerBoundsOrigin = sublayer.bounds.origin; CGPoint layerOffset = offset; if ( !self.renderingRecursively ) { layerOffset.x += sublayerFrameOrigin.x - sublayerBoundsOrigin.x; layerOffset.y += sublayerFrameOrigin.y - sublayerBoundsOrigin.y; } if ( [self.superlayer isKindOfClass:[CPLayer class]] ) { [(CPLayer *)self.superlayer applySublayerMaskToContext:context forSublayer:self withOffset:layerOffset]; } CGPathRef maskPath = self.sublayerMaskingPath; if ( maskPath ) { CGContextTranslateCTM(context, -layerOffset.x, -layerOffset.y); CGContextAddPath(context, maskPath); CGContextClip(context); CGContextTranslateCTM(context, layerOffset.x, layerOffset.y); } } /** @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:CGPointMake(0.0, 0.0)]; } CGPathRef maskPath = self.maskingPath; if ( maskPath ) { CGContextAddPath(context, maskPath); CGContextClip(context); } } #pragma mark - #pragma mark Bindings static NSString * const BindingsNotSupportedString = @"Bindings are not supported on the iPhone in Core Plot"; +(void)exposeBinding:(NSString *)binding { #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE #else [super exposeBinding:binding]; #endif } -(void)bind:(NSString *)binding toObject:(id)observable withKeyPath:(NSString *)keyPath options:(NSDictionary *)options { #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE [NSException raise:CPException format:BindingsNotSupportedString]; #else [super bind:binding toObject:observable withKeyPath:keyPath options:options]; #endif } -(void)unbind:(NSString *)binding { #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE [NSException raise:CPException format:BindingsNotSupportedString]; #else [super unbind:binding]; #endif } -(Class)valueClassForBinding:(NSString *)binding { #if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE [NSException raise:CPException format:BindingsNotSupportedString]; return Nil; #else return [super valueClassForBinding:binding]; #endif } /// @} - (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)); } } @end
08iteng-ipad
systemtests/tests/Source/CPLayer.m
Objective-C
bsd
12,989
#import "CPBarPlot.h" #import "CPXYPlotSpace.h" #import "CPColor.h" #import "CPLineStyle.h" #import "CPFill.h" #import "CPPlotRange.h" #import "CPGradient.h" #import "CPUtilities.h" #import "CPExceptions.h" NSString * const CPBarPlotBindingBarLengths = @"barLengths"; ///< Bar lengths. static NSString * const CPBarLengthsBindingContext = @"CPBarLengthsBindingContext"; /// @cond @interface CPBarPlot () @property (nonatomic, readwrite, assign) id observedObjectForBarLengthValues; @property (nonatomic, readwrite, copy) NSString *keyPathForBarLengthValues; @property (nonatomic, readwrite, copy) NSArray *barLengths; @property (nonatomic, readwrite, copy) NSArray *barLocations; -(void)drawBarInContext:(CGContextRef)context fromBasePoint:(CGPoint *)basePoint toTipPoint:(CGPoint *)tipPoint recordIndex:(NSUInteger)index; @end /// @endcond /** @brief A two-dimensional bar plot. **/ @implementation CPBarPlot @synthesize observedObjectForBarLengthValues; @synthesize keyPathForBarLengthValues; /** @property cornerRadius * @brief The corner radius for the end of the bars. **/ @synthesize cornerRadius; /** @property barOffset * @brief The starting offset of the first bar in units of bar width. **/ @synthesize barOffset; /** @property barWidth * @brief The width of each bar. **/ @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. **/ @synthesize baseValue; /** @property doublePrecisionBaseValue * @brief The coordinate value of the fixed end of the bars, as a double. **/ @synthesize doublePrecisionBaseValue; /** @property plotRange * @brief Sets the plot range for the independent axis. * * The bars are spaced evenly throughout the plot range. If plotRange is nil, the first bar will be placed * at zero (0) and subsequent bars will be at successive positive integer coordinates. **/ @synthesize plotRange; #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]; CPLineStyle *barLineStyle = [[CPLineStyle alloc] init]; barLineStyle.lineWidth = 1.0f; barLineStyle.lineColor = [CPColor blackColor]; barPlot.lineStyle = barLineStyle; [barLineStyle release]; barPlot.barsAreHorizontal = horizontal; barPlot.barWidth = 10.0f; barPlot.cornerRadius = 2.0f; CPGradient *fillGradient = [CPGradient gradientWithBeginningColor:color endingColor:[CPColor blackColor]]; fillGradient.angle = (horizontal ? -90.0f : 0.0f); barPlot.fill = [CPFill fillWithGradient:fillGradient]; return [barPlot autorelease]; } #pragma mark - #pragma mark Initialization -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { observedObjectForBarLengthValues = nil; keyPathForBarLengthValues = nil; lineStyle = [[CPLineStyle alloc] init]; fill = [[CPFill fillWithColor:[CPColor blackColor]] retain]; barWidth = 10.0f; barOffset = 0.0f; cornerRadius = 0.0f; baseValue = [[NSDecimalNumber zero] decimalValue]; doublePrecisionBaseValue = 0.0f; barLengths = nil; barsAreHorizontal = NO; plotRange = nil; self.needsDisplayOnBoundsChange = YES; } return self; } -(void)dealloc { if ( observedObjectForBarLengthValues ) [self unbind:CPBarPlotBindingBarLengths]; observedObjectForBarLengthValues = nil; [keyPathForBarLengthValues release]; [lineStyle release]; [fill release]; [barLengths release]; [plotRange release]; [super dealloc]; } -(void)bind:(NSString *)binding toObject:(id)observable withKeyPath:(NSString *)keyPath options:(NSDictionary *)options { [super bind:binding toObject:observable withKeyPath:keyPath options:options]; if ([binding isEqualToString:CPBarPlotBindingBarLengths]) { [observable addObserver:self forKeyPath:keyPath options:0 context:CPBarLengthsBindingContext]; self.observedObjectForBarLengthValues = observable; self.keyPathForBarLengthValues = keyPath; } [self setNeedsDisplay]; } -(void)unbind:(NSString *)bindingName { if ([bindingName isEqualToString:CPBarPlotBindingBarLengths]) { [observedObjectForBarLengthValues removeObserver:self forKeyPath:keyPathForBarLengthValues]; self.observedObjectForBarLengthValues = nil; self.keyPathForBarLengthValues = nil; } [super unbind:bindingName]; [self reloadData]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == CPBarLengthsBindingContext) { [self reloadData]; } } #pragma mark - #pragma mark Data Loading -(void)reloadData { [super reloadData]; CPXYPlotSpace *xyPlotSpace = (CPXYPlotSpace *)self.plotSpace; self.barLengths = nil; // Bar lengths if ( self.observedObjectForBarLengthValues ) { // Use bindings to retrieve data self.barLengths = [self.observedObjectForBarLengthValues valueForKeyPath:self.keyPathForBarLengthValues]; } else if ( self.dataSource ) { NSRange indexRange = [self recordIndexRangeForPlotRange:xyPlotSpace.xRange]; self.barLengths = [self numbersFromDataSourceForField:CPBarPlotFieldBarLength recordIndexRange:indexRange]; } // Locations of bars NSDecimal delta = [[NSDecimalNumber one] decimalValue]; double doublePrecisionDelta = 1.0; if ( self.plotRange && self.barLengths.count > 1 ) { delta = CPDecimalDivide(self.plotRange.length, CPDecimalFromInt(self.barLengths.count - 1)); doublePrecisionDelta = self.plotRange.doublePrecisionLength / (double)(self.barLengths.count - 1); } NSMutableArray *newLocations = [NSMutableArray arrayWithCapacity:self.barLengths.count]; for (NSUInteger ii = 0; ii < self.barLengths.count; ii++) { id dependentCoordValue = [self.barLengths objectAtIndex:ii]; if ([dependentCoordValue isKindOfClass:[NSDecimalNumber class]]) { NSDecimal location = CPDecimalMultiply(delta, CPDecimalFromInt(ii)); if ( self.plotRange ) { location = CPDecimalAdd(location, self.plotRange.location); } [newLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]]; } else { double location = doublePrecisionDelta * (double)ii + self.plotRange.doublePrecisionLocation; [newLocations addObject:[NSNumber numberWithDouble:location]]; } } self.barLocations = newLocations; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { if ( self.barLengths == nil ) return; if ( self.lineStyle == nil && self.fill == nil ) return; [super renderAsVectorInContext:theContext]; CGPoint tipPoint, basePoint; CPCoordinate independentCoord = ( self.barsAreHorizontal ? CPCoordinateY : CPCoordinateX ); CPCoordinate dependentCoord = ( self.barsAreHorizontal ? CPCoordinateX : CPCoordinateY ); NSArray *locations = self.barLocations; NSArray *lengths = self.barLengths; for (NSUInteger ii = 0; ii < [lengths count]; ii++) { id dependentCoordValue = [lengths objectAtIndex:ii]; id independentCoordValue = [locations objectAtIndex:ii]; if ( [dependentCoordValue isKindOfClass:[NSDecimalNumber class]] ) { double plotPoint[2]; plotPoint[independentCoord] = [independentCoordValue doubleValue]; // Tip point plotPoint[dependentCoord] = [dependentCoordValue doubleValue]; tipPoint = [self.plotSpace viewPointInLayer:self forDoublePrecisionPlotPoint:plotPoint]; // Base point plotPoint[dependentCoord] = self.doublePrecisionBaseValue; basePoint = [self.plotSpace viewPointInLayer:self forDoublePrecisionPlotPoint:plotPoint]; } else { NSDecimal plotPoint[2]; plotPoint[independentCoord] = [[locations objectAtIndex:ii] decimalValue]; // Tip point plotPoint[dependentCoord] = [[lengths objectAtIndex:ii] decimalValue]; tipPoint = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; // Base point plotPoint[dependentCoord] = baseValue; basePoint = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; } // Offset CGFloat viewOffset = self.barOffset * barWidth; if ( self.barsAreHorizontal ) { basePoint.y += viewOffset; tipPoint.y += viewOffset; } else { basePoint.x += viewOffset; tipPoint.x += viewOffset; } // Draw [self drawBarInContext:theContext fromBasePoint:&basePoint toTipPoint:&tipPoint recordIndex:ii]; } } -(void)drawBarInContext:(CGContextRef)context fromBasePoint:(CGPoint *)basePoint toTipPoint:(CGPoint *)tipPoint recordIndex:(NSUInteger)index { CPCoordinate widthCoordinate = ( self.barsAreHorizontal ? CPCoordinateY : CPCoordinateX ); CGFloat halfBarWidth = 0.5 * self.barWidth; CGFloat point[2]; point[CPCoordinateX] = basePoint->x; point[CPCoordinateY] = basePoint->y; point[widthCoordinate] += halfBarWidth; CGPoint alignedPoint1 = CPAlignPointToUserSpace(context, CGPointMake(point[CPCoordinateX], point[CPCoordinateY])); point[CPCoordinateX] = tipPoint->x; point[CPCoordinateY] = tipPoint->y; point[widthCoordinate] += halfBarWidth; CGPoint alignedPoint2 = CPAlignPointToUserSpace(context, CGPointMake(point[CPCoordinateX], point[CPCoordinateY])); point[CPCoordinateX] = tipPoint->x; point[CPCoordinateY] = tipPoint->y; CGPoint alignedPoint3 = CPAlignPointToUserSpace(context, CGPointMake(point[CPCoordinateX], point[CPCoordinateY])); point[CPCoordinateX] = tipPoint->x; point[CPCoordinateY] = tipPoint->y; point[widthCoordinate] -= halfBarWidth; CGPoint alignedPoint4 = CPAlignPointToUserSpace(context, CGPointMake(point[CPCoordinateX], point[CPCoordinateY])); point[CPCoordinateX] = basePoint->x; point[CPCoordinateY] = basePoint->y; point[widthCoordinate] -= halfBarWidth; CGPoint alignedPoint5 = CPAlignPointToUserSpace(context, CGPointMake(point[CPCoordinateX], point[CPCoordinateY])); CGFloat radius = MIN(self.cornerRadius, halfBarWidth); if ( self.barsAreHorizontal ) { 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); 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 ( nil != dataSourceFill ) currentBarFill = dataSourceFill; } if ( currentBarFill != nil && ![currentBarFill isKindOfClass:[NSNull class]] ) { CGContextBeginPath(context); CGContextAddPath(context, path); [currentBarFill fillPathInContext:context]; } if ( self.lineStyle ) { CGContextBeginPath(context); CGContextAddPath(context, path); [self.lineStyle setLineStyleInContext:context]; CGContextStrokePath(context); } CGContextRestoreGState(context); CGPathRelease(path); } #pragma mark - #pragma mark Accessors -(NSArray *)barLengths { return [self cachedNumbersForField:CPBarPlotFieldBarLength]; } -(void)setBarLengths:(NSArray *)newLengths { [self cacheNumbers:[[newLengths copy] autorelease] forField:CPBarPlotFieldBarLength]; } -(NSArray *)barLocations { return [self cachedNumbersForField:CPBarPlotFieldBarLocation]; } -(void)setBarLocations:(NSArray *)newLocations { [self cacheNumbers:[[newLocations copy] autorelease] 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:(CGFloat)newBarWidth { if (barWidth != newBarWidth) { barWidth = ABS(newBarWidth); [self setNeedsDisplay]; } } -(void)setBarOffset:(CGFloat)newBarOffset { if (barOffset != newBarOffset) { barOffset = newBarOffset; [self setNeedsDisplay]; } } -(void)setCornerRadius:(CGFloat)newCornerRadius { if (cornerRadius != newCornerRadius) { cornerRadius = ABS(newCornerRadius); [self setNeedsDisplay]; } } -(void)setBaseValue:(NSDecimal)newBaseValue { if ( !CPDecimalEquals(baseValue, newBaseValue) ) { baseValue = newBaseValue; [self setNeedsDisplay]; } } -(void)setDoublePrecisionBaseValue:(double)newDoublePrecisionBaseValue { if (doublePrecisionBaseValue != newDoublePrecisionBaseValue) { doublePrecisionBaseValue = newDoublePrecisionBaseValue; [self setNeedsDisplay]; } } -(void)setBarsAreHorizontal:(BOOL)newBarsAreHorizontal { if (barsAreHorizontal != newBarsAreHorizontal) { barsAreHorizontal = newBarsAreHorizontal; [self setNeedsDisplay]; } } #pragma mark - #pragma mark Fields -(NSUInteger)numberOfFields { return 2; } -(NSArray *)fieldIdentifiers { return [NSArray arrayWithObjects:[NSNumber numberWithUnsignedInt:CPBarPlotFieldBarLocation], [NSNumber numberWithUnsignedInt:CPBarPlotFieldBarLength], nil]; } -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord { NSArray *result = nil; switch (coord) { case CPCoordinateX: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:(self.barsAreHorizontal ? CPBarPlotFieldBarLength : CPBarPlotFieldBarLocation)]]; break; case CPCoordinateY: result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:(self.barsAreHorizontal ? CPBarPlotFieldBarLocation : CPBarPlotFieldBarLength)]]; break; default: [NSException raise:CPException format:@"Invalid coordinate passed to fieldIdentifiersForCoordinate:"]; break; } return result; } @end
08iteng-ipad
systemtests/tests/Source/CPBarPlot.m
Objective-C
bsd
15,306
#import "CPAxisLabel.h" #import "CPLayer.h" #import "CPTextLayer.h" #import "CPTextStyle.h" #import "CPExceptions.h" #import "CPUtilities.h" /// @cond @interface CPAxisLabel() @property (nonatomic, readwrite, retain) CPLayer *contentLayer; @end /// @endcond /** @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 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:(CPTextStyle *)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.0f; rotation = 0.0f; tickLocation = CPDecimalFromInt(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 axis coordinate. * @param direction The offset direction. **/ -(void)positionRelativeToViewPoint:(CGPoint)point forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction { CGPoint newPosition = point; CGFloat *value = (coordinate == CPCoordinateX ? &(newPosition.x) : &(newPosition.y)); CGPoint anchor = CGPointZero; // If there is no rotation, position the anchor point along the closest edge. // If there is rotation, leave the anchor in the center. switch ( direction ) { case CPSignNone: case CPSignNegative: *value -= offset; if ( rotation == 0.0f ) { anchor = (coordinate == CPCoordinateX ? CGPointMake(1.0, 0.5) : CGPointMake(0.5, 1.0)); } else { anchor = (coordinate == CPCoordinateX ? CGPointMake(1.0, 0.5) : CGPointMake(1.0, 0.5)); } break; case CPSignPositive: *value += offset; if ( rotation == 0.0f ) { anchor = (coordinate == CPCoordinateX ? CGPointMake(0.0, 0.5) : CGPointMake(0.5, 0.0)); } else { anchor = (coordinate == CPCoordinateX ? CGPointMake(0.0, 0.5) : CGPointMake(0.0, 0.5)); } break; default: [NSException raise:CPException format:@"Invalid sign in positionRelativeToViewPoint:inDirection:"]; break; } // Pixel-align the label layer to prevent blurriness CGSize currentSize = self.contentLayer.bounds.size; newPosition.x = round(newPosition.x - (currentSize.width * anchor.x)) + floor(currentSize.width * anchor.x); newPosition.y = round(newPosition.y - (currentSize.height * anchor.y)) + floor(currentSize.height * anchor.y); self.contentLayer.anchorPoint = anchor; self.contentLayer.position = newPosition; self.contentLayer.transform = CATransform3DMakeRotation(rotation, 0.0f, 0.0f, 1.0f); [self.contentLayer 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"]; } @end
08iteng-ipad
systemtests/tests/Source/CPAxisLabel.m
Objective-C
bsd
5,006
#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 end * @brief The ending value of the range. **/ @dynamic end; /** @property doublePrecisionLocation * @brief The starting value of the range, as a double. **/ @synthesize doublePrecisionLocation; /** @property doublePrecisionLength * @brief The length of the range, as a double. **/ @synthesize doublePrecisionLength; /** @property doublePrecisionEnd * @brief The ending value of the range, as a double. **/ @dynamic doublePrecisionEnd; #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] ) { location = loc; length = len; } return self; } #pragma mark - #pragma mark Accessors -(void)setLocation:(NSDecimal)newLocation; { if (CPDecimalEquals(location, newLocation)) { return; } location = newLocation; doublePrecisionLocation = [[NSDecimalNumber decimalNumberWithDecimal:location] doubleValue]; } -(void)setLength:(NSDecimal)newLength; { if (CPDecimalEquals(length, newLength)) { return; } length = newLength; doublePrecisionLength = [[NSDecimalNumber decimalNumberWithDecimal:length] doubleValue]; } -(NSDecimal)end { return CPDecimalAdd(self.location, self.length); } -(double)doublePrecisionEnd { return (self.doublePrecisionLocation + self.doublePrecisionLength); } #pragma mark - #pragma mark NSCopying -(id)copyWithZone:(NSZone *)zone { CPPlotRange *newRange = [[CPPlotRange allocWithZone:zone] init]; newRange.location = self.location; newRange.length = self.length; 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 { self = [super init]; if (self) { 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 <tt>location</tt> ≤ <tt>number</tt> ≤ <tt>end</tt>. **/ -(BOOL)contains:(NSDecimal)number { return (CPDecimalGreaterThanOrEqualTo(number, location) && CPDecimalLessThanOrEqualTo(number, self.end)); } #pragma mark - #pragma mark Combining ranges /** @brief Extends the range to include another range. * @param other The other plot range. **/ -(void)unionPlotRange:(CPPlotRange *)other { NSDecimal newLocation = (CPDecimalLessThan(self.location, other.location) ? self.location : other.location); NSDecimal max1 = CPDecimalAdd(self.location, self.length); NSDecimal max2 = CPDecimalAdd(other.location, other.length); NSDecimal max = (CPDecimalGreaterThan(max1, max2) ? max1 : max2); NSDecimal newLength = CPDecimalSubtract(max, newLocation); self.location = newLocation; self.length = newLength; } #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 newLength = CPDecimalMultiply(length, factor); NSDecimal locationOffset = CPDecimalDivide( CPDecimalSubtract(newLength, length), CPDecimalFromInt(2)); NSDecimal newLocation = CPDecimalSubtract(location, locationOffset); self.location = newLocation; self.length = newLength; } #pragma mark - #pragma mark Description -(NSString *)description { return [NSString stringWithFormat:@"{%@, %@}", NSDecimalString(&location, [NSLocale currentLocale]), NSDecimalString(&length, [NSLocale currentLocale])]; } @end
08iteng-ipad
systemtests/tests/Source/CPPlotRange.m
Objective-C
bsd
5,010
#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 cornerRadius * @brief Radius for the rounded corners of the layer. **/ @synthesize cornerRadius; /** @property fill * @brief The fill for the layer background. * If nil, the layer background is not filled. **/ @synthesize fill; /** @property masksToBorder * @brief If YES (the default), a sublayer mask is applied to clip sublayer content to the inside of the border. **/ @synthesize masksToBorder; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { borderLineStyle = nil; fill = nil; cornerRadius = 0.0f; outerBorderPath = NULL; innerBorderPath = NULL; masksToBorder = YES; self.needsDisplayOnBoundsChange = YES; } return self; } -(void)dealloc { [borderLineStyle release]; [fill release]; CGPathRelease(outerBorderPath); CGPathRelease(innerBorderPath); [super dealloc]; } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)context { [super renderAsVectorInContext:context]; [self.fill fillRect:self.bounds inContext:context]; if ( self.borderLineStyle ) { CGFloat inset = self.borderLineStyle.lineWidth / 2; CGRect selfBounds = CGRectInset(self.bounds, inset, inset); [self.borderLineStyle setLineStyleInContext:context]; CGContextBeginPath(context); if ( self.cornerRadius > 0.0f ) { CGFloat radius = MIN(MIN(self.cornerRadius, selfBounds.size.width / 2), selfBounds.size.height / 2); AddRoundedRectPath(context, selfBounds, radius); } else { CGContextAddRect(context, selfBounds); } CGContextStrokePath(context); } } #pragma mark - #pragma mark Layout -(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 // TODO: create a generic layout manager akin to CAConstraintLayoutManager ("struts and springs" is not flexible enough) // Sublayers fill the super layer's bounds minus any padding by default CGRect selfBounds = self.bounds; CGSize subLayerSize = selfBounds.size; CGFloat lineWidth = self.borderLineStyle.lineWidth; subLayerSize.width -= self.paddingLeft + self.paddingRight + lineWidth; subLayerSize.width = MAX(subLayerSize.width, 0.0f); subLayerSize.height -= self.paddingTop + self.paddingBottom + lineWidth; subLayerSize.height = MAX(subLayerSize.height, 0.0f); for (CALayer *subLayer in self.sublayers) { CGRect subLayerBounds = subLayer.bounds; subLayerBounds.size = subLayerSize; subLayer.bounds = subLayerBounds; subLayer.anchorPoint = CGPointZero; subLayer.position = CGPointMake(selfBounds.origin.x + self.paddingLeft, selfBounds.origin.y + self.paddingBottom); } } #pragma mark - #pragma mark Masking -(CGPathRef)maskingPath { if ( outerBorderPath ) return outerBorderPath; CGPathRelease(outerBorderPath); CGFloat lineWidth = self.borderLineStyle.lineWidth; CGRect selfBounds = self.bounds; if ( self.cornerRadius > 0.0f ) { CGFloat radius = MIN(MIN(self.cornerRadius + lineWidth / 2, selfBounds.size.width / 2), selfBounds.size.height / 2); outerBorderPath = CreateRoundedRectPath(selfBounds, radius); } else { CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, selfBounds); outerBorderPath = path; } return outerBorderPath; } -(CGPathRef)sublayerMaskingPath { if ( self.masksToBorder ) { if ( innerBorderPath ) return innerBorderPath; CGPathRelease(innerBorderPath); CGFloat lineWidth = self.borderLineStyle.lineWidth; CGRect selfBounds = CGRectInset(self.bounds, lineWidth, lineWidth); if ( self.cornerRadius > 0.0f ) { CGFloat radius = MIN(MIN(self.cornerRadius - lineWidth / 2, selfBounds.size.width / 2), selfBounds.size.height / 2); innerBorderPath = CreateRoundedRectPath(selfBounds, radius); } else { CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, selfBounds); innerBorderPath = path; } return innerBorderPath; } else { return NULL; } } #pragma mark - #pragma mark Accessors -(void)setBorderLineStyle:(CPLineStyle *)newLineStyle { if ( newLineStyle != borderLineStyle ) { if ( newLineStyle.lineWidth != borderLineStyle.lineWidth ) { CGPathRelease(innerBorderPath); innerBorderPath = NULL; } [borderLineStyle release]; borderLineStyle = [newLineStyle copy]; [self setNeedsDisplay]; } } -(void)setCornerRadius:(CGFloat)newRadius { if ( newRadius != cornerRadius ) { cornerRadius = ABS(newRadius); [self setNeedsDisplay]; CGPathRelease(outerBorderPath); outerBorderPath = NULL; CGPathRelease(innerBorderPath); innerBorderPath = NULL; } } -(void)setFill:(CPFill *)newFill { if ( newFill != fill ) { [fill release]; fill = [newFill copy]; [self setNeedsDisplay]; } } -(void)setBounds:(CGRect)newBounds { [super setBounds:newBounds]; CGPathRelease(outerBorderPath); outerBorderPath = NULL; CGPathRelease(innerBorderPath); innerBorderPath = NULL; } @end
08iteng-ipad
systemtests/tests/Source/CPBorderedLayer.m
Objective-C
bsd
5,379
#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
systemtests/tests/Source/CPTimeFormatter.h
Objective-C
bsd
373
#import "CPDefinitions.h" #import "CPPlotRange.h" #import "CPLayer.h" @class CPPlot; @class CPPlotSpace; @class CPPlotRange; /** @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 Determines the record index range corresponding to a given range of data. * This method is optional. * @param plot The plot. * @param plotRange The range expressed in data values. * @return The range of record indexes. **/ -(NSRange)recordIndexRangeForPlot:(CPPlot *)plot plotRange:(CPPlotRange *)plotRange; @end @interface CPPlot : CPLayer { @private id <CPPlotDataSource> dataSource; id <NSCopying, NSObject> identifier; CPPlotSpace *plotSpace; BOOL dataNeedsReloading; NSMutableDictionary *cachedData; } @property (nonatomic, readwrite, assign) id <CPPlotDataSource> dataSource; @property (nonatomic, readwrite, copy) id <NSCopying, NSObject> identifier; @property (nonatomic, readwrite, retain) CPPlotSpace *plotSpace; @property (nonatomic, readonly, assign) BOOL dataNeedsReloading; /// @name Data Loading /// @{ -(void)setDataNeedsReloading; -(void)reloadData; /// @} /// @name Plot Data /// @{ -(NSArray *)numbersFromDataSourceForField:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange; -(NSRange)recordIndexRangeForPlotRange:(CPPlotRange *)plotRange; /// @} /// @name Data Cache /// @{ -(NSArray *)cachedNumbersForField:(NSUInteger)fieldEnum; -(void)cacheNumbers:(NSArray *)numbers forField:(NSUInteger)fieldEnum; /// @} /// @name Plot Data Ranges /// @{ -(CPPlotRange *)plotRangeForField:(NSUInteger)fieldEnum; -(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coord; /// @} /// @name Fields /// @{ -(NSUInteger)numberOfFields; -(NSArray *)fieldIdentifiers; -(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord; /// @} @end
08iteng-ipad
systemtests/tests/Source/CPPlot.h
Objective-C
bsd
2,705
#import "CPBorderedLayer.h" @class CPAxisSet; @class CPPlotGroup; @interface CPPlotArea : CPBorderedLayer { @private CPAxisSet *axisSet; CPPlotGroup *plotGroup; } @property (nonatomic, readwrite, retain) CPAxisSet *axisSet; @property (nonatomic, readwrite, retain) CPPlotGroup *plotGroup; @end
08iteng-ipad
systemtests/tests/Source/CPPlotArea.h
Objective-C
bsd
306
#import <Foundation/Foundation.h> #import "CPLayer.h" #import "CPDefinitions.h" /// @file @class CPLineStyle; @class CPPlotSpace; @class CPPlotRange; @class CPAxis; @class CPTextStyle; @class CPAxisTitle; /** @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 (not implemented). // TODO: Implement logarithmic labeling CPAxisLabelingPolicyLogarithmic ///< logarithmic labeling policy (not implemented). } CPAxisLabelingPolicy; /** @brief Axis labeling delegate. **/ @protocol CPAxisDelegate /// @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; /// @} @end @interface CPAxis : CPLayer { @private CPCoordinate coordinate; CPPlotSpace *plotSpace; NSSet *majorTickLocations; NSSet *minorTickLocations; CGFloat majorTickLength; CGFloat minorTickLength; CGFloat axisLabelOffset; CGFloat axisLabelRotation; CPLineStyle *axisLineStyle; CPLineStyle *majorTickLineStyle; CPLineStyle *minorTickLineStyle; CPLineStyle *majorGridLineStyle; CPLineStyle *minorGridLineStyle; NSDecimal fixedPoint; // TODO: NSDecimal instance variables in CALayers cause an unhandled property type encoding error NSDecimal majorIntervalLength; // TODO: NSDecimal instance variables in CALayers cause an unhandled property type encoding error NSUInteger minorTicksPerInterval; NSUInteger preferredNumberOfMajorTicks; CPAxisLabelingPolicy axisLabelingPolicy; CPTextStyle *axisLabelTextStyle; CPTextStyle *axisTitleTextStyle; NSNumberFormatter *axisLabelFormatter; NSSet *axisLabels; CPAxisTitle *axisTitle; NSString *title; CGFloat axisTitleOffset; CPSign tickDirection; BOOL needsRelabel; NSArray *labelExclusionRanges; id <CPAxisDelegate> delegate; } /// @name Axis /// @{ @property (nonatomic, readwrite, copy) CPLineStyle *axisLineStyle; @property (nonatomic, readwrite, assign) CPCoordinate coordinate; @property (nonatomic, readwrite) NSDecimal fixedPoint; @property (nonatomic, readwrite, assign) CPSign tickDirection; /// @} /// @name Title /// @{ @property (nonatomic, readwrite, copy) CPTextStyle *axisTitleTextStyle; @property (nonatomic, readwrite, retain) CPAxisTitle *axisTitle; @property (nonatomic, readwrite, assign) CGFloat axisTitleOffset; @property (nonatomic, readwrite, retain) NSString *title; /// @} /// @name Labels /// @{ @property (nonatomic, readwrite, assign) CPAxisLabelingPolicy axisLabelingPolicy; @property (nonatomic, readwrite, assign) CGFloat axisLabelOffset; @property (nonatomic, readwrite, assign) CGFloat axisLabelRotation; @property (nonatomic, readwrite, copy) CPTextStyle *axisLabelTextStyle; @property (nonatomic, readwrite, retain) NSNumberFormatter *axisLabelFormatter; @property (nonatomic, readwrite, retain) NSSet *axisLabels; @property (nonatomic, readonly, assign) BOOL needsRelabel; @property (nonatomic, readwrite, retain) NSArray *labelExclusionRanges; @property (nonatomic, readwrite, assign) id <CPAxisDelegate> delegate; /// @} /// @name Major Ticks /// @{ @property (nonatomic, readwrite) 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, retain) CPPlotSpace *plotSpace; /// @name Labels /// @{ -(void)relabel; -(void)setNeedsRelabel; -(NSArray *)newAxisLabelsAtLocations:(NSArray *)locations; -(NSDecimal)axisTitleLocation; /// @} /// @name Ticks /// @{ -(NSSet *)filteredMajorTickLocations:(NSSet *)allLocations; -(NSSet *)filteredMinorTickLocations:(NSSet *)allLocations; /// @} @end @interface CPAxis(AbstractMethods) /// @name Coordinate Space Conversions /// @{ -(CGPoint)viewPointForCoordinateDecimalNumber:(NSDecimal)coordinateDecimalNumber; /// @} @end
08iteng-ipad
systemtests/tests/Source/CPAxis.h
Objective-C
bsd
5,137
#import "CPDataSourceTestCase.h" #import "CPScatterPlot.h" @interface CPScatterPlotTests : CPDataSourceTestCase { CPScatterPlot *plot; } @property (retain,readwrite) CPScatterPlot *plot; - (void)setPlotRanges; @end
08iteng-ipad
systemtests/tests/Source/CPScatterPlotTests.h
Objective-C
bsd
224
#import "CPXYPlotSpaceTests.h" #import "CPLayer.h" #import "CPXYPlotSpace.h" #import "CPExceptions.h" #import "CPPlotRange.h" #import "CPUtilities.h" @interface CPXYPlotSpace (UnitTesting) - (void)gtm_unitTestEncodeState:(NSCoder*)inCoder; @end @implementation CPXYPlotSpace (UnitTesting) -(void)gtm_unitTestEncodeState:(NSCoder*)inCoder { [super gtm_unitTestEncodeState:inCoder]; [inCoder encodeObject:self.xRange forKey:@"xRange"]; [inCoder encodeObject:self.yRange forKey:@"yRange"]; } @end @implementation CPXYPlotSpaceTests @synthesize layer; @synthesize plotSpace; - (void)setUp { self.layer = [[(CPLayer *)[CPLayer alloc] initWithFrame:CGRectMake(0., 0., 100., 50.)] autorelease]; self.plotSpace = [[[CPXYPlotSpace alloc] init] autorelease]; } - (void)tearDown { self.layer = nil; self.plotSpace = nil; } - (void)testViewPointForPlotPoint { self.plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.) length:CPDecimalFromFloat(10.)]; self.plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.) length:CPDecimalFromFloat(10.)]; GTMAssertObjectStateEqualToStateNamed(self.plotSpace, @"CPCartesianPlotSpaceTests-testViewPointForPlotPointSmoke1", @""); NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = CPDecimalFromString(@"5.0"); plotPoint[CPCoordinateY] = CPDecimalFromString(@"5.0"); CGPoint viewPoint = [[self plotSpace] viewPointInLayer:self.layer forPlotPoint:plotPoint]; STAssertEqualsWithAccuracy(viewPoint.x, (CGFloat)50., (CGFloat)0.01, @""); STAssertEqualsWithAccuracy(viewPoint.y, (CGFloat)25., (CGFloat)0.01, @""); self.plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.) length:CPDecimalFromFloat(10.)]; self.plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.) length:CPDecimalFromFloat(5.)]; GTMAssertObjectStateEqualToStateNamed(self.plotSpace, @"CPCartesianPlotSpaceTests-testViewPointForPlotPointSmoke2", @""); viewPoint = [[self plotSpace] viewPointInLayer:self.layer forPlotPoint:plotPoint]; STAssertEqualsWithAccuracy(viewPoint.x, (CGFloat)50., (CGFloat)0.01, @""); STAssertEqualsWithAccuracy(viewPoint.y, (CGFloat)50., (CGFloat)0.01, @""); } - (void)testPlotPointForViewPoint { self.plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.) length:CPDecimalFromFloat(10.)]; self.plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.) length:CPDecimalFromFloat(10.)]; GTMAssertObjectStateEqualToStateNamed(self.plotSpace, @"CPCartesianPlotSpaceTests-testPlotPointForViewPoint", @""); NSDecimal plotPoint[2]; CGPoint viewPoint = CGPointMake(50., 25.); [[self plotSpace] plotPoint:plotPoint forViewPoint:viewPoint inLayer:self.layer]; STAssertTrue(CPDecimalEquals(plotPoint[CPCoordinateX], CPDecimalFromString(@"5.0")), @""); STAssertTrue(CPDecimalEquals(plotPoint[CPCoordinateY], CPDecimalFromString(@"5.0")), @""); } @end
08iteng-ipad
systemtests/tests/Source/CPXYPlotSpaceTests.m
Objective-C
bsd
3,406
#import "CPScatterPlotTests.h" #import "CPDataSourceTestCase.h" @class CPScatterPlot; @interface CPScatterPlotPerformanceTests : CPDataSourceTestCase { CPScatterPlot *plot; } @property (retain,readwrite) CPScatterPlot *plot; - (void)setPlotRanges; @end
08iteng-ipad
systemtests/tests/Source/CPScatterPlotPerformanceTests.h
Objective-C
bsd
264
#import <Foundation/Foundation.h> @class CPGraph; @class CPPlotArea; @class CPAxisSet; @class CPTextStyle; /// @file /// @name Theme Names /// @{ extern NSString * const kCPDarkGradientTheme; extern NSString * const kCPPlainWhiteTheme; extern NSString * const kCPPlainBlackTheme; extern NSString * const kCPStocksTheme; /// @} @interface CPTheme : NSObject { @private NSString *name; Class graphClass; } @property (nonatomic, readwrite, copy) NSString *name; @property (nonatomic, readwrite, retain) Class graphClass; +(NSArray *)themeClasses; +(CPTheme *)themeNamed:(NSString *)theme; +(void)addTheme:(CPTheme *)newTheme; +(NSString *)defaultName; -(id)newGraph; -(void)applyThemeToGraph:(CPGraph *)graph; -(void)applyThemeToBackground:(CPGraph *)graph; -(void)applyThemeToPlotArea:(CPPlotArea *)plotArea; -(void)applyThemeToAxisSet:(CPAxisSet *)axisSet; @end
08iteng-ipad
systemtests/tests/Source/CPTheme.h
Objective-C
bsd
875
#import <Foundation/Foundation.h> #import "CPDefinitions.h" @class CPLayer; @class CPTextStyle; @interface CPAxisLabel : NSObject { @private CPLayer *contentLayer; CGFloat offset; CGFloat rotation; NSDecimal tickLocation; // TODO: NSDecimal instance variables in CALayers cause an unhandled property type encoding error } @property (nonatomic, readonly, retain) CPLayer *contentLayer; @property (nonatomic, readwrite, assign) CGFloat offset; @property (nonatomic, readwrite, assign) CGFloat rotation; @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
systemtests/tests/Source/CPAxisLabel.h
Objective-C
bsd
1,047
#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
systemtests/tests/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)init { if ( self = [super init] ) { identifier = nil; } 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
systemtests/tests/Source/CPPlotGroup.m
Objective-C
bsd
970
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPStocksTheme : CPXYTheme { } @end
08iteng-ipad
systemtests/tests/Source/CPStocksTheme.h
Objective-C
bsd
106
#import "CPAnimationTransition.h" #import "CPAnimationKeyFrame.h" #import "CPAnimation.h" /** @brief An animation transition. * @note Not implemented. * @todo * - Implement CPAnimationTransition. * - Add documentation for CPAnimationTransition. **/ @implementation CPAnimationTransition /// @defgroup CPAnimationTransition CPAnimationTransition /// @{ /** @property identifier * @todo Needs documentation. **/ @synthesize identifier; /** @property duration * @todo Needs documentation. **/ @synthesize duration; /** @property reversible * @todo Needs documentation. **/ @synthesize reversible; /** @property animation * @todo Needs documentation. **/ @synthesize animation; /** @property startKeyFrame * @todo Needs documentation. **/ @synthesize startKeyFrame; /** @property endKeyFrame * @todo Needs documentation. **/ @synthesize endKeyFrame; /** @property continuingTransition * @todo Needs documentation. **/ @synthesize continuingTransition; #pragma mark - #pragma mark Init/Dealloc -(id)init { if ( self = [super init] ) { identifier = nil; startKeyFrame = nil; endKeyFrame = nil; continuingTransition = nil; duration = 0.0; animation = nil; reversible = NO; } return self; } -(void)dealloc { [identifier release]; [animation release]; [startKeyFrame release]; [endKeyFrame release]; [continuingTransition release]; [super dealloc]; } /// @} @end /// @brief CPAnimationTransition abstract methods—must be overridden by subclasses @implementation CPAnimationTransition(AbstractMethods) /// @addtogroup CPAnimationTransition /// @{ /** @todo Needs documentation. **/ -(void)performTransition { } /// @} @end
08iteng-ipad
systemtests/tests/Source/CPAnimationTransition.m
Objective-C
bsd
1,699
#import "CPLineStyle.h" #import "CPLayer.h" #import "CPColor.h" /** @brief 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. **/ @implementation CPLineStyle /** @property lineCap * @brief Sets the style for the endpoints of lines drawn in a graphics context. **/ @synthesize lineCap; /** @property lineJoin * @brief Sets the style for the joins of connected lines in a graphics context. **/ @synthesize lineJoin; /** @property miterLimit * @brief Sets the miter limit for the joins of connected lines in a graphics context. **/ @synthesize miterLimit; /** @property lineWidth * @brief Sets the line width for a graphics context. **/ @synthesize lineWidth; /** @property patternPhase * @brief Sets the pattern phase of a context. **/ @synthesize patternPhase; /** @property lineColor * @brief Sets 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. **/ +(CPLineStyle *)lineStyle { return [[[self alloc] init] autorelease]; } -(id)init { if ( self = [super init] ) { lineCap = kCGLineCapButt; lineJoin = kCGLineJoinMiter; miterLimit = 10.f; lineWidth = 1.f; patternPhase = CGSizeMake(0.f, 0.f); lineColor = [[CPColor blackColor] retain]; } return self; } -(void)dealloc { [lineColor 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); CGContextSetPatternPhase(theContext, patternPhase); CGContextSetStrokeColorWithColor(theContext, lineColor.cgColor); } #pragma mark - #pragma mark NSCopying methods -(id)copyWithZone:(NSZone *)zone { CPLineStyle *styleCopy = [[[self class] allocWithZone:zone] init]; styleCopy->lineCap = self->lineCap; styleCopy->lineJoin = self->lineJoin; styleCopy->miterLimit = self->miterLimit; styleCopy->lineWidth = self->lineWidth; styleCopy->patternPhase = self->patternPhase; styleCopy->lineColor = [self->lineColor copy]; return styleCopy; } @end
08iteng-ipad
systemtests/tests/Source/CPLineStyle.m
Objective-C
bsd
2,806
// Abstract class #import "CPBorderedLayer.h" @class CPAxisSet; @class CPPlot; @class CPPlotArea; @class CPPlotSpace; @class CPTheme; @interface CPGraph : CPBorderedLayer { @private CPPlotArea *plotArea; NSMutableArray *plots; NSMutableArray *plotSpaces; } @property (nonatomic, readwrite, retain) CPAxisSet *axisSet; @property (nonatomic, readwrite, retain) CPPlotArea *plotArea; @property (nonatomic, readonly, retain) CPPlotSpace *defaultPlotSpace; /// @name Data Source /// @{ -(void)reloadData; /// @} /// @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 @interface CPGraph (AbstractFactoryMethods) -(CPPlotSpace *)newPlotSpace; -(CPAxisSet *)newAxisSet; @end
08iteng-ipad
systemtests/tests/Source/CPGraph.h
Objective-C
bsd
1,550
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPPlainWhiteTheme : CPXYTheme { } @end
08iteng-ipad
systemtests/tests/Source/CPPlainWhiteTheme.h
Objective-C
bsd
110
#import <Foundation/Foundation.h> #import "CPXYTheme.h" @interface CPDarkGradientTheme : CPXYTheme { } @end
08iteng-ipad
systemtests/tests/Source/CPDarkGradientTheme.h
Objective-C
bsd
110
#import "CPPlainWhiteTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotArea.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPLineStyle.h" #import "CPTextStyle.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:(CPPlotArea *)plotArea { plotArea.fill = [CPFill fillWithColor:[CPColor whiteColor]]; CPLineStyle *borderLineStyle = [CPLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor blackColor]; borderLineStyle.lineWidth = 1.0f; plotArea.borderLineStyle = borderLineStyle; plotArea.cornerRadius = 0.0f; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPLineStyle *majorLineStyle = [CPLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapButt; majorLineStyle.lineColor = [CPColor colorWithGenericGray:0.5]; majorLineStyle.lineWidth = 1.0f; CPLineStyle *minorLineStyle = [CPLineStyle lineStyle]; minorLineStyle.lineCap = kCGLineCapButt; minorLineStyle.lineColor = [CPColor blackColor]; minorLineStyle.lineWidth = 1.0f; CPXYAxis *x = axisSet.xAxis; CPTextStyle *blackTextStyle = [[[CPTextStyle alloc] init] autorelease]; blackTextStyle.color = [CPColor blackColor]; blackTextStyle.fontSize = 14.0; x.axisLabelingPolicy = CPAxisLabelingPolicyFixedInterval; x.majorIntervalLength = CPDecimalFromString(@"0.5"); x.constantCoordinateValue = CPDecimalFromString(@"0"); x.tickDirection = CPSignNone; x.minorTicksPerInterval = 4; x.majorTickLineStyle = majorLineStyle; x.minorTickLineStyle = minorLineStyle; x.axisLineStyle = majorLineStyle; x.majorTickLength = 7.0f; x.minorTickLength = 5.0f; x.axisLabelTextStyle = blackTextStyle; x.axisTitleTextStyle = blackTextStyle; CPXYAxis *y = axisSet.yAxis; y.axisLabelingPolicy = CPAxisLabelingPolicyFixedInterval; y.majorIntervalLength = CPDecimalFromString(@"0.5"); y.minorTicksPerInterval = 4; y.constantCoordinateValue = CPDecimalFromString(@"0"); y.tickDirection = CPSignNone; y.majorTickLineStyle = majorLineStyle; y.minorTickLineStyle = minorLineStyle; y.axisLineStyle = majorLineStyle; y.majorTickLength = 7.0f; y.minorTickLength = 5.0f; y.axisLabelTextStyle = blackTextStyle; y.axisTitleTextStyle = blackTextStyle; } @end
08iteng-ipad
systemtests/tests/Source/CPPlainWhiteTheme.m
Objective-C
bsd
2,664
// 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)colorStopAtIndex:(NSUInteger)index; -(CGColorRef)colorAtPosition:(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
systemtests/tests/Source/CPGradient.h
Objective-C
bsd
2,961
#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; CGMutablePathRef symbolPath; CGPathRef customSymbolPath; BOOL usesEvenOddClipRule; } @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; //+(CPPlotSymbol *)plotSymbolWithString:(NSString *)aString; /// @} /// @name Drawing /// @{ -(void)renderInContext:(CGContextRef)theContext atPoint:(CGPoint)center; /// @} @end
08iteng-ipad
systemtests/tests/Source/CPPlotSymbol.h
Objective-C
bsd
2,082
#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
systemtests/tests/Source/_CPFillColor.h
Objective-C
bsd
383
#import "CPXYGraphTests.h" #import "CPExceptions.h" #import "CPPlotRange.h" #import "CPScatterPlot.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPLineStyle.h" #import "CPPlotArea.h" #import "CPPlotSymbol.h" #import "CPFill.h" #import "CPColor.h" #import "GTMTestTimer.h" #import "CPPlatformSpecificFunctions.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" @interface CPXYGraph (UnitTesting) - (void)gtm_unitTestEncodeState:(NSCoder*)inCoder; @end @implementation CPXYGraph (UnitTesting) -(void)gtm_unitTestEncodeState:(NSCoder*)inCoder { [super gtm_unitTestEncodeState:inCoder]; } @end @implementation CPXYGraphTests @synthesize graph; - (void)setUp { self.graph = [[[CPXYGraph alloc] init] autorelease]; CGColorRef grayColor = CGColorCreateGenericGray(0.7, 1.0); self.graph.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:grayColor]]; CGColorRelease(grayColor); grayColor = CGColorCreateGenericGray(0.2, 0.3); self.graph.plotArea.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:grayColor]]; CGColorRelease(grayColor); self.nRecords = 100; } - (void)tearDown { self.graph = nil; } - (void)addScatterPlot { [self addScatterPlotUsingSymbols:NO]; } - (void)addScatterPlotUsingSymbols:(BOOL)useSymbols { self.graph.bounds = CGRectMake(0., 0., 400., 200.); CPScatterPlot *scatterPlot = [[[CPScatterPlot alloc] init] autorelease]; scatterPlot.identifier = @"Scatter Plot"; scatterPlot.dataLineStyle.lineWidth = 1.0; scatterPlot.dataSource = self; [self addPlot:scatterPlot]; // Add plot symbols if(useSymbols) { CPPlotSymbol *greenCirclePlotSymbol = [CPPlotSymbol ellipsePlotSymbol]; CGColorRef greenColor = CPNewCGColorFromNSColor([NSColor greenColor]); greenCirclePlotSymbol.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:greenColor]]; greenCirclePlotSymbol.size = CGSizeMake(5.0, 5.0); greenCirclePlotSymbol.lineStyle.lineWidth = 0.1; scatterPlot.plotSymbol = greenCirclePlotSymbol; CGColorRelease(greenColor); } CPXYPlotSpace *plotSpace; if([[self.graph allPlotSpaces] count] == 0) { plotSpace = (CPXYPlotSpace*)[[self graph] newPlotSpace]; [[self graph] addPlotSpace:plotSpace]; [plotSpace release]; } else { plotSpace = (CPXYPlotSpace*)[[self graph] defaultPlotSpace]; } _GTMDevAssert(plotSpace != nil, @""); plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInt(0) length:CPDecimalFromInt(self.nRecords)]; plotSpace.yRange = [self yRange]; _GTMDevLog(@"%@", [self yRange]); [[self graph] addPlot:scatterPlot toPlotSpace:plotSpace]; } - (void)addXYAxisSet { CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet; CPXYAxis *x = axisSet.xAxis; x.majorIntervalLength = CPDecimalFromString(@"0.5"); x.constantCoordinateValue = CPDecimalFromString(@"2"); x.minorTicksPerInterval = 2; CPXYAxis *y = axisSet.yAxis; y.majorIntervalLength = CPDecimalFromString(@"0.5"); y.minorTicksPerInterval = 5; y.constantCoordinateValue = CPDecimalFromString(@"2"); } /** This is really an integration test. This test verifies that a complete graph (with one scatter plot and plot symbols) renders correctly. */ - (void)testRenderScatterWithSymbol { self.nRecords = 1e2; [self buildData]; [self addScatterPlotUsingSymbols:YES]; [self addXYAxisSet]; GTMAssertObjectImageEqualToImageNamed(self.graph, @"CPXYGraphTests-testRenderScatterWithSymbol", @"Should render a sine wave with green symbols."); } - (void)testRenderMultipleScatter { self.nRecords = 1e2; [self buildData]; [self addScatterPlot]; [self addScatterPlot]; [self addScatterPlot]; GTMAssertObjectImageEqualToImageNamed(self.graph, @"CPXYGraphTests-testRenderMultipleScatter", @"Should render 3 offset sine waves with no symbols."); } @end
08iteng-ipad
systemtests/tests/Source/CPXYGraphTests.m
Objective-C
bsd
4,033
#import <Foundation/Foundation.h> /// @file /// @name Custom Exception Identifiers /// @{ extern NSString * const CPException; extern NSString * const CPDataException; /// @}
08iteng-ipad
systemtests/tests/Source/CPExceptions.h
Objective-C
bsd
178
#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
systemtests/tests/Source/_CPFillGradient.m
Objective-C
bsd
2,099
#import "CPColorTests.h" #import "CPColor.h" @interface CPColor (UnitTesting) - (void)gtm_unitTestEncodeState:(NSCoder*)inCoder; @end @implementation CPColor (UnitTesting) - (void)gtm_unitTestEncodeState:(NSCoder*)inCoder { [super gtm_unitTestEncodeState:inCoder]; [self encodeWithCoder:inCoder]; } @end @implementation CPColorTests - (void)testFactories { GTMAssertObjectStateEqualToStateNamed([CPColor clearColor], @"CPColorTests-testFactories-clearColor", @""); GTMAssertObjectStateEqualToStateNamed([CPColor whiteColor], @"CPColorTests-testFactories-whiteColor", @""); GTMAssertObjectStateEqualToStateNamed([CPColor blackColor], @"CPColorTests-testFactories-blackColor", @""); GTMAssertObjectStateEqualToStateNamed([CPColor redColor], @"CPColorTests-testFactories-redColor", @""); } - (void)testCGColorRoundTrip { CGFloat compValue = 0.2; CGColorRef expected = CGColorCreateGenericRGB(compValue, compValue, compValue, compValue); CPColor *cpColor = [[CPColor alloc] initWithCGColor:expected]; GTMAssertObjectStateEqualToStateNamed(cpColor, @"CPColorTests-testCGColorRoundTrip", @""); const CGFloat *actual = CGColorGetComponents(cpColor.cgColor); for(int i=0; i<4; i++) { STAssertEqualsWithAccuracy(actual[i], compValue, .001f, @"round-trip CGColor components not equal"); } [cpColor release]; CFRelease(expected); } @end
08iteng-ipad
systemtests/tests/Source/CPColorTests.m
Objective-C
bsd
1,434
#import "CPTestCase.h" @interface CPColorTests : CPTestCase { } @end
08iteng-ipad
systemtests/tests/Source/CPColorTests.h
Objective-C
bsd
72
#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 *)blackColor; +(CPColor *)redColor; +(CPColor *)greenColor; +(CPColor *)blueColor; +(CPColor *)darkGrayColor; +(CPColor *)lightGrayColor; +(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
systemtests/tests/Source/CPColor.h
Objective-C
bsd
913
#import "CPDataSourceTestCase.h" #import "CPXYGraph.h" @interface CPXYGraphTests : CPDataSourceTestCase { CPXYGraph *graph; } @property (retain,readwrite) CPXYGraph *graph; - (void)addScatterPlot; - (void)addScatterPlotUsingSymbols:(BOOL)useSymbols; - (void)addXYAxisSet; @end
08iteng-ipad
systemtests/tests/Source/CPXYGraphTests.h
Objective-C
bsd
286
#import <Foundation/Foundation.h> @class CPAnimation; @class CPAnimationKeyFrame; @interface CPAnimationTransition : NSObject { @private id <NSObject, NSCopying> identifier; CPAnimationKeyFrame *startKeyFrame; CPAnimationKeyFrame *endKeyFrame; CPAnimationTransition *continuingTransition; NSTimeInterval duration; CPAnimation *animation; BOOL reversible; } @property (nonatomic, readwrite, copy) id <NSCopying> identifier; @property (nonatomic, readwrite, assign) NSTimeInterval duration; @property (nonatomic, readonly, assign) BOOL reversible; @property (nonatomic, readwrite, assign) CPAnimation *animation; @property (nonatomic, readwrite, retain) CPAnimationKeyFrame *startKeyFrame; @property (nonatomic, readwrite, retain) CPAnimationKeyFrame *endKeyFrame; @property (nonatomic, readwrite, retain) CPAnimationTransition *continuingTransition; @end @interface CPAnimationTransition(AbstractMethods) -(void)performTransition; @end
08iteng-ipad
systemtests/tests/Source/CPAnimationTransition.h
Objective-C
bsd
969
#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)axialGradientInRect:(CGRect)rect; -(CGShadingRef)radialGradientInRect:(CGRect)rect context:(CGContextRef)context; -(CPGradientElement *)elementAtIndex:(NSUInteger)index; -(CPGradientElement)removeElementAtIndex:(NSUInteger)index; -(CPGradientElement)removeElementAtPosition:(CGFloat)position; @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); /** @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.0f; gradientType = CPGradientTypeAxial; } return self; } -(void)commonInit { colorspace = [[CPColorSpace genericRGBSpace] retain]; elementList = NULL; } -(void)dealloc { [colorspace release]; CGFunctionRelease(gradientFunction); CPGradientElement *elementToRemove = elementList; while (elementList != NULL) { elementToRemove = elementList; elementList = elementList->nextElement; free(elementToRemove); } [super dealloc]; } -(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 encodeFloat: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 decodeFloatForKey:@"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; CPGradientElement color2; color2.color.red = 0.42; color2.color.green = 0.68; color2.color.blue = 0.90; color2.color.alpha = 1.00; color2.position = 11.5/23; CPGradientElement color3; color3.color.red = 0.64; color3.color.green = 0.80; color3.color.blue = 0.94; color3.color.alpha = 1.00; color3.position = 11.5/23; 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; [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; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.83; color2.color.alpha = 1.00; color2.position = 11.5/23; CPGradientElement color3; color3.color.red = color3.color.green = color3.color.blue = 0.95; color3.color.alpha = 1.00; color3.position = 11.5/23; CPGradientElement color4; color4.color.red = color4.color.green = color4.color.blue = 0.92; color4.color.alpha = 1.00; color4.position = 1; [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; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.64; color2.color.alpha = 1.00; color2.position = 11.5/23; CPGradientElement color3; color3.color.red = color3.color.green = color3.color.blue = 0.80; color3.color.alpha = 1.00; color3.position = 11.5/23; CPGradientElement color4; color4.color.red = color4.color.green = color4.color.blue = 0.77; color4.color.alpha = 1.00; color4.position = 1; [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; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.95; color2.color.alpha = 1.00; color2.position = 1; [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; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.90; color2.color.alpha = 1.00; color2.position = 1; [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; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.75; color2.color.alpha = 1.00; color2.position = 1; [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; CPGradientElement color2; color2.color.red = color2.color.green = color2.color.blue = 0.83; color2.color.alpha = 1.00; color2.position = 1; [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; 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; [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; 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; [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; int i; for(i = 0; i < 4; i++) { CGFloat color[4]; color[0] = colorBands[i].hue - 180*colorBands[i].width; color[1] = 1; color[2] = 0.001; color[3] = 1; 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; color[2] = 1; color[3] = 1; 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*colorBands[i].width; color[1] = 1; color[2] = 0.001; color[3] = 1; 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 (%f)", [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)colorStopAtIndex:(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)colorAtPosition:(CGFloat)position { CGFloat components[4]; 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 (components[3] != 0) { //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; CGContextSaveGState(context); CGContextClipToRect(context, *(CGRect *)&rect); switch (self.gradientType) { case CPGradientTypeAxial: myCGShading = [self axialGradientInRect:rect]; break; case CPGradientTypeRadial: myCGShading = [self radialGradientInRect: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; CGContextSaveGState(context); CGRect bounds = CGContextGetPathBoundingBox(context); CGContextClip(context); switch (self.gradientType) { case CPGradientTypeAxial: myCGShading = [self axialGradientInRect:bounds]; break; case CPGradientTypeRadial: myCGShading = [self radialGradientInRect:bounds context:context]; break; } CGContextDrawShading(context, myCGShading); CGShadingRelease(myCGShading); CGContextRestoreGState(context); } } #pragma mark - #pragma mark Private Methods -(CGShadingRef)axialGradientInRect:(CGRect)rect { // First Calculate where the beginning and ending points should be CGPoint startPoint; CGPoint endPoint; if (self.angle == 0) { startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)); // right of rect endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect)); // left of rect } else if (self.angle == 90) { 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; //convert the angle to radians if (fabs(tan(rangle))<=1) { //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; deltay = length*sina/2; } 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; deltay = length*cosa/2; } 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)radialGradientInRect:(CGRect)rect context:(CGContextRef)context { CGPoint startPoint, endPoint; CGFloat startRadius, endRadius; CGFloat scalex, scaley; startPoint = endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)); startRadius = -1; if (CGRectGetHeight(rect)>CGRectGetWidth(rect)) { scalex = CGRectGetWidth(rect)/CGRectGetHeight(rect); startPoint.x /= scalex; endPoint.x /= scalex; scaley = 1; endRadius = CGRectGetHeight(rect)/2; } else { scalex = 1; scaley = CGRectGetHeight(rect)/CGRectGetWidth(rect); startPoint.y /= scaley; endPoint.y /= scaley; endRadius = CGRectGetWidth(rect)/2; } 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; 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)); *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; } -(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; 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; 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; // 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; // 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, S, V; CGFloat R = components[0], G = components[1], 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 == MIN) { H = NAN; } else if (MAX == R) { if (G >= B) { H = 60*(G-B)/(MAX-MIN)+0; } else { H = 60*(G-B)/(MAX-MIN)+360; } } else if (MAX == G) { H = 60*(B-R)/(MAX-MIN)+120; } else if (MAX == B) { H = 60*(R-G)/(MAX-MIN)+240; } 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, G, B; CGFloat H = fmod(components[0],359); //map to [0,360) CGFloat S = components[1]; CGFloat V = components[2]; int Hi = (int)floor(H/60.) % 6; CGFloat f = H/60-Hi; CGFloat p = V*(1-S); CGFloat q = V*(1-f*S); CGFloat t = V*(1-(1-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
systemtests/tests/Source/CPGradient.m
Objective-C
bsd
42,474
#import "CPExceptions.h" NSString * const CPException = @"CPException"; ///< General Core Plot exceptions. NSString * const CPDataException = @"CPDataException"; ///< Core Plot data exceptions.
08iteng-ipad
systemtests/tests/Source/CPExceptions.m
Objective-C
bsd
201
#import "CPPlotAreaTests.h" #import "CPColor.h" #import "CPPlotArea.h" #import "CPFill.h" #import "GTMNSObject+BindingUnitTesting.h" #import "GTMNSObject+UnitTesting.h" @interface CPPlotArea (UnitTesting) -(void)gtm_unitTestEncodeState:(NSCoder*)inCoder; @end @implementation CPPlotArea (UnitTesting) -(void)gtm_unitTestEncodeState:(NSCoder*)inCoder { [super gtm_unitTestEncodeState:inCoder]; NSLog(@"CPPlotArea gtm_unitTestEncodeState %@", self.fill); @try { [self.fill encodeWithCoder:inCoder]; } @catch (NSException *exception) { NSLog(@"gtm_unitTestEncodeState: Caught %@: %@", [exception name], [exception reason]); } } @end @implementation CPPlotAreaTests -(void)testBindings { CPPlotArea *plotArea = [[CPPlotArea alloc] init]; NSArray *errors; STAssertTrue(GTMDoExposedBindingsFunctionCorrectly(plotArea, &errors), @"CPPlotArea bindings do not work as expected: %@", errors); [plotArea release]; } -(void)testDrawInContextRendersAsExpected { CPPlotArea *plotArea = [[CPPlotArea alloc] init]; [plotArea setFrame:CGRectMake(0, 0, 50, 50)]; [plotArea setBounds:CGRectMake(0, 0, 50, 50)]; plotArea.fill = [CPFill fillWithColor:[CPColor blueColor]]; GTMAssertObjectImageEqualToImageNamed(plotArea, @"CPPlotAreaTests-testDrawInContextRendersAsExpected-blueFill", @""); [plotArea release]; } @end
08iteng-ipad
systemtests/tests/Source/CPPlotAreaTests.m
Objective-C
bsd
1,384
// // CPPlotSymbolTests.h // CorePlot // #import "CPDataSourceTestCase.h" @class CPScatterPlot; @interface CPPlotSymbolTests : CPDataSourceTestCase { CPScatterPlot *plot; } @property (retain,readwrite) CPScatterPlot *plot; - (void)setUpPlotSpace; - (void)buildData; @end
08iteng-ipad
systemtests/tests/Source/CPPlotSymbolTests.h
Objective-C
bsd
284
#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
systemtests/tests/Source/CPXYAxisSet.h
Objective-C
bsd
236
#import <stdlib.h> #import "CPScatterPlot.h" #import "CPLineStyle.h" #import "CPPlotSpace.h" #import "CPExceptions.h" #import "CPUtilities.h" #import "CPXYPlotSpace.h" #import "CPPlotSymbol.h" #import "CPFill.h" NSString * const CPScatterPlotBindingXValues = @"xValues"; ///< X values. NSString * const CPScatterPlotBindingYValues = @"yValues"; ///< Y values. NSString * const CPScatterPlotBindingPlotSymbols = @"plotSymbols"; ///< Plot symbols. static NSString * const CPXValuesBindingContext = @"CPXValuesBindingContext"; static NSString * const CPYValuesBindingContext = @"CPYValuesBindingContext"; static NSString * const CPPlotSymbolsBindingContext = @"CPPlotSymbolsBindingContext"; /// @cond @interface CPScatterPlot () @property (nonatomic, readwrite, assign) id observedObjectForXValues; @property (nonatomic, readwrite, assign) id observedObjectForYValues; @property (nonatomic, readwrite, assign) id observedObjectForPlotSymbols; @property (nonatomic, readwrite, copy) NSString *keyPathForXValues; @property (nonatomic, readwrite, copy) NSString *keyPathForYValues; @property (nonatomic, readwrite, copy) NSString *keyPathForPlotSymbols; @property (nonatomic, readwrite, copy) NSArray *xValues; @property (nonatomic, readwrite, copy) NSArray *yValues; @property (nonatomic, readwrite, retain) NSArray *plotSymbols; @end /// @endcond /** @brief A two-dimensional scatter plot. **/ @implementation CPScatterPlot @synthesize observedObjectForXValues; @synthesize observedObjectForYValues; @synthesize observedObjectForPlotSymbols; @synthesize keyPathForXValues; @synthesize keyPathForYValues; @synthesize keyPathForPlotSymbols; @synthesize plotSymbols; /** @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 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 doublePrecisionAreaBaseValue * @brief The Y coordinate of the straight boundary of the area fill, as a double. * If nil, 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 doublePrecisionAreaBaseValue; #pragma mark - #pragma mark init/dealloc +(void)initialize { if (self == [CPScatterPlot class]) { [self exposeBinding:CPScatterPlotBindingXValues]; [self exposeBinding:CPScatterPlotBindingYValues]; [self exposeBinding:CPScatterPlotBindingPlotSymbols]; } } -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { observedObjectForXValues = nil; observedObjectForYValues = nil; observedObjectForPlotSymbols = nil; keyPathForXValues = nil; keyPathForYValues = nil; keyPathForPlotSymbols = nil; dataLineStyle = [[CPLineStyle alloc] init]; plotSymbol = nil; areaFill = nil; areaBaseValue = [[NSDecimalNumber notANumber] decimalValue]; doublePrecisionAreaBaseValue = NAN; plotSymbols = nil; self.needsDisplayOnBoundsChange = YES; } return self; } -(void)dealloc { if ( observedObjectForXValues ) [self unbind:CPScatterPlotBindingXValues]; observedObjectForXValues = nil; if ( observedObjectForYValues ) [self unbind:CPScatterPlotBindingYValues]; observedObjectForYValues = nil; if ( observedObjectForPlotSymbols ) [self unbind:CPScatterPlotBindingPlotSymbols]; observedObjectForPlotSymbols = nil; [keyPathForXValues release]; [keyPathForYValues release]; [keyPathForPlotSymbols release]; [dataLineStyle release]; [plotSymbol release]; [areaFill release]; [plotSymbols release]; [super dealloc]; } -(void)bind:(NSString *)binding toObject:(id)observable withKeyPath:(NSString *)keyPath options:(NSDictionary *)options { [super bind:binding toObject:observable withKeyPath:keyPath options:options]; if ([binding isEqualToString:CPScatterPlotBindingXValues]) { [observable addObserver:self forKeyPath:keyPath options:0 context:CPXValuesBindingContext]; self.observedObjectForXValues = observable; self.keyPathForXValues = keyPath; [self setDataNeedsReloading]; } else if ([binding isEqualToString:CPScatterPlotBindingYValues]) { [observable addObserver:self forKeyPath:keyPath options:0 context:CPYValuesBindingContext]; self.observedObjectForYValues = observable; self.keyPathForYValues = keyPath; [self setDataNeedsReloading]; } else if ([binding isEqualToString:CPScatterPlotBindingPlotSymbols]) { [observable addObserver:self forKeyPath:keyPath options:0 context:CPPlotSymbolsBindingContext]; self.observedObjectForPlotSymbols = observable; self.keyPathForPlotSymbols = keyPath; [self setDataNeedsReloading]; } } -(void)unbind:(NSString *)bindingName { if ([bindingName isEqualToString:CPScatterPlotBindingXValues]) { [observedObjectForXValues removeObserver:self forKeyPath:self.keyPathForXValues]; self.observedObjectForXValues = nil; self.keyPathForXValues = nil; [self setDataNeedsReloading]; } else if ([bindingName isEqualToString:CPScatterPlotBindingYValues]) { [observedObjectForYValues removeObserver:self forKeyPath:self.keyPathForYValues]; self.observedObjectForYValues = nil; self.keyPathForYValues = nil; [self setDataNeedsReloading]; } else if ([bindingName isEqualToString:CPScatterPlotBindingPlotSymbols]) { [observedObjectForPlotSymbols removeObserver:self forKeyPath:self.keyPathForPlotSymbols]; self.observedObjectForPlotSymbols = nil; self.keyPathForPlotSymbols = nil; [self setDataNeedsReloading]; } [super unbind:bindingName]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == CPXValuesBindingContext) { [self setDataNeedsReloading]; } else if (context == CPYValuesBindingContext) { [self setDataNeedsReloading]; } else if (context == CPPlotSymbolsBindingContext) { [self setDataNeedsReloading]; } } -(Class)valueClassForBinding:(NSString *)binding { if ([binding isEqualToString:CPScatterPlotBindingXValues]) { return [NSArray class]; } else if ([binding isEqualToString:CPScatterPlotBindingYValues]) { return [NSArray class]; } else if ([binding isEqualToString:CPScatterPlotBindingPlotSymbols]) { return [NSArray class]; } else { return [super valueClassForBinding:binding]; } } #pragma mark - #pragma mark Data Loading -(void)reloadData { [super reloadData]; self.xValues = nil; self.yValues = nil; self.plotSymbols = nil; if ( self.observedObjectForXValues && self.observedObjectForYValues ) { // Use bindings to retrieve data self.xValues = [self.observedObjectForXValues valueForKeyPath:self.keyPathForXValues]; self.yValues = [self.observedObjectForYValues valueForKeyPath:self.keyPathForYValues]; self.plotSymbols = [self.observedObjectForPlotSymbols valueForKeyPath:self.keyPathForPlotSymbols]; } else if ( self.dataSource ) { // Expand the index range each end, to make sure that plot lines go to offscreen points NSUInteger numberOfRecords = [self.dataSource numberOfRecordsForPlot:self]; CPXYPlotSpace *xyPlotSpace = (CPXYPlotSpace *)self.plotSpace; NSRange indexRange = [self recordIndexRangeForPlotRange:xyPlotSpace.xRange]; NSRange expandedRange = CPExpandedRange(indexRange, 1); NSRange completeIndexRange = NSMakeRange(0, numberOfRecords); indexRange = NSIntersectionRange(expandedRange, completeIndexRange); self.xValues = [self numbersFromDataSourceForField:CPScatterPlotFieldX recordIndexRange:indexRange]; self.yValues = [self numbersFromDataSourceForField:CPScatterPlotFieldY recordIndexRange:indexRange]; // Plot symbols if ( [self.dataSource respondsToSelector:@selector(symbolsForScatterPlot:recordIndexRange:)] ) { self.plotSymbols = [(id <CPScatterPlotDataSource>)self.dataSource symbolsForScatterPlot:self recordIndexRange:indexRange]; } else if ([self.dataSource respondsToSelector:@selector(symbolForScatterPlot:recordIndex:)]) { NSMutableArray *symbols = [NSMutableArray arrayWithCapacity:indexRange.length]; for ( NSUInteger recordIndex = indexRange.location; recordIndex < indexRange.location + indexRange.length; recordIndex++ ) { CPPlotSymbol *theSymbol = [(id <CPScatterPlotDataSource>)self.dataSource symbolForScatterPlot:self recordIndex:recordIndex]; if (theSymbol) { [symbols addObject:theSymbol]; } else { [symbols addObject:[NSNull null]]; } } self.plotSymbols = symbols; } } } #pragma mark - #pragma mark Drawing -(void)renderAsVectorInContext:(CGContextRef)theContext { if ( self.xValues == nil || self.yValues == nil ) return; if ( self.xValues.count == 0 ) return; if ( [self.xValues count] != [self.yValues count] ) { [NSException raise:CPException format:@"Number of x and y values do not match"]; } [super renderAsVectorInContext:theContext]; // calculate view points CGPoint *viewPoints = malloc(self.xValues.count * sizeof(CGPoint)); if ( self.dataLineStyle || self.areaFill || self.plotSymbol || self.plotSymbols.count ) { for (NSUInteger i = 0; i < [self.xValues count]; i++) { id xValue = [self.xValues objectAtIndex:i]; id yValue = [self.yValues objectAtIndex:i]; if ([xValue isKindOfClass:[NSDecimalNumber class]] && [yValue isKindOfClass:[NSDecimalNumber class]]) { // Do higher-precision NSDecimal calculations NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = [xValue decimalValue]; plotPoint[CPCoordinateY] = [yValue decimalValue]; viewPoints[i] = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; } else { // Go floating-point route for calculations double doublePrecisionPlotPoint[2]; doublePrecisionPlotPoint[CPCoordinateX] = [xValue doubleValue]; doublePrecisionPlotPoint[CPCoordinateY] = [yValue doubleValue]; viewPoints[i] = [self.plotSpace viewPointInLayer:self forDoublePrecisionPlotPoint:doublePrecisionPlotPoint]; } } } // path CGMutablePathRef dataLinePath = NULL; if ( self.dataLineStyle || self.areaFill ) { dataLinePath = CGPathCreateMutable(); CGPoint alignedPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[0].x, viewPoints[0].y)); CGPathMoveToPoint(dataLinePath, NULL, alignedPoint.x, alignedPoint.y); for (NSUInteger i = 1; i < self.xValues.count; i++) { alignedPoint = CPAlignPointToUserSpace(theContext, CGPointMake(viewPoints[i].x, viewPoints[i].y)); CGPathAddLineToPoint(dataLinePath, NULL, alignedPoint.x, alignedPoint.y); } } // draw fill NSDecimal temporaryAreaBaseValue = self.areaBaseValue; if ( self.areaFill && (!NSDecimalIsNotANumber(&temporaryAreaBaseValue)) ) { id xValue = [self.xValues objectAtIndex:0]; CGPoint baseLinePoint; if ([xValue isKindOfClass:[NSDecimalNumber class]]) { // Do higher-precision NSDecimal calculations NSDecimal plotPoint[2]; plotPoint[CPCoordinateX] = [xValue decimalValue]; plotPoint[CPCoordinateY] = self.areaBaseValue; baseLinePoint = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; } else { // Go floating-point route for calculations double doublePrecisionPlotPoint[2]; doublePrecisionPlotPoint[CPCoordinateX] = [xValue doubleValue]; doublePrecisionPlotPoint[CPCoordinateY] = self.doublePrecisionAreaBaseValue; baseLinePoint = [self.plotSpace viewPointInLayer:self forDoublePrecisionPlotPoint:doublePrecisionPlotPoint]; } CGFloat baseLineYValue = baseLinePoint.y; CGPoint baseViewPoint1 = viewPoints[self.xValues.count-1]; baseViewPoint1.y = baseLineYValue; baseViewPoint1 = CPAlignPointToUserSpace(theContext, baseViewPoint1); CGPoint baseViewPoint2 = viewPoints[0]; baseViewPoint2.y = baseLineYValue; baseViewPoint2 = CPAlignPointToUserSpace(theContext, baseViewPoint2); CGMutablePathRef fillPath = CGPathCreateMutableCopy(dataLinePath); CGPathAddLineToPoint(fillPath, NULL, baseViewPoint1.x, baseViewPoint1.y); CGPathAddLineToPoint(fillPath, NULL, baseViewPoint2.x, baseViewPoint2.y); CGPathCloseSubpath(fillPath); CGContextBeginPath(theContext); CGContextAddPath(theContext, fillPath); [self.areaFill fillPathInContext:theContext]; CGPathRelease(fillPath); } // draw line if ( self.dataLineStyle ) { CGContextBeginPath(theContext); CGContextAddPath(theContext, dataLinePath); [self.dataLineStyle setLineStyleInContext:theContext]; CGContextStrokePath(theContext); } if ( dataLinePath ) CGPathRelease(dataLinePath); // draw plot symbols if (self.plotSymbol || self.plotSymbols.count) { if ( self.plotSymbols.count > 0 ) { for (NSUInteger i = 0; i < self.xValues.count; i++) { if (i < self.plotSymbols.count) { id <NSObject> currentSymbol = [self.plotSymbols objectAtIndex:i]; if ([currentSymbol isKindOfClass:[CPPlotSymbol class]]) { [(CPPlotSymbol *)currentSymbol renderInContext:theContext atPoint:CPAlignPointToUserSpace(theContext, viewPoints[i])]; } } } } else { CPPlotSymbol *theSymbol = self.plotSymbol; for (NSUInteger i = 0; i < self.xValues.count; i++) { [theSymbol renderInContext:theContext atPoint:CPAlignPointToUserSpace(theContext,viewPoints[i])]; } } } free(viewPoints); } #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 Accessors -(void)setPlotSymbol:(CPPlotSymbol *)aSymbol { if (aSymbol != plotSymbol) { [plotSymbol release]; plotSymbol = [aSymbol copy]; [self setNeedsDisplay]; } } -(void)setDataLineStyle:(CPLineStyle *)value { if (dataLineStyle != value) { [dataLineStyle release]; dataLineStyle = [value copy]; [self setNeedsDisplay]; } } -(void)setAreaBaseValue:(NSDecimal)newAreaBaseValue { if (CPDecimalEquals(areaBaseValue, newAreaBaseValue)) { return; } areaBaseValue = newAreaBaseValue; doublePrecisionAreaBaseValue = [[NSDecimalNumber decimalNumberWithDecimal:areaBaseValue] doubleValue]; } -(void)setXValues:(NSArray *)newValues { [self cacheNumbers:newValues forField:CPScatterPlotFieldX]; } -(NSArray *)xValues { return [self cachedNumbersForField:CPScatterPlotFieldX]; } -(void)setYValues:(NSArray *)newValues { [self cacheNumbers:newValues forField:CPScatterPlotFieldY]; } -(NSArray *)yValues { return [self cachedNumbersForField:CPScatterPlotFieldY]; } @end
08iteng-ipad
systemtests/tests/Source/CPScatterPlot.m
Objective-C
bsd
15,606
#import "CPTestCase.h" #import "CPPlot.h" @class CPPlotRange; @class CPPlot; @interface CPDataSourceTestCase : CPTestCase <CPPlotDataSource> { 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; /** If you are using this data source for more than one plot, you must call addPlot: for each plot. */ - (void)addPlot:(CPPlot*)newPlot; @end
08iteng-ipad
systemtests/tests/Source/CPDataSourceTestCase.h
Objective-C
bsd
726
#import "NSNumberExtensions.h" /** @brief Core Plot extensions to NSNumber. **/ @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
systemtests/tests/Source/NSNumberExtensions.m
Objective-C
bsd
478
#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
systemtests/tests/Source/CPPlotGroup.h
Objective-C
bsd
322
#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
systemtests/tests/Source/CPPolarPlotSpace.m
Objective-C
bsd
211
#import "CPTestCase.h" @interface CPTextLayerTests : CPTestCase { } @end
08iteng-ipad
systemtests/tests/Source/CPTextLayerTests.h
Objective-C
bsd
78
#import <Foundation/Foundation.h> #import "CPTheme.h" @interface CPXYTheme : CPTheme { } @end
08iteng-ipad
systemtests/tests/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 "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 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]; } } } /// @defgroup CPTheme CPTheme /// @{ /** @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], [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 { static NSMutableDictionary *themes = nil; 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]; } /** @brief Creates a new graph styled with the theme. * @return The new graph. **/ -(id)newGraph { return nil; } /** @brief Applies the theme to the provided graph. * @param graph The graph to style. **/ -(void)applyThemeToGraph:(CPGraph *)graph { [self applyThemeToBackground:graph]; [self applyThemeToPlotArea:graph.plotArea]; [self applyThemeToAxisSet:graph.axisSet]; } /** @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 plotArea The plot area to style. **/ -(void)applyThemeToPlotArea:(CPPlotArea *)plotArea { } /** @brief Applies the theme to the provided axis set. * @param axisSet The axis set to style. **/ -(void)applyThemeToAxisSet:(CPAxisSet *)axisSet { } /// @} @end
08iteng-ipad
systemtests/tests/Source/CPTheme.m
Objective-C
bsd
4,105
#import "CPTestCase.h" @interface CPBorderedLayerTests : CPTestCase { } @end
08iteng-ipad
systemtests/tests/Source/CPBorderedLayerTests.h
Objective-C
bsd
82
#import "CPPlotSpace.h" #import "CPLayer.h" #import "CPPlotArea.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 /// @defgroup CPPlotSpace CPPlotSpace /// @{ /** @property identifier * @brief An object used to identify the plot in collections. **/ @synthesize identifier; #pragma mark - #pragma mark Initialize/Deallocate -(id)init { if ( self = [super init] ) { identifier = nil; } return self; } -(void)dealloc { [identifier release]; [super dealloc]; } #pragma mark - #pragma mark Layout +(CGFloat)defaultZPosition { return CPDefaultZPositionPlotSpace; } /// @} @end /// @brief CPPlotSpace abstract methods—must be overridden by subclasses @implementation CPPlotSpace(AbstractMethods) /// @addtogroup CPPlotSpace /// @{ /** @brief Converts a data point to drawing coordinates. * @param layer The layer containing the point to convert. * @param plotPoint A c-style array of data point coordinates (as NSDecimals). * @return The drawing coordinates of the data point. **/ -(CGPoint)viewPointInLayer:(CPLayer *)layer forPlotPoint:(NSDecimal *)plotPoint { return CGPointMake(0.0f, 0.0f); } /** @brief Converts a data point to drawing coordinates. * @param layer The layer containing the point to convert. * @param plotPoint A c-style array of data point coordinates (as doubles). * @return The drawing coordinates of the data point. **/ -(CGPoint)viewPointInLayer:(CPLayer *)layer forDoublePrecisionPlotPoint:(double *)plotPoint; { return CGPointMake(0.0f, 0.0f); } /** @brief Converts a point given in 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. * @param layer The layer containing the point to convert. **/ -(void)plotPoint:(NSDecimal *)plotPoint forViewPoint:(CGPoint)point inLayer:(CPLayer *)layer { } /** @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. * @param layer The layer containing the point to convert. **/ -(void)doublePrecisionPlotPoint:(double *)plotPoint forViewPoint:(CGPoint)point inLayer:(CPLayer *)layer { } /** @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 { } /// @} @end
08iteng-ipad
systemtests/tests/Source/CPPlotSpace.m
Objective-C
bsd
3,140
#import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPExceptions.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPAxisSet.h" #import "CPPlot.h" /// @cond @interface CPXYPlotSpace () -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range plotCoordinateValue:(NSDecimal)plotCoord; -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range doublePrecisionPlotCoordinateValue:(double)plotCoord; @end /// @endcond /** @brief A plot space using a two-dimensional cartesian coordinate system. **/ @implementation CPXYPlotSpace /** @property xRange * @brief The range of the x-axis. **/ @synthesize xRange; /** @property yRange * @brief The range of the y-axis. **/ @synthesize yRange; /** @property xScaleType * @brief The scale type of the x-axis. **/ @synthesize xScaleType; /** @property yScaleType * @brief The scale type of the y-axis. **/ @synthesize yScaleType; #pragma mark - #pragma mark Initialize/Deallocate -(id)init { if ( self = [super init] ) { xRange = nil; yRange = nil; xScaleType = CPScaleTypeLinear; yScaleType = CPScaleTypeLinear; } return self; } -(void)dealloc { [xRange release]; [yRange release]; [super dealloc]; } #pragma mark - #pragma mark Ranges -(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coordinate { return ( coordinate == CPCoordinateX ? self.xRange : self.yRange ); } -(void)setXRange:(CPPlotRange *)range { if ( range != xRange ) { [xRange release]; xRange = [range copy]; [[NSNotificationCenter defaultCenter] postNotificationName:CPPlotSpaceCoordinateMappingDidChangeNotification object:self]; } } -(void)setYRange:(CPPlotRange *)range { if ( range != yRange ) { [yRange release]; yRange = [range copy]; [[NSNotificationCenter defaultCenter] postNotificationName:CPPlotSpaceCoordinateMappingDidChangeNotification object:self]; } } -(void)scaleToFitPlots:(NSArray *)plots { if ( plots.count == 0 ) return; // Determine union of ranges CPPlotRange *unionXRange = [[plots objectAtIndex:0] plotRangeForCoordinate:CPCoordinateX]; CPPlotRange *unionYRange = [[plots objectAtIndex:0] plotRangeForCoordinate:CPCoordinateY]; for ( CPPlot *plot in plots ) { [unionXRange unionPlotRange:[plot plotRangeForCoordinate:CPCoordinateX]]; [unionYRange unionPlotRange:[plot plotRangeForCoordinate:CPCoordinateY]]; } // Set range NSDecimal zero = CPDecimalFromInt(0); if ( !CPDecimalEquals(unionXRange.length, zero) ) self.xRange = unionXRange; if ( !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.0f; NSDecimal factor = CPDecimalDivide(CPDecimalSubtract(plotCoord, range.location), range.length); if ( NSDecimalIsNotANumber(&factor) ) { factor = CPDecimalFromInt(0); } CGFloat viewCoordinate = viewLength * [[NSDecimalNumber decimalNumberWithDecimal:factor] doubleValue]; return viewCoordinate; } -(CGFloat)viewCoordinateForViewLength:(CGFloat)viewLength linearPlotRange:(CPPlotRange *)range doublePrecisionPlotCoordinateValue:(double)plotCoord; { if ( !range || range.doublePrecisionLength == 0.0 ) return 0.0f; return viewLength * ((plotCoord - range.doublePrecisionLocation) / range.doublePrecisionLength); } -(CGPoint)viewPointInLayer:(CPLayer *)layer forPlotPoint:(NSDecimal *)plotPoint { CGFloat viewX, viewY; CGSize layerSize = layer.bounds.size; switch ( self.xScaleType ) { case CPScaleTypeLinear: viewX = [self viewCoordinateForViewLength:layerSize.width linearPlotRange: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:yRange plotCoordinateValue:plotPoint[CPCoordinateY]]; break; default: [NSException raise:CPException format:@"Scale type not supported in CPXYPlotSpace"]; } return CGPointMake(viewX, viewY); } -(CGPoint)viewPointInLayer:(CPLayer *)layer forDoublePrecisionPlotPoint:(double *)plotPoint { CGFloat viewX, viewY; CGSize layerSize = layer.bounds.size; switch ( self.xScaleType ) { case CPScaleTypeLinear: viewX = [self viewCoordinateForViewLength:layerSize.width linearPlotRange: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:yRange doublePrecisionPlotCoordinateValue:plotPoint[CPCoordinateY]]; break; default: [NSException raise:CPException format:@"Scale type not supported in CPXYPlotSpace"]; } return CGPointMake(viewX, viewY); } -(void)plotPoint:(NSDecimal *)plotPoint forViewPoint:(CGPoint)point inLayer:(CPLayer *)layer { NSDecimal pointx = CPDecimalFromFloat(point.x); NSDecimal pointy = CPDecimalFromFloat(point.y); NSDecimal boundsw = CPDecimalFromFloat(layer.bounds.size.width); NSDecimal boundsh = CPDecimalFromFloat(layer.bounds.size.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 forViewPoint:(CGPoint)point inLayer:(CPLayer *)layer { // TODO: implement doublePrecisionPlotPoint:forViewPoint: } @end
08iteng-ipad
systemtests/tests/Source/CPXYPlotSpace.m
Objective-C
bsd
6,279
#import "CPGradientTests.h" #import "CPGradient.h" #import "GTMGarbageCollection.h" #import "GTMNSObject+UnitTesting.h" @interface CPGradient (UnitTesting) - (CGImageRef)gtm_unitTestImage; @end @implementation CPGradient (UnitTesting) - (CGImageRef)gtm_unitTestImage { CGFloat edgeLength = 200; //arbitrary edge size CGSize contextSize = CGSizeMake(edgeLength, edgeLength); CGContextRef context = GTMCreateUnitTestBitmapContextOfSizeWithData(contextSize, NULL); _GTMDevAssert(context, @"Couldn't create context"); [self drawSwatchInRect:CGRectMake(0, 0, edgeLength, edgeLength) inContext:context]; CGImageRef imageRef = CGBitmapContextCreateImage(context); CFRelease(context); return (CGImageRef)GTMCFAutorelease(imageRef); } @end @implementation CPGradientTests - (void)testDrawSwatchRendersCorrectlyForFactoryGradients { NSArray *factoryMethods = [NSArray arrayWithObjects: @"aquaSelectedGradient", @"aquaNormalGradient", @"aquaPressedGradient", @"unifiedSelectedGradient", @"unifiedNormalGradient", @"unifiedPressedGradient", @"unifiedDarkGradient", @"sourceListSelectedGradient", @"sourceListUnselectedGradient", @"rainbowGradient", @"hydrogenSpectrumGradient", nil]; for(NSString *factoryMethod in factoryMethods) { CPGradient *gradient = [[CPGradient class] performSelector:NSSelectorFromString(factoryMethod)]; NSString *imageName = [NSString stringWithFormat:@"CPGradientTests-testDrawSwatchRendersCorrectlyForFactoryGradients-%@", factoryMethod]; GTMAssertObjectImageEqualToImageNamed(gradient, imageName, @""); } } - (void)testFillPathRendersCorrectly { //STFail(@"Implement test."); } @end
08iteng-ipad
systemtests/tests/Source/CPGradientTests.m
Objective-C
bsd
2,085
#import "CPXYTheme.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:CPDecimalFromFloat(-1.0) length:CPDecimalFromFloat(1.0)]; plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.0) length:CPDecimalFromFloat(1.0)]; [self applyThemeToGraph:graph]; return graph; } @end
08iteng-ipad
systemtests/tests/Source/CPXYTheme.m
Objective-C
bsd
1,103
#import "CPDarkGradientTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotArea.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPLineStyle.h" #import "CPTextStyle.h" #import "CPBorderedLayer.h" #import "CPExceptions.h" /// @cond @interface CPDarkGradientTheme () -(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle minorLineStyle:(CPLineStyle *)minorLineStyle textStyle:(CPTextStyle *)textStyle; @end /// @endcond #pragma mark - /** @brief Creates a CPXYGraph instance formatted with dark gray gradient backgrounds and light gray lines. **/ @implementation CPDarkGradientTheme /// @defgroup CPDarkGradientTheme CPDarkGradientTheme /// @{ +(NSString *)defaultName { return kCPDarkGradientTheme; } -(void)applyThemeToAxis:(CPXYAxis *)axis usingMajorLineStyle:(CPLineStyle *)majorLineStyle minorLineStyle:(CPLineStyle *)minorLineStyle textStyle:(CPTextStyle *)textStyle { axis.axisLabelingPolicy = CPAxisLabelingPolicyFixedInterval; axis.majorIntervalLength = CPDecimalFromString(@"0.5"); axis.constantCoordinateValue = CPDecimalFromString(@"0"); axis.tickDirection = CPSignNone; axis.minorTicksPerInterval = 4; axis.majorTickLineStyle = majorLineStyle; axis.minorTickLineStyle = minorLineStyle; axis.axisLineStyle = majorLineStyle; axis.majorTickLength = 7.0f; axis.minorTickLength = 5.0f; axis.axisLabelTextStyle = textStyle; axis.axisTitleTextStyle = 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.0f; graph.fill = [CPFill fillWithGradient:graphGradient]; } -(void)applyThemeToPlotArea:(CPPlotArea *)plotArea { CPGradient *gradient = [CPGradient gradientWithBeginningColor:[CPColor colorWithGenericGray:0.1] endingColor:[CPColor colorWithGenericGray:0.3]]; gradient.angle = 90.0; plotArea.fill = [CPFill fillWithGradient:gradient]; CPLineStyle *borderLineStyle = [CPLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor colorWithGenericGray:0.2]; borderLineStyle.lineWidth = 4.0f; plotArea.borderLineStyle = borderLineStyle; plotArea.cornerRadius = 10.0f; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPLineStyle *majorLineStyle = [CPLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapSquare; majorLineStyle.lineColor = [CPColor colorWithGenericGray:0.5]; majorLineStyle.lineWidth = 2.0f; CPLineStyle *minorLineStyle = [CPLineStyle lineStyle]; minorLineStyle.lineCap = kCGLineCapSquare; minorLineStyle.lineColor = [CPColor darkGrayColor]; minorLineStyle.lineWidth = 1.0f; CPTextStyle *whiteTextStyle = [[[CPTextStyle alloc] init] autorelease]; whiteTextStyle.color = [CPColor whiteColor]; whiteTextStyle.fontSize = 14.0; for (CPXYAxis *axis in axisSet.axes) { [self applyThemeToAxis:axis usingMajorLineStyle:majorLineStyle minorLineStyle:minorLineStyle textStyle:whiteTextStyle]; } } /// @} @end
08iteng-ipad
systemtests/tests/Source/CPDarkGradientTheme.m
Objective-C
bsd
3,494
#import "CPPlotRange.h" #import "CPPlotSpace.h" #import "CPDefinitions.h" @interface CPXYPlotSpace : CPPlotSpace { @private CPPlotRange *xRange; CPPlotRange *yRange; CPScaleType xScaleType; // TODO: Implement scale types CPScaleType yScaleType; // TODO: Implement scale types } @property (nonatomic, readwrite, copy) CPPlotRange *xRange; @property (nonatomic, readwrite, copy) CPPlotRange *yRange; @property (nonatomic, readwrite, assign) CPScaleType xScaleType; @property (nonatomic, readwrite, assign) CPScaleType yScaleType; @end
08iteng-ipad
systemtests/tests/Source/CPXYPlotSpace.h
Objective-C
bsd
548
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> @interface CPImage : NSObject <NSCopying> { @private CGImageRef image; BOOL tiled; } @property (assign) CGImageRef image; @property (assign, getter=isTiled) BOOL tiled; /// @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
systemtests/tests/Source/CPImage.h
Objective-C
bsd
606
#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., @"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., @"Result incorrect"); d = [NSDecimalNumber decimalNumberWithString:@"42.1"]; STAssertEquals((double)CPDecimalDoubleValue([d decimalValue]), (double)42.1, @"Result incorrect"); } - (void)testToDecimalConversion { NSInteger i = 100; float f = 3.141; double d = 42.1; STAssertEqualObjects([NSDecimalNumber decimalNumberWithString:@"100"], [NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromInt(i)], @"NSInteger to NSDecimal conversion failed"); STAssertEqualsWithAccuracy([[NSDecimalNumber numberWithFloat:f] floatValue], [[NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromFloat(f)] floatValue], 1.e-7, @"float to NSDecimal conversion failed"); STAssertEqualObjects([NSDecimalNumber numberWithDouble:d], [NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromDouble(d)], @"double to NSDecimal conversion failed."); } @end
08iteng-ipad
systemtests/tests/Source/CPUtilitiesTests.m
Objective-C
bsd
1,955
#import <Foundation/Foundation.h> #import "CPPlot.h" #import "CPDefinitions.h" /// @file @class CPLineStyle; @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 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 @interface CPScatterPlot : CPPlot { @private id observedObjectForXValues; id observedObjectForYValues; id observedObjectForPlotSymbols; NSString *keyPathForXValues; NSString *keyPathForYValues; NSString *keyPathForPlotSymbols; CPLineStyle *dataLineStyle; CPPlotSymbol *plotSymbol; CPFill *areaFill; NSDecimal areaBaseValue; // TODO: NSDecimal instance variables in CALayers cause an unhandled property type encoding error double doublePrecisionAreaBaseValue; NSArray *plotSymbols; } @property (nonatomic, readwrite, copy) CPLineStyle *dataLineStyle; @property (nonatomic, readwrite, copy) CPPlotSymbol *plotSymbol; @property (nonatomic, readwrite, copy) CPFill *areaFill; @property (nonatomic, readwrite) NSDecimal areaBaseValue; @property (nonatomic, readwrite) double doublePrecisionAreaBaseValue; @end
08iteng-ipad
systemtests/tests/Source/CPScatterPlot.h
Objective-C
bsd
2,230
#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]; } #pragma mark - #pragma mark Factory Methods -(CPPlotSpace *)newPlotSpace { CPXYPlotSpace *space; 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
systemtests/tests/Source/CPXYGraph.m
Objective-C
bsd
1,883
#import "CPPlainBlackTheme.h" #import "CPXYGraph.h" #import "CPColor.h" #import "CPGradient.h" #import "CPFill.h" #import "CPPlotArea.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPLineStyle.h" #import "CPTextStyle.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:(CPPlotArea *)plotArea { plotArea.fill = [CPFill fillWithColor:[CPColor blackColor]]; CPLineStyle *borderLineStyle = [CPLineStyle lineStyle]; borderLineStyle.lineColor = [CPColor whiteColor]; borderLineStyle.lineWidth = 1.0f; plotArea.borderLineStyle = borderLineStyle; plotArea.cornerRadius = 0.0f; } -(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet { CPLineStyle *majorLineStyle = [CPLineStyle lineStyle]; majorLineStyle.lineCap = kCGLineCapRound; majorLineStyle.lineColor = [CPColor whiteColor]; majorLineStyle.lineWidth = 3.0f; CPLineStyle *minorLineStyle = [CPLineStyle lineStyle]; minorLineStyle.lineColor = [CPColor whiteColor]; minorLineStyle.lineWidth = 3.0f; CPXYAxis *x = axisSet.xAxis; CPTextStyle *whiteTextStyle = [[[CPTextStyle alloc] init] autorelease]; whiteTextStyle.color = [CPColor whiteColor]; whiteTextStyle.fontSize = 14.0; x.axisLabelingPolicy = CPAxisLabelingPolicyFixedInterval; x.majorIntervalLength = CPDecimalFromString(@"0.5"); x.constantCoordinateValue = CPDecimalFromString(@"0"); x.tickDirection = CPSignNone; x.minorTicksPerInterval = 4; x.majorTickLineStyle = majorLineStyle; x.minorTickLineStyle = minorLineStyle; x.axisLineStyle = majorLineStyle; x.majorTickLength = 7.0f; x.minorTickLength = 5.0f; x.axisLabelTextStyle = whiteTextStyle; x.axisTitleTextStyle = whiteTextStyle; CPXYAxis *y = axisSet.yAxis; y.axisLabelingPolicy = CPAxisLabelingPolicyFixedInterval; y.majorIntervalLength = CPDecimalFromString(@"0.5"); y.minorTicksPerInterval = 4; y.constantCoordinateValue = CPDecimalFromString(@"0"); y.tickDirection = CPSignNone; y.majorTickLineStyle = majorLineStyle; y.minorTickLineStyle = minorLineStyle; y.axisLineStyle = majorLineStyle; y.majorTickLength = 7.0f; y.minorTickLength = 5.0f; y.axisLabelTextStyle = whiteTextStyle; y.axisTitleTextStyle = whiteTextStyle; } @end
08iteng-ipad
systemtests/tests/Source/CPPlainBlackTheme.m
Objective-C
bsd
2,631
#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
systemtests/tests/Source/_CPFillColor.m
Objective-C
bsd
2,265
#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
systemtests/tests/Source/CPXYGraph.h
Objective-C
bsd
340
#import "CPTestCase.h" @class CPLayer; @class CPXYPlotSpace; @interface CPXYPlotSpaceTests : CPTestCase { CPLayer *layer; CPXYPlotSpace *plotSpace; } @property (retain,readwrite) CPLayer *layer; @property (retain,readwrite) CPXYPlotSpace *plotSpace; @end
08iteng-ipad
systemtests/tests/Source/CPXYPlotSpaceTests.h
Objective-C
bsd
268
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> @interface NSDecimalNumber(CPExtensions) -(CGFloat)floatValue; @end
08iteng-ipad
systemtests/tests/Source/NSDecimalNumberExtensions.h
Objective-C
bsd
139
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> /// @file /** * @brief Enumeration of numeric types **/ typedef enum _CPNumericType { CPNumericTypeInteger, ///< Integer CPNumericTypeFloat, ///< Float CPNumericTypeDouble ///< Double } CPNumericType; /** * @brief Enumeration of error bar types **/ typedef enum _CPErrorBarType { CPErrorBarTypeCustom, ///< Custom error bars CPErrorBarTypeConstantRatio, ///< Constant ratio error bars CPErrorBarTypeConstantValue ///< Constant value error bars } CPErrorBarType; /** * @brief Enumeration of axis scale types **/ typedef enum _CPScaleType { CPScaleTypeLinear, ///< Linear axis scale CPScaleTypeLogN, ///< Log base <i>n</i> axis scale CPScaleTypeLog10, ///< Log base 10 axis scale CPScaleTypeAngular, ///< Angular axis scale CPScaleTypeDateTime, ///< Date/time axis scale CPScaleTypeCategory ///< Category axis scale } CPScaleType; /** * @brief Enumeration of axis coordinates **/ typedef enum _CPCoordinate { CPCoordinateX = 0, ///< X axis CPCoordinateY = 1, ///< Y axis CPCoordinateZ = 2 ///< Z axis } CPCoordinate; /** * @brief RGBA color for gradients **/ typedef struct _CPRGBAColor { CGFloat red; ///< The red component (0 ≤ red ≤ 1). CGFloat green; ///< The green component (0 ≤ green ≤ 1). CGFloat blue; ///< The blue component (0 ≤ blue ≤ 1). CGFloat alpha; ///< The alpha component (0 ≤ alpha ≤ 1). } CPRGBAColor; /** * @brief Enumeration of label positioning offset directions **/ typedef enum _CPSign { CPSignNone, ///< No offset CPSignPositive, ///< Positive offset CPSignNegative ///< Negative offset } CPSign; /// @name Default Z Positions /// @{ extern const CGFloat CPDefaultZPositionAxis; extern const CGFloat CPDefaultZPositionAxisSet; extern const CGFloat CPDefaultZPositionGraph; extern const CGFloat CPDefaultZPositionPlot; extern const CGFloat CPDefaultZPositionPlotArea; extern const CGFloat CPDefaultZPositionPlotGroup; extern const CGFloat CPDefaultZPositionPlotSpace; /// @}
08iteng-ipad
systemtests/tests/Source/CPDefinitions.h
Objective-C
bsd
2,080
#import <Foundation/Foundation.h> #import "CPPlotSpace.h" @interface CPPolarPlotSpace : CPPlotSpace { } @end
08iteng-ipad
systemtests/tests/Source/CPPolarPlotSpace.h
Objective-C
bsd
117
#import "CPXYGraph.h" @interface CPDerivedXYGraph : CPXYGraph { } @end
08iteng-ipad
systemtests/tests/Source/CPDerivedXYGraph.h
Objective-C
bsd
74
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> @class CPColor; @interface CPLineStyle : NSObject <NSCopying> { @private CGLineCap lineCap; // CGLineDash lineDash; // We should make a struct to keep this information CGLineJoin lineJoin; CGFloat miterLimit; CGFloat lineWidth; CGSize patternPhase; // StrokePattern; // We should make a struct to keep this information CPColor *lineColor; } @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, assign) CGSize patternPhase; @property (nonatomic, readwrite, retain) CPColor *lineColor; /// @name Factory Methods /// @{ +(CPLineStyle *)lineStyle; /// @} /// @name Drawing /// @{ -(void)setLineStyleInContext:(CGContextRef)theContext; /// @} @end
08iteng-ipad
systemtests/tests/Source/CPLineStyle.h
Objective-C
bsd
950
#import "CPDataSourceTestCase.h" #import "CPExceptions.h" #import "CPScatterPlot.h" #import "CPPlotRange.h" #import "CPUtilities.h" const CGFloat CPDataSourceTestCasePlotOffset = 0.5; /// @cond @interface CPDataSourceTestCase () - (CPPlotRange*)plotRangeForData:(NSArray*)dataArray; @end /// @endcond @implementation CPDataSourceTestCase @synthesize xData; @synthesize yData; @synthesize nRecords; @synthesize xRange; @synthesize yRange; @synthesize plots; - (void)dealloc { self.plots = nil; [super dealloc]; } - (void)setUp { //check CPDataSource conformance STAssertTrue([self conformsToProtocol:@protocol(CPPlotDataSource)], @"CPDataSourceTestCase should conform to <CPPlotDataSource>"); } - (void)tearDown { self.xData = nil; self.yData = nil; [[self plots] removeAllObjects]; } - (void)buildData { NSMutableArray *arr = [NSMutableArray arrayWithCapacity:self.nRecords]; for(NSUInteger i=0; i<self.nRecords; i++) { [arr insertObject:[NSDecimalNumber numberWithUnsignedInteger:i] atIndex:i]; } self.xData = arr; arr = [NSMutableArray arrayWithCapacity:self.nRecords]; for(NSUInteger i=0; i<self.nRecords; i++) { [arr insertObject:[NSDecimalNumber numberWithFloat:sin(2*M_PI*(float)i/(float)nRecords)] atIndex:i]; } self.yData = arr; } - (void)addPlot:(CPPlot*)newPlot { if(nil == self.plots) { self.plots = [NSMutableArray array]; } [[self plots] addObject:newPlot]; } - (CPPlotRange*)xRange { [self buildData]; return [self plotRangeForData:self.xData]; } - (CPPlotRange*)yRange { [self buildData]; CPPlotRange *range = [self plotRangeForData:self.yData]; if(self.plots.count > 1) { range.length = CPDecimalAdd([range length], CPDecimalFromDouble(self.plots.count)); } return range; } - (CPPlotRange*)plotRangeForData:(NSArray*)dataArray { double min = [[dataArray valueForKeyPath:@"@min.doubleValue"] doubleValue]; double max = [[dataArray valueForKeyPath:@"@max.doubleValue"] doubleValue]; double range = max-min; return [CPPlotRange plotRangeWithLocation:CPDecimalFromDouble(min - 0.05*range) length:CPDecimalFromDouble(range + 0.1*range)]; } #pragma mark - #pragma mark Plot Data Source Methods -(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot { return self.nRecords; } -(NSArray *)numbersForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange { NSArray *result; switch(fieldEnum) { case CPScatterPlotFieldX: result = [[self xData] objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:indexRange]]; break; case CPScatterPlotFieldY: result = [[self yData] objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:indexRange]]; if(self.plots.count > 1) { _GTMDevAssert([[self plots] containsObject:plot], @""); NSMutableArray *shiftedResult = [NSMutableArray arrayWithCapacity:result.count]; for(NSDecimalNumber *d in result) { [shiftedResult addObject:[d decimalNumberByAdding:[NSDecimalNumber decimalNumberWithDecimal:CPDecimalFromFloat(CPDataSourceTestCasePlotOffset * ([[self plots] indexOfObject:plot]+1))]]]; } result = shiftedResult; } break; default: [NSException raise:CPDataException format:@"Unexpected fieldEnum"]; } return result; } @end
08iteng-ipad
systemtests/tests/Source/CPDataSourceTestCase.m
Objective-C
bsd
3,636
#import "CPXYAxisSet.h" #import "CPXYAxis.h" #import "CPDefinitions.h" #import "CPPlotArea.h" #import "CPBorderedLayer.h" /** @brief A set of cartesian (X-Y) axes. **/ @implementation CPXYAxisSet /** @property xAxis * @brief The x-axis. **/ @dynamic xAxis; /** @property yAxis * @brief The y-axis. **/ @dynamic yAxis; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { CPXYAxis *xAxis = [(CPXYAxis *)[CPXYAxis alloc] initWithFrame:newFrame]; xAxis.coordinate = CPCoordinateX; xAxis.tickDirection = CPSignNegative; CPXYAxis *yAxis = [(CPXYAxis *)[CPXYAxis alloc] initWithFrame:newFrame]; yAxis.coordinate = CPCoordinateY; yAxis.tickDirection = CPSignNegative; self.axes = [NSArray arrayWithObjects:xAxis, yAxis, nil]; [xAxis release]; [yAxis release]; } return self; } #pragma mark - #pragma mark Accessors -(CPXYAxis *)xAxis { return [self.axes objectAtIndex:CPCoordinateX]; } -(CPXYAxis *)yAxis { return [self.axes objectAtIndex:CPCoordinateY]; } @end
08iteng-ipad
systemtests/tests/Source/CPXYAxisSet.m
Objective-C
bsd
1,092
#import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> /** @brief Defines a layer layout manager. All methods are optional. **/ @protocol CPLayoutManager <NSObject> @optional /** @brief Invalidates the layout of a layer. * @param layer The layer that requires layout. * * This method is called when the preferred size of the layer may have changed. * The receiver should invalidate any cached state. **/ -(void)invalidateLayoutOfLayer:(CALayer *)layer; /** @brief Layout each sublayer of the given layer. * @param layer The layer whose sublayers require layout. * * The recevier should set the frame of each sublayer that requires layout. **/ -(void)layoutSublayersOfLayer:(CALayer *)layer; /** @brief Returns the preferred size of a layer in its coordinate system. * @param layer The layer that requires layout. * @return The preferred size of the layer. * * If this method is not implemented the preferred size is assumed to be the size of the bounds of <code>layer</code>. **/ -(CGSize)preferredSizeOfLayer:(CALayer *)layer; /** @brief Returns the minimum size of a layer in its coordinate system. * @param layer The layer that requires layout. * @return The minimum size of the layer. * * If this method is not implemented the minimum size is assumed to be (0, 0). **/ -(CGSize)minimumSizeOfLayer:(CALayer *)layer; /** @brief Returns the maximum size of a layer in its coordinate system. * @param layer The layer that requires layout. * @return The maximum size of the layer. * * If this method is not implemented the maximimum size is assumed to be the size of the bounds of <code>layer</code>'s superlayer. **/ -(CGSize)maximumSizeOfLayer:(CALayer *)layer; @end
08iteng-ipad
systemtests/tests/Source/CPLayoutManager.h
Objective-C
bsd
1,717
#import <Foundation/Foundation.h> @interface NSNumber(CPExtensions) -(NSDecimalNumber *)decimalNumber; @end
08iteng-ipad
systemtests/tests/Source/NSNumberExtensions.h
Objective-C
bsd
112
#import "CPAnimationKeyFrame.h" /** @brief An animation key frame. * @note Not implemented. * @todo * - Implement CPAnimationKeyFrame. * - Add documentation for CPAnimationKeyFrame. **/ @implementation CPAnimationKeyFrame /** @property identifier * @todo Needs documentation. **/ @synthesize identifier; /** @property isInitialFrame * @todo Needs documentation. **/ @synthesize isInitialFrame; /** @property duration * @todo Needs documentation. **/ @synthesize duration; #pragma mark - #pragma mark Init/Dealloc /** @todo Needs documentation. * @param isFirst Needs documentation. * @return Needs documentation. **/ -(id)initAsInitialFrame:(BOOL)isFirst { if ( self = [super init] ) { identifier = nil; isInitialFrame = isFirst; duration = 0.0; } return self; } -(void)dealloc { [identifier release]; [super dealloc]; } @end
08iteng-ipad
systemtests/tests/Source/CPAnimationKeyFrame.m
Objective-C
bsd
882
#import <Foundation/Foundation.h> #import "CPFill.h" @class CPGradient; @interface _CPFillGradient : CPFill <NSCopying, NSCoding> { @private CPGradient *fillGradient; } /// @name Initialization /// @{ -(id)initWithGradient:(CPGradient *)aGradient; /// @} /// @name Drawing /// @{ -(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext; -(void)fillPathInContext:(CGContextRef)theContext; /// @} @end
08iteng-ipad
systemtests/tests/Source/_CPFillGradient.h
Objective-C
bsd
419
#import "CPColor.h" #import "CPTextLayerTests.h" #import "CPTextLayer.h" #import "CPTextStyle.h" #import <QuartzCore/QuartzCore.h> @interface CPTextLayer (UnitTesting) -(void)gtm_unitTestEncodeState:(NSCoder*)inCoder; @end @implementation CPTextLayer (UnitTesting) -(void)gtm_unitTestEncodeState:(NSCoder*)inCoder { [super gtm_unitTestEncodeState:inCoder]; [inCoder encodeObject:self.text forKey:@"Text"]; [self.textStyle encodeWithCoder:inCoder]; [inCoder encodeRect:NSRectFromCGRect([self frame]) forKey:@"FrameRect"]; } @end @implementation CPTextLayerTests -(void)testInitWithText { NSString *expectedString = @"testInit-expectedString"; CPTextLayer *layer = [[CPTextLayer alloc] initWithText:expectedString]; GTMAssertObjectStateEqualToStateNamed(layer, @"CPTextLayerTests-testInit1", @"state following initWithText: is incorrect"); [layer release]; } -(void)testInitWithTextStyle { NSString *expectedString = @"testInit-expectedString"; CPTextStyle *expectedStyle = [[CPTextStyle alloc] init]; CPTextLayer *layer = [[CPTextLayer alloc] initWithText:expectedString style:expectedStyle]; [expectedStyle release]; GTMAssertObjectStateEqualToStateNamed(layer, @"CPTextLayerTests-testInit2", @"state following initWithText:style: is incorrect"); [layer release]; } -(void)testDrawInContext { CPTextLayer *layer = [[CPTextLayer alloc] initWithText:@"testInit-expectedString"]; GTMAssertObjectImageEqualToImageNamed(layer, @"CPTextLayerTests-testRendering1", @"Rendered image does not match"); layer.text = @"testInit-expectedString2"; GTMAssertObjectImageEqualToImageNamed(layer, @"CPTextLayerTests-testRendering2", @"Rendered image does not match"); layer.text = @"testInit-expectedString3"; layer.textStyle.fontSize = 10.; GTMAssertObjectImageEqualToImageNamed(layer, @"CPTextLayerTests-testRendering3", @"Rendered image does not match"); layer.textStyle.fontSize = 100.; GTMAssertObjectImageEqualToImageNamed(layer, @"CPTextLayerTests-testRendering4", @"Rendered image does not match"); layer.textStyle.color = [CPColor redColor]; GTMAssertObjectImageEqualToImageNamed(layer, @"CPTextLayerTests-testRendering5", @"Rendered image does not match"); layer.textStyle.fontName = @"Times-BoldItalic"; GTMAssertObjectImageEqualToImageNamed(layer, @"CPTextLayerTests-testRendering6", @"Rendered image does not match"); [layer release]; } @end
08iteng-ipad
systemtests/tests/Source/CPTextLayerTests.m
Objective-C
bsd
2,471
#import <Foundation/Foundation.h> @class CPGraph; @class CPAnimationTransition; @class CPAnimationKeyFrame; @interface CPAnimation : NSObject { @private CPGraph *graph; NSMutableSet *mutableKeyFrames; NSMutableSet *mutableTransitions; CPAnimationKeyFrame *currentKeyFrame; } @property (nonatomic, readonly, retain) CPGraph *graph; @property (nonatomic, readonly, retain) NSSet *animationKeyFrames; @property (nonatomic, readonly, retain) NSSet *animationTransitions; @property (nonatomic, readonly, retain) CPAnimationKeyFrame *currentKeyFrame; /// @name Initialization /// @{ -(id)initWithGraph:(CPGraph *)graph; /// @} /// @name Key Frames /// @{ -(void)addAnimationKeyFrame:(CPAnimationKeyFrame *)newKeyFrame; -(CPAnimationKeyFrame *)animationKeyFrameWithIdentifier:(id <NSCopying>)identifier; /// @} /// @name Transitions /// @{ -(void)addAnimationTransition:(CPAnimationTransition *)newTransition fromKeyFrame:(CPAnimationKeyFrame *)startFrame toKeyFrame:(CPAnimationKeyFrame *)endFrame; -(CPAnimationTransition *)animationTransitionWithIdentifier:(id <NSCopying>)identifier; -(void)animationTransitionDidFinish:(CPAnimationTransition *)transition; /// @} /// @name Animating /// @{ -(void)performTransition:(CPAnimationTransition *)transition; -(void)performTransitionToKeyFrame:(CPAnimationKeyFrame *)keyFrame; /// @} @end
08iteng-ipad
systemtests/tests/Source/CPAnimation.h
Objective-C
bsd
1,356
#import "CPDefinitions.h" const CGFloat CPDefaultZPositionAxis = 0; ///< Default Z position for CPAxis. const CGFloat CPDefaultZPositionAxisSet = 0; ///< Default Z position for CPAxisSet. const CGFloat CPDefaultZPositionGraph = 0; ///< Default Z position for CPGraph. const CGFloat CPDefaultZPositionPlot = 0; ///< Default Z position for CPPlot. const CGFloat CPDefaultZPositionPlotArea = 0; ///< Default Z position for CPPlotArea. const CGFloat CPDefaultZPositionPlotGroup = 0; ///< Default Z position for CPPlotGroup. const CGFloat CPDefaultZPositionPlotSpace = 0; ///< Default Z position for CPPlotSpace.
08iteng-ipad
systemtests/tests/Source/CPDefinitions.m
Objective-C
bsd
620
#import "CPXYAxis.h" #import "CPPlotSpace.h" #import "CPPlotRange.h" #import "CPUtilities.h" #import "CPLineStyle.h" #import "CPAxisLabel.h" /// @cond @interface CPXYAxis () -(void)drawTicksInContext:(CGContextRef)theContext atLocations:(NSSet *)locations withLength:(CGFloat)length isMajor:(BOOL)major; -(void)drawGridLinesInContext:(CGContextRef)theContext atLocations:(NSSet *)locations isMajor:(BOOL)major; -(void)terminalPointsForGridLineWithCoordinateDecimalNumber:(NSDecimal)coordinateDecimalNumber startPoint:(CGPoint *)startPoint endPoint:(CGPoint *)endPoint; @end /// @endcond /** @brief A 2-dimensional cartesian (X-Y) axis class. **/ @implementation CPXYAxis /** @property constantCoordinateValue * @brief The data coordinate value where the axis crosses the orthogonal axis. **/ @synthesize constantCoordinateValue; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { constantCoordinateValue = [[NSDecimalNumber zero] decimalValue]; self.tickDirection = CPSignNone; self.needsDisplayOnBoundsChange = YES; } return self; } #pragma mark - #pragma mark Drawing -(CGPoint)viewPointForCoordinateDecimalNumber:(NSDecimal)coordinateDecimalNumber { CPCoordinate orthogonalCoordinate = (self.coordinate == CPCoordinateX ? CPCoordinateY : CPCoordinateX); NSDecimal plotPoint[2]; plotPoint[self.coordinate] = coordinateDecimalNumber; plotPoint[orthogonalCoordinate] = self.constantCoordinateValue; CGPoint point = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; return point; } -(void)drawTicksInContext:(CGContextRef)theContext atLocations:(NSSet *)locations withLength:(CGFloat)length isMajor:(BOOL)major { [(major ? self.majorTickLineStyle : self.minorTickLineStyle) setLineStyleInContext:theContext]; CGContextBeginPath(theContext); for ( NSDecimalNumber *tickLocation in locations ) { // Tick end points CGPoint baseViewPoint = [self viewPointForCoordinateDecimalNumber:[tickLocation decimalValue]]; CGPoint startViewPoint = baseViewPoint; CGPoint endViewPoint = baseViewPoint; CGFloat startFactor, endFactor; switch ( self.tickDirection ) { case CPSignPositive: startFactor = 0; endFactor = 1; break; case CPSignNegative: startFactor = 0; endFactor = -1; break; case CPSignNone: startFactor = -0.5; endFactor = 0.5; break; default: NSLog(@"Invalid sign in drawTicksInContext..."); break; } if ( self.coordinate == CPCoordinateX ) { startViewPoint.y += length * startFactor; endViewPoint.y += length * endFactor; } else { startViewPoint.x += length * startFactor; endViewPoint.x += length * endFactor; } startViewPoint = CPAlignPointToUserSpace(theContext, startViewPoint); endViewPoint = CPAlignPointToUserSpace(theContext, endViewPoint); // Add tick line CGContextMoveToPoint(theContext, startViewPoint.x, startViewPoint.y); CGContextAddLineToPoint(theContext, endViewPoint.x, endViewPoint.y); } // Stroke tick line CGContextStrokePath(theContext); } -(void)terminalPointsForGridLineWithCoordinateDecimalNumber:(NSDecimal)coordinateDecimalNumber startPoint:(CGPoint *)startPoint endPoint:(CGPoint *)endPoint { CPCoordinate orthogonalCoordinate = (self.coordinate == CPCoordinateX ? CPCoordinateY : CPCoordinateX); CPPlotRange *orthogonalRange = [self.plotSpace plotRangeForCoordinate:orthogonalCoordinate]; // Start point NSDecimal plotPoint[2]; plotPoint[self.coordinate] = coordinateDecimalNumber; plotPoint[orthogonalCoordinate] = orthogonalRange.location; *startPoint = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; // End point plotPoint[orthogonalCoordinate] = orthogonalRange.end; *endPoint = [self.plotSpace viewPointInLayer:self forPlotPoint:plotPoint]; } -(void)drawGridLinesInContext:(CGContextRef)theContext atLocations:(NSSet *)locations isMajor:(BOOL)major { if ( major && !self.majorGridLineStyle ) return; if ( !major && !self.minorGridLineStyle ) return; [(major ? self.majorGridLineStyle : self.minorGridLineStyle) setLineStyleInContext:theContext]; CGContextBeginPath(theContext); for ( NSDecimalNumber *location in locations ) { CGPoint startViewPoint; CGPoint endViewPoint; [self terminalPointsForGridLineWithCoordinateDecimalNumber:[location decimalValue] startPoint:&startViewPoint endPoint:&endViewPoint]; // Align to pixels startViewPoint = CPAlignPointToUserSpace(theContext, startViewPoint); endViewPoint = CPAlignPointToUserSpace(theContext, endViewPoint); // Add grid line CGContextMoveToPoint(theContext, startViewPoint.x, startViewPoint.y); CGContextAddLineToPoint(theContext, endViewPoint.x, endViewPoint.y); } // Stroke grid line CGContextStrokePath(theContext); } -(void)renderAsVectorInContext:(CGContextRef)theContext { [super renderAsVectorInContext:theContext]; // Grid Lines [self drawGridLinesInContext:theContext atLocations:self.minorTickLocations isMajor:NO]; [self drawGridLinesInContext:theContext atLocations:self.majorTickLocations isMajor:YES]; // Ticks [self drawTicksInContext:theContext atLocations:self.minorTickLocations withLength:self.minorTickLength isMajor:NO]; [self drawTicksInContext:theContext atLocations:self.majorTickLocations withLength:self.majorTickLength isMajor:YES]; // Axis Line if ( self.axisLineStyle ) { CPPlotRange *range = [self.plotSpace plotRangeForCoordinate:self.coordinate]; CGPoint startViewPoint = CPAlignPointToUserSpace(theContext, [self viewPointForCoordinateDecimalNumber:range.location]); CGPoint endViewPoint = CPAlignPointToUserSpace(theContext, [self viewPointForCoordinateDecimalNumber:range.end]); [self.axisLineStyle setLineStyleInContext:theContext]; CGContextBeginPath(theContext); CGContextMoveToPoint(theContext, startViewPoint.x, startViewPoint.y); CGContextAddLineToPoint(theContext, endViewPoint.x, endViewPoint.y); CGContextStrokePath(theContext); } } #pragma mark - #pragma mark Description -(NSString *)description { CPPlotRange *range = [self.plotSpace plotRangeForCoordinate:self.coordinate]; CGPoint startViewPoint = [self viewPointForCoordinateDecimalNumber:range.location]; CGPoint endViewPoint = [self viewPointForCoordinateDecimalNumber:range.end]; return [NSString stringWithFormat:@"CPXYAxis with range %@ viewCoordinates: {%f, %f} to {%f, %f}", range, startViewPoint.x, startViewPoint.y, endViewPoint.x, endViewPoint.y]; }; #pragma mark - #pragma mark Labels -(NSDecimal)axisTitleLocation { // Find the longest range, before or after the constant coordinate location, and divide that by two CPPlotRange *axisRange = [self.plotSpace plotRangeForCoordinate:self.coordinate]; NSDecimal distanceAfterConstantCoordinate = CPDecimalSubtract(axisRange.end, self.constantCoordinateValue); NSDecimal distanceBeforeConstantCoordinate = CPDecimalSubtract(self.constantCoordinateValue, axisRange.location); if (CPDecimalLessThan(distanceAfterConstantCoordinate, distanceBeforeConstantCoordinate)) { return CPDecimalDivide(CPDecimalAdd(self.constantCoordinateValue, axisRange.location), CPDecimalFromDouble(2.0)); } else { return CPDecimalDivide(CPDecimalAdd(axisRange.end, self.constantCoordinateValue), CPDecimalFromDouble(2.0)); } } @end
08iteng-ipad
systemtests/tests/Source/CPXYAxis.m
Objective-C
bsd
7,571
#import "CPScatterPlotPerformanceTests.h" #import "CPScatterPlot.h" #import "CPExceptions.h" #import "CPPlotRange.h" #import "CPScatterPlot.h" #import "CPXYPlotSpace.h" #import "CPUtilities.h" #import "CPLineStyle.h" #import "CPFill.h" #import "CPPlotSymbol.h" #import "GTMTestTimer.h" @implementation CPScatterPlotPerformanceTests @synthesize plot; - (void)setUp { CPXYPlotSpace *plotSpace = [[[CPXYPlotSpace alloc] init] autorelease]; plotSpace.bounds = CGRectMake(0., 0., 100., 100.); self.plot = [[[CPScatterPlot alloc] init] autorelease]; [plotSpace addSublayer:self.plot]; self.plot.frame = plotSpace.bounds; self.plot.plotSpace = plotSpace; self.plot.identifier = @"Scatter Plot"; self.plot.dataSource = self; } - (void)tearDown { self.plot = nil; } - (void)setPlotRanges { [(CPXYPlotSpace*)[[self plot] plotSpace] setXRange:[self xRange]]; [(CPXYPlotSpace*)[[self plot] plotSpace] setYRange:[self yRange]]; } // Verify that CPScatterPlot can render 1e5 points in less than 1 second. - (void)testRenderScatterTimeLimit { self.nRecords = 1e5; [self buildData]; [self setPlotRanges]; //set up CGContext CGContextRef ctx = GTMCreateUnitTestBitmapContextOfSizeWithData(self.plot.bounds.size, NULL); GTMTestTimer *t = GTMTestTimerCreate(); // render several times for(NSUInteger i = 0; i<3; i++) { [self.plot setDataNeedsReloading]; GTMTestTimerStart(t); [self.plot drawInContext:ctx]; GTMTestTimerStop(t); } //verify performance double avgTime = GTMTestTimerGetSeconds(t)/GTMTestTimerGetIterations(t); STAssertTrue(avgTime < 1.0, @"Avg. time = %g sec. for %lu points.", avgTime, (unsigned long)self.nRecords); // clean up GTMTestTimerRelease(t); CFRelease(ctx); } - (void)testRenderScatterStressTest { self.nRecords = 1e6; [self buildData]; [self setPlotRanges]; GTMAssertObjectImageEqualToImageNamed(self.plot, @"CPScatterPlotTests-testRenderStressTest", @"Should render a sine wave."); } @end
08iteng-ipad
systemtests/tests/Source/CPScatterPlotPerformanceTests.m
Objective-C
bsd
2,082
#import <Foundation/Foundation.h> #import "CPDefinitions.h" @interface CPPlotRange : NSObject <NSCoding, NSCopying> { @private NSDecimal location; NSDecimal length; double doublePrecisionLocation; double doublePrecisionLength; } @property (readwrite) NSDecimal location; @property (readwrite) NSDecimal length; @property (readonly) NSDecimal end; @property (readwrite) double doublePrecisionLocation; @property (readwrite) double doublePrecisionLength; @property (readonly) double doublePrecisionEnd; +(CPPlotRange *)plotRangeWithLocation:(NSDecimal)loc length:(NSDecimal)len; -(id)initWithLocation:(NSDecimal)loc length:(NSDecimal)len; -(BOOL)contains:(NSDecimal)number; -(void)unionPlotRange:(CPPlotRange *)otherRange; -(void)expandRangeByFactor:(NSDecimal)factor; @end
08iteng-ipad
systemtests/tests/Source/CPPlotRange.h
Objective-C
bsd
786
#import "GTMSenTestCase.h" #import "GTMNSObject+UnitTesting.h" #import "GTMNSObject+BindingUnitTesting.h" #import "GTMCALayer+UnitTesting.h" #import "GTMAppKit+UnitTesting.h" @interface CPTestCase : GTMTestCase { } @end
08iteng-ipad
systemtests/tests/Source/CPTestCase.h
Objective-C
bsd
224
#import "CPGraph.h" #import "CPExceptions.h" #import "CPPlot.h" #import "CPPlotArea.h" #import "CPPlotSpace.h" #import "CPFill.h" #import "CPAxisSet.h" #import "CPAxis.h" #import "CPTheme.h" /// @cond @interface CPGraph() @property (nonatomic, readwrite, retain) NSMutableArray *plots; @property (nonatomic, readwrite, retain) NSMutableArray *plotSpaces; -(void)plotSpaceMappingDidChange:(NSNotification *)notif; @end /// @endcond /** @brief An abstract graph class. * @todo More documentation needed **/ @implementation CPGraph /// @defgroup CPGraph CPGraph /// @{ /** @property axisSet * @brief The axis set. **/ @dynamic axisSet; /** @property plotArea * @brief The plot area. **/ @synthesize plotArea; /** @property plots * @brief An array of all plots associated with the graph. **/ @synthesize plots; /** @property plotSpaces * @brief An array of all plot spaces associated with the graph. **/ @synthesize plotSpaces; /** @property defaultPlotSpace * @brief The default plot space. **/ @dynamic defaultPlotSpace; #pragma mark - #pragma mark Init/Dealloc -(id)initWithFrame:(CGRect)newFrame { if ( self = [super initWithFrame:newFrame] ) { plots = [[NSMutableArray alloc] init]; // Margins self.paddingLeft = 20.0; self.paddingTop = 20.0; self.paddingRight = 20.0; self.paddingBottom = 20.0; // Plot area plotArea = [(CPPlotArea *)[CPPlotArea alloc] initWithFrame:self.bounds]; [self addSublayer:plotArea]; // Plot spaces plotSpaces = [[NSMutableArray alloc] init]; CPPlotSpace *newPlotSpace = [self newPlotSpace]; [self addPlotSpace:newPlotSpace]; [newPlotSpace release]; // Axis set CPAxisSet *newAxisSet = [self newAxisSet]; self.axisSet = newAxisSet; [newAxisSet release]; self.needsDisplayOnBoundsChange = YES; } return self; } -(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [plotArea release]; [plots release]; [plotSpaces release]; [super dealloc]; } #pragma mark - #pragma mark Retrieving Plots /** @brief Makes all plots reload their data. **/ -(void)reloadData { [[self allPlots] makeObjectsPerformSelector:@selector(reloadData)]; } /** @brief All plots associated with the graph. * @return An array of all plots associated with the graph. **/ -(NSArray *)allPlots { return [NSArray arrayWithArray:self.plots]; } /** @brief Gets the plot at the given index in the plot array. * @param index An index within the bounds of the plot array. * @return The plot at the given index. **/ -(CPPlot *)plotAtIndex:(NSUInteger)index { return [self.plots objectAtIndex:index]; } /** @brief Gets the plot with the given identifier. * @param identifier A plot identifier. * @return The plot with the given identifier. **/ -(CPPlot *)plotWithIdentifier:(id <NSCopying>)identifier { for (CPPlot *plot in self.plots) { if ( [[plot identifier] isEqual:identifier] ) return plot; } return nil; } #pragma mark - #pragma mark Organizing Plots /** @brief Add a plot to the default plot space. * @param plot The plot. **/ -(void)addPlot:(CPPlot *)plot { [self addPlot:plot toPlotSpace:self.defaultPlotSpace]; } /** @brief Add a plot to the given plot space. * @param plot The plot. * @param space The plot space. **/ -(void)addPlot:(CPPlot *)plot toPlotSpace:(CPPlotSpace *)space { if ( plot ) { [self.plots addObject:plot]; plot.plotSpace = space; [self.plotArea.plotGroup addPlot:plot]; } } /** @brief Remove a plot from the graph. * @param plot The plot to remove. **/ -(void)removePlot:(CPPlot *)plot { if ( [self.plots containsObject:plot] ) { [self.plots removeObject:plot]; plot.plotSpace = nil; [self.plotArea.plotGroup removePlot:plot]; } else { [NSException raise:CPException format:@"Tried to remove CPPlot which did not exist."]; } } /** @brief Add a plot to the default plot space at the given index in the plot array. * @param plot The plot. * @param index An index within the bounds of the plot array. **/ -(void)insertPlot:(CPPlot* )plot atIndex:(NSUInteger)index { [self insertPlot:plot atIndex:index intoPlotSpace:self.defaultPlotSpace]; } /** @brief Add a plot to the given plot space at the given index in the plot array. * @param plot The plot. * @param index An index within the bounds of the plot array. * @param space The plot space. **/ -(void)insertPlot:(CPPlot* )plot atIndex:(NSUInteger)index intoPlotSpace:(CPPlotSpace *)space { if (plot) { [self.plots insertObject:plot atIndex:index]; plot.plotSpace = space; [self.plotArea.plotGroup addPlot:plot]; } } /** @brief Remove a plot from the graph. * @param identifier The identifier of the plot to remove. **/ -(void)removePlotWithIdentifier:(id <NSCopying>)identifier { CPPlot* plotToRemove = [self plotWithIdentifier:identifier]; if (plotToRemove) { plotToRemove.plotSpace = nil; [self.plotArea.plotGroup removePlot:plotToRemove]; [self.plots removeObjectIdenticalTo:plotToRemove]; } } #pragma mark - #pragma mark Retrieving Plot Spaces -(CPPlotSpace *)defaultPlotSpace { return ( self.plotSpaces.count > 0 ? [self.plotSpaces objectAtIndex:0] : nil ); } /** @brief All plot spaces associated with the graph. * @return An array of all plot spaces associated with the graph. **/ -(NSArray *)allPlotSpaces { return [NSArray arrayWithArray:self.plotSpaces]; } /** @brief Gets the plot space at the given index in the plot space array. * @param index An index within the bounds of the plot space array. * @return The plot space at the given index. **/ -(CPPlotSpace *)plotSpaceAtIndex:(NSUInteger)index { return ( self.plotSpaces.count > index ? [self.plotSpaces objectAtIndex:index] : nil ); } /** @brief Gets the plot space with the given identifier. * @param identifier A plot space identifier. * @return The plot space with the given identifier. **/ -(CPPlotSpace *)plotSpaceWithIdentifier:(id <NSCopying>)identifier { for (CPPlotSpace *plotSpace in self.plotSpaces) { if ( [[plotSpace identifier] isEqual:identifier] ) return plotSpace; } return nil; } #pragma mark - #pragma mark Organizing Plot Spaces /** @brief Add a plot space to the graph. * @param space The plot space. **/ -(void)addPlotSpace:(CPPlotSpace *)space { [self.plotSpaces addObject:space]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(plotSpaceMappingDidChange:) name:CPPlotSpaceCoordinateMappingDidChangeNotification object:space]; } /** @brief Remove a plot space from the graph. * @param plotSpace The plot space. **/ -(void)removePlotSpace:(CPPlotSpace *)plotSpace { if ( [self.plotSpaces containsObject:plotSpace] ) { [[NSNotificationCenter defaultCenter] removeObserver:self name:CPPlotSpaceCoordinateMappingDidChangeNotification object:plotSpace]; [self.plotSpaces removeObject:plotSpace]; for ( CPAxis *axis in self.axisSet.axes ) { if ( axis.plotSpace == plotSpace ) axis.plotSpace = nil; } } else { [NSException raise:CPException format:@"Tried to remove CPPlotSpace which did not exist."]; } } #pragma mark - #pragma mark Coordinate Changes in Plot Spaces -(void)plotSpaceMappingDidChange:(NSNotification *)notif { [self setNeedsLayout]; [self.axisSet relabelAxes]; for ( CPPlot *plot in self.plots ) { [plot setNeedsDisplay]; } } #pragma mark - #pragma mark Axis Set -(CPAxisSet *)axisSet { return self.plotArea.axisSet; } -(void)setAxisSet:(CPAxisSet *)newSet { newSet.graph = self; self.plotArea.axisSet = newSet; } #pragma mark - #pragma mark Themes /** @brief Apply a theme to style the graph. * @param theme The theme object used to style the graph. **/ -(void)applyTheme:(CPTheme *)theme { [theme applyThemeToGraph:self]; } #pragma mark - #pragma mark Layout +(CGFloat)defaultZPosition { return CPDefaultZPositionGraph; } #pragma mark - #pragma mark Accessors /// @} @end /// @brief CPGraph abstract methods—must be overridden by subclasses @implementation CPGraph(AbstractFactoryMethods) /// @addtogroup CPGraph /// @{ /** @brief Creates a new plot space for the graph. * @return A new plot space. **/ -(CPPlotSpace *)newPlotSpace { return nil; } /** @brief Creates a new axis set for the graph. * @return A new axis set. **/ -(CPAxisSet *)newAxisSet { return nil; } /// @} @end
08iteng-ipad
systemtests/tests/Source/CPGraph.m
Objective-C
bsd
8,474
#import "CPColor.h" #import "CPTextStyle.h" #import "CPTextStyleTests.h" #import <QuartzCore/QuartzCore.h> @implementation CPTextStyleTests -(void)testDefaults { CPTextStyle *textStyle= [CPTextStyle textStyle]; STAssertEqualObjects(@"Helvetica", textStyle.fontName, @"Default font name is not Helvetica"); STAssertEquals(12.0f, textStyle.fontSize, @"Default font size is not 12.0"); STAssertEqualObjects([CPColor blackColor], textStyle.color, @"Default color is not [CPColor blackColor]"); } @end
08iteng-ipad
systemtests/tests/Source/CPTextStyleTests.m
Objective-C
bsd
508
#import "CPTestCase.h" @interface CPAxisLabelTests : CPTestCase { } @end
08iteng-ipad
systemtests/tests/Source/CPAxisLabelTests.h
Objective-C
bsd
77
// // GTMNSBezierPath+Shading.h // // Category for radial and axial stroke and fill functions for NSBezierPaths // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import "GTMDefines.h" @protocol GTMShading; // /// Category for radial and axial stroke and fill functions for NSBezierPaths // @interface NSBezierPath (GTMBezierPathShadingAdditions) /// Stroke the path axially with a color blend defined by |shading|. // /// The fill will extend from |fromPoint| to |toPoint| and will extend /// indefinitely perpendicular to the axis of the line defined by the /// two points. You can extend beyond the |fromPoint|/|toPoint by setting /// |extendingStart|/|extendingEnd| respectively. // // Args: // fromPoint: point to start the shading at // toPoint: point to end the shading at // extendingStart: should we extend the shading before |fromPoint| using // the first color in our shading? // extendingEnd: should we extend the shading after |toPoint| using the // last color in our shading? // shading: the shading to use to take our colors from. // - (void)gtm_strokeAxiallyFrom:(NSPoint)fromPoint to:(NSPoint)toPoint extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading; /// Stroke the path radially with a color blend defined by |shading|. // /// The fill will extend from the circle with center |fromPoint| /// and radius |fromRadius| to the circle with center |toPoint| /// with radius |toRadius|. /// You can extend beyond the |fromPoint|/|toPoint| by setting /// |extendingStart|/|extendingEnd| respectively. // // Args: // fromPoint: center of the circle to start the shading at // fromRadius: radius of the circle to start the shading at // toPoint: center of the circle to to end the shading at // toRadius: raidus of the circle to end the shading at // extendingStart: should we extend the shading before |fromPoint| using // the first color in our shading? // extendingEnd: should we extend the shading after |toPoint| using the // last color in our shading? // shading: the shading to use to take our colors from. // - (void)gtm_strokeRadiallyFrom:(NSPoint)fromPoint fromRadius:(CGFloat)fromRadius to:(NSPoint)toPoint toRadius:(CGFloat)toRadius extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading; /// Fill the path radially with a color blend defined by |shading|. // /// The fill will extend from the circle with center |fromPoint| /// and radius |fromRadius| to the circle with center |toPoint| /// with radius |toRadius|. /// You can extend beyond the |fromPoint|/|toPoint by setting /// |extendingStart|/|extendingEnd| respectively. // // Args: // fromPoint: center of the circle to start the shading at // fromRadius: radius of the circle to start the shading at // toPoint: center of the circle to to end the shading at // toRadius: radius of the circle to end the shading at // extendingStart: should we extend the shading before |fromPoint| using // the first color in our shading? // extendingEnd: should we extend the shading after |toPoint| using the // last color in our shading? // shading: the shading to use to take our colors from. // - (void)gtm_fillAxiallyFrom:(NSPoint)fromPoint to:(NSPoint)toPoint extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading; /// Fill the path radially with a color blend defined by |shading|. // /// The fill will extend from the circle with center |fromPoint| /// and radius |fromRadius| to the circle with center |toPoint| /// with radius |toRadius|. /// You can extend beyond the |fromPoint|/|toPoint by setting /// |extendingStart|/|extendingEnd| respectively. // // Args: // fromPoint: center of the circle to start the shading at // fromRadius: radius of the circle to start the shading at // toPoint: center of the circle to to end the shading at // toRadius: radius of the circle to end the shading at // extendingStart: should we extend the shading before |fromPoint| using // the first color in our shading? // extendingEnd: should we extend the shading after |toPoint| using the // last color in our shading? // shading: the shading to use to take our colors from. // - (void)gtm_fillRadiallyFrom:(NSPoint)fromPoint fromRadius:(CGFloat)fromRadius to:(NSPoint)toPoint toRadius:(CGFloat)toRadius extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading; @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+Shading.h
Objective-C
bsd
5,480
// // GTMLoginItems.h // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Foundation/Foundation.h> /// Login items key constants, used as keys in |+loginItems| // // Item name extern NSString * const kGTMLoginItemsNameKey; // Item path extern NSString * const kGTMLoginItemsPathKey; // Hidden (NSNumber bool) extern NSString * const kGTMLoginItemsHiddenKey; /// GTMLoginItems // /// A helper class to manipulate the user's Login Items. @interface GTMLoginItems : NSObject /// Obtain a complete list of all login items. // // Returns: // Autoreleased array of dictionaries keyed with kGTMLoginItemsPathKey, etc. // + (NSArray *)loginItems:(NSError **)errorInfo; /// Check if the given path is in the current user's Login Items // // Args: // path: path to the application // // Returns: // YES if the path is in the Login Items // + (BOOL)pathInLoginItems:(NSString *)path; /// Check if the given name is in the current user's Login Items // // Args: // name: name to the application // // Returns: // YES if the name is in the Login Items // + (BOOL)itemWithNameInLoginItems:(NSString *)name; /// Add the given path to the current user's Login Items. Does nothing if the /// path is already there. // // Args: // path: path to add // hide: Set to YES to have the item launch hidden // + (void)addPathToLoginItems:(NSString *)path hide:(BOOL)hide; /// Remove the given path from the current user's Login Items. Does nothing if /// the path is not there. // // Args: // path: the path to remove // + (void)removePathFromLoginItems:(NSString *)path; /// Remove the given item name from the current user's Login Items. Does nothing /// if no item with that name is present. // // Args: // name: name of the item to remove // + (void)removeItemWithNameFromLoginItems:(NSString *)name; @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMLoginItems.h
Objective-C
bsd
2,395
// // GTMNSBezierPath+RoundRect.h // // Category for adding utility functions for creating // round rectangles. // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMNSBezierPath+RoundRect.h" @implementation NSBezierPath (GTMBezierPathRoundRectAdditions) + (NSBezierPath *)gtm_bezierPathWithRoundRect:(NSRect)rect cornerRadius:(CGFloat)radius { NSBezierPath *bezier = [NSBezierPath bezierPath]; [bezier gtm_appendBezierPathWithRoundRect:rect cornerRadius:radius]; return bezier; } - (void)gtm_appendBezierPathWithRoundRect:(NSRect)rect cornerRadius:(CGFloat)radius { if (!NSIsEmptyRect(rect)) { if (radius > 0.0) { // Clamp radius to be no larger than half the rect's width or height. radius = MIN(radius, 0.5 * MIN(rect.size.width, rect.size.height)); NSPoint topLeft = NSMakePoint(NSMinX(rect), NSMaxY(rect)); NSPoint topRight = NSMakePoint(NSMaxX(rect), NSMaxY(rect)); NSPoint bottomRight = NSMakePoint(NSMaxX(rect), NSMinY(rect)); [self moveToPoint:NSMakePoint(NSMidX(rect), NSMaxY(rect))]; [self appendBezierPathWithArcFromPoint:topLeft toPoint:rect.origin radius:radius]; [self appendBezierPathWithArcFromPoint:rect.origin toPoint:bottomRight radius:radius]; [self appendBezierPathWithArcFromPoint:bottomRight toPoint:topRight radius:radius]; [self appendBezierPathWithArcFromPoint:topRight toPoint:topLeft radius:radius]; [self closePath]; } else { // When radius <= 0.0, use plain rectangle. [self appendBezierPathWithRect:rect]; } } } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+RoundRect.m
Objective-C
bsd
2,503
// // GTMNSBezierPath+CGPathTest.m // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import <SenTestingKit/SenTestingKit.h> #import "GTMNSBezierPath+CGPath.h" #import "GTMAppKit+UnitTesting.h" #import "GTMSenTestCase.h" @interface GTMNSBezierPath_CGPathTest : GTMTestCase<GTMUnitTestViewDrawer> @end @implementation GTMNSBezierPath_CGPathTest - (void)testCreateCGPath { GTMAssertDrawingEqualToImageNamed(self, NSMakeSize(100, 100), @"GTMNSBezierPath+CGPathTest", nil, nil); } // Draws all of our tests so that we can compare this to our stored image file. - (void)gtm_unitTestViewDrawRect:(NSRect)rect contextInfo:(void*)contextInfo{ NSBezierPath *thePath = [NSBezierPath bezierPath]; NSPoint theStart = NSMakePoint(20.0, 20.0); // Test moveto/lineto [thePath moveToPoint: theStart]; for (NSUInteger i = 0; i < 10; ++i) { NSPoint theNewPoint = NSMakePoint(i * 5, i * 10); [thePath lineToPoint: theNewPoint]; theNewPoint = NSMakePoint(i * 2, i * 6); [thePath moveToPoint: theNewPoint]; } // Test moveto/curveto for (NSUInteger i = 0; i < 10; ++i) { NSPoint startPoint = NSMakePoint(5.0, 50.0); NSPoint endPoint = NSMakePoint(55.0, 50.0); NSPoint controlPoint1 = NSMakePoint(17.5, 50.0 + 5.0 * i); NSPoint controlPoint2 = NSMakePoint(42.5, 50.0 - 5.0 * i); [thePath moveToPoint:startPoint]; [thePath curveToPoint:endPoint controlPoint1:controlPoint1 controlPoint2:controlPoint2]; } // test close [thePath closePath]; CGPathRef cgPath = [thePath gtm_createCGPath]; STAssertNotNULL(cgPath, @"Nil CGPath"); CGContextRef cgContext = [[NSGraphicsContext currentContext] graphicsPort]; STAssertNotNULL(cgContext, @"Nil cgContext"); CGContextAddPath(cgContext, cgPath); CGContextStrokePath(cgContext); CGPathRelease(cgPath); } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+CGPathTest.m
Objective-C
bsd
2,519
// // GTMNSWorkspace+ScreenSaver.h // // Category for seeing if the screen saver is running. // Requires linkage with the ScreenSaver.framework. Warning, uses some // undocumented methods in the ScreenSaver.framework. // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> @interface NSWorkspace (GTMScreenSaverAddition) // Check if the screen saver is running. // Returns YES if it is running. // Requires linking to the ScreenSaver.framework. + (BOOL)gtm_isScreenSaverActive; @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSWorkspace+ScreenSaver.h
Objective-C
bsd
1,072
// // GTMDelegatingTableColumn.h // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import "GTMDefines.h" // NOTE: If you're using the 10.5 SDK, just use the new delegate method: // tableView:dataCellForTableColumn:row: @interface GTMDelegatingTableColumn : NSTableColumn // no instance state or new method, it will just invoke the tableview's delegate // w/ the method below. @end // the method delegated to @interface NSObject (GTMDelegatingTableColumnDelegate) - (id)gtm_tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row; @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMDelegatingTableColumn.h
Objective-C
bsd
1,192
// // NSBezierPath+RoundRectTest.m // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import <SenTestingKit/SenTestingKit.h> #import "GTMNSBezierPath+RoundRect.h" #import "GTMAppKit+UnitTesting.h" @interface GTMNSBezierPath_RoundRectTest : GTMTestCase<GTMUnitTestViewDrawer> @end @implementation GTMNSBezierPath_RoundRectTest - (void)testRoundRects { GTMAssertDrawingEqualToImageNamed(self, NSMakeSize(330, 430), @"GTMNSBezierPath+RoundRectTest", nil, nil); } // Draws all of our tests so that we can compare this to our stored TIFF file. - (void)gtm_unitTestViewDrawRect:(NSRect)rect contextInfo:(void*)contextInfo{ NSRect theRects[] = { NSMakeRect(0.0, 10.0, 0.0, 0.0), //Empty Rect test NSMakeRect(50.0, 10.0, 30.0, 30.0), //Square Test NSMakeRect(100.0, 10.0, 1.0, 2.0), //Small Test NSMakeRect(120.0, 10.0, 15.0, 20.0), //Medium Test NSMakeRect(140.0, 10.0, 150.0, 30.0) //Large Test }; const NSUInteger theRectCount = sizeof(theRects) / sizeof(NSRect); // Line Width Tests CGFloat theLineWidths[] = { 0.5, 50.0, 2.0 }; const NSUInteger theLineWidthCount = sizeof(theLineWidths) / sizeof(CGFloat); NSUInteger i,j; for (i = 0; i < theLineWidthCount; ++i) { for (j = 0; j < theRectCount; ++j) { NSBezierPath *roundRect = [NSBezierPath gtm_bezierPathWithRoundRect:theRects[j] cornerRadius:20.0]; [roundRect setLineWidth: theLineWidths[i]]; [roundRect stroke]; CGFloat newWidth = 35.0; if (i < theLineWidthCount - 1) { newWidth += theLineWidths[i + 1] + theLineWidths[i]; } theRects[j].origin.y += newWidth; } } // Fill test NSColor *theColors[] = { [NSColor colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:1.0], [NSColor colorWithCalibratedRed:0.2 green:0.4 blue:0.6 alpha:0.4] }; const NSUInteger theColorCount = sizeof(theColors)/sizeof(NSColor); for (i = 0; i < theColorCount; ++i) { for (j = 0; j < theRectCount; ++j) { NSBezierPath *roundRect = [NSBezierPath gtm_bezierPathWithRoundRect:theRects[j] cornerRadius:10.0]; [theColors[i] setFill]; [roundRect fill]; theRects[j].origin.y += 35.0; } } // Flatness test CGFloat theFlatness[] = {0.0, 0.1, 1.0, 10.0}; const NSUInteger theFlatnessCount = sizeof(theFlatness)/sizeof(CGFloat); for (i = 0; i < theFlatnessCount; i++) { for (j = 0; j < theRectCount; ++j) { NSBezierPath *roundRect = [NSBezierPath gtm_bezierPathWithRoundRect:theRects[j] cornerRadius:6.0]; [roundRect setFlatness:theFlatness[i]]; [roundRect stroke]; theRects[j].origin.y += 35.0; } } } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+RoundRectTest.m
Objective-C
bsd
3,452
// // GTMNSBezierPath+Shading.m // // Category for radial and axial stroke and fill functions for NSBezierPaths // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMNSBezierPath+Shading.h" #import "GTMNSBezierPath+CGPath.h" #import "GTMShading.h" #import "GTMGeometryUtils.h" #import "GTMMethodCheck.h" @interface NSBezierPath (GTMBezierPathShadingAdditionsPrivate) // Fills a CGPathRef either axially or radially with the given shading. // // Args: // path: path to fill // axially: if YES fill axially, otherwise fill radially // asStroke: if YES, clip to the stroke of the path, otherwise // clip to the fill // from: where to shade from // fromRadius: in a radial fill, the radius of the from circle // to: where to shade to // toRadius: in a radial fill, the radius of the to circle // extendingStart: if true, extend the fill with the first color of the shade // beyond |from| away from |to| // extendingEnd: if true, extend the fill with the last color of the shade // beyond |to| away from |from| // shading: the shading to use for the fill // - (void)gtm_fillCGPath:(CGPathRef)path axially:(BOOL)axially asStroke:(BOOL)asStroke from:(NSPoint)fromPoint fromRadius:(CGFloat)fromRadius to:(NSPoint)toPoint toRadius:(CGFloat)toRadius extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading; // Returns the point which is the projection of a line from point |pointA| // to |pointB| by length // // Args: // pointA: first point // pointB: second point // length: distance to project beyond |pointB| which is in line with // |pointA| and |pointB| // // Returns: // the projected point - (NSPoint)gtm_projectLineFrom:(NSPoint)pointA to:(NSPoint)pointB by:(CGFloat)length; @end @implementation NSBezierPath (GTMBezierPathAdditionsPrivate) - (void)gtm_fillCGPath:(CGPathRef)path axially:(BOOL)axially asStroke:(BOOL)asStroke from:(NSPoint)fromPoint fromRadius:(CGFloat)fromRadius to:(NSPoint)toPoint toRadius:(CGFloat)toRadius extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading { CGFunctionRef shadingFunction = [shading shadeFunction]; if (nil != shadingFunction) { CGContextRef currentContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort]; if (nil != currentContext) { CGContextSaveGState(currentContext); CGFloat lineWidth = [self lineWidth]; CGContextSetLineWidth(currentContext, lineWidth); if (asStroke) { // if we are using the stroke, we offset the from and to points // by half the stroke width away from the center of the stroke. // Otherwise we tend to end up with fills that only cover half of the // because users set the start and end points based on the center // of the stroke. CGFloat halfWidth = lineWidth * 0.5; fromPoint = [self gtm_projectLineFrom:toPoint to:fromPoint by:halfWidth]; toPoint = [self gtm_projectLineFrom:fromPoint to:toPoint by:-halfWidth]; } CGColorSpaceRef colorspace = [shading colorSpace]; if (nil != colorspace) { CGPoint toCGPoint = GTMNSPointToCGPoint(toPoint); CGPoint fromCGPoint = GTMNSPointToCGPoint(fromPoint); CGShadingRef myCGShading; if(axially) { myCGShading = CGShadingCreateAxial(colorspace, fromCGPoint, toCGPoint, shadingFunction, extendingStart == YES, extendingEnd == YES); } else { myCGShading = CGShadingCreateRadial(colorspace, fromCGPoint, fromRadius, toCGPoint, toRadius, shadingFunction, extendingStart == YES, extendingEnd == YES); } if (nil != myCGShading) { CGContextAddPath(currentContext,path); if(asStroke) { CGContextReplacePathWithStrokedPath(currentContext); } CGContextClip(currentContext); CGContextDrawShading(currentContext, myCGShading); CGShadingRelease(myCGShading); } } CGContextRestoreGState(currentContext); } } } - (NSPoint)gtm_projectLineFrom:(NSPoint)pointA to:(NSPoint)pointB by:(CGFloat)length { NSPoint newPoint = pointB; CGFloat x = (pointB.x - pointA.x); CGFloat y = (pointB.y - pointA.y); if (fpclassify(x) == FP_ZERO) { newPoint.y += length; } else if (fpclassify(y) == FP_ZERO) { newPoint.x += length; } else { #if CGFLOAT_IS_DOUBLE CGFloat angle = atan(y / x); newPoint.x += sin(angle) * length; newPoint.y += cos(angle) * length; #else CGFloat angle = atanf(y / x); newPoint.x += sinf(angle) * length; newPoint.y += cosf(angle) * length; #endif } return newPoint; } @end @implementation NSBezierPath (GTMBezierPathShadingAdditions) GTM_METHOD_CHECK(NSBezierPath, gtm_createCGPath); // COV_NF_LINE - (void)gtm_strokeAxiallyFrom:(NSPoint)fromPoint to:(NSPoint)toPoint extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading { CGPathRef thePath = [self gtm_createCGPath]; if (nil != thePath) { [self gtm_fillCGPath:thePath axially:YES asStroke:YES from:fromPoint fromRadius:(CGFloat)0.0 to:toPoint toRadius:(CGFloat)0.0 extendingStart:extendingStart extendingEnd:extendingEnd shading:shading]; CGPathRelease(thePath); } } - (void)gtm_strokeRadiallyFrom:(NSPoint)fromPoint fromRadius:(CGFloat)fromRadius to:(NSPoint)toPoint toRadius:(CGFloat)toRadius extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading { CGPathRef thePath = [self gtm_createCGPath]; if (nil != thePath) { [self gtm_fillCGPath:thePath axially:NO asStroke:YES from:fromPoint fromRadius:fromRadius to:toPoint toRadius:toRadius extendingStart:extendingStart extendingEnd:extendingEnd shading:shading]; CGPathRelease(thePath); } } - (void)gtm_fillAxiallyFrom:(NSPoint)fromPoint to:(NSPoint)toPoint extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading { CGPathRef thePath = [self gtm_createCGPath]; if (nil != thePath) { [self gtm_fillCGPath:thePath axially:YES asStroke:NO from:fromPoint fromRadius:(CGFloat)0.0 to:toPoint toRadius:(CGFloat)0.0 extendingStart:extendingStart extendingEnd:extendingEnd shading:shading]; CGPathRelease(thePath); } } - (void)gtm_fillRadiallyFrom:(NSPoint)fromPoint fromRadius:(CGFloat)fromRadius to:(NSPoint)toPoint toRadius:(CGFloat)toRadius extendingStart:(BOOL)extendingStart extendingEnd:(BOOL)extendingEnd shading:(id<GTMShading>)shading { CGPathRef thePath = [self gtm_createCGPath]; if (nil != thePath) { [self gtm_fillCGPath:thePath axially:NO asStroke:NO from:fromPoint fromRadius:fromRadius to:toPoint toRadius:toRadius extendingStart:extendingStart extendingEnd:extendingEnd shading:shading]; CGPathRelease(thePath); } } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+Shading.m
Objective-C
bsd
8,535
// // GTMLinearRGBShading.m // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMLinearRGBShading.h" // Carbon callback function required for CoreGraphics static void cShadeFunction(void *info, const CGFloat *inPos, CGFloat *outVals); @implementation GTMLinearRGBShading + (id)shadingFromColor:(NSColor *)begin toColor:(NSColor *)end fromSpaceNamed:(NSString*)colorSpaceName { NSColor *theColors[] = { begin, end }; CGFloat thePositions[] = { 0.0, 1.0 }; return [[self class] shadingWithColors:theColors fromSpaceNamed:colorSpaceName atPositions:thePositions count:(sizeof(thePositions)/sizeof(CGFloat))]; } + (id)shadingWithColors:(NSColor **)colors fromSpaceNamed:(NSString*)colorSpaceName atPositions:(CGFloat *)positions count:(NSUInteger)count { GTMLinearRGBShading *theShading = [[[[self class] alloc] initWithColorSpaceName:colorSpaceName] autorelease]; for (NSUInteger i = 0; i < count; ++i) { [theShading insertStop:colors[i] atPosition:positions[i]]; } return theShading; } - (id)initWithColorSpaceName:(NSString*)colorSpaceName { if ((self = [super init])) { if ([colorSpaceName isEqualToString:NSDeviceRGBColorSpace]) { isCalibrated_ = NO; } else if ([colorSpaceName isEqualToString:NSCalibratedRGBColorSpace]) { isCalibrated_ = YES; } else { [self release]; self = nil; } } return self; } - (void)finalize { if (nil != function_) { CGFunctionRelease(function_); } if (nil != colorSpace_) { CGColorSpaceRelease(colorSpace_); } [super finalize]; } - (void)dealloc { if (nil != function_) { CGFunctionRelease(function_); } if (nil != colorSpace_) { CGColorSpaceRelease(colorSpace_); } [super dealloc]; } - (void)insertStop:(id)item atPosition:(CGFloat)position { NSString *colorSpaceName = isCalibrated_ ? NSCalibratedRGBColorSpace : NSDeviceRGBColorSpace; NSColor *tempColor = [item colorUsingColorSpaceName: colorSpaceName]; if (nil != tempColor) { [super insertStop:tempColor atPosition:position]; } } // Calculate a linear value based on our stops - (id)valueAtPosition:(CGFloat)position { NSUInteger positionIndex = 0; NSUInteger colorCount = [self stopCount]; CGFloat stop1Position = 0.0; NSColor *stop1Color = [self stopAtIndex:positionIndex position:&stop1Position]; positionIndex += 1; CGFloat stop2Position = 0.0; NSColor *stop2Color = nil; NSColor *theColor = nil; if (colorCount > 1) { stop2Color = [self stopAtIndex:positionIndex position:&stop2Position]; positionIndex += 1; } else { // if we only have one value, that's what we return stop2Position = stop1Position; stop2Color = stop1Color; } while (positionIndex < colorCount && stop2Position < position) { stop1Color = stop2Color; stop1Position = stop2Position; stop2Color = [self stopAtIndex:positionIndex position:&stop2Position]; positionIndex += 1; } if (position <= stop1Position) { // if we are less than our lowest position, return our first color theColor = stop1Color; [stop1Color getRed:&colorValue_[0] green:&colorValue_[1] blue:&colorValue_[2] alpha:&colorValue_[3]]; } else if (position >= stop2Position) { // likewise if we are greater than our highest position, return the last color [stop2Color getRed:&colorValue_[0] green:&colorValue_[1] blue:&colorValue_[2] alpha:&colorValue_[3]]; } else { // otherwise interpolate between the two position = (position - stop1Position) / (stop2Position - stop1Position); CGFloat red1, red2, green1, green2, blue1, blue2, alpha1, alpha2; [stop1Color getRed:&red1 green:&green1 blue:&blue1 alpha:&alpha1]; [stop2Color getRed:&red2 green:&green2 blue:&blue2 alpha:&alpha2]; colorValue_[0] = (red2 - red1) * position + red1; colorValue_[1] = (green2 - green1) * position + green1; colorValue_[2] = (blue2 - blue1) * position + blue1; colorValue_[3] = (alpha2 - alpha1) * position + alpha1; } // Yes, I am casting a CGFloat[] to an id to pass it by the compiler. This // significantly improves performance though as I avoid creating an NSColor // for every scanline which later has to be cleaned up in an autorelease pool // somewhere. Causes guardmalloc to run significantly faster. return (id)colorValue_; } // // switch from C to obj-C. The callback to a shader is a c function // but we want to call our objective c object to do all the // calculations for us. We have passed our function our // GTMLinearRGBShading as an obj-c object in the |info| so // we just turn around and ask it to calculate our value based // on |inPos| and then stick the results back in |outVals| // // Args: // info: is the GTMLinearRGBShading as an // obj-C object. // inPos: the position to calculate values for. This is a pointer to // a single float value // outVals: where we store our return values. Since we are calculating // an RGBA color, this is a pointer to an array of four float values // ranging from 0.0 to 1.0 // // static void cShadeFunction(void *info, const CGFloat *inPos, CGFloat *outVals) { id object = (id)info; CGFloat *colorValue = (CGFloat*)[object valueAtPosition:*inPos]; outVals[0] = colorValue[0]; outVals[1] = colorValue[1]; outVals[2] = colorValue[2]; outVals[3] = colorValue[3]; } - (CGFunctionRef) shadeFunction { // lazily create the function as necessary if (nil == function_) { // We have to go to carbon here, and create the CGFunction. Note that this // diposed if necessary in the dealloc call. const CGFunctionCallbacks shadeFunctionCallbacks = { 0, &cShadeFunction, NULL }; // TODO: this code assumes that we have a range from 0.0 to 1.0 // which may not be true according to the stops that the user has given us. // In general you have stops at 0.0 and 1.0, so this will do for right now // but may be an issue in the future. const CGFloat inRange[2] = { 0.0, 1.0 }; const CGFloat outRange[8] = { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 }; function_ = CGFunctionCreate(self, sizeof(inRange) / (sizeof(CGFloat) * 2), inRange, sizeof(outRange) / (sizeof(CGFloat) * 2), outRange, &shadeFunctionCallbacks); } return function_; } - (CGColorSpaceRef)colorSpace { // lazily create the colorspace as necessary if (nil == colorSpace_) { if (isCalibrated_) { colorSpace_ = CGColorSpaceCreateWithName(kCGColorSpaceUserRGB); } else { colorSpace_ = CGColorSpaceCreateDeviceRGB(); } } return colorSpace_; } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMLinearRGBShading.m
Objective-C
bsd
7,412
// // GTMLinearRGBShading.h // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import "GTMShading.h" #import "GTMCalculatedRange.h" /// A shading that does returns smooth linear values for RGB. // /// Thus if you create a shading from 0.0->red to 1.0->blue you will get /// \verbatim /// - 0.5->purple /// - 0.75->eggplant /// - 0.25->magenta /// \endverbatim @interface GTMLinearRGBShading : GTMCalculatedRange <GTMShading> { @private CGFunctionRef function_; // function used to calculated shading (STRONG) CGColorSpaceRef colorSpace_; // colorspace used for shading (STRONG) BOOL isCalibrated_; // are we using calibrated or device RGB. CGFloat colorValue_[4]; // the RGBA color values } /// Generate a shading with color |begin| at position 0.0 and color |end| at 1.0. // // Args: // begin: color at beginning of range // end: color at end of range // colorSpaceName: name of colorspace to draw into must be either // NSCalibratedRGBColorSpace or NSDeviceRGBColorSpace // // Returns: // a GTMLinearRGBShading + (id)shadingFromColor:(NSColor *)begin toColor:(NSColor *)end fromSpaceNamed:(NSString*)colorSpaceName; /// Generate a shading with a collection of colors at various positions. // // Args: // colors: a C style array containg the colors we are adding // colorSpaceName: name of colorspace to draw into must be either // NSCalibratedRGBColorSpace or NSDeviceRGBColorSpace // positions: a C style array containg the positions we want to // add the colors at // numberOfColors: how many colors/positions we are adding // // Returns: // a GTMLinearRGBShading + (id)shadingWithColors:(NSColor **)colors fromSpaceNamed:(NSString*)colorSpaceName atPositions:(CGFloat *)positions count:(NSUInteger)numberOfColors; /// Designated initializer // Args: // colorSpaceName - name of the colorspace to use must be either // NSCalibratedRGBColorSpace or NSDeviceRGBColorSpace - (id)initWithColorSpaceName:(NSString*)colorSpaceName; @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMLinearRGBShading.h
Objective-C
bsd
2,708
// // GTMLoginItems.m // Based on AELoginItems from DTS. // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMLoginItems.h" #import "GTMDefines.h" #include <Carbon/Carbon.h> // Exposed constants NSString * const kGTMLoginItemsNameKey = @"Name"; NSString * const kGTMLoginItemsPathKey = @"Path"; NSString * const kGTMLoginItemsHiddenKey = @"Hide"; @interface GTMLoginItems (PrivateMethods) + (NSInteger)indexOfLoginItemWithValue:(id)value forKey:(NSString *)key loginItems:(NSArray *)items; + (BOOL)compileAndRunScript:(NSString *)script withError:(NSError **)errorInfo; @end @implementation GTMLoginItems (PrivateMethods) + (NSInteger)indexOfLoginItemWithValue:(id)value forKey:(NSString *)key loginItems:(NSArray *)items { if (!value || !key || !items) return NSNotFound; NSDictionary *item = nil; NSEnumerator *itemsEnum = [items objectEnumerator]; NSInteger found = -1; while ((item = [itemsEnum nextObject])) { ++found; id itemValue = [item objectForKey:key]; if (itemValue && [itemValue isEqual:value]) { return found; } } return NSNotFound; } + (BOOL)compileAndRunScript:(NSString *)script withError:(NSError **)errorInfo { if ([script length] == 0) { if (errorInfo) *errorInfo = [NSError errorWithDomain:@"GTMLoginItems" code:-90 userInfo:nil]; return NO; } NSAppleScript *query = [[[NSAppleScript alloc] initWithSource:script] autorelease]; NSDictionary *errDict = nil; if ( ![query compileAndReturnError:&errDict]) { if (errorInfo) *errorInfo = [NSError errorWithDomain:@"GTMLoginItems" code:-91 userInfo:errDict]; return NO; } NSAppleEventDescriptor *scriptResult = [query executeAndReturnError:&errDict]; if (!scriptResult) { if (*errorInfo) *errorInfo = [NSError errorWithDomain:@"GTMLoginItems" code:-92 userInfo:errDict]; return NO; } // we don't process the result return YES; } @end @implementation GTMLoginItems + (NSArray*)loginItems:(NSError **)errorInfo { NSDictionary *errDict = nil; // get the script compiled and saved off static NSAppleScript *query = nil; if (!query) { NSString *querySource = @"tell application \"System Events\" to get properties of login items"; query = [[NSAppleScript alloc] initWithSource:querySource]; if ( ![query compileAndReturnError:&errDict]) { if (errorInfo) *errorInfo = [NSError errorWithDomain:@"GTMLoginItems" code:-1 userInfo:errDict]; [query release]; query = nil; return nil; } } // run the script NSAppleEventDescriptor *scriptResult = [query executeAndReturnError:&errDict]; if (!scriptResult) { if (*errorInfo) *errorInfo = [NSError errorWithDomain:@"GTMLoginItems" code:-2 userInfo:errDict]; return nil; } // build our results NSMutableArray *result = [NSMutableArray array]; NSInteger count = [scriptResult numberOfItems]; for (NSInteger i = 0; i < count; ++i) { NSAppleEventDescriptor *aeItem = [scriptResult descriptorAtIndex:i+1]; NSAppleEventDescriptor *hidn = [aeItem descriptorForKeyword:kAEHidden]; NSAppleEventDescriptor *nam = [aeItem descriptorForKeyword:pName]; NSAppleEventDescriptor *ppth = [aeItem descriptorForKeyword:'ppth']; NSMutableDictionary *item = [NSMutableDictionary dictionary]; if (hidn && [hidn booleanValue]) { [item setObject:[NSNumber numberWithBool:YES] forKey:kGTMLoginItemsHiddenKey]; } if (nam) { NSString *name = [nam stringValue]; if (name) { [item setObject:name forKey:kGTMLoginItemsNameKey]; } } if (ppth) { NSString *path = [ppth stringValue]; if (path) { [item setObject:path forKey:kGTMLoginItemsPathKey]; } } [result addObject:item]; } return result; } + (BOOL)pathInLoginItems:(NSString *)path { NSArray *loginItems = [self loginItems:nil]; NSInteger itemIndex = [self indexOfLoginItemWithValue:path forKey:kGTMLoginItemsPathKey loginItems:loginItems]; return (itemIndex != NSNotFound) ? YES : NO; } + (BOOL)itemWithNameInLoginItems:(NSString *)name { NSArray *loginItems = [self loginItems:nil]; NSInteger itemIndex = [self indexOfLoginItemWithValue:name forKey:kGTMLoginItemsNameKey loginItems:loginItems]; return (itemIndex != NSNotFound) ? YES : NO; } + (void)addPathToLoginItems:(NSString*)path hide:(BOOL)hide { if (!path) return; // make sure it isn't already there if ([self pathInLoginItems:path]) return; // now append it NSString *scriptSource = [NSString stringWithFormat: @"tell application \"System Events\" to make new login item with properties { path:\"%s\", hidden:%s } at end", [path UTF8String], (hide ? "yes" : "no")]; [self compileAndRunScript:scriptSource withError:nil]; } + (void)removePathFromLoginItems:(NSString*)path { if ([path length] == 0) return; NSString *scriptSource = [NSString stringWithFormat: @"tell application \"System Events\" to delete (login items whose path is \"%s\")", [path UTF8String]]; [self compileAndRunScript:scriptSource withError:nil]; } + (void)removeItemWithNameFromLoginItems:(NSString *)name { if ([name length] == 0) return; NSString *scriptSource = [NSString stringWithFormat: @"tell application \"System Events\" to delete (login items whose name is \"%s\")", [name UTF8String]]; [self compileAndRunScript:scriptSource withError:nil]; } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMLoginItems.m
Objective-C
bsd
6,338
// // GTMLoginItemsTest.m // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <SenTestingKit/SenTestingKit.h> #import "GTMSenTestCase.h" #import "GTMLoginItems.h" // we don't really run this test because if someone had it in some automated // tests, then if something did fail, it could leave things in the login items // on the computer which could be a nasty surprise. #define TESTS_ENABLED 0 @interface GTMLoginItemsTest : GTMTestCase @end #if TESTS_ENABLED static BOOL ItemsListHasPath(NSArray *items, NSString *path) { NSDictionary *item = nil; NSEnumerator *itemsEnum = [items objectEnumerator]; while ((item = [itemsEnum nextObject])) { NSString *itemPath = [item objectForKey:kGTMLoginItemsPathKey]; if (itemPath && [itemPath isEqual:path]) { return YES; } } return NO; } #endif // TESTS_ENABLED @implementation GTMLoginItemsTest - (void)testGTMLoginItems { #if TESTS_ENABLED NSError *error = nil; NSString *textEditPath = @"/Applications/TextEdit.app"; NSString *textEditName = @"TextEdit"; // fetch the starting values NSArray *initialItems = [GTMLoginItems loginItems:&error]; STAssertNotNil(initialItems, @"shouldn't be nil (%@)", error); STAssertFalse(ItemsListHasPath(initialItems, textEditPath), @"textedit shouldn't be in list to start for test (%@)", initialItems); // add textedit [GTMLoginItems addPathToLoginItems:textEditPath hide:NO]; NSArray *curItems = [GTMLoginItems loginItems:nil]; STAssertNotEqualObjects(initialItems, curItems, nil); // check by path STAssertTrue([GTMLoginItems pathInLoginItems:textEditPath], nil); // check by name STAssertTrue([GTMLoginItems itemWithNameInLoginItems:textEditName], nil); // remove it by path [GTMLoginItems removePathFromLoginItems:textEditPath]; curItems = [GTMLoginItems loginItems:nil]; STAssertEqualObjects(initialItems, curItems, nil); // check by path STAssertFalse([GTMLoginItems pathInLoginItems:textEditPath], nil); // check by name STAssertFalse([GTMLoginItems itemWithNameInLoginItems:textEditName], nil); // add textedit [GTMLoginItems addPathToLoginItems:textEditPath hide:NO]; curItems = [GTMLoginItems loginItems:nil]; STAssertNotEqualObjects(initialItems, curItems, nil); // check by path STAssertTrue([GTMLoginItems pathInLoginItems:textEditPath], nil); // check by name STAssertTrue([GTMLoginItems itemWithNameInLoginItems:textEditName], nil); // remove it by name [GTMLoginItems removeItemWithNameFromLoginItems:textEditName]; curItems = [GTMLoginItems loginItems:nil]; STAssertEqualObjects(initialItems, curItems, nil); // check by path STAssertFalse([GTMLoginItems pathInLoginItems:textEditPath], nil); // check by name STAssertFalse([GTMLoginItems itemWithNameInLoginItems:textEditName], nil); #endif // TESTS_ENABLED } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMLoginItemsTest.m
Objective-C
bsd
3,463
// // GTMNSBezierPath+RoundRect.h // // Category for adding utility functions for creating // round rectangles. // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import "GTMDefines.h" /// Category for adding utility functions for creating round rectangles. @interface NSBezierPath (GMBezierPathRoundRectAdditions) /// Inscribe a round rectangle inside of rectangle |rect| with a corner radius of |radius| // // Args: // rect: outer rectangle to inscribe into // radius: radius of the corners. |radius| is clamped internally // to be no larger than the smaller of half |rect|'s width or height // // Returns: // Auto released NSBezierPath + (NSBezierPath *)gtm_bezierPathWithRoundRect:(NSRect)rect cornerRadius:(CGFloat)radius; /// Adds a path which is a round rectangle inscribed inside of rectangle |rect| with a corner radius of |radius| // // Args: // rect: outer rectangle to inscribe into // radius: radius of the corners. |radius| is clamped internally // to be no larger than the smaller of half |rect|'s width or height - (void)gtm_appendBezierPathWithRoundRect:(NSRect)rect cornerRadius:(CGFloat)radius; @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+RoundRect.h
Objective-C
bsd
1,815
// // GTMNSBezierPath+ShadingTest.m // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Cocoa/Cocoa.h> #import <SenTestingKit/SenTestingKit.h> #import "GTMLinearRGBShading.h" #import "GTMAppKit+UnitTesting.h" #import "GTMNSBezierPath+Shading.h" @interface GTMNSBezierPath_ShadingTest : GTMTestCase<GTMUnitTestViewDrawer> @end @implementation GTMNSBezierPath_ShadingTest - (void)testShadings { GTMAssertDrawingEqualToImageNamed(self, NSMakeSize(200, 200), @"GTMNSBezierPath+ShadingTest", nil, nil); } - (void)gtm_unitTestViewDrawRect:(NSRect)rect contextInfo:(void*)contextInfo { NSColor *theColorArray[] = { [NSColor blueColor], [NSColor redColor], [NSColor yellowColor], [NSColor blueColor], [NSColor greenColor], [NSColor redColor] }; CGFloat theFloatArray[] = { 0.0, 0.2, 0.4, 0.6, 0.8, 1.0 }; GTMLinearRGBShading *shading = [GTMLinearRGBShading shadingWithColors:theColorArray fromSpaceNamed:NSCalibratedRGBColorSpace atPositions:theFloatArray count:sizeof(theFloatArray)/sizeof(CGFloat)]; NSBezierPath *shadedPath; // axialStrokeRect test NSRect axialStrokeRect = NSMakeRect(10.0f, 10.0f, 90.0f, 90.0f); shadedPath = [NSBezierPath bezierPathWithRect:axialStrokeRect]; [shadedPath setLineWidth: 10.0f]; NSPoint startPoint = NSMakePoint(axialStrokeRect.origin.x + 20.0f, axialStrokeRect.origin.y + 20.0f); NSPoint endPoint = NSMakePoint(axialStrokeRect.origin.x + axialStrokeRect.size.width - 20.0f, axialStrokeRect.origin.y + axialStrokeRect.size.height - 20.0f); [shadedPath gtm_strokeAxiallyFrom:startPoint to:endPoint extendingStart:YES extendingEnd:YES shading:shading]; // axial fill NSRect axialFillRect = NSMakeRect(10.0f, 110.0f, 90.0f, 90.0f); shadedPath = [NSBezierPath bezierPathWithRect:axialFillRect]; startPoint = NSMakePoint(axialFillRect.origin.x + 20.0f, axialFillRect.origin.y + 20.0f); endPoint = NSMakePoint(axialFillRect.origin.x + axialFillRect.size.width - 20.0f, axialFillRect.origin.y + axialFillRect.size.height - 20.0f); [shadedPath gtm_fillAxiallyFrom:startPoint to:endPoint extendingStart:YES extendingEnd:YES shading:shading]; // radial stroke NSRect radialStrokeRect = NSMakeRect(110.0f, 110.0f, 90.0f, 90.0f); shadedPath = [NSBezierPath bezierPathWithRect:radialStrokeRect]; startPoint = NSMakePoint(radialStrokeRect.origin.x + 20.0f, radialStrokeRect.origin.y + 20.0f); endPoint = NSMakePoint(radialStrokeRect.origin.x + radialStrokeRect.size.width - 20.0f, radialStrokeRect.origin.y + radialStrokeRect.size.height - 20.0f); [shadedPath gtm_strokeRadiallyFrom:startPoint fromRadius:60.0f to:endPoint toRadius:20.0f extendingStart:YES extendingEnd:YES shading:shading]; // radial fill NSRect radialFillRect = NSMakeRect(110.0f, 10.0f, 90.0f, 90.0f); shadedPath = [NSBezierPath bezierPathWithRect:radialFillRect]; startPoint = NSMakePoint(radialFillRect.origin.x + 20.0f, radialFillRect.origin.y + 20.0f); endPoint = NSMakePoint(radialFillRect.origin.x + radialFillRect.size.width - 20.0f, radialFillRect.origin.y + radialFillRect.size.height - 20.0f); [shadedPath gtm_fillRadiallyFrom:startPoint fromRadius:10.0f to:endPoint toRadius:20.0f extendingStart:YES extendingEnd:YES shading:shading]; } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMNSBezierPath+ShadingTest.m
Objective-C
bsd
4,312
// // GTMLinearRGBShadingTest.m // // Copyright 2006-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <SenTestingKit/SenTestingKit.h> #import "GTMSenTestCase.h" #import "GTMLinearRGBShading.h" @interface GTMLinearRGBShadingTest : GTMTestCase @end @implementation GTMLinearRGBShadingTest - (void)testShadingFrom { // Create a shading from red to blue, and check if 50% is purple NSColor *red = [NSColor redColor]; NSColor *blue = [NSColor blueColor]; NSColor *purple = [NSColor purpleColor]; GTMLinearRGBShading *theShading = [GTMLinearRGBShading shadingFromColor:red toColor:blue fromSpaceNamed:NSCalibratedRGBColorSpace]; STAssertNotNil(theShading,nil); STAssertEquals([theShading stopCount], (NSUInteger)2, nil); CGFloat *theColor = (CGFloat*)[theShading valueAtPosition: 0.5]; STAssertEqualsWithAccuracy(theColor[0], [purple redComponent], 0.001, nil); STAssertEqualsWithAccuracy(theColor[1], [purple greenComponent], 0.001, nil); STAssertEqualsWithAccuracy(theColor[2], [purple blueComponent], 0.001, nil); STAssertEqualsWithAccuracy(theColor[3], [purple alphaComponent], 0.001, nil); } - (void)testShadingWith { // Create a shading with kColorCount colors and make sure all the values are there. const NSUInteger kColorCount = 100; NSColor *theColors[kColorCount]; CGFloat thePositions[kColorCount]; const CGFloat kColorIncrement = 1.0 / kColorCount; for (NSUInteger i = 0; i < kColorCount; i++) { CGFloat newValue = kColorIncrement * i; thePositions[i] = newValue; theColors[i] = [NSColor colorWithCalibratedRed:newValue green:newValue blue:newValue alpha:newValue]; } GTMLinearRGBShading *theShading = [GTMLinearRGBShading shadingWithColors:theColors fromSpaceNamed:NSCalibratedRGBColorSpace atPositions:thePositions count:kColorCount]; for (NSUInteger i = 0; i < kColorCount; i++) { CGFloat newValue = kColorIncrement * i; CGFloat *theColor = (CGFloat*)[theShading valueAtPosition:newValue]; STAssertEqualsWithAccuracy(theColor[0], newValue, 0.001, nil); STAssertEqualsWithAccuracy(theColor[1], newValue, 0.001, nil); STAssertEqualsWithAccuracy(theColor[2], newValue, 0.001, nil); STAssertEqualsWithAccuracy(theColor[3], newValue, 0.001, nil); } } - (void)testShadeFunction { GTMLinearRGBShading *theShading = [GTMLinearRGBShading shadingWithColors:nil fromSpaceNamed:NSCalibratedRGBColorSpace atPositions:nil count:0]; CGFunctionRef theFunction = [theShading shadeFunction]; STAssertNotNULL(theFunction, nil); STAssertEquals(CFGetTypeID(theFunction), CGFunctionGetTypeID(), nil); } - (void)testColorSpace { GTMLinearRGBShading *theShading = [GTMLinearRGBShading shadingWithColors:nil fromSpaceNamed:NSCalibratedRGBColorSpace atPositions:nil count:0]; CGColorSpaceRef theColorSpace = [theShading colorSpace]; STAssertNotNULL(theColorSpace, nil); STAssertEquals(CFGetTypeID(theColorSpace), CGColorSpaceGetTypeID(), nil); } @end
08iteng-ipad
systemtests/google-toolbox-for-mac/AppKit/GTMLinearRGBShadingTest.m
Objective-C
bsd
3,992