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 |
|---|---|---|---|---|---|
//
// CPTestApp_iPadViewController.h
// CPTestApp-iPad
//
// Created by Brad Larson on 4/1/2010.
//
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface CPTestApp_iPadViewController : UIViewController <CPPlotDataSource, CPPieChartDataSource, CPBarPlotDelegate>
{
IBOutlet CPGraphHostingView *scatterPlotView, *barChartView, *pieChartView;
CPXYGraph *graph, *barChart, *pieChart;
NSMutableArray *dataForChart, *dataForPlot;
}
@property(readwrite, retain, nonatomic) NSMutableArray *dataForChart, *dataForPlot;
// Plot construction methods
-(void)constructScatterPlot;
-(void)constructBarChart;
-(void)constructPieChart;
@end
| 08iteng-ipad | examples/CPTestApp-iPad/Classes/CPTestApp_iPadViewController.h | Objective-C | bsd | 652 |
//
// CPTestApp_iPadViewController.m
// CPTestApp-iPad
//
// Created by Brad Larson on 4/1/2010.
//
#import "CPTestApp_iPadViewController.h"
@implementation CPTestApp_iPadViewController
@synthesize dataForChart, dataForPlot;
#pragma mark -
#pragma mark Initialization and teardown
- (void)viewDidLoad
{
[super viewDidLoad];
[self constructScatterPlot];
[self constructBarChart];
[self constructPieChart];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if (UIInterfaceOrientationIsLandscape(fromInterfaceOrientation))
{
// Move the plots into place for portrait
scatterPlotView.frame = CGRectMake(20.0f, 55.0f, 728.0f, 556.0f);
barChartView.frame = CGRectMake(20.0f, 644.0f, 340.0f, 340.0f);
pieChartView.frame = CGRectMake(408.0f, 644.0f, 340.0f, 340.0f);
}
else
{
// Move the plots into place for landscape
scatterPlotView.frame = CGRectMake(20.0f, 51.0f, 628.0f, 677.0f);
barChartView.frame = CGRectMake(684.0f, 51.0f, 320.0f, 320.0f);
pieChartView.frame = CGRectMake(684.0f, 408.0f, 320.0f, 320.0f);
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[dataForChart release];
[dataForPlot release];
[super dealloc];
}
#pragma mark -
#pragma mark Plot construction methods
- (void)constructScatterPlot
{
// Create graph from theme
graph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
scatterPlotView.hostedGraph = graph;
graph.paddingLeft = 10.0;
graph.paddingTop = 10.0;
graph.paddingRight = 10.0;
graph.paddingBottom = 10.0;
// Setup plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(2.0)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromString(@"0.5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 2;
NSArray *exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(2.99) length:CPDecimalFromFloat(0.02)],
nil];
x.labelExclusionRanges = exclusionRanges;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.99) length:CPDecimalFromFloat(0.02)],
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(3.99) length:CPDecimalFromFloat(0.02)],
nil];
y.labelExclusionRanges = exclusionRanges;
// Create a green plot area
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Green Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor greenColor];
lineStyle.dashPattern = [NSArray arrayWithObjects:[NSNumber numberWithFloat:5.0f], [NSNumber numberWithFloat:5.0f], nil];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
// Put an area gradient under the plot above
CPColor *areaColor = [CPColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.8];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0f;
CPFill *areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromString(@"1.75");
// Animate in the new plot, as an example
dataSourceLinePlot.opacity = 0.0f;
dataSourceLinePlot.cachePrecision = CPPlotCachePrecisionDecimal;
[graph addPlot:dataSourceLinePlot];
CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeInAnimation.duration = 1.0f;
fadeInAnimation.removedOnCompletion = NO;
fadeInAnimation.fillMode = kCAFillModeForwards;
fadeInAnimation.toValue = [NSNumber numberWithFloat:1.0];
[dataSourceLinePlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
// Create a blue plot area
CPScatterPlot *boundLinePlot = [[[CPScatterPlot alloc] init] autorelease];
boundLinePlot.identifier = @"Blue Plot";
lineStyle = [[boundLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.miterLimit = 1.0f;
lineStyle.lineWidth = 3.0f;
lineStyle.lineColor = [CPColor blueColor];
lineStyle = lineStyle;
boundLinePlot.dataSource = self;
boundLinePlot.cachePrecision = CPPlotCachePrecisionDouble;
boundLinePlot.interpolation = CPScatterPlotInterpolationHistogram;
[graph addPlot:boundLinePlot];
// Do a blue gradient
CPColor *areaColor1 = [CPColor colorWithComponentRed:0.3 green:0.3 blue:1.0 alpha:0.8];
CPGradient *areaGradient1 = [CPGradient gradientWithBeginningColor:areaColor1 endingColor:[CPColor clearColor]];
areaGradient1.angle = -90.0f;
areaGradientFill = [CPFill fillWithGradient:areaGradient1];
boundLinePlot.areaFill = areaGradientFill;
boundLinePlot.areaBaseValue = [[NSDecimalNumber zero] decimalValue];
// Add plot symbols
CPMutableLineStyle *symbolLineStyle = [CPMutableLineStyle lineStyle];
symbolLineStyle.lineColor = [CPColor blackColor];
CPPlotSymbol *plotSymbol = [CPPlotSymbol ellipsePlotSymbol];
plotSymbol.fill = [CPFill fillWithColor:[CPColor blueColor]];
plotSymbol.lineStyle = symbolLineStyle;
plotSymbol.size = CGSizeMake(10.0, 10.0);
boundLinePlot.plotSymbol = plotSymbol;
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for ( i = 0; i < 60; i++ ) {
id x = [NSNumber numberWithFloat:1+i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, @"x", y, @"y", nil]];
}
self.dataForPlot = contentArray;
}
- (void)constructBarChart
{
// Create barChart from theme
barChart = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[barChart applyTheme:theme];
barChartView.hostedGraph = barChart;
barChart.plotAreaFrame.masksToBorder = NO;
barChart.paddingLeft = 70.0;
barChart.paddingTop = 20.0;
barChart.paddingRight = 20.0;
barChart.paddingBottom = 80.0;
// Add plot space for horizontal bar charts
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)barChart.defaultPlotSpace;
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(300.0f)];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0f) length:CPDecimalFromFloat(16.0f)];
CPXYAxisSet *axisSet = (CPXYAxisSet *)barChart.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.axisLineStyle = nil;
x.majorTickLineStyle = nil;
x.minorTickLineStyle = nil;
x.majorIntervalLength = CPDecimalFromString(@"5");
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
x.title = @"X Axis";
x.titleLocation = CPDecimalFromFloat(7.5f);
x.titleOffset = 55.0f;
// Define some custom labels for the data elements
x.labelRotation = M_PI/4;
x.labelingPolicy = CPAxisLabelingPolicyNone;
NSArray *customTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:1], [NSDecimalNumber numberWithInt:5], [NSDecimalNumber numberWithInt:10], [NSDecimalNumber numberWithInt:15], nil];
NSArray *xAxisLabels = [NSArray arrayWithObjects:@"Label A", @"Label B", @"Label C", @"Label D", @"Label E", nil];
NSUInteger labelLocation = 0;
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
for (NSNumber *tickLocation in customTickLocations) {
CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText: [xAxisLabels objectAtIndex:labelLocation++] textStyle:x.labelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;
newLabel.rotation = M_PI/4;
[customLabels addObject:newLabel];
[newLabel release];
}
x.axisLabels = [NSSet setWithArray:customLabels];
CPXYAxis *y = axisSet.yAxis;
y.axisLineStyle = nil;
y.majorTickLineStyle = nil;
y.minorTickLineStyle = nil;
y.majorIntervalLength = CPDecimalFromString(@"50");
y.orthogonalCoordinateDecimal = CPDecimalFromString(@"0");
y.title = @"Y Axis";
y.titleOffset = 45.0f;
y.titleLocation = CPDecimalFromFloat(150.0f);
// First bar plot
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor darkGrayColor] horizontalBars:NO];
barPlot.baseValue = CPDecimalFromString(@"0");
barPlot.dataSource = self;
barPlot.barOffset = CPDecimalFromFloat(-0.25f);
barPlot.identifier = @"Bar Plot 1";
[barChart addPlot:barPlot toPlotSpace:plotSpace];
// Second bar plot
barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor blueColor] horizontalBars:NO];
barPlot.dataSource = self;
barPlot.baseValue = CPDecimalFromString(@"0");
barPlot.barOffset = CPDecimalFromFloat(0.25f);
barPlot.barCornerRadius = 2.0f;
barPlot.identifier = @"Bar Plot 2";
barPlot.delegate = self;
[barChart addPlot:barPlot toPlotSpace:plotSpace];
}
- (void)constructPieChart
{
// Create pieChart from theme
pieChart = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[pieChart applyTheme:theme];
pieChartView.hostedGraph = pieChart;
pieChart.plotAreaFrame.masksToBorder = NO;
pieChart.paddingLeft = 20.0;
pieChart.paddingTop = 20.0;
pieChart.paddingRight = 20.0;
pieChart.paddingBottom = 20.0;
pieChart.axisSet = nil;
// Prepare a radial overlay gradient for shading/gloss
CPGradient *overlayGradient = [[[CPGradient alloc] init] autorelease];
overlayGradient.gradientType = CPGradientTypeRadial;
overlayGradient = [overlayGradient addColorStop:[[CPColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.0];
overlayGradient = [overlayGradient addColorStop:[[CPColor blackColor] colorWithAlphaComponent:0.3] atPosition:0.9];
overlayGradient = [overlayGradient addColorStop:[[CPColor blackColor] colorWithAlphaComponent:0.7] atPosition:1.0];
// Add pie chart
CPPieChart *piePlot = [[CPPieChart alloc] init];
piePlot.dataSource = self;
piePlot.pieRadius = 130.0;
piePlot.identifier = @"Pie Chart 1";
piePlot.startAngle = M_PI_4;
piePlot.sliceDirection = CPPieDirectionCounterClockwise;
piePlot.borderLineStyle = [CPLineStyle lineStyle];
piePlot.sliceLabelOffset = 5.0;
piePlot.overlayFill = [CPFill fillWithGradient:overlayGradient];
[pieChart addPlot:piePlot];
[piePlot release];
// Add some initial data
NSMutableArray *contentArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithDouble:20.0], [NSNumber numberWithDouble:30.0], [NSNumber numberWithDouble:NAN], [NSNumber numberWithDouble:60.0], nil];
self.dataForChart = contentArray;
}
#pragma mark -
#pragma mark CPBarPlot delegate method
-(void)barPlot:(CPBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
NSLog(@"barWasSelectedAtRecordIndex %d", index);
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
if ([plot isKindOfClass:[CPPieChart class]])
return [self.dataForChart count];
else if ([plot isKindOfClass:[CPBarPlot class]])
return 16;
else
return [dataForPlot count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = nil;
if ( [plot isKindOfClass:[CPPieChart class]] ) {
if ( index >= [self.dataForChart count] ) return nil;
if ( fieldEnum == CPPieChartFieldSliceWidth ) {
num = [self.dataForChart objectAtIndex:index];
}
else {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
}
}
else if ( [plot isKindOfClass:[CPBarPlot class]] ) {
switch ( fieldEnum ) {
case CPBarPlotFieldBarLocation:
if ( index == 4 ) {
num = [NSDecimalNumber notANumber];
}
else {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
}
break;
case CPBarPlotFieldBarTip:
if ( index == 8 ) {
num = [NSDecimalNumber notANumber];
}
else {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:(index+1)*(index+1)];
if ( [plot.identifier isEqual:@"Bar Plot 2"] ) {
num = [num decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:@"10"]];
}
}
break;
}
}
else {
if ( index % 8 ) {
num = [[dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPScatterPlotFieldX ? @"x" : @"y")];
// Green plot gets shifted above the blue
if ( [(NSString *)plot.identifier isEqualToString:@"Green Plot"] ) {
if ( fieldEnum == CPScatterPlotFieldY ) {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithDouble:[num doubleValue] + 1.0];
}
}
}
else {
num = [NSDecimalNumber notANumber];
}
}
return num;
}
-(CPFill *)barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSNumber *)index
{
return nil;
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
static CPMutableTextStyle *whiteText = nil;
if ( !whiteText ) {
whiteText = [[CPMutableTextStyle alloc] init];
whiteText.color = [CPColor whiteColor];
}
CPTextLayer *newLayer = nil;
if ( [plot isKindOfClass:[CPPieChart class]] ) {
switch ( index ) {
case 0:
newLayer = (id)[NSNull null];
break;
default:
newLayer = [[[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%lu", index] style:whiteText] autorelease];
break;
}
}
else if ( [plot isKindOfClass:[CPScatterPlot class]] ) {
newLayer = [[[CPTextLayer alloc] initWithText:[NSString stringWithFormat:@"%lu", index] style:whiteText] autorelease];
}
return newLayer;
}
@end
| 08iteng-ipad | examples/CPTestApp-iPad/Classes/CPTestApp_iPadViewController.m | Objective-C | bsd | 15,086 |
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
} | 08iteng-ipad | examples/AAPLot/main.m | Objective-C | bsd | 216 |
#import "APYahooDataPuller.h"
#import "APFinancialData.h"
NSTimeInterval timeIntervalForNumberOfWeeks(float numberOfWeeks)
{
NSTimeInterval seconds = fabs(60.0 * 60.0 * 24.0 * 7.0 * numberOfWeeks);
return seconds;
}
@interface APYahooDataPuller ()
@property (nonatomic, copy) NSString *csvString;
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, assign) BOOL loadingData;
@property (nonatomic, readwrite, retain) NSDecimalNumber *overallHigh;
@property (nonatomic, readwrite, retain) NSDecimalNumber *overallLow;
@property (nonatomic, readwrite, retain) NSDecimalNumber *overallVolumeHigh;
@property (nonatomic, readwrite, retain) NSDecimalNumber *overallVolumeLow;
@property (nonatomic, readwrite, retain) NSArray *financialData;
-(void)fetch;
-(NSString *)URL;
-(void)notifyPulledData;
-(void)parseCSVAndPopulate;
@end
@implementation APYahooDataPuller
@synthesize symbol;
@synthesize startDate;
@synthesize endDate;
@synthesize targetStartDate;
@synthesize targetEndDate;
@synthesize targetSymbol;
@synthesize overallLow;
@synthesize overallHigh;
@synthesize overallVolumeHigh;
@synthesize overallVolumeLow;
@synthesize csvString;
@synthesize financialData;
@synthesize receivedData;
@synthesize connection;
@synthesize loadingData;
-(id)delegate
{
return delegate;
}
-(void)setDelegate:(id)aDelegate
{
if(delegate != aDelegate)
{
delegate = aDelegate;
if([self.financialData count] > 0)
[self notifyPulledData]; //loads cached data onto UI
}
}
- (NSDictionary *)plistRep
{
NSMutableDictionary *rep = [NSMutableDictionary dictionaryWithCapacity:7];
[rep setObject:[self symbol] forKey:@"symbol"];
[rep setObject:[self startDate] forKey:@"startDate"];
[rep setObject:[self endDate] forKey:@"endDate"];
[rep setObject:[self overallHigh] forKey:@"overallHigh"];
[rep setObject:[self overallLow] forKey:@"overallLow"];
[rep setObject:[self overallVolumeHigh] forKey:@"overallVolumeHigh"];
[rep setObject:[self overallVolumeLow] forKey:@"overallVolumeLow"];
[rep setObject:[self financialData] forKey:@"financalData"];
return [NSDictionary dictionaryWithDictionary:rep];
}
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag;
{
NSLog(@"writeToFile:%@", path);
BOOL success = [[self plistRep] writeToFile:path atomically:flag];
return success;
}
-(id)initWithDictionary:(NSDictionary *)aDict targetSymbol:(NSString *)aSymbol targetStartDate:(NSDate *)aStartDate targetEndDate:(NSDate *)anEndDate
{
self = [super init];
if (self != nil) {
self.symbol = [aDict objectForKey:@"symbol"];
self.startDate = [aDict objectForKey:@"startDate"];
self.overallLow = [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"overallLow"] decimalValue]];
self.overallHigh = [NSDecimalNumber decimalNumberWithDecimal:[[aDict objectForKey:@"overallHigh"] decimalValue]];
self.endDate = [aDict objectForKey:@"endDate"];
self.financialData = [aDict objectForKey:@"financalData"];
self.targetSymbol = aSymbol;
self.targetStartDate = aStartDate;
self.targetEndDate = anEndDate;
self.csvString = @"";
[self performSelector:@selector(fetch) withObject:nil afterDelay:0.01];
}
return self;
}
-(NSString *)pathForSymbol:(NSString *)aSymbol
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *docPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", aSymbol]];
return docPath;
}
-(NSString *)faultTolerantPathForSymbol:(NSString *)aSymbol
{
NSString *docPath = [self pathForSymbol:aSymbol];;
if (![[NSFileManager defaultManager] fileExistsAtPath:docPath]) {
//if there isn't one in the user's documents directory, see if we ship with this data
docPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", aSymbol]];
}
return docPath;
}
//Always returns *something*
-(NSDictionary *)dictionaryForSymbol:(NSString *)aSymbol
{
NSString *path = [self faultTolerantPathForSymbol:aSymbol];
NSMutableDictionary *localPlistDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
return localPlistDict;
}
-(id)initWithTargetSymbol:(NSString *)aSymbol targetStartDate:(NSDate *)aStartDate targetEndDate:(NSDate *)anEndDate
{
NSDictionary *cachedDictionary = [self dictionaryForSymbol:aSymbol];
if (nil != cachedDictionary)
{
return [self initWithDictionary:cachedDictionary targetSymbol:aSymbol targetStartDate:aStartDate targetEndDate:anEndDate];
}
NSMutableDictionary *rep = [NSMutableDictionary dictionaryWithCapacity:7];
[rep setObject:aSymbol forKey:@"symbol"];
[rep setObject:aStartDate forKey:@"startDate"];
[rep setObject:anEndDate forKey:@"endDate"];
[rep setObject:[NSDecimalNumber notANumber] forKey:@"overallHigh"];
[rep setObject:[NSDecimalNumber notANumber] forKey:@"overallLow"];
[rep setObject:[NSArray array] forKey:@"financalData"];
return [self initWithDictionary:rep targetSymbol:aSymbol targetStartDate:aStartDate targetEndDate:anEndDate];
}
-(id)init
{
NSTimeInterval secondsAgo = -timeIntervalForNumberOfWeeks(14.0f); //12 weeks ago
NSDate *start = [NSDate dateWithTimeIntervalSinceNow:secondsAgo];
NSDate *end = [NSDate date];
return [self initWithTargetSymbol:@"GOOG" targetStartDate:start targetEndDate:end];
}
-(void)dealloc
{
[symbol release];
[startDate release];
[endDate release];
[csvString release];
[financialData release];
symbol = nil;
startDate = nil;
endDate = nil;
csvString = nil;
financialData = nil;
delegate = nil;
[super dealloc];
}
// http://www.goldb.org/ystockquote.html
-(NSString *)URL;
{
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *compsStart = [gregorian components:unitFlags fromDate:targetStartDate];
NSDateComponents *compsEnd = [gregorian components:unitFlags fromDate:targetEndDate];
[gregorian release];
NSString *url = [NSString stringWithFormat:@"http://ichart.yahoo.com/table.csv?s=%@&", [self targetSymbol]];
url = [url stringByAppendingFormat:@"a=%d&", [compsStart month]-1];
url = [url stringByAppendingFormat:@"b=%d&", [compsStart day]];
url = [url stringByAppendingFormat:@"c=%d&", [compsStart year]];
url = [url stringByAppendingFormat:@"d=%d&", [compsEnd month]-1];
url = [url stringByAppendingFormat:@"e=%d&", [compsEnd day]];
url = [url stringByAppendingFormat:@"f=%d&", [compsEnd year]];
url = [url stringByAppendingString:@"g=d&"];
url = [url stringByAppendingString:@"ignore=.csv"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return url;
}
-(void)notifyPulledData
{
if (delegate && [delegate respondsToSelector:@selector(dataPullerDidFinishFetch:)]) {
[delegate performSelector:@selector(dataPullerDidFinishFetch:) withObject:self];
}
}
#pragma mark -
#pragma mark Downloading of data
-(BOOL)shouldDownload
{
BOOL shouldDownload = YES;
return shouldDownload;
}
-(void)fetch
{
if ( self.loadingData ) return;
if ([self shouldDownload])
{
self.loadingData = YES;
NSString *urlString = [self URL];
NSLog(@"URL = %@", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
self.connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
if (self.connection) {
self.receivedData = [NSMutableData data];
}
else {
//TODO: Inform the user that the download could not be started
self.loadingData = NO;
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
[self.receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// this method is called when the server has determined that it
// has enough information to create the NSURLResponse
// it can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
[self.receivedData setLength:0];
}
-(void)cancelDownload
{
if (self.loadingData) {
[self.connection cancel];
self.loadingData = NO;
self.receivedData = nil;
self.connection = nil;
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
self.loadingData = NO;
self.receivedData = nil;
self.connection = nil;
NSLog(@"err = %@", [error localizedDescription]);
//TODO:report err
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.loadingData = NO;
self.connection = nil;
NSString *csv = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
self.csvString = csv;
[csv release];
self.receivedData = nil;
[self parseCSVAndPopulate];
//see if we need to write to file
NSDictionary *dictionaryForSymbol = [self dictionaryForSymbol:self.symbol];
if (![[self symbol] isEqualToString:[dictionaryForSymbol objectForKey:@"symbol"]] ||
[[self startDate] compare:[dictionaryForSymbol objectForKey:@"startDate"]] != NSOrderedSame ||
[[self endDate] compare:[dictionaryForSymbol objectForKey:@"endDate"]] != NSOrderedSame)
{
[self writeToFile:[self pathForSymbol:self.symbol] atomically:YES];
}
else {
NSLog(@"Not writing to file -- No Need, its data is fresh.");
}
}
-(void)parseCSVAndPopulate;
{
NSArray *csvLines = [self.csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *newFinancials = [NSMutableArray arrayWithCapacity:[csvLines count]];
NSDictionary *currentFinancial = nil;
NSString *line = nil;
self.overallHigh = [NSDecimalNumber notANumber];
self.overallLow = [NSDecimalNumber notANumber];
self.overallVolumeHigh = [NSDecimalNumber notANumber];
self.overallVolumeLow = [NSDecimalNumber notANumber];
for (NSUInteger i=1; i<[csvLines count]-1; i++) {
line = (NSString *)[csvLines objectAtIndex:i];
currentFinancial = [NSDictionary dictionaryWithCSVLine:line];
[newFinancials addObject:currentFinancial];
NSDecimalNumber *high = [currentFinancial objectForKey:@"high"];
NSDecimalNumber *low = [currentFinancial objectForKey:@"low"];
NSDecimalNumber *volume = [currentFinancial objectForKey:@"volume"];;
if ( [self.overallHigh isEqual:[NSDecimalNumber notANumber]] ) {
self.overallHigh = high;
}
if ( [self.overallLow isEqual:[NSDecimalNumber notANumber]] ) {
self.overallLow = low;
}
if ( [low compare:self.overallLow] == NSOrderedAscending ) {
self.overallLow = low;
}
if ( [high compare:self.overallHigh] == NSOrderedDescending ) {
self.overallHigh = high;
}
if ( [self.overallVolumeHigh isEqual:[NSDecimalNumber notANumber]] ) {
self.overallVolumeHigh = volume;
}
if ( [self.overallVolumeLow isEqual:[NSDecimalNumber notANumber]] ) {
self.overallVolumeLow = volume;
}
if ( [volume compare:self.overallVolumeLow] == NSOrderedAscending ) {
self.overallVolumeLow = volume;
}
if ( [volume compare:self.overallVolumeHigh] == NSOrderedDescending ) {
self.overallVolumeHigh = volume;
}
}
self.startDate = self.targetStartDate;
self.endDate = self.targetEndDate;
self.symbol = self.targetSymbol;
[self setFinancialData:[NSArray arrayWithArray:newFinancials]];
[self notifyPulledData];
}
@end
| 08iteng-ipad | examples/AAPLot/APYahooDataPuller.m | Objective-C | bsd | 12,697 |
#import <Foundation/Foundation.h>
@interface NSDictionary (APFinancialData)
+(id)dictionaryWithCSVLine:(NSString*)csvLine;
@end
| 08iteng-ipad | examples/AAPLot/APFinancialData.h | Objective-C | bsd | 132 |
#import "NSDateFormatterExtensions.h"
@implementation NSDateFormatter (APExtensions)
+(NSDateFormatter *)csvDateFormatter
{
static NSDateFormatter *df = nil;
if (!df) {
df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
}
return df;
}
@end
| 08iteng-ipad | examples/AAPLot/NSDateFormatterExtensions.m | Objective-C | bsd | 297 |
#import <Foundation/Foundation.h>
@class APYahooDataPuller;
@protocol APYahooDataPullerDelegate
@optional
-(void)dataPullerDidFinishFetch:(APYahooDataPuller *)dp;
@end
@interface APYahooDataPuller : NSObject {
NSString *symbol;
NSDate *startDate;
NSDate *endDate;
NSDate *targetStartDate;
NSDate *targetEndDate;
NSString *targetSymbol;
id delegate;
NSDecimalNumber *overallHigh;
NSDecimalNumber *overallLow;
NSDecimalNumber *overallVolumeHigh;
NSDecimalNumber *overallVolumeLow;
@private
NSString *csvString;
NSArray *financialData; // consists of dictionaries
BOOL loadingData;
NSMutableData *receivedData;
NSURLConnection *connection;
}
@property (nonatomic, assign) id delegate;
@property (nonatomic, copy) NSString *symbol;
@property (nonatomic, retain) NSDate *startDate;
@property (nonatomic, retain) NSDate *endDate;
@property (nonatomic, copy) NSString *targetSymbol;
@property (nonatomic, retain) NSDate *targetStartDate;
@property (nonatomic, retain) NSDate *targetEndDate;
@property (nonatomic, readonly, retain) NSArray *financialData;
@property (nonatomic, readonly, retain) NSDecimalNumber *overallHigh;
@property (nonatomic, readonly, retain) NSDecimalNumber *overallLow;
@property (nonatomic, readonly, retain) NSDecimalNumber *overallVolumeHigh;
@property (nonatomic, readonly, retain) NSDecimalNumber *overallVolumeLow;
-(id)initWithTargetSymbol:(NSString *)aSymbol targetStartDate:(NSDate *)aStartDate targetEndDate:(NSDate *)anEndDate;
@end
| 08iteng-ipad | examples/AAPLot/APYahooDataPuller.h | Objective-C | bsd | 1,548 |
#import <Foundation/Foundation.h>
@interface NSDateFormatter (APExtensions)
+(NSDateFormatter *)csvDateFormatter;
@end
| 08iteng-ipad | examples/AAPLot/NSDateFormatterExtensions.h | Objective-C | bsd | 124 |
//
// RootViewController.h
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import <UIKit/UIKit.h>
@class MainViewController;
@class FlipsideViewController;
@interface RootViewController : UIViewController {
UIButton *infoButton;
MainViewController *mainViewController;
FlipsideViewController *flipsideViewController;
UINavigationBar *flipsideNavigationBar;
}
@property (nonatomic, retain) IBOutlet UIButton *infoButton;
@property (nonatomic, retain) MainViewController *mainViewController;
@property (nonatomic, retain) UINavigationBar *flipsideNavigationBar;
@property (nonatomic, retain) FlipsideViewController *flipsideViewController;
- (IBAction)toggleView;
@end
| 08iteng-ipad | examples/AAPLot/Classes/RootViewController.h | Objective-C | bsd | 763 |
//
// RootViewController.m
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import "RootViewController.h"
#import "MainViewController.h"
#import "FlipsideViewController.h"
@implementation RootViewController
@synthesize infoButton;
@synthesize flipsideNavigationBar;
@synthesize mainViewController;
@synthesize flipsideViewController;
- (void)viewDidLoad {
[super viewDidLoad];
MainViewController *viewController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
self.mainViewController = viewController;
[viewController release];
[self.view insertSubview:mainViewController.view belowSubview:infoButton];
}
- (void)loadFlipsideViewController {
FlipsideViewController *viewController = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
self.flipsideViewController = viewController;
[viewController release];
// Set up the navigation bar
UINavigationBar *aNavigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
aNavigationBar.barStyle = UIBarStyleBlackOpaque;
self.flipsideNavigationBar = aNavigationBar;
[aNavigationBar release];
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(toggleView)];
UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"AAPLot"];
navigationItem.rightBarButtonItem = buttonItem;
[flipsideNavigationBar pushNavigationItem:navigationItem animated:NO];
[navigationItem release];
[buttonItem release];
}
- (IBAction)toggleView {
/*
This method is called when the info or Done button is pressed.
It flips the displayed view from the main view to the flipside view and vice-versa.
*/
if (flipsideViewController == nil) {
[self loadFlipsideViewController];
}
UIView *mainView = mainViewController.view;
UIView *flipsideView = flipsideViewController.view;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:([mainView superview] ? UIViewAnimationTransitionFlipFromRight : UIViewAnimationTransitionFlipFromLeft) forView:self.view cache:YES];
if ([mainView superview] != nil) {
[flipsideViewController viewWillAppear:YES];
[mainViewController viewWillDisappear:YES];
[mainView removeFromSuperview];
[infoButton removeFromSuperview];
[self.view addSubview:flipsideView];
[self.view insertSubview:flipsideNavigationBar aboveSubview:flipsideView];
[mainViewController viewDidDisappear:YES];
[flipsideViewController viewDidAppear:YES];
} else {
[mainViewController viewWillAppear:YES];
[flipsideViewController viewWillDisappear:YES];
[flipsideView removeFromSuperview];
[flipsideNavigationBar removeFromSuperview];
[self.view addSubview:mainView];
[self.view insertSubview:infoButton aboveSubview:mainViewController.view];
[flipsideViewController viewDidDisappear:YES];
[mainViewController viewDidAppear:YES];
}
[UIView commitAnimations];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[infoButton release];
[flipsideNavigationBar release];
[mainViewController release];
[flipsideViewController release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/RootViewController.m | Objective-C | bsd | 3,982 |
#import "MainViewController.h"
#import "APYahooDataPuller.h"
#import "APFinancialData.h"
@interface MainViewController()
@property(nonatomic, retain) CPXYGraph *graph;
@property(nonatomic, retain) APYahooDataPuller *datapuller;
@end
@implementation MainViewController
@synthesize graph;
@synthesize datapuller;
@synthesize graphHost;
-(void)dealloc
{
[datapuller release];
[graph release];
[graphHost release];
datapuller = nil;
graph = nil;
graphHost = nil;
[super dealloc];
}
-(void)setView:(UIView *)aView;
{
[super setView:aView];
if ( nil == aView ) {
self.graph = nil;
self.graphHost = nil;
}
}
-(void)viewDidLoad
{
graph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPStocksTheme];
[graph applyTheme:theme];
graph.frame = self.view.bounds;
graph.paddingRight = 50.0f;
graph.paddingLeft = 50.0f;
graph.plotAreaFrame.masksToBorder = NO;
graph.plotAreaFrame.cornerRadius = 0.0f;
CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPColor whiteColor];
borderLineStyle.lineWidth = 2.0f;
graph.plotAreaFrame.borderLineStyle = borderLineStyle;
self.graphHost.hostedGraph = graph;
// Axes
CPXYAxisSet *xyAxisSet = (id)graph.axisSet;
CPXYAxis *xAxis = xyAxisSet.xAxis;
CPMutableLineStyle *lineStyle = [xAxis.axisLineStyle mutableCopy];
lineStyle.lineCap = kCGLineCapButt;
xAxis.axisLineStyle = lineStyle;
[lineStyle release];
xAxis.labelingPolicy = CPAxisLabelingPolicyNone;
CPXYAxis *yAxis = xyAxisSet.yAxis;
yAxis.axisLineStyle = nil;
// Line plot with gradient fill
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
dataSourceLinePlot.dataLineStyle = nil;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
CPColor *areaColor = [CPColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.6];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0f;
CPFill *areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPDecimalFromDouble(200.0);
areaColor = [CPColor colorWithComponentRed:0.0 green:1.0 blue:0.0 alpha:0.6];
areaGradient = [CPGradient gradientWithBeginningColor:[CPColor clearColor] endingColor:areaColor];
areaGradient.angle = -90.0f;
areaGradientFill = [CPFill fillWithGradient:areaGradient];
dataSourceLinePlot.areaFill2 = areaGradientFill;
dataSourceLinePlot.areaBaseValue2 = CPDecimalFromDouble(400.0);
// OHLC plot
CPMutableLineStyle *whiteLineStyle = [CPMutableLineStyle lineStyle];
whiteLineStyle.lineColor = [CPColor whiteColor];
whiteLineStyle.lineWidth = 1.0f;
CPTradingRangePlot *ohlcPlot = [[[CPTradingRangePlot alloc] initWithFrame:graph.bounds] autorelease];
ohlcPlot.identifier = @"OHLC";
ohlcPlot.lineStyle = whiteLineStyle;
CPMutableTextStyle *whiteTextStyle = [CPMutableTextStyle textStyle];
whiteTextStyle.color = [CPColor whiteColor];
whiteTextStyle.fontSize = 8.0;
ohlcPlot.labelTextStyle = whiteTextStyle;
ohlcPlot.labelOffset = 5.0;
ohlcPlot.stickLength = 2.0f;
ohlcPlot.dataSource = self;
ohlcPlot.plotStyle = CPTradingRangePlotStyleOHLC;
[graph addPlot:ohlcPlot];
// Add plot space for horizontal bar charts
CPXYPlotSpace *volumePlotSpace = [[CPXYPlotSpace alloc] init];
volumePlotSpace.identifier = @"Volume Plot Space";
[graph addPlotSpace:volumePlotSpace];
[volumePlotSpace release];
CPBarPlot *volumePlot = [CPBarPlot tubularBarPlotWithColor:[CPColor blackColor] horizontalBars:NO];
volumePlot.dataSource = self;
lineStyle = [volumePlot.lineStyle mutableCopy];
lineStyle.lineColor = [CPColor whiteColor];
volumePlot.lineStyle = lineStyle;
[lineStyle release];
volumePlot.fill = nil;
volumePlot.barWidth = CPDecimalFromFloat(1.0f);
volumePlot.identifier = @"Volume Plot";
[graph addPlot:volumePlot toPlotSpace:volumePlotSpace];
// Data puller
NSDate *start = [NSDate dateWithTimeIntervalSinceNow:-60.0 * 60.0 * 24.0 * 7.0 * 12.0]; // 12 weeks ago
NSDate *end = [NSDate date];
APYahooDataPuller *dp = [[APYahooDataPuller alloc] initWithTargetSymbol:@"AAPL" targetStartDate:start targetEndDate:end];
[self setDatapuller:dp];
[dp setDelegate:self];
[dp release];
[super viewDidLoad];
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
}
return self;
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot {
return self.datapuller.financialData.count;;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSDecimalNumber *num = [NSDecimalNumber zero];
if ( [plot.identifier isEqual:@"Data Source Plot"] ) {
if (fieldEnum == CPScatterPlotFieldX) {
num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
}
else if (fieldEnum == CPScatterPlotFieldY) {
NSArray *financialData = self.datapuller.financialData;
NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count] - index - 1];
num = [fData objectForKey:@"close"];
NSAssert(nil != num, @"grrr");
}
}
else if ( [plot.identifier isEqual:@"Volume Plot"] ) {
if (fieldEnum == CPBarPlotFieldBarLocation) {
num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
}
else if (fieldEnum == CPBarPlotFieldBarTip ) {
NSArray *financialData = self.datapuller.financialData;
NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count] - index - 1];
num = [fData objectForKey:@"volume"];
NSAssert(nil != num, @"grrr");
}
}
else {
NSArray *financialData = self.datapuller.financialData;
NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count] - index - 1];
switch ( fieldEnum ) {
case CPTradingRangePlotFieldX:
num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
break;
case CPTradingRangePlotFieldClose:
num = [fData objectForKey:@"close"];
break;
case CPTradingRangePlotFieldHigh:
num = [fData objectForKey:@"high"];
break;
case CPTradingRangePlotFieldLow:
num = [fData objectForKey:@"low"];
break;
case CPTradingRangePlotFieldOpen:
num = [fData objectForKey:@"open"];
break;
}
}
return num;
}
-(CPLayer *)dataLabelForPlot:(CPPlot *)plot recordIndex:(NSUInteger)index
{
if ( ![(NSString *)plot.identifier isEqualToString:@"OHLC"] )
return (id)[NSNull null]; // Don't show any label
else if ( index % 5 ) {
return (id)[NSNull null];
}
else {
return nil; // Use default label style
}
}
-(void)dataPullerDidFinishFetch:(APYahooDataPuller *)dp;
{
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)self.graph.defaultPlotSpace;
CPXYPlotSpace *volumePlotSpace = (CPXYPlotSpace *)[self.graph plotSpaceWithIdentifier:@"Volume Plot Space"];
NSDecimalNumber *high = [datapuller overallHigh];
NSDecimalNumber *low = [datapuller overallLow];
NSDecimalNumber *length = [high decimalNumberBySubtracting:low];
NSLog(@"high = %@, low = %@, length = %@", high, low, length);
NSDecimalNumber *pricePlotSpaceDisplacementPercent = [NSDecimalNumber decimalNumberWithMantissa:33
exponent:-2
isNegative:NO];
NSDecimalNumber *lengthDisplacementValue = [length decimalNumberByMultiplyingBy:pricePlotSpaceDisplacementPercent];
NSDecimalNumber *lowDisplayLocation = [low decimalNumberBySubtracting:lengthDisplacementValue];
NSDecimalNumber *lengthDisplayLocation = [length decimalNumberByAdding:lengthDisplacementValue];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0f) length:CPDecimalFromInteger([datapuller.financialData count])];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:[lowDisplayLocation decimalValue] length:[lengthDisplayLocation decimalValue]];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
NSDecimalNumber *overallVolumeHigh = [datapuller overallVolumeHigh];
NSDecimalNumber *overallVolumeLow = [datapuller overallVolumeLow];
NSDecimalNumber *volumeLength = [overallVolumeHigh decimalNumberBySubtracting:overallVolumeLow];
// make the length aka height for y 3 times more so that we get a 1/3 area covered by volume
NSDecimalNumber *volumePlotSpaceDisplacementPercent = [NSDecimalNumber decimalNumberWithMantissa:3
exponent:0
isNegative:NO];
NSDecimalNumber *volumeLengthDisplacementValue = [volumeLength decimalNumberByMultiplyingBy:volumePlotSpaceDisplacementPercent];
NSDecimalNumber *volumeLowDisplayLocation = overallVolumeLow;
NSDecimalNumber *volumeLengthDisplayLocation = [volumeLength decimalNumberByAdding:volumeLengthDisplacementValue];
volumePlotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromInteger([datapuller.financialData count])];
volumePlotSpace.yRange = [CPPlotRange plotRangeWithLocation:[volumeLowDisplayLocation decimalValue]length:[volumeLengthDisplayLocation decimalValue]];
axisSet.xAxis.orthogonalCoordinateDecimal = [low decimalValue];
axisSet.yAxis.majorIntervalLength = CPDecimalFromString(@"50.0");
axisSet.yAxis.minorTicksPerInterval = 4;
axisSet.yAxis.orthogonalCoordinateDecimal = CPDecimalFromString(@"1.0");
NSArray *exclusionRanges = [NSArray arrayWithObjects:
[CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0) length:[low decimalValue]],
nil];
axisSet.yAxis.labelExclusionRanges = exclusionRanges;
[graph reloadData];
}
-(APYahooDataPuller *)datapuller
{
return datapuller;
}
-(void)setDatapuller:(APYahooDataPuller *)aDatapuller
{
if (datapuller != aDatapuller) {
[aDatapuller retain];
[datapuller release];
datapuller = aDatapuller;
}
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/MainViewController.m | Objective-C | bsd | 10,766 |
//
// FlipsideViewController.h
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FlipsideViewController : UIViewController {
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/FlipsideViewController.h | Objective-C | bsd | 241 |
//
// AAPLotAppDelegate.h
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import <UIKit/UIKit.h>
@class RootViewController;
@interface AAPLotAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
RootViewController *rootViewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
@end
| 08iteng-ipad | examples/AAPLot/Classes/AAPLotAppDelegate.h | Objective-C | bsd | 478 |
#import <UIKit/UIKit.h>
#import "APYahooDataPuller.h"
#import "CorePlot-CocoaTouch.h"
@class CPGraphHostingView;
@class APYahooDataPuller;
@class CPXYGraph;
@interface MainViewController : UIViewController <APYahooDataPullerDelegate, CPPlotDataSource> {
CPGraphHostingView *graphHost;
@private
APYahooDataPuller *datapuller;
CPXYGraph *graph;
}
@property (nonatomic, retain) IBOutlet CPGraphHostingView *graphHost;
@end | 08iteng-ipad | examples/AAPLot/Classes/MainViewController.h | Objective-C | bsd | 442 |
//
// FlipsideView.h
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FlipsideView : UIView {
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/FlipsideView.h | Objective-C | bsd | 211 |
//
// AAPLotAppDelegate.m
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import "AAPLotAppDelegate.h"
#import "RootViewController.h"
@implementation AAPLotAppDelegate
@synthesize window;
@synthesize rootViewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:[rootViewController view]];
[window makeKeyAndVisible];
}
- (void)dealloc {
[rootViewController release];
[window release];
[super dealloc];
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/AAPLotAppDelegate.m | Objective-C | bsd | 563 |
//
// FlipsideViewController.m
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import "FlipsideViewController.h"
@implementation FlipsideViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[super dealloc];
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/FlipsideViewController.m | Objective-C | bsd | 896 |
//
// FlipsideView.m
// AAPLot
//
// Created by Jonathan Saggau on 6/9/09.
// Copyright Sounds Broken inc. 2009. All rights reserved.
//
#import "FlipsideView.h"
@implementation FlipsideView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
}
- (void)dealloc {
[super dealloc];
}
@end
| 08iteng-ipad | examples/AAPLot/Classes/FlipsideView.m | Objective-C | bsd | 443 |
#import "APFinancialData.h"
#import "NSDateFormatterExtensions.h"
@implementation NSDictionary (APFinancialData)
+(id)dictionaryWithCSVLine:(NSString*)csvLine;
{
NSArray *csvChunks = [csvLine componentsSeparatedByString:@","];
NSMutableDictionary *csvDict = [NSMutableDictionary dictionaryWithCapacity:7];
// Date,Open,High,Low,Close,Volume,Adj Close
// 2009-06-08,143.82,144.23,139.43,143.85,33255400,143.85
NSDate *theDate = [[NSDateFormatter csvDateFormatter] dateFromString:(NSString *)[csvChunks objectAtIndex:0]];
[csvDict setObject:theDate forKey:@"date"];
NSDecimalNumber *theOpen = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:1]];
[csvDict setObject:theOpen forKey:@"open"];
NSDecimalNumber *theHigh = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:2]];
[csvDict setObject:theHigh forKey:@"high"];
NSDecimalNumber *theLow = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:3]];
[csvDict setObject:theLow forKey:@"low"];
NSDecimalNumber *theClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:4]];
[csvDict setObject:theClose forKey:@"close"];
NSDecimalNumber *theVolume = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:5]];
[csvDict setObject:theVolume forKey:@"volume"];
NSDecimalNumber *theAdjClose = [NSDecimalNumber decimalNumberWithString:(NSString *)[csvChunks objectAtIndex:6]];
[csvDict setObject:theAdjClose forKey:@"adjClose"];
//non-mutable autoreleased dict
return [NSDictionary dictionaryWithDictionary:csvDict];
}
@end
| 08iteng-ipad | examples/AAPLot/APFinancialData.m | Objective-C | bsd | 1,704 |
#import "Controller.h"
#import <CorePlot/CorePlot.h>
@implementation Controller
-(void)dealloc
{
[plotData release];
[graph release];
[areaFill release];
[barLineStyle release];
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
NSDate *refDate = [NSDate dateWithNaturalLanguageString:@"12:00 Oct 29, 2009"];
NSTimeInterval oneDay = 24 * 60 * 60;
// Create graph from theme
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
hostView.hostedLayer = graph;
// Title
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = [CPColor whiteColor];
textStyle.fontSize = 18.0f;
textStyle.fontName = @"Helvetica";
graph.title = @"Click to Toggle Range Plot Style";
graph.titleTextStyle = textStyle;
graph.titleDisplacement = CGPointMake(0.0f, -20.0f);
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
NSTimeInterval xLow = oneDay*0.5f;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(xLow) length:CPDecimalFromFloat(oneDay*5.0f)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(oneDay);
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 0;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *timeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromFloat(oneDay);
// Create a plot that uses the data source method
CPRangePlot *dataSourceLinePlot = [[[CPRangePlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Date Plot";
// Add line style
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineWidth = 1.0f;
lineStyle.lineColor = [CPColor greenColor];
barLineStyle = [lineStyle retain];
dataSourceLinePlot.barLineStyle = barLineStyle;
// Bar properties
dataSourceLinePlot.barWidth = 10.0f;
dataSourceLinePlot.gapWidth = 20.0f;
dataSourceLinePlot.gapHeight = 20.0f;
dataSourceLinePlot.dataSource = self;
// Add plot
[graph addPlot:dataSourceLinePlot];
graph.defaultPlotSpace.delegate = self;
// Store area fill for use later
CPColor *transparentGreen = [[CPColor greenColor] colorWithAlphaComponent:0.2];
areaFill = [[CPFill alloc] initWithColor:(id)transparentGreen];
// Add some data
NSMutableArray *newData = [NSMutableArray array];
NSUInteger i;
for ( i = 0; i < 5; i++ ) {
NSTimeInterval x = oneDay*(i+1.0);
float y = 3.0f*rand()/(float)RAND_MAX + 1.2f;
float rHigh = rand()/(float)RAND_MAX * 0.5f + 0.25f;
float rLow = rand()/(float)RAND_MAX * 0.5f + 0.25f;
float rLeft = (rand()/(float)RAND_MAX * 0.125f + 0.125f) * oneDay;
float rRight = (rand()/(float)RAND_MAX * 0.125f + 0.125f) * oneDay;
[newData addObject:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPRangePlotFieldX],
[NSDecimalNumber numberWithFloat:y], [NSNumber numberWithInt:CPRangePlotFieldY],
[NSDecimalNumber numberWithFloat:rHigh], [NSNumber numberWithInt:CPRangePlotFieldHigh],
[NSDecimalNumber numberWithFloat:rLow], [NSNumber numberWithInt:CPRangePlotFieldLow],
[NSDecimalNumber numberWithFloat:rLeft], [NSNumber numberWithInt:CPRangePlotFieldLeft],
[NSDecimalNumber numberWithFloat:rRight], [NSNumber numberWithInt:CPRangePlotFieldRight],
nil]];
}
plotData = newData;
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return plotData.count;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
return num;
}
- (BOOL)plotSpace:(CPPlotSpace *)space shouldHandlePointingDeviceUpEvent:(id)event atPoint:(CGPoint)point {
CPRangePlot *rangePlot = (CPRangePlot *)[graph plotWithIdentifier:@"Date Plot"];
rangePlot.areaFill = ( rangePlot.areaFill ? nil : areaFill );
rangePlot.barLineStyle = ( rangePlot.barLineStyle ? nil : barLineStyle );
return NO;
}
@end
| 08iteng-ipad | examples/RangePlot/Controller.m | Objective-C | bsd | 5,107 |
//
// main.m
// CPTestApp
//
// Created by Dirkjan Krijnders on 2/2/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
| 08iteng-ipad | examples/RangePlot/Source/main.m | Objective-C | bsd | 259 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface Controller : NSObject <CPPlotDataSource> {
IBOutlet CPLayerHostingView *hostView;
CPXYGraph *graph;
NSArray *plotData;
CPFill *areaFill;
CPLineStyle *barLineStyle;
}
@end
| 08iteng-ipad | examples/RangePlot/Controller.h | Objective-C | bsd | 261 |
#import "Controller.h"
#import <CorePlot/CorePlot.h>
@implementation Controller
-(void)dealloc
{
[plotData release];
[graph release];
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
NSDate *refDate = [NSDate dateWithNaturalLanguageString:@"12:00 Oct 29, 2009"];
NSTimeInterval oneDay = 24 * 60 * 60;
// Create graph from theme
graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = [CPTheme themeNamed:kCPDarkGradientTheme];
[graph applyTheme:theme];
hostView.hostedLayer = graph;
// Setup scatter plot space
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
NSTimeInterval xLow = 0.0f;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(xLow) length:CPDecimalFromFloat(oneDay*5.0f)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(1.0) length:CPDecimalFromFloat(3.0)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(oneDay);
x.orthogonalCoordinateDecimal = CPDecimalFromString(@"2");
x.minorTicksPerInterval = 0;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *timeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@"0.5");
y.minorTicksPerInterval = 5;
y.orthogonalCoordinateDecimal = CPDecimalFromFloat(oneDay);
// Create a plot that uses the data source method
CPScatterPlot *dataSourceLinePlot = [[[CPScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = @"Date Plot";
CPMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor greenColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
// Add some data
NSMutableArray *newData = [NSMutableArray array];
NSUInteger i;
for ( i = 0; i < 5; i++ ) {
NSTimeInterval x = oneDay*i;
id y = [NSDecimalNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[newData addObject:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPScatterPlotFieldX],
y, [NSNumber numberWithInt:CPScatterPlotFieldY],
nil]];
}
plotData = newData;
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return plotData.count;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
return num;
}
@end
| 08iteng-ipad | examples/DatePlot/Controller.m | Objective-C | bsd | 3,327 |
//
// main.m
// CPTestApp
//
// Created by Dirkjan Krijnders on 2/2/09.
// Copyright __MyCompanyName__ 2009. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
| 08iteng-ipad | examples/DatePlot/Source/main.m | Objective-C | bsd | 259 |
#import <Cocoa/Cocoa.h>
#import <CorePlot/CorePlot.h>
@interface Controller : NSObject <CPPlotDataSource> {
IBOutlet CPLayerHostingView *hostView;
CPXYGraph *graph;
NSArray *plotData;
}
@end
| 08iteng-ipad | examples/DatePlot/Controller.h | Objective-C | bsd | 208 |
#pragma D option quiet
CorePlot$target:::layer_position_change
{
printf("Misaligned layer: %20s (%u.%03u, %u.%03u, %u.%03u, %u.%03u)\n", copyinstr(arg0), arg1 / 1000, arg1 % 1000, arg2 / 1000, arg2 % 1000, arg3 / 1000, arg3 % 1000, arg4 / 1000, arg4 % 1000 );
} | 08iteng-ipad | systemtests/tests/TestResources/checkformisalignedlayers.d | DTrace | bsd | 263 |
provider CorePlot {
probe layer_position_change(char *, int, int, int, int);
}; | 08iteng-ipad | systemtests/tests/TestResources/CorePlotProbes.d | DTrace | bsd | 80 |
//
// main.m
// CorePlot-CocoaTouch
//
// Created by Brad Larson on 5/11/2009.
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
| 08iteng-ipad | systemtests/tests/main-cocoatouch.m | Objective-C | bsd | 312 |
#import "CPPlatformSpecificCategories.h"
@implementation CPLayer (CPPlatformSpecificLayerExtensions)
-(CPNativeImage *)imageOfLayer
{
UIGraphicsBeginImageContext(self.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetAllowsAntialiasing(context, true);
CGContextTranslateCTM(context, 0.0f, self.bounds.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
[self recursivelyRenderInContext:context];
CPNativeImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
CGContextSetAllowsAntialiasing(context, false);
CGContextRestoreGState(context);
UIGraphicsEndImageContext();
return layerImage;
}
@end
@implementation NSNumber (CPPlatformSpecificExtensions)
-(BOOL)isLessThan:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedAscending );
}
-(BOOL)isLessThanOrEqualTo:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedSame || [self compare:other] == NSOrderedAscending );
}
-(BOOL)isGreaterThan:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedDescending );
}
-(BOOL)isGreaterThanOrEqualTo:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedSame || [self compare:other] == NSOrderedDescending );
}
@end | 08iteng-ipad | systemtests/tests/iPhoneOnly/CPPlatformSpecificCategories.m | Objective-C | bsd | 1,277 |
#import "CPTextStyle.h"
#import "CPTextStylePlatformSpecific.h"
#import "CPPlatformSpecificCategories.h"
#import "CPPlatformSpecificFunctions.h"
#import "CPColor.h"
@implementation NSString(CPTextStyleExtensions)
#pragma mark -
#pragma mark Layout
-(CGSize)sizeWithStyle:(CPTextStyle *)style
{
UIFont *theFont = [UIFont fontWithName:style.fontName size:style.fontSize];
CGSize textSize = [self sizeWithFont:theFont];
return textSize;
}
#pragma mark -
#pragma mark Drawing of Text
-(void)drawAtPoint:(CGPoint)point withStyle:(CPTextStyle *)style inContext:(CGContextRef)context
{
if ( style.color == nil ) return;
CGContextSaveGState(context);
CGColorRef textColor = style.color.cgColor;
CGContextSetStrokeColorWithColor(context, textColor);
CGContextSetFillColorWithColor(context, textColor);
CPPushCGContext(context);
UIFont *theFont = [UIFont fontWithName:style.fontName size:style.fontSize];
[self drawAtPoint:CGPointZero withFont:theFont];
CGContextRestoreGState(context);
CPPopCGContext();
}
@end
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPTextStylePlatformSpecific.m | Objective-C | bsd | 1,043 |
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef UIImage CPNativeImage;
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPPlatformSpecificDefines.h | Objective-C | bsd | 91 |
#import <UIKit/UIKit.h>
@class CPLayer;
@interface CPLayerHostingView : UIView {
@protected
CPLayer *hostedLayer, *layerBeingTouched;
}
@property (nonatomic, readwrite, retain) CPLayer *hostedLayer;
@end
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPLayerHostingView.h | Objective-C | bsd | 210 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
void CPPushCGContext(CGContextRef context);
void CPPopCGContext(void); | 08iteng-ipad | systemtests/tests/iPhoneOnly/CPPlatformSpecificFunctions.h | Objective-C | bsd | 140 |
#import <Foundation/Foundation.h>
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPTextStylePlatformSpecific.h | Objective-C | bsd | 35 |
#import <UIKit/UIKit.h>
#import "CPPlatformSpecificFunctions.h"
#import "CPExceptions.h"
void CPPushCGContext(CGContextRef newContext)
{
UIGraphicsPushContext(newContext);
}
void CPPopCGContext(void)
{
UIGraphicsPopContext();
}
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPPlatformSpecificFunctions.m | Objective-C | bsd | 240 |
#import "CPLayerHostingView.h"
#import "CPLayer.h"
@implementation CPLayerHostingView
@synthesize hostedLayer;
+(Class)layerClass
{
return [CPLayer class];
}
-(id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
hostedLayer = nil;
layerBeingTouched = nil;
// This undoes the normal coordinate space inversion that UIViews apply to their layers
self.layer.sublayerTransform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f);
// self.layer.transform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f);
self.backgroundColor = [UIColor clearColor];
}
return self;
}
// On the iPhone, the init method is not called when loading from a XIB
- (void)awakeFromNib
{
hostedLayer = nil;
layerBeingTouched = nil;
// This undoes the normal coordinate space inversion that UIViews apply to their layers
self.layer.sublayerTransform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f);
// self.layer.transform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f);
self.backgroundColor = [UIColor clearColor];
}
-(void)dealloc {
[hostedLayer release];
[super dealloc];
}
#pragma mark -
#pragma mark Touch handling
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// Ignore pinch or other multitouch gestures
if ([[event allTouches] count] > 1) {
return;
}
CGPoint pointOfTouch = [[[event touchesForView:self] anyObject] locationInView:self];
CALayer *hitLayer = [self.layer hitTest:pointOfTouch];
if ( (hitLayer != nil) && [hitLayer isKindOfClass:[CPLayer class]]) {
layerBeingTouched = (CPLayer *)hitLayer;
[(CPLayer *)hitLayer mouseOrFingerDownAtPoint:pointOfTouch];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
{
if (layerBeingTouched == nil) {
return;
}
CGPoint pointOfTouch = [[[event touchesForView:self] anyObject] locationInView:self];
[layerBeingTouched mouseOrFingerDraggedAtPoint:pointOfTouch];
layerBeingTouched = nil;
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (layerBeingTouched == nil) {
return;
}
CGPoint pointOfTouch = [[[event touchesForView:self] anyObject] locationInView:self];
[layerBeingTouched mouseOrFingerUpAtPoint:pointOfTouch];
layerBeingTouched = nil;
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
// Ignore pinch or other multitouch gestures
if (layerBeingTouched == nil) {
return;
}
[layerBeingTouched mouseOrFingerCancelled];
layerBeingTouched = nil;
}
#pragma mark -
#pragma mark Accessors
-(void)setHostedLayer:(CPLayer *)newLayer
{
if (newLayer == hostedLayer) {
return;
}
[hostedLayer removeFromSuperlayer];
[hostedLayer release];
hostedLayer = [newLayer retain];
[self.layer addSublayer:hostedLayer];
}
@end
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPLayerHostingView.m | Objective-C | bsd | 2,743 |
#import <UIKit/UIKit.h>
#import "CPLayer.h"
#import "CPPlatformSpecificDefines.h"
@interface CPLayer (CPPlatformSpecificLayerExtensions)
-(CPNativeImage *)imageOfLayer;
@end
@interface NSNumber (CPPlatformSpecificExtensions)
-(BOOL)isLessThan:(NSNumber *)other;
-(BOOL)isLessThanOrEqualTo:(NSNumber *)other;
-(BOOL)isGreaterThan:(NSNumber *)other;
-(BOOL)isGreaterThanOrEqualTo:(NSNumber *)other;
@end
| 08iteng-ipad | systemtests/tests/iPhoneOnly/CPPlatformSpecificCategories.h | Objective-C | bsd | 409 |
//
// main.m
// CorePlot
//
// Created by Barry Wark on 2/11/09.
// Copyright 2009 Barry Wark. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "GTMUnitTestingUtilities.h"
void GTMRestoreColorProfile(void);
int main(int argc, char *argv[])
{
//configure environment for standard unit testing
[GTMUnitTestingUtilities setUpForUIUnitTestsIfBeingTested];
return NSApplicationMain(argc, (const char **) argv);
//setUpForUIUnitTestsIfBeingTested modifies the system-wide color profile. Make sure it gets restored.
GTMRestoreColorProfile();
}
| 08iteng-ipad | systemtests/tests/main.m | Objective-C | bsd | 584 |
#import "iPhoneOnly/CPPlatformSpecificDefines.h"
#import "Source/CPAxis.h"
#import "Source/CPAxisLabel.h"
#import "Source/CPAxisTitle.h"
#import "Source/CPAxisSet.h"
#import "Source/CPBarPlot.h"
#import "Source/CPBorderedLayer.h"
#import "Source/CPColor.h"
#import "Source/CPColorSpace.h"
#import "Source/CPDarkGradientTheme.h"
#import "Source/CPDefinitions.h"
#import "Source/CPExceptions.h"
#import "Source/CPFill.h"
#import "Source/CPGradient.h"
#import "Source/CPGraph.h"
#import "Source/CPLayer.h"
#import "Source/CPLayoutManager.h"
#import "Source/CPLineStyle.h"
#import "iPhoneOnly/CPPlatformSpecificFunctions.h"
#import "iPhoneOnly/CPPlatformSpecificCategories.h"
#import "Source/CPPathExtensions.h"
#import "Source/CPPlainBlackTheme.h"
#import "Source/CPPlainWhiteTheme.h"
#import "Source/CPPlotArea.h"
#import "Source/CPPlot.h"
#import "Source/CPPlotGroup.h"
#import "Source/CPPlotSpace.h"
#import "Source/CPPlotSymbol.h"
#import "Source/CPPolarPlotSpace.h"
#import "Source/CPScatterPlot.h"
#import "Source/CPStocksTheme.h"
#import "Source/CPTextStyle.h"
#import "Source/CPTheme.h"
#import "Source/CPTimeFormatter.h"
#import "Source/CPUtilities.h"
#import "Source/CPXYAxis.h"
#import "Source/CPXYAxisSet.h"
#import "Source/CPXYGraph.h"
#import "Source/CPXYPlotSpace.h"
#import "Source/CPXYTheme.h"
#import "iPhoneOnly/CPLayerHostingView.h"
| 08iteng-ipad | systemtests/tests/CorePlot-CocoaTouch.h | Objective-C | bsd | 1,350 |
#import <CorePlot/CPAnimation.h>
#import <CorePlot/CPAnimationKeyFrame.h>
#import <CorePlot/CPAnimationTransition.h>
#import <CorePlot/CPAxis.h>
#import <CorePlot/CPAxisSet.h>
#import <CorePlot/CPAxisTitle.h>
#import <CorePlot/CPBarPlot.h>
#import <CorePlot/CPBorderedLayer.h>
#import <CorePlot/CPColor.h>
#import <CorePlot/CPColorSpace.h>
#import <CorePlot/CPDarkGradientTheme.h>
#import <CorePlot/CPDecimalNumberValueTransformer.h>
#import <CorePlot/CPDefinitions.h>
#import <CorePlot/CPExceptions.h>
#import <CorePlot/CPFill.h>
#import <CorePlot/CPGradient.h>
#import <CorePlot/CPGraph.h>
#import <CorePlot/CPImage.h>
#import <CorePlot/CPLayoutManager.h>
#import <CorePlot/CPLineStyle.h>
#import <CorePlot/CPPlainBlackTheme.h>
#import <CorePlot/CPPlainWhiteTheme.h>
#import <CorePlot/CPPlatformSpecificDefines.h>
#import <CorePlot/CPPlatformSpecificFunctions.h>
#import <CorePlot/CPPlatformSpecificCategories.h>
#import <CorePlot/CPPlotArea.h>
#import <CorePlot/CPPlot.h>
#import <CorePlot/CPPlotGroup.h>
#import <CorePlot/CPPlotSpace.h>
#import <CorePlot/CPPlotSymbol.h>
#import <CorePlot/CPPolarPlotSpace.h>
#import <CorePlot/CPScatterPlot.h>
#import <CorePlot/CPStocksTheme.h>
#import <CorePlot/CPTextLayer.h>
#import <CorePlot/CPTextStyle.h>
#import <CorePlot/CPTheme.h>
#import <CorePlot/CPTimeFormatter.h>
#import <CorePlot/CPUtilities.h>
#import <CorePlot/CPXYAxis.h>
#import <CorePlot/CPXYAxisSet.h>
#import <CorePlot/CPXYGraph.h>
#import <CorePlot/CPXYPlotSpace.h>
#import <CorePlot/CPXYTheme.h>
#import <CorePlot/CPLayerHostingView.h>
| 08iteng-ipad | systemtests/tests/CorePlot.h | Objective-C | bsd | 1,548 |
#import <AppKit/AppKit.h>
#import "CPPlatformSpecificCategories.h"
#import "CPUtilities.h"
/** @brief Platform-specific extensions to CPLayer.
**/
@implementation CPLayer(CPPlatformSpecificLayerExtensions)
/// @addtogroup CPLayer
/// @{
/** @brief Gets an image of the layer contents.
* @return A native image representation of the layer content.
**/
-(CPNativeImage *)imageOfLayer
{
CGSize boundsSize = self.bounds.size;
NSBitmapImageRep *layerImage = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:boundsSize.width pixelsHigh:boundsSize.height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:(NSInteger)boundsSize.width * 4 bitsPerPixel:32];
NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:layerImage];
CGContextRef context = (CGContextRef)[bitmapContext graphicsPort];
CGContextClearRect(context, CGRectMake(0.0f, 0.0f, boundsSize.width, boundsSize.height));
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldSmoothFonts(context, false);
[self recursivelyRenderInContext:context];
CGContextFlush(context);
NSImage *image = [[NSImage alloc] initWithSize:NSSizeFromCGSize(boundsSize)];
[image addRepresentation:layerImage];
[layerImage release];
return [image autorelease];
}
/// @}
@end
/** @brief Platform-specific extensions to CPColor.
**/
@implementation CPColor(CPPlatformSpecificColorExtensions)
/// @addtogroup CPColor
/// @{
/** @property nsColor
* @brief Gets the color value as an NSColor.
**/
-(NSColor *)nsColor
{
return [NSColor colorWithCIColor:[CIColor colorWithCGColor:self.cgColor]];
}
/// @}
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPPlatformSpecificCategories.m | Objective-C | bsd | 1,705 |
#import "CPTextStyle.h"
#import "CPTextStylePlatformSpecific.h"
#import "CPPlatformSpecificCategories.h"
#import "CPPlatformSpecificFunctions.h"
/** @brief NSString extensions for drawing styled text.
**/
@implementation NSString(CPTextStyleExtensions)
#pragma mark -
#pragma mark Layout
/** @brief Determines the size of text drawn with the given style.
* @param style The text style.
* @return The size of the text when drawn with the given style.
**/
-(CGSize)sizeWithStyle:(CPTextStyle *)style
{
NSFont *theFont = [NSFont fontWithName:style.fontName size:style.fontSize];
CGSize textSize;
if (theFont) {
textSize = NSSizeToCGSize([self sizeWithAttributes:[NSDictionary dictionaryWithObject:theFont forKey:NSFontAttributeName]]);
} else {
textSize = CGSizeMake(0.0, 0.0);
}
return textSize;
}
#pragma mark -
#pragma mark Drawing
/** @brief Draws the text into the given graphics context using the given style.
* @param point The origin of the drawing position.
* @param style The text style.
* @param context The graphics context to draw into.
**/
-(void)drawAtPoint:(CGPoint)point withStyle:(CPTextStyle *)style inContext:(CGContextRef)context
{
if ( style.color == nil ) return;
CGColorRef textColor = style.color.cgColor;
CGContextSetStrokeColorWithColor(context, textColor);
CGContextSetFillColorWithColor(context, textColor);
CPPushCGContext(context);
NSFont *theFont = [NSFont fontWithName:style.fontName size:style.fontSize];
if (theFont) {
NSColor *foregroundColor = style.color.nsColor;
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:theFont, NSFontAttributeName, foregroundColor, NSForegroundColorAttributeName, nil];
[self drawAtPoint:NSPointFromCGPoint(point) withAttributes:attributes];
}
CPPopCGContext();
}
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPTextStylePlatformSpecific.m | Objective-C | bsd | 1,810 |
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
/// @file
typedef NSImage CPNativeImage; ///< Platform-native image format.
/** @brief Node in a linked list of graphics contexts.
**/
typedef struct _CPContextNode {
NSGraphicsContext *context; ///< The graphics context.
struct _CPContextNode *nextNode; ///< Pointer to the next node in the list.
} CPContextNode;
| 08iteng-ipad | systemtests/tests/MacOnly/CPPlatformSpecificDefines.h | Objective-C | bsd | 384 |
#import <Cocoa/Cocoa.h>
@class CPLayer;
@interface CPLayerHostingView : NSView {
@private
CPLayer *hostedLayer, *layerBeingClickedOn;
}
@property (nonatomic, readwrite, retain) CPLayer *hostedLayer;
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPLayerHostingView.h | Objective-C | bsd | 209 |
#import <Foundation/Foundation.h>
@interface CPDecimalNumberValueTransformer : NSValueTransformer {
}
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPDecimalNumberValueTransformer.h | Objective-C | bsd | 112 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import "CPDefinitions.h"
/// @file
/// @name Graphics Context Save Stack
/// @{
void CPPushCGContext(CGContextRef context);
void CPPopCGContext(void);
/// @}
/// @name Color Conversion
/// @{
CGColorRef CPNewCGColorFromNSColor(NSColor *nsColor);
CPRGBAColor CPRGBAColorFromNSColor(NSColor *nsColor);
/// @}
| 08iteng-ipad | systemtests/tests/MacOnly/CPPlatformSpecificFunctions.h | Objective-C | bsd | 380 |
#import <Foundation/Foundation.h>
| 08iteng-ipad | systemtests/tests/MacOnly/CPTextStylePlatformSpecific.h | Objective-C | bsd | 35 |
#import "CPPlatformSpecificFunctions.h"
#import "CPPlatformSpecificDefines.h"
#import "CPDefinitions.h"
#pragma mark -
#pragma mark Graphics Context
// linked list to store saved contexts
static CPContextNode *pushedContexts = NULL;
/** @brief Pushes the current AppKit graphics context onto a stack and replaces it with the given Core Graphics context.
* @param newContext The graphics context.
**/
void CPPushCGContext(CGContextRef newContext)
{
if (newContext) {
CPContextNode *newNode = malloc(sizeof(CPContextNode));
(*newNode).context = [NSGraphicsContext currentContext];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:newContext flipped:NO]];
(*newNode).nextNode = pushedContexts;
pushedContexts = newNode;
}
}
/** @brief Pops the top context off the stack and restores it to the AppKit graphics context.
**/
void CPPopCGContext(void)
{
if (pushedContexts) {
[NSGraphicsContext setCurrentContext:(*pushedContexts).context];
CPContextNode *next = (*pushedContexts).nextNode;
free(pushedContexts);
pushedContexts = next;
}
}
#pragma mark -
#pragma mark Colors
/** @brief Creates a CGColorRef from an NSColor.
*
* The caller must release the returned CGColorRef. Pattern colors are not supported.
*
* @param nsColor The NSColor.
* @return The CGColorRef.
**/
CGColorRef CPNewCGColorFromNSColor(NSColor *nsColor)
{
NSColor *rgbColor = [nsColor colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
CGFloat r, g, b, a;
[rgbColor getRed:&r green:&g blue:&b alpha:&a];
return CGColorCreateGenericRGB(r, g, b, a);
}
/** @brief Creates a CPRGBAColor from an NSColor.
*
* Pattern colors are not supported.
*
* @param nsColor The NSColor.
* @return The CPRGBAColor.
**/
CPRGBAColor CPRGBAColorFromNSColor(NSColor *nsColor)
{
CGFloat red, green, blue, alpha;
[[nsColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&red green:&green blue:&blue alpha:&alpha];
CPRGBAColor rgbColor;
rgbColor.red = red;
rgbColor.green = green;
rgbColor.blue = blue;
rgbColor.alpha = alpha;
return rgbColor;
}
| 08iteng-ipad | systemtests/tests/MacOnly/CPPlatformSpecificFunctions.m | Objective-C | bsd | 2,108 |
#import "CPLayerHostingView.h"
#import "CPLayer.h"
/// @cond
@interface CPLayerHostingView()
@property (nonatomic, readwrite, assign) CPLayer *layerBeingClickedOn;
@end
/// @endcond
/** @brief A container view for displaying a CPLayer.
**/
@implementation CPLayerHostingView
/** @property hostedLayer
* @brief The CPLayer hosted inside this view.
**/
@synthesize hostedLayer;
@synthesize layerBeingClickedOn;
-(id)initWithFrame:(NSRect)frame
{
if (self = [super initWithFrame:frame]) {
hostedLayer = nil;
layerBeingClickedOn = nil;
CPLayer *mainLayer = [(CPLayer *)[CPLayer alloc] initWithFrame:NSRectToCGRect(frame)];
self.layer = mainLayer;
[mainLayer release];
}
return self;
}
-(void)dealloc
{
[hostedLayer removeFromSuperlayer];
[hostedLayer release];
layerBeingClickedOn = nil;
[super dealloc];
}
#pragma mark -
#pragma mark Mouse handling
-(BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
return YES;
}
-(void)mouseDown:(NSEvent *)theEvent
{
CGPoint pointOfMouseDown = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow] fromView:nil]);
CALayer *hitLayer = [self.layer hitTest:pointOfMouseDown];
if ( (hitLayer != nil) && [hitLayer isKindOfClass:[CPLayer class]]) {
self.layerBeingClickedOn = (CPLayer *)hitLayer;
[(CPLayer *)hitLayer mouseOrFingerDownAtPoint:pointOfMouseDown];
}
}
-(void)mouseDragged:(NSEvent *)theEvent
{
if (self.layerBeingClickedOn == nil) {
return;
}
CGPoint pointOfMouseDrag = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow] fromView:nil]);
[self.layerBeingClickedOn mouseOrFingerUpAtPoint:pointOfMouseDrag];
self.layerBeingClickedOn = nil;
}
-(void)mouseUp:(NSEvent *)theEvent
{
if (self.layerBeingClickedOn == nil) {
return;
}
CGPoint pointOfMouseUp = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow] fromView:nil]);
[self.layerBeingClickedOn mouseOrFingerUpAtPoint:pointOfMouseUp];
self.layerBeingClickedOn = nil;
}
#pragma mark -
#pragma mark Accessors
-(void)setHostedLayer:(CPLayer *)newLayer
{
if (newLayer != hostedLayer) {
self.wantsLayer = YES;
[hostedLayer removeFromSuperlayer];
[hostedLayer release];
hostedLayer = [newLayer retain];
if (hostedLayer) {
[self.layer addSublayer:hostedLayer];
}
}
}
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPLayerHostingView.m | Objective-C | bsd | 2,323 |
#import <AppKit/AppKit.h>
#import <QuartzCore/QuartzCore.h>
#import "CPLayer.h"
#import "CPColor.h"
@interface CPLayer(CPPlatformSpecificLayerExtensions)
/// @name Images
/// @{
-(CPNativeImage *)imageOfLayer;
/// @}
@end
@interface CPColor(CPPlatformSpecificColorExtensions)
@property (nonatomic, readonly, retain) NSColor *nsColor;
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPPlatformSpecificCategories.h | Objective-C | bsd | 345 |
#import "CPDecimalNumberValueTransformer.h"
#import "NSNumberExtensions.h"
/** @brief A Cocoa Bindings value transformer for NSDecimalNumber objects.
**/
@implementation CPDecimalNumberValueTransformer
+(BOOL)allowsReverseTransformation
{
return YES;
}
+(Class)transformedValueClass
{
return [NSNumber class];
}
-(id)transformedValue:(id)value {
return [[value copy] autorelease];
}
-(id)reverseTransformedValue:(id)value {
return [value decimalNumber];
}
@end
| 08iteng-ipad | systemtests/tests/MacOnly/CPDecimalNumberValueTransformer.m | Objective-C | bsd | 488 |
#import "CPAnimation.h"
#import "CPAnimationTransition.h"
#import "CPAnimationKeyFrame.h"
/** @brief An animation.
* @note Not implemented.
* @todo
* - Implement CPAnimation.
* - Add documentation for CPAnimation.
**/
@implementation CPAnimation
/** @property graph
* @todo Needs documentation.
**/
@synthesize graph;
/** @property animationKeyFrames
* @todo Needs documentation.
**/
@synthesize animationKeyFrames = mutableKeyFrames;
/** @property animationTransitions
* @todo Needs documentation.
**/
@synthesize animationTransitions = mutableTransitions;
/** @property currentKeyFrame
* @todo Needs documentation.
**/
@synthesize currentKeyFrame;
#pragma mark -
#pragma mark Init/Dealloc
-(id)initWithGraph:(CPGraph *)newGraph
{
if ( self = [super init] ) {
graph = [newGraph retain];
mutableKeyFrames = nil;
mutableTransitions = nil;
currentKeyFrame = nil;
}
return self;
}
-(void)dealloc
{
[graph release];
[mutableKeyFrames release];
[mutableTransitions release];
[currentKeyFrame release];
[super dealloc];
}
#pragma mark -
#pragma mark Key Frames
-(void)addAnimationKeyFrame:(CPAnimationKeyFrame *)newKeyFrame
{
}
-(CPAnimationKeyFrame *)animationKeyFrameWithIdentifier:(id <NSCopying>)identifier
{
return nil;
}
#pragma mark -
#pragma mark Transitions
-(void)addAnimationTransition:(CPAnimationTransition *)newTransition fromKeyFrame:(CPAnimationKeyFrame *)startFrame toKeyFrame:(CPAnimationKeyFrame *)endFrame
{
}
-(CPAnimationTransition *)animationTransitionWithIdentifier:(id <NSCopying>)identifier
{
return nil;
}
-(void)animationTransitionDidFinish:(CPAnimationTransition *)transition
{
// Update state here
}
#pragma mark -
#pragma mark Animating
-(void)performTransition:(CPAnimationTransition *)transition
{
}
-(void)performTransitionToKeyFrame:(CPAnimationKeyFrame *)keyFrame
{
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPAnimation.m | Objective-C | bsd | 1,908 |
#import "CPImage.h"
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
// iPhone-specific image library as equivalent to ImageIO?
#else
//#import <ImageIO/ImageIO.h>
#endif
/** @brief Wrapper around CGImageRef.
*
* A wrapper class around CGImageRef.
*
* @todo More documentation needed
**/
@implementation CPImage
/** @property image
* @brief The CGImageRef to wrap around.
**/
@synthesize image;
/** @property tiled
* @brief Draw as a tiled image?
*
* If YES, the image is drawn repeatedly to fill the current clip region.
* Otherwise, the image is drawn one time only in the provided rectangle.
* The default value is NO.
**/
@synthesize tiled;
#pragma mark -
#pragma mark Initialization
/** @brief Initializes a CPImage instance with the provided CGImageRef.
*
* This is the designated initializer.
*
* @param anImage The image to wrap.
* @return A CPImage instance initialized with the provided CGImageRef.
**/
-(id)initWithCGImage:(CGImageRef)anImage
{
if ( self = [super init] ) {
CGImageRetain(anImage);
image = anImage;
tiled = NO;
}
return self;
}
-(id)init
{
return [self initWithCGImage:NULL];
}
/** @brief Initializes a CPImage instance with the contents of a PNG file.
* @param path The file system path of the file.
* @return A CPImage instance initialized with the contents of the PNG file.
**/
-(id)initForPNGFile:(NSString *)path
{
CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename([path cStringUsingEncoding:NSUTF8StringEncoding]);
CGImageRef cgImage = CGImageCreateWithPNGDataProvider(dataProvider, NULL, YES, kCGRenderingIntentDefault);
if ( cgImage ) {
self = [self initWithCGImage:cgImage];
}
else {
[self release];
self = nil;
}
CGImageRelease(cgImage);
CGDataProviderRelease(dataProvider);
return self;
}
-(void)dealloc
{
CGImageRelease(image);
[super dealloc];
}
-(id)copyWithZone:(NSZone *)zone
{
CPImage *copy = [[[self class] allocWithZone:zone] init];
copy->image = CGImageCreateCopy(self.image);
copy->tiled = self->tiled;
return copy;
}
#pragma mark -
#pragma mark Factory Methods
/** @brief Creates and returns a new CPImage instance initialized with the provided CGImageRef.
* @param anImage The image to wrap.
* @return A new CPImage instance initialized with the provided CGImageRef.
**/
+(CPImage *)imageWithCGImage:(CGImageRef)anImage
{
return [[[self alloc] initWithCGImage:anImage] autorelease];
}
/** @brief Creates and returns a new CPImage instance initialized with the contents of a PNG file.
* @param path The file system path of the file.
* @return A new CPImage instance initialized with the contents of the PNG file.
**/
+(CPImage *)imageForPNGFile:(NSString *)path
{
return [[[self alloc] initForPNGFile:path] autorelease];
}
#pragma mark -
#pragma mark Accessors
-(void)setImage:(CGImageRef)anImage
{
if (anImage != image) {
CGImageRetain(anImage);
CGImageRelease(image);
image = anImage;
}
}
#pragma mark -
#pragma mark Drawing
/** @brief Draws the image into the given graphics context.
*
* If the tiled property is TRUE, the image is repeatedly drawn to fill the clipping region, otherwise the image is
* scaled to fit in rect.
*
* @param rect The rectangle to draw into.
* @param context The graphics context to draw into.
**/
-(void)drawInRect:(CGRect)rect inContext:(CGContextRef)context
{
if (self.image) {
if (self.tiled) {
CGContextDrawTiledImage(context, rect, self.image);
} else {
CGContextDrawImage(context, rect, self.image);
}
}
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPImage.m | Objective-C | bsd | 3,613 |
#import <Foundation/Foundation.h>
#import "CPLayer.h"
@class CPLineStyle;
@class CPFill;
@interface CPBorderedLayer : CPLayer {
@private
CPLineStyle *borderLineStyle;
CPFill *fill;
CGFloat cornerRadius;
CGPathRef outerBorderPath;
CGPathRef innerBorderPath;
BOOL masksToBorder;
}
@property (nonatomic, readwrite, copy) CPLineStyle *borderLineStyle;
@property (nonatomic, readwrite, assign) CGFloat cornerRadius;
@property (nonatomic, readwrite, copy) CPFill *fill;
@property (nonatomic, readwrite, assign) BOOL masksToBorder;
@end
| 08iteng-ipad | systemtests/tests/Source/CPBorderedLayer.h | Objective-C | bsd | 545 |
#import "CPLayer.h"
/// @file
@class CPTextStyle;
extern const CGFloat kCPTextLayerMarginWidth; ///< Margin width around the text.
@interface CPTextLayer : CPLayer {
@private
NSString *text;
CPTextStyle *textStyle;
}
@property(readwrite, copy, nonatomic) NSString *text;
@property(readwrite, retain, nonatomic) CPTextStyle *textStyle;
/// @name Initialization
/// @{
-(id)initWithText:(NSString *)newText;
-(id)initWithText:(NSString *)newText style:(CPTextStyle *)newStyle;
/// @}
/// @name Layout
/// @{
-(void)sizeToFit;
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPTextLayer.h | Objective-C | bsd | 548 |
#import "NSDecimalNumberExtensions.h"
/** @brief Core Plot extensions to NSDecimalNumber.
**/
@implementation NSDecimalNumber(CPExtensions)
/** @brief Returns the approximate value of the receiver as a CGFloat.
* @return The approximate value of the receiver as a CGFloat.
**/
-(CGFloat)floatValue
{
return (CGFloat)[self doubleValue];
}
/** @brief Returns the value of the receiver as an NSDecimalNumber.
* @return The value of the receiver as an NSDecimalNumber.
**/
-(NSDecimalNumber *)decimalNumber
{
return [[self copy] autorelease];
}
@end
| 08iteng-ipad | systemtests/tests/Source/NSDecimalNumberExtensions.m | Objective-C | bsd | 564 |
#import "CPColorSpace.h"
/// @cond
@interface CPColorSpace ()
@property (nonatomic, readwrite, assign) CGColorSpaceRef cgColorSpace;
@end
/// @endcond
/** @brief Wrapper around CGColorSpaceRef
*
* A wrapper class around CGColorSpaceRef
*
* @todo More documentation needed
**/
@implementation CPColorSpace
/** @property cgColorSpace.
* @brief The CGColorSpace to wrap around
**/
@synthesize cgColorSpace;
#pragma mark -
#pragma mark Class methods
/** @brief Returns a shared instance of CPColorSpace initialized with the standard RGB space
*
* For the iPhone this is CGColorSpaceCreateDeviceRGB(), for Mac OS X CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB).
*
* @return A shared CPColorSpace object initialized with the standard RGB colorspace.
**/
+(CPColorSpace *)genericRGBSpace;
{
static CPColorSpace *space = nil;
if (nil == space) {
CGColorSpaceRef cgSpace = NULL;
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
cgSpace = CGColorSpaceCreateDeviceRGB();
#else
cgSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
#endif
space = [[CPColorSpace alloc] initWithCGColorSpace:cgSpace];
}
return space;
}
#pragma mark -
#pragma mark Init/Dealloc
/** @brief Initializes a newly allocated colorspace object with the specified color space.
* This is the designated initializer.
*
* @param colorSpace The color space.
* @return The initialized CPColorSpace object.
**/
-(id)initWithCGColorSpace:(CGColorSpaceRef)colorSpace {
if ( self = [super init] ) {
CGColorSpaceRetain(colorSpace);
cgColorSpace = colorSpace;
}
return self;
}
-(void)dealloc {
CGColorSpaceRelease(cgColorSpace);
[super dealloc];
}
#pragma mark -
#pragma mark Accessors
-(void)setCGColorSpace:(CGColorSpaceRef)newSpace {
if ( newSpace != cgColorSpace ) {
CGColorSpaceRelease(cgColorSpace);
CGColorSpaceRetain(newSpace);
cgColorSpace = newSpace;
}
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPColorSpace.m | Objective-C | bsd | 1,973 |
#import "CPPlot.h"
#import "CPPlotSpace.h"
#import "CPPlotRange.h"
#import "NSNumberExtensions.h"
#import "CPUtilities.h"
/// @cond
@interface CPPlot()
@property (nonatomic, readwrite, assign) BOOL dataNeedsReloading;
@property (nonatomic, readwrite, retain) NSMutableDictionary *cachedData;
@end
/// @endcond
/** @brief An abstract plot class.
*
* Each data series on the graph is represented by a plot.
**/
@implementation CPPlot
/** @property dataSource
* @brief The data source for the plot.
**/
@synthesize dataSource;
/** @property identifier
* @brief An object used to identify the plot in collections.
**/
@synthesize identifier;
/** @property plotSpace
* @brief The plot space for the plot.
**/
@synthesize plotSpace;
/** @property dataNeedsReloading
* @brief If YES, the plot data will be reloaded from the data source before the layer content is drawn.
**/
@synthesize dataNeedsReloading;
@synthesize cachedData;
#pragma mark -
#pragma mark init/dealloc
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
cachedData = nil;
dataSource = nil;
identifier = nil;
plotSpace = nil;
dataNeedsReloading = YES;
}
return self;
}
-(void)dealloc
{
[cachedData release];
[identifier release];
[plotSpace release];
[super dealloc];
}
#pragma mark -
#pragma mark Drawing
-(void)drawInContext:(CGContextRef)theContext
{
if ( self.dataNeedsReloading ) [self reloadData];
[super drawInContext:theContext];
}
#pragma mark -
#pragma mark Layout
+(CGFloat)defaultZPosition
{
return CPDefaultZPositionPlot;
}
#pragma mark -
#pragma mark Fields
/** @brief Number of fields in a plot data record.
* @return The number of fields.
**/
-(NSUInteger)numberOfFields
{
return 0;
}
/** @brief Identifiers (enum values) identifying the fields.
* @return Array of NSNumbers for the various field identifiers.
**/
-(NSArray *)fieldIdentifiers
{
return [NSArray array];
}
/** @brief The field identifiers that correspond to a particular coordinate.
* @param coord The coordinate for which the corresponding field identifiers are desired.
* @return Array of NSNumbers for the field identifiers.
**/
-(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord
{
return [NSArray array];
}
#pragma mark -
#pragma mark Data Source
/** @brief Reload data from the data source.
**/
-(void)reloadData
{
self.dataNeedsReloading = NO;
[self setNeedsDisplay];
}
/** @brief Gets a range of plot data for the given plot and field.
* @param fieldEnum The field index.
* @param indexRange The range of the data indexes of interest.
* @return An array of data points.
**/
-(NSArray *)numbersFromDataSourceForField:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
NSArray *numbers;
if ( self.dataSource ) {
if ( [self.dataSource respondsToSelector:@selector(numbersForPlot:field:recordIndexRange:)] ) {
numbers = [NSArray arrayWithArray:[self.dataSource numbersForPlot:self field:fieldEnum recordIndexRange:indexRange]];
}
else {
BOOL respondsToSingleValueSelector = [self.dataSource respondsToSelector:@selector(numberForPlot:field:recordIndex:)];
NSUInteger recordIndex;
NSMutableArray *fieldValues = [NSMutableArray arrayWithCapacity:indexRange.length];
for ( recordIndex = indexRange.location; recordIndex < indexRange.location + indexRange.length; ++recordIndex ) {
if ( respondsToSingleValueSelector ) {
NSNumber *number = [self.dataSource numberForPlot:self field:fieldEnum recordIndex:recordIndex];
[fieldValues addObject:number];
}
else {
[fieldValues addObject:[NSDecimalNumber zero]];
}
}
numbers = fieldValues;
}
}
else {
numbers = [NSArray array];
}
return numbers;
}
/** @brief Determines the record index range corresponding to a given range of data.
* This method is optional.
* @param plotRange The range expressed in data values.
* @return The range of record indexes.
**/
-(NSRange)recordIndexRangeForPlotRange:(CPPlotRange *)plotRange
{
if ( nil == self.dataSource ) return NSMakeRange(0, 0);
NSRange resultRange;
if ( [self.dataSource respondsToSelector:@selector(recordIndexRangeForPlot:plotRange:)] ) {
resultRange = [self.dataSource recordIndexRangeForPlot:self plotRange:plotRange];
}
else {
resultRange = NSMakeRange(0, [self.dataSource numberOfRecordsForPlot:self]);
}
return resultRange;
}
#pragma mark -
#pragma mark Data Caching
/** @brief Stores an array of numbers in the cache.
* @param numbers An array of numbers to cache.
* @param fieldEnum The field enumerator identifying the field.
**/
-(void)cacheNumbers:(NSArray *)numbers forField:(NSUInteger)fieldEnum
{
if ( numbers == nil ) return;
if ( cachedData == nil ) cachedData = [[NSMutableDictionary alloc] initWithCapacity:5];
[cachedData setObject:[[numbers copy] autorelease] forKey:[NSNumber numberWithUnsignedInt:fieldEnum]];
}
/** @brief Retrieves an array of numbers from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @return The array of cached numbers.
**/
-(NSArray *)cachedNumbersForField:(NSUInteger)fieldEnum
{
return [self.cachedData objectForKey:[NSNumber numberWithUnsignedInt:fieldEnum]];
}
#pragma mark -
#pragma mark Data Ranges
/** @brief Determines the smallest plot range that fully encloses the data for a particular field.
* @param fieldEnum The field enumerator identifying the field.
* @return The plot range enclosing the data.
**/
-(CPPlotRange *)plotRangeForField:(NSUInteger)fieldEnum
{
if ( self.dataNeedsReloading ) [self reloadData];
NSArray *numbers = [self cachedNumbersForField:fieldEnum];
NSNumber *min = [numbers valueForKeyPath:@"@min.self"];
NSNumber *max = [numbers valueForKeyPath:@"@max.self"];
NSDecimal length = CPDecimalSubtract([max decimalValue], [min decimalValue]);
return [CPPlotRange plotRangeWithLocation:[min decimalValue] length:length];
}
/** @brief Determines the smallest plot range that fully encloses the data for a particular coordinate.
* @param coord The coordinate identifier.
* @return The plot range enclosing the data.
**/
-(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coord
{
NSArray *fields = [self fieldIdentifiersForCoordinate:coord];
if ( fields.count == 0 ) return nil;
CPPlotRange *unionRange = [self plotRangeForField:[[fields lastObject] unsignedIntValue]];
for ( NSNumber *field in fields ) {
[unionRange unionPlotRange:[self plotRangeForField:field.unsignedIntValue]];
}
return unionRange;
}
#pragma mark -
#pragma mark Accessors
-(void)setDataSource:(id <CPPlotDataSource>)newSource
{
if ( newSource != dataSource ) {
dataSource = newSource;
self.dataNeedsReloading = YES;
[self setNeedsDisplay];
}
}
/** @brief Marks the receiver as needing the data source reloaded before the content is next drawn.
**/
-(void)setDataNeedsReloading
{
self.dataNeedsReloading = YES;
[self setNeedsDisplay];
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPPlot.m | Objective-C | bsd | 7,302 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
/// @file
CGPathRef CreateRoundedRectPath(CGRect rect, CGFloat cornerRadius);
void AddRoundedRectPath(CGContextRef context, CGRect rect, CGFloat cornerRadius); | 08iteng-ipad | systemtests/tests/Source/CPPathExtensions.h | Objective-C | bsd | 230 |
#import "CPAxis.h"
#import "CPPlotSpace.h"
#import "CPUtilities.h"
#import "CPPlotRange.h"
#import "CPLineStyle.h"
#import "CPTextStyle.h"
#import "CPTextLayer.h"
#import "CPAxisLabel.h"
#import "CPAxisTitle.h"
#import "CPPlatformSpecificCategories.h"
#import "CPUtilities.h"
#import "NSDecimalNumberExtensions.h"
/// @cond
@interface CPAxis ()
@property (nonatomic, readwrite, assign) BOOL needsRelabel;
-(void)tickLocationsBeginningAt:(NSDecimal)beginNumber increasing:(BOOL)increasing majorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations;
-(NSDecimal)nextLocationFromCoordinateValue:(NSDecimal)coord increasing:(BOOL)increasing interval:(NSDecimal)interval;
-(NSSet *)filteredTickLocations:(NSSet *)allLocations;
@end
/// @endcond
/** @brief An abstract axis class.
**/
@implementation CPAxis
/// @defgroup CPAxis CPAxis
/// @{
// Axis
/** @property axisLineStyle
* @brief The line style for the axis line.
* If nil, the line is not drawn.
**/
@synthesize axisLineStyle;
/** @property coordinate
* @brief The axis coordinate.
**/
@synthesize coordinate;
/** @property fixedPoint
* @brief The axis origin.
**/
@synthesize fixedPoint;
/** @property tickDirection
* @brief The tick direction.
**/
@synthesize tickDirection;
// Title
/** @property axisTitleTextStyle
* @brief The text style used to draw the axis title text.
**/
@synthesize axisTitleTextStyle;
/** @property axisTitle
* @brief The axis title.
* If nil, no title is drawn.
**/
@synthesize axisTitle;
/** @property axisTitleOffset
* @brief The offset distance between the axis title and the axis line.
**/
@synthesize axisTitleOffset;
/** @property title
* @brief A convenience property for setting the text title of the axis.
**/
@synthesize title;
// Plot space
/** @property plotSpace
* @brief The plot space for the axis.
**/
@synthesize plotSpace;
// Labels
/** @property axisLabelingPolicy
* @brief The axis labeling policy.
**/
@synthesize axisLabelingPolicy;
/** @property axisLabelOffset
* @brief The offset distance between the tick marks and labels.
**/
@synthesize axisLabelOffset;
/** @property axisLabelRotation
* @brief The rotation of the axis labels in radians.
* Set this property to M_PI/2.0 to have labels read up the screen, for example.
**/
@synthesize axisLabelRotation;
/** @property axisLabelTextStyle
* @brief The text style used to draw the label text.
**/
@synthesize axisLabelTextStyle;
/** @property axisLabelFormatter
* @brief The number formatter used to format the label text.
* If you need a non-numerical label, such as a date, you can use a formatter than turns
* the numerical plot coordinate into a string (eg 'Jan 10, 2010').
* The CPTimeFormatter is useful for this purpose.
**/
@synthesize axisLabelFormatter;
/** @property axisLabels
* @brief The set of axis labels.
**/
@synthesize axisLabels;
/** @property needsRelabel
* @brief If YES, the axis needs to be relabeled before the layer content is drawn.
**/
@synthesize needsRelabel;
/** @property labelExclusionRanges
* @brief An array of CPPlotRange objects. Any tick marks and labels falling inside any of the ranges in the array will not be drawn.
**/
@synthesize labelExclusionRanges;
/** @property delegate
* @brief The axis delegate.
**/
@synthesize delegate;
// Major ticks
/** @property majorIntervalLength
* @brief The distance between major tick marks expressed in data coordinates.
**/
@synthesize majorIntervalLength;
/** @property majorTickLineStyle
* @brief The line style for the major tick marks.
* If nil, the major ticks are not drawn.
**/
@synthesize majorTickLineStyle;
/** @property majorTickLength
* @brief The length of the major tick marks.
**/
@synthesize majorTickLength;
/** @property majorTickLocations
* @brief A set of axis coordinates for all major tick marks.
**/
@synthesize majorTickLocations;
/** @property preferredNumberOfMajorTicks
* @brief The number of ticks that should be targeted when autogenerating positions.
* This property only applies when the CPAxisLabelingPolicyAutomatic policy is in use.
**/
@synthesize preferredNumberOfMajorTicks;
// Minor ticks
/** @property minorTicksPerInterval
* @brief The number of minor tick marks drawn in each major tick interval.
**/
@synthesize minorTicksPerInterval;
/** @property minorTickLineStyle
* @brief The line style for the minor tick marks.
* If nil, the minor ticks are not drawn.
**/
@synthesize minorTickLineStyle;
/** @property minorTickLength
* @brief The length of the minor tick marks.
**/
@synthesize minorTickLength;
/** @property minorTickLocations
* @brief A set of axis coordinates for all minor tick marks.
**/
@synthesize minorTickLocations;
// Grid Lines
/** @property majorGridLineStyle
* @brief The line style for the major grid lines.
* If nil, the major grid lines are not drawn.
**/
@synthesize majorGridLineStyle;
/** @property minorGridLineStyle
* @brief The line style for the minor grid lines.
* If nil, the minor grid lines are not drawn.
**/
@synthesize minorGridLineStyle;
#pragma mark -
#pragma mark Init/Dealloc
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
plotSpace = nil;
majorTickLocations = [[NSArray array] retain];
minorTickLocations = [[NSArray array] retain];
preferredNumberOfMajorTicks = 5;
minorTickLength = 3.f;
majorTickLength = 5.f;
axisLabelOffset = 2.f;
axisLabelRotation = 0.f;
axisTitleOffset = 30.0f;
axisLineStyle = [[CPLineStyle alloc] init];
majorTickLineStyle = [[CPLineStyle alloc] init];
minorTickLineStyle = [[CPLineStyle alloc] init];
majorGridLineStyle = nil;
minorGridLineStyle = nil;
fixedPoint = [[NSDecimalNumber zero] decimalValue];
majorIntervalLength = [[NSDecimalNumber one] decimalValue];
minorTicksPerInterval = 1;
coordinate = CPCoordinateX;
axisLabelingPolicy = CPAxisLabelingPolicyFixedInterval;
axisLabelTextStyle = [[CPTextStyle alloc] init];
NSNumberFormatter *newFormatter = [[NSNumberFormatter alloc] init];
newFormatter.minimumIntegerDigits = 1;
newFormatter.maximumFractionDigits = 1;
newFormatter.minimumFractionDigits = 1;
axisLabelFormatter = newFormatter;
axisLabels = [[NSSet set] retain];
tickDirection = CPSignNone;
axisTitle = nil;
axisTitleTextStyle = [[CPTextStyle alloc] init];
needsRelabel = YES;
labelExclusionRanges = nil;
delegate = nil;
}
return self;
}
-(void)dealloc
{
[plotSpace release];
[majorTickLocations release];
[minorTickLocations release];
[axisLineStyle release];
[majorTickLineStyle release];
[minorTickLineStyle release];
[majorGridLineStyle release];
[minorGridLineStyle release];
[axisLabelFormatter release];
[axisLabels release];
[axisLabelTextStyle release];
[axisTitleTextStyle release];
[labelExclusionRanges release];
[super dealloc];
}
#pragma mark -
#pragma mark Ticks
-(NSDecimal)nextLocationFromCoordinateValue:(NSDecimal)coord increasing:(BOOL)increasing interval:(NSDecimal)interval
{
if ( increasing ) {
return CPDecimalAdd(coord, interval);
} else {
return CPDecimalSubtract(coord, interval);
}
}
-(void)tickLocationsBeginningAt:(NSDecimal)beginNumber increasing:(BOOL)increasing majorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations
{
NSMutableSet *majorLocations = [NSMutableSet set];
NSMutableSet *minorLocations = [NSMutableSet set];
NSDecimal majorInterval = self.majorIntervalLength;
NSDecimal coord = beginNumber;
CPPlotRange *range = [self.plotSpace plotRangeForCoordinate:self.coordinate];
while ( (increasing && CPDecimalLessThanOrEqualTo(coord, range.end)) || (!increasing && CPDecimalGreaterThanOrEqualTo(coord, range.location)) ) {
// Major tick
if ( CPDecimalLessThanOrEqualTo(coord, range.end) && CPDecimalGreaterThanOrEqualTo(coord, range.location) ) {
[majorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:coord]];
}
// Minor ticks
if ( self.minorTicksPerInterval > 0 ) {
NSDecimal minorInterval = CPDecimalDivide(majorInterval, CPDecimalFromInt(self.minorTicksPerInterval+1));
NSDecimal minorCoord;
minorCoord = [self nextLocationFromCoordinateValue:coord increasing:increasing interval:minorInterval];
for ( NSUInteger minorTickIndex = 0; minorTickIndex < self.minorTicksPerInterval; minorTickIndex++) {
if ( CPDecimalLessThanOrEqualTo(minorCoord, range.end) && CPDecimalGreaterThanOrEqualTo(minorCoord, range.location)) {
[minorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:minorCoord]];
}
minorCoord = [self nextLocationFromCoordinateValue:minorCoord increasing:increasing interval:minorInterval];
}
}
coord = [self nextLocationFromCoordinateValue:coord increasing:increasing interval:majorInterval];
}
*newMajorLocations = majorLocations;
*newMinorLocations = minorLocations;
}
-(void)autoGenerateMajorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations
{
NSMutableSet *majorLocations = [NSMutableSet setWithCapacity:preferredNumberOfMajorTicks];
NSMutableSet *minorLocations = [NSMutableSet setWithCapacity:(preferredNumberOfMajorTicks + 1) * minorTicksPerInterval];
if ( preferredNumberOfMajorTicks == 0 ) {
*newMajorLocations = majorLocations;
*newMinorLocations = minorLocations;
return;
}
// Determine starting interval
NSUInteger numTicks = preferredNumberOfMajorTicks;
CPPlotRange *range = [self.plotSpace plotRangeForCoordinate:self.coordinate];
NSUInteger numIntervals = MAX( 1, (NSInteger)numTicks - 1 );
NSDecimalNumber *rangeLength = [NSDecimalNumber decimalNumberWithDecimal:range.length];
NSDecimalNumber *interval = [rangeLength decimalNumberByDividingBy:
(NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:numIntervals]];
// Determine round number using the NSString with scientific format of numbers
NSString *intervalString = [NSString stringWithFormat:@"%e", [interval doubleValue]];
NSScanner *numberScanner = [NSScanner scannerWithString:intervalString];
NSInteger firstDigit;
[numberScanner scanInteger:&firstDigit];
// Ignore decimal part of scientific number
[numberScanner scanUpToString:@"e" intoString:nil];
[numberScanner scanString:@"e" intoString:nil];
// Scan the exponent
NSInteger exponent;
[numberScanner scanInteger:&exponent];
// Set interval which has been rounded. Make sure it is not zero.
interval = [NSDecimalNumber decimalNumberWithMantissa:MAX(1,firstDigit) exponent:exponent isNegative:NO];
// Determine how many points there should be now
NSDecimalNumber *numPointsDecimal = [rangeLength decimalNumberByDividingBy:interval];
NSInteger numPoints = [numPointsDecimal integerValue];
// Find first location
NSDecimalNumber *rangeLocation = [NSDecimalNumber decimalNumberWithDecimal:range.location];
NSInteger firstPointMultiple = [[rangeLocation decimalNumberByDividingBy:interval] integerValue];
NSDecimalNumber *pointLocation = [interval decimalNumberByMultiplyingBy:(NSDecimalNumber *)[NSDecimalNumber numberWithInteger:firstPointMultiple]];
if ( firstPointMultiple >= 0 && ![rangeLocation isEqualToNumber:pointLocation] ) {
firstPointMultiple++;
pointLocation = [interval decimalNumberByMultiplyingBy:(NSDecimalNumber *)[NSDecimalNumber numberWithInteger:firstPointMultiple]];
}
// Determine all locations
NSInteger majorIndex;
NSDecimalNumber *minorInterval = nil;
if ( minorTicksPerInterval > 0 ) minorInterval = [interval decimalNumberByDividingBy:
(NSDecimalNumber *)[NSDecimalNumber numberWithInteger:minorTicksPerInterval+1]];
for ( majorIndex = 0; majorIndex < numPoints; majorIndex++ ) {
// Major ticks
[majorLocations addObject:pointLocation];
pointLocation = [pointLocation decimalNumberByAdding:interval];
// Minor ticks
if ( !minorInterval ) continue;
NSInteger minorIndex;
NSDecimalNumber *minorLocation = [pointLocation decimalNumberByAdding:minorInterval];
for ( minorIndex = 0; minorIndex < minorTicksPerInterval; minorIndex++ ) {
[minorLocations addObject:minorLocation];
minorLocation = [minorLocation decimalNumberByAdding:minorInterval];
}
}
*newMajorLocations = majorLocations;
*newMinorLocations = minorLocations;
}
#pragma mark -
#pragma mark Labels
/** @brief Creates new axis labels at the given locations.
* @param locations An array of NSDecimalNumber label locations.
* @return An array of CPAxisLabels positioned at the given locations.
**/
-(NSArray *)newAxisLabelsAtLocations:(NSArray *)locations
{
NSMutableArray *newLabels = [[NSMutableArray alloc] initWithCapacity:locations.count];
for ( NSDecimalNumber *tickLocation in locations ) {
NSString *labelString = [self.axisLabelFormatter stringForObjectValue:tickLocation];
CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText:labelString textStyle:self.axisLabelTextStyle];
newLabel.tickLocation = [tickLocation decimalValue];
newLabel.rotation = self.axisLabelRotation;
switch ( self.tickDirection ) {
case CPSignNone:
newLabel.offset = self.axisLabelOffset + self.majorTickLength / 2.0f;
break;
case CPSignPositive:
case CPSignNegative:
newLabel.offset = self.axisLabelOffset + self.majorTickLength;
break;
}
[newLabels addObject:newLabel];
[newLabel release];
}
return newLabels;
}
/** @brief Calculates the optimal location of the axis title, in axis units.
**/
-(NSDecimal)axisTitleLocation
{
return CPDecimalFromFloat(0.0f);
}
/** @brief Marks the receiver as needing to update the labels before the content is next drawn.
**/
-(void)setNeedsRelabel
{
self.needsRelabel = YES;
}
/** @brief Updates the axis labels.
**/
-(void)relabel
{
if (!self.needsRelabel) return;
if (!self.plotSpace) return;
if ( self.delegate && ![self.delegate axisShouldRelabel:self] ) {
self.needsRelabel = NO;
return;
}
NSMutableSet *allNewMajorLocations = [NSMutableSet set];
NSMutableSet *allNewMinorLocations = [NSMutableSet set];
NSSet *newMajorLocations, *newMinorLocations;
switch (self.axisLabelingPolicy) {
case CPAxisLabelingPolicyNone:
case CPAxisLabelingPolicyLocationsProvided:
// Assume locations are set by user
allNewMajorLocations = [[self.majorTickLocations mutableCopy] autorelease];
allNewMinorLocations = [[self.minorTickLocations mutableCopy] autorelease];
break;
case CPAxisLabelingPolicyFixedInterval:
// Add ticks in negative direction
[self tickLocationsBeginningAt:self.fixedPoint increasing:NO majorTickLocations:&newMajorLocations minorTickLocations:&newMinorLocations];
[allNewMajorLocations unionSet:newMajorLocations];
[allNewMinorLocations unionSet:newMinorLocations];
// Add ticks in positive direction
[self tickLocationsBeginningAt:self.fixedPoint increasing:YES majorTickLocations:&newMajorLocations minorTickLocations:&newMinorLocations];
[allNewMajorLocations unionSet:newMajorLocations];
[allNewMinorLocations unionSet:newMinorLocations];
break;
case CPAxisLabelingPolicyAutomatic:
[self autoGenerateMajorTickLocations:&newMajorLocations minorTickLocations:&newMinorLocations];
[allNewMajorLocations unionSet:newMajorLocations];
[allNewMinorLocations unionSet:newMinorLocations];
break;
case CPAxisLabelingPolicyLogarithmic:
// TODO: logarithmic labeling policy
break;
}
if ( self.axisLabelingPolicy != CPAxisLabelingPolicyNone &&
self.axisLabelingPolicy != CPAxisLabelingPolicyLocationsProvided ) {
// Filter and set tick locations
self.majorTickLocations = [self filteredMajorTickLocations:allNewMajorLocations];
self.minorTickLocations = [self filteredMinorTickLocations:allNewMinorLocations];
}
if ( self.axisLabelingPolicy != CPAxisLabelingPolicyNone ) {
// Label ticks
NSArray *newLabels = [self newAxisLabelsAtLocations:self.majorTickLocations.allObjects];
self.axisLabels = [NSSet setWithArray:newLabels];
[newLabels release];
}
self.needsRelabel = NO;
[self.delegate axisDidRelabel:self];
}
-(NSSet *)filteredTickLocations:(NSSet *)allLocations
{
NSMutableSet *filteredLocations = [allLocations mutableCopy];
for ( CPPlotRange *range in self.labelExclusionRanges ) {
for ( NSDecimalNumber *location in allLocations ) {
if ( [range contains:[location decimalValue]] ) [filteredLocations removeObject:location];
}
}
return [filteredLocations autorelease];
}
/** @brief Removes any major ticks falling inside the label exclusion ranges from the set of tick locations.
* @param allLocations A set of major tick locations.
* @return The filted set.
**/
-(NSSet *)filteredMajorTickLocations:(NSSet *)allLocations
{
return [self filteredTickLocations:allLocations];
}
/** @brief Removes any minor ticks falling inside the label exclusion ranges from the set of tick locations.
* @param allLocations A set of minor tick locations.
* @return The filted set.
**/
-(NSSet *)filteredMinorTickLocations:(NSSet *)allLocations
{
return [self filteredTickLocations:allLocations];
}
#pragma mark -
#pragma mark Sublayer Layout
+(CGFloat)defaultZPosition
{
return CPDefaultZPositionAxis;
}
-(void)layoutSublayers
{
if ( self.needsRelabel ) [self relabel];
for ( CPAxisLabel *label in self.axisLabels ) {
CGPoint tickBasePoint = [self viewPointForCoordinateDecimalNumber:label.tickLocation];
[label positionRelativeToViewPoint:tickBasePoint forCoordinate:CPOrthogonalCoordinate(self.coordinate) inDirection:self.tickDirection];
}
NSDecimal axisTitleLocation = [self axisTitleLocation];
[axisTitle positionRelativeToViewPoint:[self viewPointForCoordinateDecimalNumber:axisTitleLocation] forCoordinate:CPOrthogonalCoordinate(self.coordinate) inDirection:self.tickDirection];
}
#pragma mark -
#pragma mark Accessors
-(void)setAxisLabels:(NSSet *)newLabels
{
if ( newLabels != axisLabels ) {
for ( CPAxisLabel *label in axisLabels ) {
[label.contentLayer removeFromSuperlayer];
}
[newLabels retain];
[axisLabels release];
axisLabels = newLabels;
for ( CPAxisLabel *label in axisLabels ) {
[self addSublayer:label.contentLayer];
}
[self setNeedsDisplay];
}
}
-(void)setAxisLabelTextStyle:(CPTextStyle *)newStyle
{
if ( newStyle != axisLabelTextStyle ) {
[axisLabelTextStyle release];
axisLabelTextStyle = [newStyle copy];
[self setNeedsLayout];
}
}
-(void)setAxisTitle:(CPAxisTitle *)newTitle;
{
if (newTitle != axisTitle)
{
[axisTitle.contentLayer removeFromSuperlayer];
[axisTitle release];
axisTitle = [newTitle retain];
axisTitle.offset = self.axisTitleOffset;
[self addSublayer:axisTitle.contentLayer];
}
}
-(void)setAxisTitleTextStyle:(CPTextStyle *)newStyle
{
if ( newStyle != axisTitleTextStyle ) {
[axisTitleTextStyle release];
axisTitleTextStyle = [newStyle copy];
[self setNeedsLayout];
}
}
-(void)setAxisTitleOffset:(CGFloat)newOffset
{
if ( newOffset != axisTitleOffset ) {
axisTitleOffset = newOffset;
self.axisTitle.offset = axisTitleOffset;
[self setNeedsLayout];
}
}
- (void)setTitle:(NSString *)newTitle
{
if (newTitle != title) {
[title release];
title = [newTitle retain];
if (axisTitle == nil) {
CPAxisTitle *newAxisTitle = [[CPAxisTitle alloc] initWithText:title textStyle:self.axisTitleTextStyle];
self.axisTitle = newAxisTitle;
[newAxisTitle release];
}
else {
[(CPTextLayer *)self.axisTitle.contentLayer setText:title];
}
[self setNeedsLayout]; }
}
-(void)setLabelExclusionRanges:(NSArray *)ranges
{
if ( ranges != labelExclusionRanges ) {
[labelExclusionRanges release];
labelExclusionRanges = [ranges retain];
[self setNeedsRelabel];
}
}
-(void)setNeedsRelabel:(BOOL)newNeedsRelabel
{
if (newNeedsRelabel != needsRelabel) {
needsRelabel = newNeedsRelabel;
if ( needsRelabel ) {
[self setNeedsLayout];
}
}
}
-(void)setMajorTickLocations:(NSSet *)newLocations
{
if ( newLocations != majorTickLocations ) {
[majorTickLocations release];
majorTickLocations = [newLocations retain];
[self setNeedsDisplay];
self.needsRelabel = YES;
}
}
-(void)setMinorTickLocations:(NSSet *)newLocations
{
if ( newLocations != majorTickLocations ) {
[minorTickLocations release];
minorTickLocations = [newLocations retain];
[self setNeedsDisplay];
self.needsRelabel = YES;
}
}
-(void)setMajorTickLength:(CGFloat)newLength
{
if ( newLength != majorTickLength ) {
majorTickLength = newLength;
[self setNeedsDisplay];
self.needsRelabel = YES;
}
}
-(void)setMinorTickLength:(CGFloat)newLength
{
if ( newLength != minorTickLength ) {
minorTickLength = newLength;
[self setNeedsDisplay];
}
}
-(void)setAxisLabelOffset:(CGFloat)newOffset
{
if ( newOffset != axisLabelOffset ) {
axisLabelOffset = newOffset;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setAxisLabelRotation:(CGFloat)newRotation
{
if ( newRotation != axisLabelRotation ) {
axisLabelRotation = newRotation;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setPlotSpace:(CPPlotSpace *)newSpace
{
if ( newSpace != plotSpace ) {
[plotSpace release];
plotSpace = [newSpace retain];
self.needsRelabel = YES;
}
}
-(void)setCoordinate:(CPCoordinate)newCoordinate
{
if (newCoordinate != coordinate) {
coordinate = newCoordinate;
self.needsRelabel = YES;
}
}
-(void)setAxisLineStyle:(CPLineStyle *)newLineStyle
{
if ( newLineStyle != axisLineStyle ) {
[axisLineStyle release];
axisLineStyle = [newLineStyle copy];
[self setNeedsDisplay];
}
}
-(void)setMajorTickLineStyle:(CPLineStyle *)newLineStyle
{
if ( newLineStyle != majorTickLineStyle ) {
[majorTickLineStyle release];
majorTickLineStyle = [newLineStyle copy];
[self setNeedsDisplay];
}
}
-(void)setMinorTickLineStyle:(CPLineStyle *)newLineStyle
{
if ( newLineStyle != minorTickLineStyle ) {
[minorTickLineStyle release];
minorTickLineStyle = [newLineStyle copy];
[self setNeedsDisplay];
}
}
-(void)setFixedPoint:(NSDecimal)newFixedPoint
{
if (CPDecimalEquals(fixedPoint, newFixedPoint)) {
return;
}
fixedPoint = newFixedPoint;
self.needsRelabel = YES;
}
-(void)setMajorIntervalLength:(NSDecimal)newIntervalLength
{
if (CPDecimalEquals(majorIntervalLength, newIntervalLength)) {
return;
}
majorIntervalLength = newIntervalLength;
self.needsRelabel = YES;
}
-(void)setMinorTicksPerInterval:(NSUInteger)newMinorTicksPerInterval
{
if (newMinorTicksPerInterval != minorTicksPerInterval) {
minorTicksPerInterval = newMinorTicksPerInterval;
self.needsRelabel = YES;
}
}
-(void)setAxisLabelingPolicy:(CPAxisLabelingPolicy)newPolicy
{
if (newPolicy != axisLabelingPolicy) {
axisLabelingPolicy = newPolicy;
self.needsRelabel = YES;
}
}
-(void)setAxisLabelFormatter:(NSNumberFormatter *)newTickLabelFormatter
{
if ( newTickLabelFormatter != axisLabelFormatter ) {
[axisLabelFormatter release];
axisLabelFormatter = [newTickLabelFormatter retain];
self.needsRelabel = YES;
}
}
-(void)setTickDirection:(CPSign)newDirection
{
if (newDirection != tickDirection) {
tickDirection = newDirection;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
/// @}
@end
#pragma mark -
/// @brief CPAxis abstract methods—must be overridden by subclasses
@implementation CPAxis(AbstractMethods)
/// @addtogroup CPAxis
/// @{
/** @brief Converts a position on the axis to drawing coordinates.
* @param coordinateDecimalNumber The axis value in data coordinate space.
* @return The drawing coordinates of the point.
**/
-(CGPoint)viewPointForCoordinateDecimalNumber:(NSDecimal)coordinateDecimalNumber
{
return CGPointMake(0.0f, 0.0f);
}
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPAxis.m | Objective-C | bsd | 24,552 |
#import "CPTestCase.h"
@interface CPThemeTests : CPTestCase {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPThemeTests.h | Objective-C | bsd | 72 |
#import "CPTestCase.h"
@interface CPTextStyleTests : CPTestCase {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPTextStyleTests.h | Objective-C | bsd | 76 |
#import "CPLayoutManager.h"
| 08iteng-ipad | systemtests/tests/Source/CPLayoutManager.m | Objective-C | bsd | 28 |
#import "CPAxisLabelTests.h"
#import "CPAxisLabel.h"
#import "CPTextStyle.h"
#import "CPFill.h"
#import "CPBorderedLayer.h"
#import "CPColor.h"
#import "CPExceptions.h"
@implementation CPAxisLabelTests
- (void)testRenderText
{
CPAxisLabel *label;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testRenderText" textStyle:[CPTextStyle textStyle]];
label.offset = 20.0f;
GTMAssertObjectImageEqualToImageNamed(label, @"CPAxisLabelTests-testRenderText", @"");
}
@finally {
[label release];
}
}
- (void)testRenderContentLayer
{
CPAxisLabel *label;
@try {
CPBorderedLayer *contentLayer = [CPBorderedLayer layer];
contentLayer.fill = [CPFill fillWithColor:[CPColor blueColor]];
contentLayer.bounds = CGRectMake(0, 0, 20, 20);
label = [[CPAxisLabel alloc] initWithContentLayer:contentLayer];
label.offset = 20.0f;
GTMAssertObjectImageEqualToImageNamed(label, @"CPAxisLabelTests-testRenderContentLayer", @"");
}
@finally {
[label release];
}
}
- (void)testPositionRelativeToViewPointRaisesForInvalidDirection
{
CPAxisLabel *label;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionRelativeToViewPointRaisesForInvalidDirection" textStyle:[CPTextStyle textStyle]];
STAssertThrowsSpecificNamed([label positionRelativeToViewPoint:CGPointZero forCoordinate:CPCoordinateX inDirection:INT_MAX], NSException, CPException, @"Should raise CPException for invalid direction (type CPSign)");
}
@finally {
[label release];
}
}
- (void)testPositionBetweenViewPointImplemented
{
CPAxisLabel *label;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionBetweenViewPointImplemented" textStyle:[CPTextStyle textStyle]];
STAssertNoThrow([label positionBetweenViewPoint:CGPointZero andViewPoint:CGPointMake(1.0, 1.0) forCoordinate:CPCoordinateX inDirection:CPSignNone], @"Current implementation throws CPException. When implemented, revise this test");
}
@finally {
[label release];
}
}
- (void)testPositionRelativeToViewPointPositionsForXCoordinate
{
CPAxisLabel *label;
CGFloat start = 100.0f;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionRelativeToViewPointPositionsForXCoordinate" textStyle:[CPTextStyle textStyle]];
CPLayer *contentLayer = label.contentLayer;
label.offset = 20.0f;
CGPoint viewPoint = CGPointMake(start, start);
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateX
inDirection:CPSignNone];
STAssertEquals(contentLayer.position, CGPointMake(start-label.offset, start), @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSMakePoint(start-label.offset, start)));
STAssertEquals(contentLayer.anchorPoint, CGPointMake(1.0, 0.5), @"Should anchor at (1.0,0.5)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateX
inDirection:CPSignNegative];
STAssertEquals(contentLayer.position, CGPointMake(start-label.offset, start), @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSMakePoint(start-label.offset, start)));
STAssertEquals(contentLayer.anchorPoint, CGPointMake(1.0, 0.5), @"Should anchor at (1.0,0.5)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateX
inDirection:CPSignPositive];
STAssertEquals(contentLayer.position, CGPointMake(start+label.offset, start), @"Should add positive offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSMakePoint(start+label.offset, start)));
STAssertEquals(contentLayer.anchorPoint, CGPointMake(0., 0.5), @"Should anchor at (0,0.5)");
}
@finally {
[label release];
}
}
- (void)testPositionRelativeToViewPointPositionsForYCoordinate
{
CPAxisLabel *label;
CGFloat start = 100.0f;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionRelativeToViewPointPositionsForYCoordinate" textStyle:[CPTextStyle textStyle]];
CPLayer *contentLayer = label.contentLayer;
label.offset = 20.0f;
CGPoint viewPoint = CGPointMake(start,start);
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateY
inDirection:CPSignNone];
STAssertEquals(contentLayer.position, CGPointMake(start, start-label.offset), @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSMakePoint(start, start-label.offset)));
STAssertEquals(contentLayer.anchorPoint, CGPointMake(0.5, 1.0), @"Should anchor at (0.5,1.0)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateY
inDirection:CPSignNegative];
STAssertEquals(contentLayer.position, CGPointMake(start, start-label.offset), @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSMakePoint(start, start-label.offset)));
STAssertEquals(contentLayer.anchorPoint, CGPointMake(0.5, 1.0), @"Should anchor at (0.5,1.0)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateY
inDirection:CPSignPositive];
STAssertEquals(contentLayer.position, CGPointMake(start, start+label.offset), @"Should add positive offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSMakePoint(start, start+label.offset)));
STAssertEquals(contentLayer.anchorPoint, CGPointMake(0.5, 0.), @"Should anchor at (0.5,0)");
}
@finally {
[label release];
}
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPAxisLabelTests.m | Objective-C | bsd | 6,982 |
#import <Foundation/Foundation.h>
#import "CPPlot.h"
#import "CPDefinitions.h"
/// @file
@class CPLineStyle;
@class CPFill;
@class CPPlotRange;
@class CPColor;
@class CPBarPlot;
/// @name Binding Identifiers
/// @{
extern NSString * const CPBarPlotBindingBarLengths;
/// @}
/** @brief Enumeration of bar plot data source field types
**/
typedef enum _CPBarPlotField {
CPBarPlotFieldBarLocation, ///< Bar location on independent coordinate axis.
CPBarPlotFieldBarLength ///< Bar length.
} CPBarPlotField;
/** @brief A bar plot data source.
**/
@protocol CPBarPlotDataSource <CPPlotDataSource>
@optional
/** @brief Gets a bar fill for the given bar plot. This method is optional.
* @param barPlot The bar plot.
* @param index The data index of interest.
* @return The bar fill for the point with the given index.
**/
-(CPFill *)barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSUInteger)index;
@end
@interface CPBarPlot : CPPlot {
@private
id observedObjectForBarLengthValues;
NSString *keyPathForBarLengthValues;
CPLineStyle *lineStyle;
CPFill *fill;
CGFloat barWidth;
CGFloat barOffset;
CGFloat cornerRadius;
NSDecimal baseValue; // TODO: NSDecimal instance variables in CALayers cause an unhandled property type encoding error
double doublePrecisionBaseValue;
NSArray *barLengths;
BOOL barsAreHorizontal;
CPPlotRange *plotRange;
}
@property (nonatomic, readwrite, assign) CGFloat barWidth;
@property (nonatomic, readwrite, assign) CGFloat barOffset; // In units of bar width
@property (nonatomic, readwrite, assign) CGFloat cornerRadius;
@property (nonatomic, readwrite, copy) CPLineStyle *lineStyle;
@property (nonatomic, readwrite, copy) CPFill *fill;
@property (nonatomic, readwrite, assign) BOOL barsAreHorizontal;
@property (nonatomic, readwrite) NSDecimal baseValue;
@property (nonatomic, readwrite) double doublePrecisionBaseValue;
@property (nonatomic, readwrite, copy) CPPlotRange *plotRange;
/// @name Factory Methods
/// @{
+(CPBarPlot *)tubularBarPlotWithColor:(CPColor *)color horizontalBars:(BOOL)horizontal;
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPBarPlot.h | Objective-C | bsd | 2,122 |
#import "CPPathExtensions.h"
/** @brief Creates a rectangular path with rounded corners.
*
* @param rect The bounding rectangle for the path.
* @param cornerRadius The radius of the rounded corners.
* @return The new path. Caller is responsible for releasing this.
**/
CGPathRef CreateRoundedRectPath(CGRect rect, CGFloat cornerRadius)
{
// In order to draw a rounded rectangle, we will take advantage of the fact that
// CGPathAddArcToPoint will draw straight lines past the start and end of the arc
// in order to create the path from the current position and the destination position.
CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect);
CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy = CGRectGetMaxY(rect);
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, minx + 0.5f, midy + 0.5f);
CGPathAddArcToPoint(path, NULL, minx + 0.5f, miny + 0.5f, midx + 0.5f, miny + 0.5f, cornerRadius);
CGPathAddArcToPoint(path, NULL, maxx + 0.5f, miny + 0.5f, maxx + 0.5f, midy + 0.5f, cornerRadius);
CGPathAddArcToPoint(path, NULL, maxx + 0.5f, maxy + 0.5f, midx + 0.5f, maxy + 0.5f, cornerRadius);
CGPathAddArcToPoint(path, NULL, minx + 0.5f, maxy + 0.5f, minx + 0.5f, midy + 0.5f, cornerRadius);
CGPathCloseSubpath(path);
return path;
}
/** @brief Adds a rectangular path with rounded corners to a graphics context.
*
* @param context The graphics context.
* @param rect The bounding rectangle for the path.
* @param cornerRadius The radius of the rounded corners.
**/
void AddRoundedRectPath(CGContextRef context, CGRect rect, CGFloat cornerRadius)
{
CGPathRef path = CreateRoundedRectPath(rect, cornerRadius);
CGContextAddPath(context, path);
CGPathRelease(path);
}
| 08iteng-ipad | systemtests/tests/Source/CPPathExtensions.m | Objective-C | bsd | 1,809 |
#import <Foundation/Foundation.h>
#import "CPLineStyle.h"
#import "CPFill.h"
#import "CPPlotSymbol.h"
/// @cond
@interface CPPlotSymbol()
-(void)setSymbolPath;
@end
/// @endcond
#pragma mark -
/** @brief Plot symbols for CPScatterPlot.
*/
@implementation CPPlotSymbol
/** @property size
* @brief The symbol size.
**/
@synthesize size;
/** @property symbolType
* @brief The symbol type.
**/
@synthesize symbolType;
/** @property lineStyle
* @brief The line style for the border of the symbol.
* If nil, the border is not drawn.
**/
@synthesize lineStyle;
/** @property fill
* @brief The fill for the interior of the symbol.
* If nil, the symbol is not filled.
**/
@synthesize fill;
/** @property customSymbolPath
* @brief The drawing path for a custom plot symbol. It will be scaled to size before being drawn.
**/
@synthesize customSymbolPath;
/** @property usesEvenOddClipRule
* @brief If YES, the even-odd rule is used to draw the symbol, otherwise the nonzero winding number rule is used.
* @see <a href="http://developer.apple.com/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_paths/dq_paths.html#//apple_ref/doc/uid/TP30001066-CH211-TPXREF106">Filling a Path</a> in the Quartz 2D Programming Guide.
**/
@synthesize usesEvenOddClipRule;
#pragma mark -
#pragma mark Init/dealloc
-(id)init
{
if ( self = [super init] ) {
size = CGSizeMake(5.0, 5.0);
symbolType = CPPlotSymbolTypeNone;
lineStyle = [[CPLineStyle alloc] init];
fill = nil;
symbolPath = NULL;
customSymbolPath = NULL;
usesEvenOddClipRule = NO;
}
return self;
}
-(void)dealloc
{
[lineStyle release];
[fill release];
CGPathRelease(symbolPath);
CGPathRelease(customSymbolPath);
[super dealloc];
}
#pragma mark -
#pragma mark Accessors
-(void)setSize:(CGSize)aSize
{
size = aSize;
[self setSymbolPath];
}
-(void)setSymbolType:(CPPlotSymbolType)theType
{
symbolType = theType;
[self setSymbolPath];
}
-(void)setCustomSymbolPath:(CGPathRef)aPath {
if (customSymbolPath != aPath) {
CGPathRelease(customSymbolPath);
customSymbolPath = CGPathRetain(aPath);
[self setSymbolPath];
}
}
#pragma mark -
#pragma mark Class methods
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeNone.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeNone.
**/
+(CPPlotSymbol *)plotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeNone;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeCross.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeCross.
**/
+(CPPlotSymbol *)crossPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeCross;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeEllipse.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeEllipse.
**/
+(CPPlotSymbol *)ellipsePlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeEllipse;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeRectangle.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeRectangle.
**/
+(CPPlotSymbol *)rectanglePlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeRectangle;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypePlus.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypePlus.
**/
+(CPPlotSymbol *)plusPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypePlus;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeStar.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeStar.
**/
+(CPPlotSymbol *)starPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeStar;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeDiamond.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeDiamond.
**/
+(CPPlotSymbol *)diamondPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeDiamond;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeTriangle.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeTriangle.
**/
+(CPPlotSymbol *)trianglePlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeTriangle;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypePentagon.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypePentagon.
**/
+(CPPlotSymbol *)pentagonPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypePentagon;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeHexagon.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeHexagon.
**/
+(CPPlotSymbol *)hexagonPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeHexagon;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeDash.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeDash.
**/
+(CPPlotSymbol *)dashPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeDash;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeSnow.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeSnow.
**/
+(CPPlotSymbol *)snowPlotSymbol
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeSnow;
return [symbol autorelease];
}
/** @brief Creates and returns a new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeCustom.
* @param aPath The bounding path for the custom symbol.
* @return A new CPPlotSymbol instance initialized with a symbol type of CPPlotSymbolTypeCustom.
**/
+(CPPlotSymbol *)customPlotSymbolWithPath:(CGPathRef)aPath
{
CPPlotSymbol *symbol = [[self alloc] init];
symbol.symbolType = CPPlotSymbolTypeCustom;
symbol.customSymbolPath = aPath;
return [symbol autorelease];
}
// +(CPPlotSymbol *)plotSymbolWithString:(NSString *)aString;
#pragma mark -
#pragma mark NSCopying methods
-(id)copyWithZone:(NSZone *)zone
{
CPPlotSymbol *copy = [[[self class] allocWithZone:zone] init];
copy.size = self.size;
copy.symbolType = self.symbolType;
copy.usesEvenOddClipRule = self.usesEvenOddClipRule;
copy.lineStyle = [[self.lineStyle copy] autorelease];
copy.fill = [[self.fill copy] autorelease];
if (self.customSymbolPath) {
CGPathRef pathCopy = CGPathCreateCopy(self.customSymbolPath);
copy.customSymbolPath = pathCopy;
CGPathRelease(pathCopy);
}
return copy;
}
#pragma mark -
#pragma mark Drawing
/** @brief Draws the plot symbol into the given graphics context centered at the provided point.
* @param theContext The graphics context to draw into.
* @param center The center point of the symbol.
**/
-(void)renderInContext:(CGContextRef)theContext atPoint:(CGPoint)center
{
if (self.symbolType != CPPlotSymbolTypeNone) {
if (self.lineStyle || self.fill) {
CGContextSaveGState(theContext);
CGContextTranslateCTM(theContext, center.x, center.y);
if (self.fill) {
// use fillRect instead of fillPath so that images and gradients are properly centered in the symbol
CGSize symbolSize = self.size;
CGSize halfSize = CGSizeMake(symbolSize.width / 2.0, symbolSize.height / 2.0);
CGRect bounds = CGRectMake(-halfSize.width, -halfSize.height, symbolSize.width, symbolSize.height);
CGContextSaveGState(theContext);
CGContextBeginPath(theContext);
CGContextAddPath(theContext, symbolPath);
if (self.usesEvenOddClipRule) {
CGContextEOClip(theContext);
} else {
CGContextClip(theContext);
}
[self.fill fillRect:bounds inContext:theContext];
CGContextRestoreGState(theContext);
}
if (self.lineStyle) {
[self.lineStyle setLineStyleInContext:theContext];
CGContextBeginPath(theContext);
CGContextAddPath(theContext, symbolPath);
CGContextStrokePath(theContext);
}
CGContextRestoreGState(theContext);
}
}
}
#pragma mark -
#pragma mark Private methods
/** @internal
* @brief Creates a drawing path for the selected symbol shape and stores it in symbolPath.
**/
-(void)setSymbolPath
{
CGFloat dx, dy;
CGSize symbolSize = self.size;
CGSize halfSize = CGSizeMake(symbolSize.width / 2.0, symbolSize.height / 2.0);
CGRect bounds = CGRectMake(-halfSize.width, -halfSize.height, symbolSize.width, symbolSize.height);
CGRect oldBounds = CGRectNull;
CGAffineTransform scaleTransform = CGAffineTransformIdentity;
CGPathRelease(symbolPath);
symbolPath = CGPathCreateMutable();
switch (self.symbolType) {
case CPPlotSymbolTypeRectangle:
CGPathAddRect(symbolPath, NULL, bounds);
break;
case CPPlotSymbolTypeEllipse:
CGPathAddEllipseInRect(symbolPath, NULL, bounds);
break;
case CPPlotSymbolTypeCross:
CGPathMoveToPoint(symbolPath, NULL, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
CGPathMoveToPoint(symbolPath, NULL, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
break;
case CPPlotSymbolTypePlus:
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, 0.0, CGRectGetMinY(bounds));
CGPathMoveToPoint(symbolPath, NULL, CGRectGetMinX(bounds), 0.0);
CGPathAddLineToPoint(symbolPath, NULL, CGRectGetMaxX(bounds), 0.0);
break;
case CPPlotSymbolTypePentagon:
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, halfSize.width * 0.95105651630, halfSize.height * 0.30901699437);
CGPathAddLineToPoint(symbolPath, NULL, halfSize.width * 0.58778525229, -halfSize.height * 0.80901699437);
CGPathAddLineToPoint(symbolPath, NULL, -halfSize.width * 0.58778525229, -halfSize.height * 0.80901699437);
CGPathAddLineToPoint(symbolPath, NULL, -halfSize.width * 0.95105651630, halfSize.height * 0.30901699437);
CGPathCloseSubpath(symbolPath);
break;
case CPPlotSymbolTypeStar:
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, halfSize.width * 0.22451398829, halfSize.height * 0.30901699437);
CGPathAddLineToPoint(symbolPath, NULL, halfSize.width * 0.95105651630, halfSize.height * 0.30901699437);
CGPathAddLineToPoint(symbolPath, NULL, halfSize.width * 0.36327126400, -halfSize.height * 0.11803398875);
CGPathAddLineToPoint(symbolPath, NULL, halfSize.width * 0.58778525229, -halfSize.height * 0.80901699437);
CGPathAddLineToPoint(symbolPath, NULL, 0.0 , -halfSize.height * 0.38196601125);
CGPathAddLineToPoint(symbolPath, NULL, -halfSize.width * 0.58778525229, -halfSize.height * 0.80901699437);
CGPathAddLineToPoint(symbolPath, NULL, -halfSize.width * 0.36327126400, -halfSize.height * 0.11803398875);
CGPathAddLineToPoint(symbolPath, NULL, -halfSize.width * 0.95105651630, halfSize.height * 0.30901699437);
CGPathAddLineToPoint(symbolPath, NULL, -halfSize.width * 0.22451398829, halfSize.height * 0.30901699437);
CGPathCloseSubpath(symbolPath);
break;
case CPPlotSymbolTypeDiamond:
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, CGRectGetMaxX(bounds), 0.0);
CGPathAddLineToPoint(symbolPath, NULL, 0.0, CGRectGetMinY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, CGRectGetMinX(bounds), 0.0);
CGPathCloseSubpath(symbolPath);
break;
case CPPlotSymbolTypeTriangle:
dx = halfSize.width * 0.86602540378; // sqrt(3.0) / 2.0;
dy = halfSize.height / 2.0;
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, dx, -dy);
CGPathAddLineToPoint(symbolPath, NULL, -dx, -dy);
CGPathCloseSubpath(symbolPath);
break;
case CPPlotSymbolTypeDash:
CGPathMoveToPoint(symbolPath, NULL, CGRectGetMinX(bounds), 0.0);
CGPathAddLineToPoint(symbolPath, NULL, CGRectGetMaxX(bounds), 0.0);
break;
case CPPlotSymbolTypeHexagon:
dx = halfSize.width * 0.86602540378; // sqrt(3.0) / 2.0;
dy = halfSize.height / 2.0;
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, dx, dy);
CGPathAddLineToPoint(symbolPath, NULL, dx, -dy);
CGPathAddLineToPoint(symbolPath, NULL, 0.0, CGRectGetMinY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, -dx, -dy);
CGPathAddLineToPoint(symbolPath, NULL, -dx, dy);
CGPathCloseSubpath(symbolPath);
break;
case CPPlotSymbolTypeSnow:
dx = halfSize.width * 0.86602540378; // sqrt(3.0) / 2.0;
dy = halfSize.height / 2.0;
CGPathMoveToPoint(symbolPath, NULL, 0.0, CGRectGetMaxY(bounds));
CGPathAddLineToPoint(symbolPath, NULL, 0.0, CGRectGetMinY(bounds));
CGPathMoveToPoint(symbolPath, NULL, dx, -dy);
CGPathAddLineToPoint(symbolPath, NULL, -dx, dy);
CGPathMoveToPoint(symbolPath, NULL, -dx, -dy);
CGPathAddLineToPoint(symbolPath, NULL, dx, dy);
break;
case CPPlotSymbolTypeCustom:
if (customSymbolPath) {
oldBounds = CGPathGetBoundingBox(customSymbolPath);
CGFloat dx1 = bounds.size.width / oldBounds.size.width;
CGFloat dy1 = bounds.size.height / oldBounds.size.height;
CGFloat f = dx1 < dy1 ? dx1 : dy1;
scaleTransform = CGAffineTransformScale(CGAffineTransformIdentity, f, f);
scaleTransform = CGAffineTransformConcat(scaleTransform,
CGAffineTransformMakeTranslation(-halfSize.width, -halfSize.height));
CGPathAddPath(symbolPath, &scaleTransform, customSymbolPath);
}
break;
}
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPPlotSymbol.m | Objective-C | bsd | 15,167 |
#import "CPTestCase.h"
#import "GTMNSObject+UnitTesting.h"
@implementation CPTestCase
- (void)invokeTest {
//set the saveTo directory to the $BUILT_PRODUCTS_DIR/CorePlot-UnitTest-Output
NSString *saveToPath = [[[NSProcessInfo processInfo] environment] objectForKey:@"BUILT_PRODUCTS_DIR"];
if(saveToPath != nil) {
saveToPath = [saveToPath stringByAppendingPathComponent:@"CorePlot-UnitTest-Output"];
if(![[NSFileManager defaultManager] fileExistsAtPath:saveToPath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:saveToPath attributes:nil];
}
[NSObject gtm_setUnitTestSaveToDirectory:saveToPath];
}
[super invokeTest];
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPTestCase.m | Objective-C | bsd | 714 |
#import <Foundation/Foundation.h>
@interface CPAnimationKeyFrame : NSObject {
@private
id <NSObject, NSCopying> identifier;
BOOL isInitialFrame;
NSTimeInterval duration;
}
@property (nonatomic, readwrite, copy) id <NSCopying> identifier;
@property (nonatomic, readwrite, assign) BOOL isInitialFrame;
@property (nonatomic, readwrite, assign) NSTimeInterval duration;
-(id)initAsInitialFrame:(BOOL)isFirst;
@end
| 08iteng-ipad | systemtests/tests/Source/CPAnimationKeyFrame.h | Objective-C | bsd | 428 |
#import "CPDerivedXYGraph.h"
/** @brief An empty XY graph class used for testing themes.
**/
@implementation CPDerivedXYGraph
@end
| 08iteng-ipad | systemtests/tests/Source/CPDerivedXYGraph.m | Objective-C | bsd | 134 |
#import "CPStocksTheme.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 a gradient background and white lines.
**/
@implementation CPStocksTheme
+(NSString *)defaultName
{
return kCPStocksTheme;
}
-(void)applyThemeToBackground:(CPXYGraph *)graph
{
graph.fill = [CPFill fillWithColor:[CPColor blackColor]];
}
-(void)applyThemeToPlotArea:(CPPlotArea *)plotArea
{
CPGradient *stocksBackgroundGradient = [[[CPGradient alloc] init] autorelease];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.21569f green:0.28627f blue:0.44706f alpha:1.0f] atPosition:0.0f];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.09412f green:0.17255f blue:0.36078f alpha:1.0f] atPosition:0.5f];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.05882f green:0.13333f blue:0.33333f alpha:1.0f] atPosition:0.5f];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.05882f green:0.13333f blue:0.33333f alpha:1.0f] atPosition:1.0f];
stocksBackgroundGradient.angle = 270.0;
plotArea.fill = [CPFill fillWithGradient:stocksBackgroundGradient];
CPLineStyle *borderLineStyle = [CPLineStyle lineStyle];
borderLineStyle.lineColor = [CPColor colorWithGenericGray:0.2];
borderLineStyle.lineWidth = 0.0f;
plotArea.borderLineStyle = borderLineStyle;
plotArea.cornerRadius = 14.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/CPStocksTheme.m | Objective-C | bsd | 3,439 |
/*! @mainpage Core Plot
*
* @section intro Introduction
*
* Core Plot is a plotting framework for Mac OS X and iPhone OS. It provides 2D visualization of data,
* and is tightly integrated with Apple technologies like Core Animation, Core Data, and Cocoa Bindings.
*
* @section start Getting Started
*
* See the project wiki at
* http://code.google.com/p/core-plot/wiki/UsingCorePlotInApplications for information on how to use Core Plot
* in your own application.
*
* @section contribute Contributing to Core Plot
*
* Core Plot is an open source project. The project home page is http://code.google.com/p/core-plot/ on Google Code.
* See http://code.google.com/p/core-plot/source/checkout for instructions on how to download the source code.
*
* @subsection coding Coding Standards
* Everyone has a their own preferred coding style, and no one way can be considered right. Nonetheless, in a
* project like Core Plot, with many developers contributing, it is worthwhile defining a set of basic coding
* standards to prevent a mishmash of different styles which can become frustrating when
* navigating the code base. See the file <code>"Coding Style.mdown"</code> found in the <code>documentation</code> directory
* of the project source for specific guidelines.
*
* @subsection documentation Documentation Policy
* See http://code.google.com/p/core-plot/wiki/DocumentationPolicy for instructions on how to
* document your code so that your comments will appear in these documentation pages.
*
* @subsection testing Testing Policy
* Because Core Plot is intended to be used in scientific, financial, and other domains where correctness is paramount,
* unit testing is integrated into the framework. Good test coverage protects developers from introducing accidental
* regressions and frees them to experiment and refactor without fear of breaking things. See
* http://code.google.com/p/core-plot/wiki/CorePlotTesting for instructions on how to build unit tests
* for any new code you add to the project.
*/
| 08iteng-ipad | systemtests/tests/Source/mainpage.h | C | bsd | 2,042 |
#import "CPTestCase.h"
@interface CPGradientTests : CPTestCase {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPGradientTests.h | Objective-C | bsd | 75 |
#import "CPAxisSet.h"
#import "CPPlotSpace.h"
#import "CPAxis.h"
#import "CPPlotArea.h"
#import "CPGraph.h"
/** @brief A container layer for the set of axes for a graph.
**/
@implementation CPAxisSet
/** @property axes
* @brief The axes in the axis set.
**/
@synthesize axes;
/** @property graph
* @brief The graph for the axis set.
**/
@synthesize graph;
#pragma mark -
#pragma mark Init/Dealloc
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
axes = [[NSArray array] retain];
self.needsDisplayOnBoundsChange = YES;
}
return self;
}
-(void)dealloc
{
[axes release];
[super dealloc];
}
#pragma mark -
#pragma mark Labeling
/** @brief Updates the axis labels for each axis in the axis set.
**/
-(void)relabelAxes
{
for ( CPAxis *axis in self.axes ) {
[axis setNeedsLayout];
[axis setNeedsRelabel];
}
}
#pragma mark -
#pragma mark Accessors
-(void)setGraph:(CPGraph *)newGraph
{
if ( graph != newGraph ) {
graph = newGraph;
[self setNeedsLayout];
[self setNeedsDisplay];
}
}
-(void)setAxes:(NSArray *)newAxes
{
if ( newAxes != axes ) {
for ( CPAxis *axis in axes ) {
[axis removeFromSuperlayer];
}
[axes release];
axes = [newAxes retain];
for ( CPAxis *axis in axes ) {
[self addSublayer:axis];
}
[self setNeedsDisplay];
}
}
#pragma mark -
#pragma mark Layout
+(CGFloat)defaultZPosition
{
return CPDefaultZPositionAxisSet;
}
#pragma mark -
#pragma mark Drawing
-(void)renderAsVectorInContext:(CGContextRef)theContext
{
// nothing to draw
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPAxisSet.m | Objective-C | bsd | 1,639 |
#import "CPTestCase.h"
@interface CPDarkGradientThemeTests : CPTestCase {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPDarkGradientThemeTests.h | Objective-C | bsd | 83 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@interface CPColorSpace : NSObject {
@private
CGColorSpaceRef cgColorSpace;
}
@property (nonatomic, readonly, assign) CGColorSpaceRef cgColorSpace;
+(CPColorSpace *)genericRGBSpace;
-(id)initWithCGColorSpace:(CGColorSpaceRef)colorSpace;
@end
| 08iteng-ipad | systemtests/tests/Source/CPColorSpace.h | Objective-C | bsd | 321 |
#import "CPDarkGradientThemeTests.h"
#import "CPDarkGradientTheme.h"
#import "CPGraph.h"
#import "CPXYGraph.h"
#import "CPDerivedXYGraph.h"
#import "CPXYPlotSpace.h"
#import "CPXYAxisSet.h"
#import "CPUtilities.h"
@implementation CPDarkGradientThemeTests
-(void)testNewThemeShouldBeCPXYGraph
{
// Arrange
CPDarkGradientTheme *theme = [[CPDarkGradientTheme alloc] init];
// Act
CPGraph *graph = [theme newGraph];
// Assert
STAssertEquals([graph class], [CPXYGraph class], @"graph should be of type CPXYGraph");
[theme release];
}
-(void)testNewThemeSetGraphClassReturnedClassShouldBeOfCorrectType
{
// Arrange
CPDarkGradientTheme *theme = [[CPDarkGradientTheme alloc] init];
[theme setGraphClass:[CPDerivedXYGraph class]];
// Act
CPGraph *graph = [theme newGraph];
// Assert
STAssertEquals([graph class], [CPDerivedXYGraph class], @"graph should be of type CPDerivedXYGraph");
[theme release];
}
-(CPXYGraph *)createTestGraph
{
CPXYGraph *graph = [(CPXYGraph *)[CPXYGraph alloc] initWithFrame:CGRectMake(0.0, 0.0, 200.0, 200.0)];
graph.paddingLeft = 20.0;
graph.paddingTop = 20.0;
graph.paddingRight = 20.0;
graph.paddingBottom = 20.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)];
return graph;
}
-(void)testRenderGraphWithNoTheme
{
// Arrange
// Act
CPXYGraph *graph = [self createTestGraph];
// Assert
GTMAssertObjectImageEqualToImageNamed(graph, @"CPDarkGradientThemeTests-testRenderGraphWithNoTheme", @"");
[graph release];
}
-(void)testApplyThemeToBackground
{
// Arrange
CPDarkGradientTheme *theme = [[CPDarkGradientTheme alloc] init];
CPXYGraph *graph = [self createTestGraph];
// Act
[theme applyThemeToBackground:graph];
// Assert
GTMAssertObjectImageEqualToImageNamed(graph, @"CPDarkGradientThemeTests-testApplyThemeToBackground", @"");
[theme release];
[graph release];
}
-(void)testApplyThemeToPlotArea
{
// Arrange
CPDarkGradientTheme *theme = [[CPDarkGradientTheme alloc] init];
CPXYGraph *graph = [self createTestGraph];
// Act
[theme applyThemeToPlotArea:graph.plotArea];
// Assert
GTMAssertObjectImageEqualToImageNamed(graph, @"CPDarkGradientThemeTests-testApplyThemeToPlotArea", @"");
[theme release];
[graph release];
}
-(void)testApplyThemeToAxisSet
{
// Arrange
CPDarkGradientTheme *theme = [[CPDarkGradientTheme alloc] init];
CPXYGraph *graph = [self createTestGraph];
// Act
[theme applyThemeToAxisSet:(CPXYAxisSet *)graph.axisSet];
// Assert
GTMAssertObjectImageEqualToImageNamed(graph, @"CPDarkGradientThemeTests-testApplyThemeToAxisSet", @"");
[theme release];
[graph release];
}
-(void)testApplyTheme
{
// Arrange
CPDarkGradientTheme *theme = [[CPDarkGradientTheme alloc] init];
CPXYGraph *graph = [self createTestGraph];
// Act
[theme applyThemeToGraph:graph];
// Assert
GTMAssertObjectImageEqualToImageNamed(graph, @"CPDarkGradientThemeTests-testApplyThemeToGraph", @"");
[theme release];
[graph release];
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPDarkGradientThemeTests.m | Objective-C | bsd | 3,323 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@class CPColor;
@interface CPTextStyle : NSObject <NSCopying, NSCoding> {
@private
NSString *fontName;
CGFloat fontSize;
CPColor *color;
}
@property(readwrite, copy, nonatomic) NSString *fontName;
@property(readwrite, assign, nonatomic) CGFloat fontSize;
@property(readwrite, copy, nonatomic) CPColor *color;
/// @name Factory Methods
/// @{
+(CPTextStyle *)textStyle;
/// @}
@end
@interface NSString(CPTextStyleExtensions)
/// @name Measurement
/// @{
-(CGSize)sizeWithStyle:(CPTextStyle *)style;
/// @}
/// @name Drawing
/// @{
-(void)drawAtPoint:(CGPoint)point withStyle:(CPTextStyle *)style inContext:(CGContextRef)context;
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPTextStyle.h | Objective-C | bsd | 729 |
#import "CPFill.h"
#import "_CPFillColor.h"
#import "_CPFillGradient.h"
#import "_CPFillImage.h"
#import "CPColor.h"
#import "CPImage.h"
/** @brief Draws area fills.
*
* CPFill instances can be used to fill drawing areas with colors (including patterns),
* gradients, and images. Drawing methods are provided to fill rectangular areas and
* arbitrary drawing paths.
**/
@implementation CPFill
/// @defgroup CPFill CPFill
/// @{
#pragma mark -
#pragma mark init/dealloc
/** @brief Creates and returns a new CPFill instance initialized with a given color.
* @param aColor The color.
* @return A new CPFill instance initialized with the given color.
**/
+(CPFill *)fillWithColor:(CPColor *)aColor
{
return [[(_CPFillColor *)[_CPFillColor alloc] initWithColor:aColor] autorelease];
}
/** @brief Creates and returns a new CPFill instance initialized with a given gradient.
* @param aGradient The gradient.
* @return A new CPFill instance initialized with the given gradient.
**/
+(CPFill *)fillWithGradient:(CPGradient *)aGradient
{
return [[[_CPFillGradient alloc] initWithGradient: aGradient] autorelease];
}
/** @brief Creates and returns a new CPFill instance initialized with a given image.
* @param anImage The image.
* @return A new CPFill instance initialized with the given image.
**/
+(CPFill *)fillWithImage:(CPImage *)anImage
{
return [[(_CPFillImage *)[_CPFillImage alloc] initWithImage:anImage] autorelease];
}
/** @brief Initializes a newly allocated CPFill object with the provided color.
* @param aColor The color.
* @return The initialized CPFill object.
**/
-(id)initWithColor:(CPColor *)aColor
{
[self release];
self = [(_CPFillColor *)[_CPFillColor alloc] initWithColor: aColor];
return self;
}
/** @brief Initializes a newly allocated CPFill object with the provided gradient.
* @param aGradient The gradient.
* @return The initialized CPFill object.
**/
-(id)initWithGradient:(CPGradient *)aGradient
{
[self release];
self = [[_CPFillGradient alloc] initWithGradient: aGradient];
return self;
}
/** @brief Initializes a newly allocated CPFill object with the provided image.
* @param anImage The image.
* @return The initialized CPFill object.
**/
-(id)initWithImage:(CPImage *)anImage
{
[self release];
self = [(_CPFillImage *)[_CPFillImage alloc] initWithImage: anImage];
return self;
}
#pragma mark -
#pragma mark NSCopying methods
-(id)copyWithZone:(NSZone *)zone
{
// do nothing--implemented in subclasses
return nil;
}
#pragma mark -
#pragma mark NSCoding methods
-(void)encodeWithCoder:(NSCoder *)coder
{
// do nothing--implemented in subclasses
}
-(id)initWithCoder:(NSCoder *)coder
{
// do nothing--implemented in subclasses
return nil;
}
/// @}
@end
/// @brief CPFill abstract methods—must be overridden by subclasses
@implementation CPFill(AbstractMethods)
/// @addtogroup CPFill
/// @{
#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
{
// do nothing--subclasses override to do drawing here
}
/** @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
{
// do nothing--subclasses override to do drawing here
}
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPFill.m | Objective-C | bsd | 3,559 |
//
// CPPlotSymbolTests.m
// CorePlot
//
#import <Cocoa/Cocoa.h>
#import "CPPlotSymbolTests.h"
#import "CPExceptions.h"
#import "CPPlotRange.h"
#import "CPScatterPlot.h"
#import "CPXYPlotSpace.h"
#import "CPUtilities.h"
#import "CPPlotSymbol.h"
@implementation CPPlotSymbolTests
@synthesize plot;
- (void)setUpPlotSpace
{
CPXYPlotSpace *plotSpace = [[[CPXYPlotSpace alloc] init] autorelease];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInt(-1)
length:CPDecimalFromInt(self.nRecords+1)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInt(-1)
length:CPDecimalFromInt(self.nRecords+1)];
self.plot = [[[CPScatterPlot alloc] init] autorelease];
self.plot.frame = CGRectMake(0.0, 0.0, 110.0, 110.0);
self.plot.dataLineStyle = nil;
self.plot.plotSpace = plotSpace;
self.plot.dataSource = self;
}
- (void)tearDown
{
self.plot = nil;
}
- (void)buildData
{
NSUInteger n = self.nRecords;
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:n*n];
for (NSUInteger i=0; i<n; i++) {
for (NSUInteger j=0; j<n; j++) {
[arr insertObject:[NSDecimalNumber numberWithUnsignedInteger:j] atIndex:i*n+j];
}
}
self.xData = arr;
arr = [NSMutableArray arrayWithCapacity:n*n];
for (NSUInteger i=0; i<n; i++) {
for (NSUInteger j=0; j<n; j++) {
[arr insertObject:[NSDecimalNumber numberWithUnsignedInteger:i] atIndex:i*n+j];
}
}
self.yData = arr;
}
- (void)testPlotSymbols
{
self.nRecords = 1;
[self buildData];
[self setUpPlotSpace];
self.plot.identifier = @"Plot Symbols";
CPPlotSymbol *plotSymbol = [[[CPPlotSymbol alloc] init] autorelease];
plotSymbol.size = CGSizeMake(100.0, 100.0);
// Create a custom path.
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 0., 0.);
CGPathAddEllipseInRect(path, NULL, CGRectMake(0., 0., 10., 10.));
CGPathAddEllipseInRect(path, NULL, CGRectMake(1.5, 4., 3., 3.));
CGPathAddEllipseInRect(path, NULL, CGRectMake(5.5, 4., 3., 3.));
CGPathMoveToPoint(path, NULL, 5., 2.);
CGPathAddArc(path, NULL, 5., 3.3, 2.8, 0., pi, TRUE);
CGPathCloseSubpath(path);
plotSymbol.customSymbolPath = path;
CGPathRelease(path);
for (NSUInteger i=CPPlotSymbolTypeNone; i<=CPPlotSymbolTypeCustom; i++) {
plotSymbol.symbolType = i;
self.plot.plotSymbol = plotSymbol;
NSString *plotName = [NSString stringWithFormat:@"CPPlotSymbolTests-testSymbol%lu", (unsigned long)i];
NSString *errorMessage = [NSString stringWithFormat:@"Should plot symbol #%lu", (unsigned long)i];
[self.plot setNeedsDisplay];
GTMAssertObjectImageEqualToImageNamed(self.plot, plotName, errorMessage);
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
NSUInteger n = self.nRecords;
return n*n;
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPPlotSymbolTests.m | Objective-C | bsd | 2,983 |
#import "CPTestCase.h"
@interface CPUtilitiesTests : CPTestCase {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPUtilitiesTests.h | Objective-C | bsd | 78 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import "CPPlatformSpecificDefines.h"
@protocol CPLayoutManager;
@interface CPLayer : CALayer {
@private
CGFloat paddingLeft;
CGFloat paddingTop;
CGFloat paddingRight;
CGFloat paddingBottom;
id <CPLayoutManager> layoutManager;
BOOL renderingRecursively;
}
/// @name Padding
/// @{
@property (nonatomic, readwrite) CGFloat paddingLeft;
@property (nonatomic, readwrite) CGFloat paddingTop;
@property (nonatomic, readwrite) CGFloat paddingRight;
@property (nonatomic, readwrite) CGFloat paddingBottom;
/// @}
/// @name Masking
/// @{
@property (nonatomic, readonly, assign) CGPathRef maskingPath;
@property (nonatomic, readonly, assign) CGPathRef sublayerMaskingPath;
/// @}
/// @name Layout
/// @{
@property (readwrite, retain) id <CPLayoutManager> layoutManager;
/// @}
/// @name Initialization
/// @{
-(id)initWithFrame:(CGRect)newFrame;
/// @}
/// @name Drawing
/// @{
-(void)renderAsVectorInContext:(CGContextRef)context;
-(void)recursivelyRenderInContext:(CGContextRef)context;
-(NSData *)dataForPDFRepresentationOfLayer;
/// @}
/// @name User Interaction
/// @{
-(void)mouseOrFingerDownAtPoint:(CGPoint)interactionPoint;
-(void)mouseOrFingerUpAtPoint:(CGPoint)interactionPoint;
-(void)mouseOrFingerDraggedAtPoint:(CGPoint)interactionPoint;
-(void)mouseOrFingerCancelled;
/// @}
/// @name Masking
/// @{
-(void)applySublayerMaskToContext:(CGContextRef)context forSublayer:(CPLayer *)sublayer withOffset:(CGPoint)offset;
-(void)applyMaskToContext:(CGContextRef)context;
/// @}
/// @name Layout
/// @{
+(CGFloat)defaultZPosition;
/// @}
/// @name Bindings
/// @{
+(void)exposeBinding:(NSString *)binding;
-(void)bind:(NSString *)binding toObject:(id)observable withKeyPath:(NSString *)keyPath options:(NSDictionary *)options;
-(void)unbind:(NSString *)binding;
-(Class)valueClassForBinding:(NSString *)binding;
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPLayer.h | Objective-C | bsd | 1,916 |
#import "CPDataSourceTestCase.h"
#import "CPXYGraph.h"
@interface CPXYGraphPerformanceTests : CPDataSourceTestCase {
CPXYGraph *graph;
}
@property (retain,readwrite) CPXYGraph *graph;
- (void)addScatterPlot;
@end | 08iteng-ipad | systemtests/tests/Source/CPXYGraphPerformanceTests.h | Objective-C | bsd | 225 |
#import <Foundation/Foundation.h>
#import "CPFill.h"
@class CPImage;
@interface _CPFillImage : CPFill <NSCopying, NSCoding> {
@private
CPImage *fillImage;
}
/// @name Initialization
/// @{
-(id)initWithImage:(CPImage *)anImage;
/// @}
/// @name Drawing
/// @{
-(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext;
-(void)fillPathInContext:(CGContextRef)theContext;
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/_CPFillImage.h | Objective-C | bsd | 399 |
#import <Foundation/Foundation.h>
#import "CPAxisLabel.h"
@interface CPAxisTitle : CPAxisLabel {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPAxisTitle.h | Objective-C | bsd | 109 |
#import "CPBorderedLayerTests.h"
#import "CPBorderedLayer.h"
#import "CPLineStyle.h"
#import "CPColor.h"
#import "CPFill.h"
#import "CPGradient.h"
@implementation CPBorderedLayerTests
- (void)testRenderingCornerRadius
{
CPBorderedLayer *layer = [CPBorderedLayer layer];
layer.bounds = CGRectMake(0, 0, 100, 100);
layer.borderLineStyle = [CPLineStyle lineStyle];
layer.borderLineStyle.lineColor = [CPColor blackColor];
layer.borderLineStyle.lineWidth = 3.0f;
layer.fill = [CPFill fillWithColor:[CPColor blueColor]];
layer.cornerRadius = 10;
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingCornerRadius-10", @"");
layer.cornerRadius = 0;
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingCornerRadius-0", @"");
layer.cornerRadius = 1;
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingCornerRadius-1", @"");
layer.cornerRadius = layer.bounds.size.width;
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingCornerRadius-bounds.size.width", @"");
}
- (void)testRenderingLineStyle
{
CPBorderedLayer *layer = [CPBorderedLayer layer];
layer.bounds = CGRectMake(0, 0, 100, 100);
layer.cornerRadius = 5;
layer.fill = [CPFill fillWithColor:[CPColor blueColor]];
CPLineStyle *lineStyle = [CPLineStyle lineStyle];
lineStyle.lineColor = [CPColor redColor];
lineStyle.lineCap = kCGLineCapButt;
lineStyle.lineJoin = kCGLineJoinBevel;
lineStyle.miterLimit = 1.0f;
lineStyle.lineWidth = 2.0f;
layer.borderLineStyle = lineStyle;
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingLineStyle-1",@"");
lineStyle.lineColor = [CPColor greenColor];
lineStyle.lineCap = kCGLineCapRound;
lineStyle.lineJoin = kCGLineJoinMiter;
lineStyle.miterLimit = 1.0f;
lineStyle.lineWidth = 5.0f;
layer.borderLineStyle = lineStyle;
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingLineStyle-2",@"");
}
- (void)testRenderingFill
{
CPBorderedLayer *layer = [CPBorderedLayer layer];
layer.bounds = CGRectMake(0, 0, 100, 100);
layer.borderLineStyle = [CPLineStyle lineStyle];
layer.cornerRadius = 5.0f;
layer.fill = [CPFill fillWithColor:[CPColor redColor]];
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingFill-Red", @"");
layer.fill = [CPFill fillWithGradient:[CPGradient gradientWithBeginningColor:[CPColor blueColor] endingColor:[CPColor redColor]]];
GTMAssertObjectImageEqualToImageNamed(layer, @"CPBorderedLayerTests-testRenderingFill-Blue-Red-Gradient", @"");
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPBorderedLayerTests.m | Objective-C | bsd | 2,795 |
#import "CPDefinitions.h"
@class CPLayer;
@class CPPlotRange;
extern NSString * const CPPlotSpaceCoordinateMappingDidChangeNotification;
@interface CPPlotSpace : NSObject {
@private
id <NSCopying, NSObject> identifier;
}
@property (nonatomic, readwrite, copy) id <NSCopying, NSObject> identifier;
@end
@interface CPPlotSpace(AbstractMethods)
/// @name Coordinate Space Conversions
/// @{
-(CGPoint)viewPointInLayer:(CPLayer *)layer forPlotPoint:(NSDecimal *)plotPoint;
-(CGPoint)viewPointInLayer:(CPLayer *)layer forDoublePrecisionPlotPoint:(double *)plotPoint;
-(void)plotPoint:(NSDecimal *)plotPoint forViewPoint:(CGPoint)point inLayer:(CPLayer *)layer;
-(void)doublePrecisionPlotPoint:(double *)plotPoint forViewPoint:(CGPoint)point inLayer:(CPLayer *)layer;
/// @}
/// @name Coordinate Range
/// @{
-(CPPlotRange *)plotRangeForCoordinate:(CPCoordinate)coordinate;
/// @}
/// @name Adjusting Ranges to Plot Data
/// @{
-(void)scaleToFitPlots:(NSArray *)plots;
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPPlotSpace.h | Objective-C | bsd | 987 |
#import "CPUtilities.h"
#pragma mark -
#pragma mark Decimal Numbers
/**
* @brief Converts an NSDecimal value to a NSInteger.
* @param decimalNumber The NSDecimal value.
* @return The converted value.
**/
NSInteger CPDecimalIntegerValue(NSDecimal decimalNumber)
{
return (NSInteger)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] intValue];
}
/**
* @brief Converts an NSDecimal value to a float.
* @param decimalNumber The NSDecimal value.
* @return The converted value.
**/
float CPDecimalFloatValue(NSDecimal decimalNumber)
{
return (float)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] floatValue];
}
/**
* @brief Converts an NSDecimal value to a double.
* @param decimalNumber The NSDecimal value.
* @return The converted value.
**/
double CPDecimalDoubleValue(NSDecimal decimalNumber)
{
return (double)[[NSDecimalNumber decimalNumberWithDecimal:decimalNumber] doubleValue];
}
/**
* @brief Converts a NSInteger value to an NSDecimal.
* @param i The NSInteger value.
* @return The converted value.
**/
NSDecimal CPDecimalFromInt(NSInteger i)
{
return [[NSNumber numberWithInt:i] decimalValue];
}
/**
* @brief Converts a float value to an NSDecimal.
* @param f The float value.
* @return The converted value.
**/
NSDecimal CPDecimalFromFloat(float f)
{
return [[NSNumber numberWithFloat:f] decimalValue];
}
/**
* @brief Converts a double value to an NSDecimal.
* @param d The double value.
* @return The converted value.
**/
NSDecimal CPDecimalFromDouble(double d)
{
return [[NSNumber numberWithDouble:d] decimalValue];
}
/**
* @brief Adds two NSDecimals together.
* @param leftOperand The left-hand side of the addition operation.
* @param rightOperand The right-hand side of the addition operation.
* @return The result of the addition.
**/
NSDecimal CPDecimalAdd(NSDecimal leftOperand, NSDecimal rightOperand)
{
NSDecimal result;
NSDecimalAdd(&result, &leftOperand, &rightOperand, NSRoundBankers);
return result;
}
/**
* @brief Subtracts one NSDecimal from another.
* @param leftOperand The left-hand side of the subtraction operation.
* @param rightOperand The right-hand side of the subtraction operation.
* @return The result of the subtraction.
**/
NSDecimal CPDecimalSubtract(NSDecimal leftOperand, NSDecimal rightOperand)
{
NSDecimal result;
NSDecimalSubtract(&result, &leftOperand, &rightOperand, NSRoundBankers);
return result;
}
/**
* @brief Multiplies two NSDecimals together.
* @param leftOperand The left-hand side of the multiplication operation.
* @param rightOperand The right-hand side of the multiplication operation.
* @return The result of the multiplication.
**/
NSDecimal CPDecimalMultiply(NSDecimal leftOperand, NSDecimal rightOperand)
{
NSDecimal result;
NSDecimalMultiply(&result, &leftOperand, &rightOperand, NSRoundBankers);
return result;
}
/**
* @brief Divides one NSDecimal by another.
* @param numerator The numerator of the multiplication operation.
* @param denominator The denominator of the multiplication operation.
* @return The result of the division.
**/
NSDecimal CPDecimalDivide(NSDecimal numerator, NSDecimal denominator)
{
NSDecimal result;
NSDecimalDivide(&result, &numerator, &denominator, NSRoundBankers);
return result;
}
/**
* @brief Checks to see if one NSDecimal is greater than another.
* @param leftOperand The left side of the comparison.
* @param rightOperand The right side of the comparison.
* @return YES if the left operand is greater than the right, NO otherwise.
**/
BOOL CPDecimalGreaterThan(NSDecimal leftOperand, NSDecimal rightOperand)
{
return (NSDecimalCompare(&leftOperand, &rightOperand) == NSOrderedDescending);
}
/**
* @brief Checks to see if one NSDecimal is greater than or equal to another.
* @param leftOperand The left side of the comparison.
* @param rightOperand The right side of the comparison.
* @return YES if the left operand is greater than or equal to the right, NO otherwise.
**/
BOOL CPDecimalGreaterThanOrEqualTo(NSDecimal leftOperand, NSDecimal rightOperand)
{
return (NSDecimalCompare(&leftOperand, &rightOperand) != NSOrderedAscending);
}
/**
* @brief Checks to see if one NSDecimal is less than another.
* @param leftOperand The left side of the comparison.
* @param rightOperand The right side of the comparison.
* @return YES if the left operand is less than the right, NO otherwise.
**/
BOOL CPDecimalLessThan(NSDecimal leftOperand, NSDecimal rightOperand)
{
return (NSDecimalCompare(&leftOperand, &rightOperand) == NSOrderedAscending);
}
/**
* @brief Checks to see if one NSDecimal is less than or equal to another.
* @param leftOperand The left side of the comparison.
* @param rightOperand The right side of the comparison.
* @return YES if the left operand is less than or equal to the right, NO otherwise.
**/
BOOL CPDecimalLessThanOrEqualTo(NSDecimal leftOperand, NSDecimal rightOperand)
{
return (NSDecimalCompare(&leftOperand, &rightOperand) != NSOrderedDescending);
}
/**
* @brief Checks to see if one NSDecimal is equal to another.
* @param leftOperand The left side of the comparison.
* @param rightOperand The right side of the comparison.
* @return YES if the left operand is equal to the right, NO otherwise.
**/
BOOL CPDecimalEquals(NSDecimal leftOperand, NSDecimal rightOperand)
{
return (NSDecimalCompare(&leftOperand, &rightOperand) == NSOrderedSame);
}
NSDecimal CPDecimalFromString(NSString *stringRepresentation)
{
// The following NSDecimalNumber-based creation of NSDecimals from strings is slower than
// the NSScanner-based method: (307000 operations per second vs. 582000 operations per second for NSScanner)
/* NSDecimalNumber *newNumber = [[NSDecimalNumber alloc] initWithString:@"1.0" locale:[NSLocale currentLocale]];
newDecimal = [newNumber decimalValue];
[newNumber release];*/
NSDecimal result;
NSScanner *theScanner = [[NSScanner alloc] initWithString:stringRepresentation];
[theScanner scanDecimal:&result];
[theScanner release];
return result;
}
#pragma mark -
#pragma mark Ranges
/**
* @brief Expands an NSRange by the given amount.
*
* The <code>location</code> of the resulting NSRange will be non-negative.
*
* @param range The NSRange to expand.
* @param expandBy The amount the expand the range by.
* @return The expanded range.
**/
NSRange CPExpandedRange(NSRange range, NSInteger expandBy)
{
NSInteger loc = MAX(0, (int)range.location - expandBy);
NSInteger lowerExpansion = range.location - loc;
NSInteger length = range.length + lowerExpansion + expandBy;
return NSMakeRange(loc, length);
}
#pragma mark -
#pragma mark Colors
/**
* @brief Extracts the color information from a CGColorRef and returns it as a CPRGBAColor.
*
* Supports RGBA and grayscale colorspaces.
*
* @param color The color.
* @return The RGBA components of the color.
**/
CPRGBAColor CPRGBAColorFromCGColor(CGColorRef color)
{
CPRGBAColor rgbColor;
size_t numComponents = CGColorGetNumberOfComponents(color);
if (numComponents == 2) {
const CGFloat *components = CGColorGetComponents(color);
CGFloat all = components[0];
rgbColor.red = all;
rgbColor.green = all;
rgbColor.blue = all;
rgbColor.alpha = components[1];
} else {
const CGFloat *components = CGColorGetComponents(color);
rgbColor.red = components[0];
rgbColor.green = components[1];
rgbColor.blue = components[2];
rgbColor.alpha = components[3];
}
return rgbColor;
}
#pragma mark -
#pragma mark Coordinates
/**
* @brief Determines the CPCoordinate that is orthogonal to the one provided.
*
* The current implementation is two-dimensional--X is orthogonal to Y and Y is orthogonal to X.
*
* @param coord The CPCoordinate.
* @return The orthogonal CPCoordinate.
**/
CPCoordinate CPOrthogonalCoordinate(CPCoordinate coord)
{
return ( coord == CPCoordinateX ? CPCoordinateY : CPCoordinateX );
}
#pragma mark -
#pragma mark Quartz pixel-alignment functions
/**
* @brief Aligns a point in user space to integral coordinates in device space.
*
* Ensures that the x and y coordinates are at a pixel corner in device space.
* Drawn from <i>Programming with Quartz</i> by D. Gelphman, B. Laden.
*
* @param context The graphics context.
* @param p The point in user space.
* @return The device aligned point in user space.
**/
CGPoint CPAlignPointToUserSpace(CGContextRef context, CGPoint p)
{
// Compute the coordinates of the point in device space.
p = CGContextConvertPointToDeviceSpace(context, p);
// Ensure that coordinates are at exactly the corner
// of a device pixel.
p.x = round(p.x) + 0.5f;
p.y = round(p.y) + 0.5f;
// Convert the device aligned coordinate back to user space.
return CGContextConvertPointToUserSpace(context, p);
}
/**
* @brief Adjusts a size in user space to integral dimensions in device space.
*
* Ensures that the width and height are an integer number of device pixels.
* Drawn from <i>Programming with Quartz</i> by D. Gelphman, B. Laden.
*
* @param context The graphics context.
* @param s The size in user space.
* @return The device aligned size in user space.
**/
CGSize CPAlignSizeToUserSpace(CGContextRef context, CGSize s)
{
// Compute the size in device space.
s = CGContextConvertSizeToDeviceSpace(context, s);
// Ensure that size is an integer multiple of device pixels.
s.width = round(s.width);
s.height = round(s.height);
// Convert back to user space.
return CGContextConvertSizeToUserSpace(context, s);
}
/**
* @brief Aligns a rectangle in user space to integral coordinates in device space.
*
* Ensures that the x and y coordinates are at a pixel corner in device space
* and the width and height are an integer number of device pixels.
* Drawn from <i>Programming with Quartz</i> by D. Gelphman, B. Laden.
*
* @note This function produces a width and height
* that is less than or equal to the original width.
* @param context The graphics context.
* @param r The rectangle in user space.
* @return The device aligned rectangle in user space.
**/
CGRect CPAlignRectToUserSpace(CGContextRef context, CGRect r)
{
// Compute the coordinates of the rectangle in device space.
r = CGContextConvertRectToDeviceSpace(context, r);
// Ensure that the x and y coordinates are at a pixel corner.
r.origin.x = round(r.origin.x) + 0.5f;
r.origin.y = round(r.origin.y) + 0.5f;
// Ensure that the width and height are an integer number of
// device pixels. We now use ceil to make something at least as large as the original
r.size.width = round(r.size.width);
r.size.height = round(r.size.height);
// Convert back to user space.
return CGContextConvertRectToUserSpace(context, r);
}
| 08iteng-ipad | systemtests/tests/Source/CPUtilities.m | Objective-C | bsd | 10,792 |
#import "CPTextStyle.h"
#import "CPColor.h"
/** @brief Wrapper for various text style properties.
**/
@implementation CPTextStyle
/** @property fontSize
* @brief Sets the font size.
**/
@synthesize fontSize;
/** @property fontName
* @brief Sets the font name.
**/
@synthesize fontName;
/** @property color
* @brief Sets the current text color.
**/
@synthesize color;
#pragma mark -
#pragma mark Initialization and teardown
-(id)init
{
if ( self = [super init] ) {
fontName = @"Helvetica";
fontSize = 12.0f;
color = [[CPColor blackColor] retain];
}
return self;
}
-(void)dealloc
{
[fontName release];
[color release];
[super dealloc];
}
#pragma mark -
#pragma mark Factory Methods
/** @brief Creates and returns a new CPTextStyle instance.
* @return A new CPTextStyle instance.
**/
+(CPTextStyle *)textStyle
{
return [[[self alloc] init] autorelease];
}
#pragma mark -
#pragma mark Copying
-(id)copyWithZone:(NSZone *)zone
{
CPTextStyle *newCopy = [[CPTextStyle allocWithZone:zone] init];
newCopy->fontName = [self->fontName copy];
newCopy->color = [self->color copy];
newCopy->fontSize = self->fontSize;
return newCopy;
}
#pragma mark -
#pragma mark NSCoding methods
-(void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.fontName forKey:@"fontName"];
[coder encodeDouble:self.fontSize forKey:@"fontSize"];
[coder encodeObject:self.color forKey:@"color"];
}
-(id)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.fontName = [coder decodeObjectForKey:@"fontName"];
self.fontSize = [coder decodeDoubleForKey:@"fontSize"];
self.color = [coder decodeObjectForKey:@"color"];
}
return self;
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPTextStyle.m | Objective-C | bsd | 1,699 |
#import <Foundation/Foundation.h>
#import "CPAxis.h"
#import "CPDefinitions.h"
@interface CPXYAxis : CPAxis {
@private
NSDecimal constantCoordinateValue; // TODO: NSDecimal instance variables in CALayers cause an unhandled property type encoding error
}
@property (nonatomic, readwrite) NSDecimal constantCoordinateValue;
@end
| 08iteng-ipad | systemtests/tests/Source/CPXYAxis.h | Objective-C | bsd | 337 |
#import "CPTextLayer.h"
#import "CPTextStyle.h"
#import "CPPlatformSpecificFunctions.h"
#import "CPColor.h"
#import "CPColorSpace.h"
#import "CPPlatformSpecificCategories.h"
#import "CPUtilities.h"
const CGFloat kCPTextLayerMarginWidth = 1.0f;
/** @brief A Core Animation layer that displays a single line of text drawn in a uniform style.
**/
@implementation CPTextLayer
/** @property text
* @brief The text to display.
**/
@synthesize text;
/** @property textStyle
* @brief The text style used to draw the text.
**/
@synthesize textStyle;
#pragma mark -
#pragma mark Initialization and teardown
/** @brief Initializes a newly allocated CPTextLayer object with the provided text and style. This is the designated initializer.
* @param newText The text to display.
* @param newStyle The text style used to draw the text.
* @return The initialized CPTextLayer object.
**/
-(id)initWithText:(NSString *)newText style:(CPTextStyle *)newStyle
{
if (self = [super initWithFrame:CGRectZero]) {
textStyle = [newStyle retain];
text = [newText copy];
self.needsDisplayOnBoundsChange = NO;
[self sizeToFit];
}
return self;
}
/** @brief Initializes a newly allocated CPTextLayer object with the provided text and the default text style.
* @param newText The text to display.
* @return The initialized CPTextLayer object.
**/
-(id)initWithText:(NSString *)newText
{
return [self initWithText:newText style:[CPTextStyle textStyle]];
}
-(void)dealloc
{
[textStyle release];
[text release];
[super dealloc];
}
#pragma mark -
#pragma mark Accessors
-(void)setText:(NSString *)newValue
{
if ( text == newValue ) return;
[text release];
text = [newValue copy];
[self sizeToFit];
}
-(void)setTextStyle:(CPTextStyle *)newStyle
{
if ( newStyle != textStyle ) {
[textStyle release];
textStyle = [newStyle retain];
[self sizeToFit];
}
}
#pragma mark -
#pragma mark Layout
/** @brief Resizes the layer to fit its contents leaving a narrow margin on all four sides.
**/
-(void)sizeToFit
{
if ( self.text == nil ) return;
CGSize textSize = [self.text sizeWithStyle:textStyle];
// Add small margin
textSize.width += 2 * kCPTextLayerMarginWidth;
textSize.height += 2 * kCPTextLayerMarginWidth;
CGRect newBounds = self.bounds;
newBounds.size = textSize;
self.bounds = newBounds;
[self setNeedsDisplay];
}
#pragma mark -
#pragma mark Drawing of text
-(void)renderAsVectorInContext:(CGContextRef)context
{
[super renderAsVectorInContext:context];
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0f, self.bounds.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
#endif
[self.text drawAtPoint:CPAlignPointToUserSpace(context, CGPointMake(kCPTextLayerMarginWidth, kCPTextLayerMarginWidth)) withStyle:self.textStyle inContext:context];
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
CGContextRestoreGState(context);
#endif
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPTextLayer.m | Objective-C | bsd | 2,953 |
#import <Foundation/Foundation.h>
#import "CPLayer.h"
@class CPPlotSpace;
@class CPPlotArea;
@class CPGraph;
@interface CPAxisSet : CPLayer {
@private
NSArray *axes;
CPGraph *graph;
}
@property (nonatomic, readwrite, retain) NSArray *axes;
@property (nonatomic, readwrite, assign) CPGraph *graph;
-(void)relabelAxes;
@end
| 08iteng-ipad | systemtests/tests/Source/CPAxisSet.h | Objective-C | bsd | 334 |
#import "CPColor.h"
#import "CPColorSpace.h"
#import "CPPlatformSpecificFunctions.h"
/** @brief Wrapper around CGColorRef
*
* A wrapper class around CGColorRef
*
* @todo More documentation needed
**/
@implementation CPColor
/// @defgroup CPColor CPColor
/// @{
/** @property cgColor
* @brief The CGColor to wrap around.
**/
@synthesize cgColor;
#pragma mark -
#pragma mark Factory Methods
/** @brief Returns a shared instance of CPColor initialized with a fully transparent color.
*
* @return A shared CPColor object initialized with a fully transparent color.
**/
+(CPColor *)clearColor
{
static CPColor *color = nil;
if ( nil == color ) {
CGColorRef clear = NULL;
CGFloat values[4] = {1.0, 1.0, 1.0, 0.0};
clear = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
color = [[CPColor alloc] initWithCGColor:clear];
CGColorRelease(clear);
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque white color.
*
* @return A shared CPColor object initialized with a fully opaque white color.
**/
+(CPColor *)whiteColor
{
static CPColor *color = nil;
if ( nil == color ) {
CGColorRef white = NULL;
CGFloat values[4] = {1.0, 1.0, 1.0, 1.0};
white = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
color = [[CPColor alloc] initWithCGColor:white];
CGColorRelease(white);
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque black color.
*
* @return A shared CPColor object initialized with a fully opaque black color.
**/
+(CPColor *)blackColor
{
static CPColor *color = nil;
if ( nil == color ) {
CGColorRef black = NULL;
CGFloat values[4] = {0.0, 0.0, 0.0, 1.0};
black = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
color = [[CPColor alloc] initWithCGColor:black];
CGColorRelease(black);
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque red color.
*
* @return A shared CPColor object initialized with a fully opaque red color.
**/
+(CPColor *)redColor
{
static CPColor *color = nil;
if ( nil == color ) {
CGColorRef red = NULL;
CGFloat values[4] = {1.0, 0.0, 0.0, 1.0};
red = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
color = [[CPColor alloc] initWithCGColor:red];
CGColorRelease(red);
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque green color.
*
* @return A shared CPColor object initialized with a fully opaque green color.
**/
+(CPColor *)greenColor
{
static CPColor *color = nil;
if ( nil == color ) {
CGColorRef green = NULL;
CGFloat values[4] = {0.0, 1.0, 0.0, 1.0};
green = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
color = [[CPColor alloc] initWithCGColor:green];
CGColorRelease(green);
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque blue color.
*
* @return A shared CPColor object initialized with a fully opaque blue color.
**/
+(CPColor *)blueColor
{
static CPColor *color = nil;
if ( nil == color ) {
CGColorRef blue = NULL;
CGFloat values[4] = {0.0, 0.0, 1.0, 1.0};
blue = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
color = [[CPColor alloc] initWithCGColor:blue];
CGColorRelease(blue);
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque 40% gray color.
*
* @return A shared CPColor object initialized with a fully opaque 40% gray color.
**/
+(CPColor *)darkGrayColor
{
static CPColor *color = nil;
if ( nil == color ) {
color = [[self colorWithGenericGray:0.4] retain];
}
return color;
}
/** @brief Returns a shared instance of CPColor initialized with a fully opaque 70% gray color.
*
* @return A shared CPColor object initialized with a fully opaque 70% gray color.
**/
+(CPColor *)lightGrayColor
{
static CPColor *color = nil;
if ( nil == color ) {
color = [[self colorWithGenericGray:0.7] retain];
}
return color;
}
/** @brief Creates and returns a new CPColor instance initialized with the provided CGColorRef.
* @param newCGColor The color to wrap.
* @return A new CPColor instance initialized with the provided CGColorRef.
**/
+(CPColor *)colorWithCGColor:(CGColorRef)newCGColor
{
return [[[CPColor alloc] initWithCGColor:newCGColor] autorelease];
}
/** @brief Creates and returns a new CPColor instance initialized with the provided RGBA color components.
* @param red The red component (0 ≤ red ≤ 1).
* @param green The green component (0 ≤ green ≤ 1).
* @param blue The blue component (0 ≤ blue ≤ 1).
* @param alpha The alpha component (0 ≤ alpha ≤ 1).
* @return A new CPColor instance initialized with the provided RGBA color components.
**/
+(CPColor *)colorWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
{
return [[[CPColor alloc] initWithComponentRed:red green:green blue:blue alpha:alpha] autorelease];
}
/** @brief Creates and returns a new CPColor instance initialized with the provided gray level.
* @param gray The gray level (0 ≤ gray ≤ 1).
* @return A new CPColor instance initialized with the provided gray level.
**/
+(CPColor *)colorWithGenericGray:(CGFloat)gray
{
CGColorRef colorRef = NULL;
CGFloat values[4] = {gray, gray, gray, 1.0};
colorRef = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, values);
CPColor *color = [[CPColor alloc] initWithCGColor:colorRef];
CGColorRelease(colorRef);
return [color autorelease];
}
#pragma mark -
#pragma mark Initialize/Deallocate
/** @brief Initializes a newly allocated CPColor object with the provided CGColorRef.
*
* @param newCGColor The color to wrap.
* @return The initialized CPColor object.
**/
-(id)initWithCGColor:(CGColorRef)newCGColor
{
if ( self = [super init] ) {
CGColorRetain(newCGColor);
cgColor = newCGColor;
}
return self;
}
/** @brief Initializes a newly allocated CPColor object with the provided RGBA color components.
*
* @param red The red component (0 ≤ red ≤ 1).
* @param green The green component (0 ≤ green ≤ 1).
* @param blue The blue component (0 ≤ blue ≤ 1).
* @param alpha The alpha component (0 ≤ alpha ≤ 1).
* @return The initialized CPColor object.
**/
-(id)initWithComponentRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
{
CGFloat colorComponents[4];
colorComponents[0] = red;
colorComponents[1] = green;
colorComponents[2] = blue;
colorComponents[3] = alpha;
CGColorRef color = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, colorComponents);
[self initWithCGColor:color];
CGColorRelease(color);
return self;
}
-(void)dealloc
{
CGColorRelease(cgColor);
[super dealloc];
}
#pragma mark -
#pragma mark Creating colors from other colors
/** @brief Creates and returns a new CPColor instance having color components identical to the current object
* but having the provided alpha component.
* @param alpha The alpha component (0 ≤ alpha ≤ 1).
* @return A new CPColor instance having the provided alpha component.
**/
-(CPColor *)colorWithAlphaComponent:(CGFloat)alpha
{
CGColorRef newCGColor = CGColorCreateCopyWithAlpha(self.cgColor, alpha);
CPColor *newColor = [CPColor colorWithCGColor:newCGColor];
CGColorRelease(newCGColor);
return newColor;
}
#pragma mark -
#pragma mark NSCoding methods
-(void)encodeWithCoder:(NSCoder *)coder
{
const CGFloat *colorComponents = CGColorGetComponents(self.cgColor);
[coder encodeDouble:colorComponents[0] forKey:@"redComponent"];
[coder encodeDouble:colorComponents[1] forKey:@"greenComponent"];
[coder encodeDouble:colorComponents[2] forKey:@"blueComponent"];
[coder encodeDouble:colorComponents[3] forKey:@"alphaComponent"];
}
-(id)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
CGFloat colorComponents[4];
colorComponents[0] = [coder decodeDoubleForKey:@"redComponent"];
colorComponents[1] = [coder decodeDoubleForKey:@"greenComponent"];
colorComponents[2] = [coder decodeDoubleForKey:@"blueComponent"];
colorComponents[3] = [coder decodeDoubleForKey:@"alphaComponent"];
cgColor = CGColorCreate([CPColorSpace genericRGBSpace].cgColorSpace, colorComponents);
}
return self;
}
#pragma mark -
#pragma mark NSCopying methods
-(id)copyWithZone:(NSZone *)zone
{
CGColorRef cgColorCopy = NULL;
if ( cgColor ) cgColorCopy = CGColorCreateCopy(cgColor);
CPColor *colorCopy = [[[self class] allocWithZone:zone] initWithCGColor:cgColorCopy];
CGColorRelease(cgColorCopy);
return colorCopy;
}
#pragma mark -
#pragma mark Color comparison
-(BOOL)isEqual:(id)object
{
if ([object isKindOfClass:[self class]]) {
return CGColorEqualToColor(self.cgColor, ((CPColor *)object).cgColor);
} else {
return NO;
}
}
-(NSUInteger)hash
{
// Equal objects must hash the same.
CGFloat theHash = 0.0f;
CGFloat multiplier = 256.0f;
CGColorRef theColor = self.cgColor;
size_t numberOfComponents = CGColorGetNumberOfComponents(theColor);
const CGFloat *colorComponents = CGColorGetComponents(theColor);
for (NSUInteger i = 0; i < numberOfComponents; i++) {
theHash += multiplier * colorComponents[i];
multiplier *= 256.0f;
}
return (NSUInteger)theHash;
}
/// @}
@end
| 08iteng-ipad | systemtests/tests/Source/CPColor.m | Objective-C | bsd | 9,724 |
#import <Foundation/Foundation.h>
#import "CPXYTheme.h"
@interface CPPlainBlackTheme : CPXYTheme {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPPlainBlackTheme.h | Objective-C | bsd | 110 |
#import "CPXYGraphPerformanceTests.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"
@implementation CPXYGraphPerformanceTests
@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.graph.bounds = CGRectMake(0., 0., 400., 200.);
CPXYPlotSpace *plotSpace = (CPXYPlotSpace*)[[self graph] defaultPlotSpace];
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromInt(0)
length:CPDecimalFromInt(self.nRecords)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-1.1)
length:CPDecimalFromFloat(2.2)];
CPScatterPlot *scatterPlot = [[[CPScatterPlot alloc] init] autorelease];
scatterPlot.identifier = @"Scatter Plot";
scatterPlot.dataLineStyle.lineWidth = 1.0;
scatterPlot.dataSource = self;
// Add plot symbols
CPPlotSymbol *greenCirclePlotSymbol = [CPPlotSymbol ellipsePlotSymbol];
CGColorRef greenColor = CPNewCGColorFromNSColor([NSColor greenColor]);
greenCirclePlotSymbol.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:greenColor]];
greenCirclePlotSymbol.size = CGSizeMake(5.0, 5.0);
scatterPlot.plotSymbol = greenCirclePlotSymbol;
CGColorRelease(greenColor);
[[self graph] addPlot:scatterPlot];
}
- (void)testRenderScatterStressTest
{
self.nRecords = 1e6;
[self buildData];
[self addScatterPlot];
GTMAssertObjectImageEqualToImageNamed(self.graph, @"CPXYGraphTests-testRenderStressTest", @"Should render a sine wave with green symbols.");
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPXYGraphPerformanceTests.m | Objective-C | bsd | 2,318 |
#import "CPTestCase.h"
@interface CPPlotAreaTests : CPTestCase {
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPPlotAreaTests.h | Objective-C | bsd | 76 |
#import "CPScatterPlotTests.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 "GTMNSObject+BindingUnitTesting.h"
@implementation CPScatterPlotTests
@synthesize plot;
- (void)setUp
{
CPXYPlotSpace *plotSpace = [[[CPXYPlotSpace alloc] init] autorelease];
self.plot = [[[CPScatterPlot alloc] init] autorelease];
self.plot.frame = CGRectMake(0., 0., 100., 100.);
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]];
}
- (void)testRenderScatter
{
self.nRecords = 1e2;
[self buildData];
[self setPlotRanges];
GTMAssertObjectImageEqualToImageNamed(self.plot, @"CPScatterPlotTests-testRenderScatter", @"Should plot sine wave");
}
-(void)testBindings
{
NSArray *errors;
STAssertTrue(GTMDoExposedBindingsFunctionCorrectly(self.plot, &errors), @"CPScatterPlot bindings do not work as expected: %@", errors);
for (id obj in errors) {
STFail(@"%@", obj);
}
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPScatterPlotTests.m | Objective-C | bsd | 1,336 |
#import "_CPFillImage.h"
#import "CPImage.h"
/// @cond
@interface _CPFillImage()
@property (nonatomic, readwrite, copy) CPImage *fillImage;
@end
/// @endcond
/** @brief Draws CPImage area fills.
*
* Drawing methods are provided to fill rectangular areas and arbitrary drawing paths.
**/
@implementation _CPFillImage
/** @property fillImage
* @brief The fill image.
**/
@synthesize fillImage;
#pragma mark -
#pragma mark init/dealloc
/** @brief Initializes a newly allocated _CPFillImage object with the provided image.
* @param anImage The image.
* @return The initialized _CPFillImage object.
**/
-(id)initWithImage:(CPImage *)anImage
{
if ( self = [super init] ) {
fillImage = [anImage retain];
}
return self;
}
-(void)dealloc
{
[fillImage release];
[super dealloc];
}
#pragma mark -
#pragma mark Drawing
/** @brief Draws the image into the given graphics context inside the provided rectangle.
* @param theRect The rectangle to draw into.
* @param theContext The graphics context to draw into.
**/
-(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext
{
[self.fillImage drawInRect:theRect inContext:theContext];
}
/** @brief Draws the image into the given graphics context clipped to the current drawing path.
* @param theContext The graphics context to draw into.
**/
-(void)fillPathInContext:(CGContextRef)theContext
{
CGContextSaveGState(theContext);
CGRect bounds = CGContextGetPathBoundingBox(theContext);
CGContextClip(theContext);
[self.fillImage drawInRect:bounds inContext:theContext];
CGContextRestoreGState(theContext);
}
#pragma mark -
#pragma mark NSCopying methods
-(id)copyWithZone:(NSZone *)zone
{
_CPFillImage *copy = [[[self class] allocWithZone:zone] init];
copy->fillImage = [self->fillImage copyWithZone:zone];
return copy;
}
#pragma mark -
#pragma mark NSCoding methods
-(Class)classForCoder
{
return [CPFill class];
}
-(void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.fillImage forKey:@"fillImage"];
}
-(id)initWithCoder:(NSCoder *)coder
{
if ( self = [super init] ) {
fillImage = [[coder decodeObjectForKey:@"fillImage"] retain];
}
return self;
}
@end
| 08iteng-ipad | systemtests/tests/Source/_CPFillImage.m | Objective-C | bsd | 2,184 |
#import <QuartzCore/QuartzCore.h>
#import <Foundation/Foundation.h>
@class CPGradient;
@class CPImage;
@class CPColor;
@interface CPFill : NSObject <NSCopying, NSCoding> {
}
/// @name Factory Methods
/// @{
+(CPFill *)fillWithColor:(CPColor *)aColor;
+(CPFill *)fillWithGradient:(CPGradient *)aGradient;
+(CPFill *)fillWithImage:(CPImage *)anImage;
/// @}
/// @name Initialization
/// @{
-(id)initWithColor:(CPColor *)aColor;
-(id)initWithGradient:(CPGradient *)aGradient;
-(id)initWithImage:(CPImage *)anImage;
/// @}
@end
@interface CPFill(AbstractMethods)
/// @name Drawing
/// @{
-(void)fillRect:(CGRect)theRect inContext:(CGContextRef)theContext;
-(void)fillPathInContext:(CGContextRef)theContext;
/// @}
@end | 08iteng-ipad | systemtests/tests/Source/CPFill.h | Objective-C | bsd | 725 |
#import "CPAxisTitle.h"
#import "CPTextLayer.h"
#import "CPExceptions.h"
@implementation CPAxisTitle
-(void)positionRelativeToViewPoint:(CGPoint)point forCoordinate:(CPCoordinate)coordinate inDirection:(CPSign)direction
{
CGPoint newPosition = point;
CGFloat *value = (coordinate == CPCoordinateX ? &(newPosition.x) : &(newPosition.y));
self.rotation = (coordinate == CPCoordinateX ? (M_PI / 2.0) : 0.0);
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 -= self.offset;
anchor = (coordinate == CPCoordinateX ? CGPointMake(0.5, 0.0) : CGPointMake(0.5, 1.0));
break;
case CPSignPositive:
*value += self.offset;
anchor = (coordinate == CPCoordinateX ? CGPointMake(0.0, 0.5) : CGPointMake(0.5, 0.0));
break;
default:
[NSException raise:CPException format:@"Invalid sign in positionRelativeToViewPoint:inDirection:"];
break;
}
// Pixel-align the 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(self.rotation, 0.0f, 0.0f, 1.0f);
[self.contentLayer setNeedsDisplay];
}
@end
| 08iteng-ipad | systemtests/tests/Source/CPAxisTitle.m | Objective-C | bsd | 1,703 |