forked from djw/core-plot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCPTPlotDocument.m
More file actions
414 lines (327 loc) · 16.9 KB
/
Copy pathCPTPlotDocument.m
File metadata and controls
414 lines (327 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#import "CPTPlotDocument.h"
#import "NSString+ParseCSV.h"
@implementation CPTPlotDocument
//#define USE_NSDECIMAL
-(id)init
{
self = [super init];
if ( self ) {
dataPoints = [[NSMutableArray alloc] init];
zoomAnnotation = nil;
dragStart = CGPointZero;
dragEnd = CGPointZero;
}
return self;
}
-(void)dealloc
{
[graph release];
[dataPoints release];
[zoomAnnotation release];
[super dealloc];
}
-(NSString *)windowNibName
{
return @"CPTPlotDocument";
}
-(void)windowControllerDidLoadNib:(NSWindowController *)windowController
{
// Create graph from theme
graph = [(CPTXYGraph *)[CPTXYGraph alloc] initWithFrame:CGRectZero];
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[graph applyTheme:theme];
graphView.hostedGraph = graph;
graph.paddingLeft = 0.0;
graph.paddingTop = 0.0;
graph.paddingRight = 0.0;
graph.paddingBottom = 0.0;
graph.plotAreaFrame.paddingLeft = 55.0;
graph.plotAreaFrame.paddingTop = 40.0;
graph.plotAreaFrame.paddingRight = 40.0;
graph.plotAreaFrame.paddingBottom = 35.0;
graph.plotAreaFrame.plotArea.fill = graph.plotAreaFrame.fill;
graph.plotAreaFrame.fill = nil;
graph.plotAreaFrame.borderLineStyle = nil;
graph.plotAreaFrame.cornerRadius = 0.0;
// Setup plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(minimumValueForXAxis)
length:CPTDecimalFromDouble(ceil( (maximumValueForXAxis - minimumValueForXAxis) / majorIntervalLengthForX ) * majorIntervalLengthForX)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(minimumValueForYAxis)
length:CPTDecimalFromDouble(ceil( (maximumValueForYAxis - minimumValueForYAxis) / majorIntervalLengthForY ) * majorIntervalLengthForY)];
// this allows the plot to respond to mouse events
[plotSpace setDelegate:self];
[plotSpace setAllowsUserInteraction:YES];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.minorTicksPerInterval = 9;
x.majorIntervalLength = CPTDecimalFromDouble(majorIntervalLengthForX);
x.labelOffset = 5.0;
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
CPTXYAxis *y = axisSet.yAxis;
y.minorTicksPerInterval = 9;
y.majorIntervalLength = CPTDecimalFromDouble(majorIntervalLengthForY);
y.labelOffset = 5.0;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
// Create the main plot for the delimited data
CPTScatterPlot *dataSourceLinePlot = [[(CPTScatterPlot *)[CPTScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.0;
lineStyle.lineColor = [CPTColor whiteColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
}
#pragma mark -
#pragma mark Data loading methods
-(NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
// Insert code here to write your document to data of the specified type. If the given outError != NULL, ensure that you set *outError when returning nil.
// You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
// For applications targeted for Panther or earlier systems, you should use the deprecated API -dataRepresentationOfType:. In this case you can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return nil;
}
-(BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
if ( [typeName isEqualToString:@"CSVDocument"] ) {
minimumValueForXAxis = MAXFLOAT;
maximumValueForXAxis = -MAXFLOAT;
minimumValueForYAxis = MAXFLOAT;
maximumValueForYAxis = -MAXFLOAT;
NSString *fileContents = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// Parse CSV
NSUInteger length = [fileContents length];
NSUInteger lineStart = 0, lineEnd = 0, contentsEnd = 0;
NSRange currentRange;
// Read headers from the first line of the file
[fileContents getParagraphStart:&lineStart end:&lineEnd contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
// currentRange = NSMakeRange(lineStart, contentsEnd - lineStart);
// NSArray *columnHeaders = [[fileContents substringWithRange:currentRange] arrayByParsingCSVLine];
// NSLog([columnHeaders objectAtIndex:0]);
while ( lineEnd < length ) {
[fileContents getParagraphStart:&lineStart end:&lineEnd contentsEnd:&contentsEnd forRange:NSMakeRange(lineEnd, 0)];
currentRange = NSMakeRange(lineStart, contentsEnd - lineStart);
NSArray *columnValues = [[fileContents substringWithRange:currentRange] arrayByParsingCSVLine];
double xValue = [[columnValues objectAtIndex:0] doubleValue];
double yValue = [[columnValues objectAtIndex:1] doubleValue];
if ( xValue < minimumValueForXAxis ) {
minimumValueForXAxis = xValue;
}
if ( xValue > maximumValueForXAxis ) {
maximumValueForXAxis = xValue;
}
if ( yValue < minimumValueForYAxis ) {
minimumValueForYAxis = yValue;
}
if ( yValue > maximumValueForYAxis ) {
maximumValueForYAxis = yValue;
}
#ifdef USE_NSDECIMAL
[dataPoints addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSDecimalNumber decimalNumberWithString:[columnValues objectAtIndex:0]], @"x", [NSDecimalNumber decimalNumberWithString:[columnValues objectAtIndex:1]], @"y", nil]];
#else
[dataPoints addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:xValue], @"x", [NSNumber numberWithDouble:yValue], @"y", nil]];
#endif
// Create a dictionary of the items, keyed to the header titles
// NSDictionary *keyedImportedItems = [[NSDictionary alloc] initWithObjects:columnValues forKeys:columnHeaders];
// Process this
}
majorIntervalLengthForX = (maximumValueForXAxis - minimumValueForXAxis) / 5.0;
if ( majorIntervalLengthForX > 0.0 ) {
majorIntervalLengthForX = pow( 10.0, ceil( log10(majorIntervalLengthForX) ) );
}
majorIntervalLengthForY = (maximumValueForYAxis - minimumValueForYAxis) / 10.0;
if ( majorIntervalLengthForY > 0.0 ) {
majorIntervalLengthForY = pow( 10.0, ceil( log10(majorIntervalLengthForY) ) );
}
minimumValueForXAxis = floor(minimumValueForXAxis / majorIntervalLengthForX) * majorIntervalLengthForX;
minimumValueForYAxis = floor(minimumValueForYAxis / majorIntervalLengthForY) * majorIntervalLengthForY;
[fileContents release];
}
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return YES;
}
#pragma mark -
#pragma mark Zoom Methods
-(IBAction)zoomIn
{
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
CPTPlotArea *plotArea = graph.plotAreaFrame.plotArea;
// convert the dragStart and dragEnd values to plot coordinates
CGPoint dragStartInPlotArea = [graph convertPoint:dragStart toLayer:plotArea];
CGPoint dragEndInPlotArea = [graph convertPoint:dragEnd toLayer:plotArea];
double start[2], end[2];
// obtain the datapoints for the drag start and end
[plotSpace doublePrecisionPlotPoint:start forPlotAreaViewPoint:dragStartInPlotArea];
[plotSpace doublePrecisionPlotPoint:end forPlotAreaViewPoint:dragEndInPlotArea];
// recalculate the min and max values
minimumValueForXAxis = MIN(start[CPTCoordinateX], end[CPTCoordinateX]);
maximumValueForXAxis = MAX(start[CPTCoordinateX], end[CPTCoordinateX]);
minimumValueForYAxis = MIN(start[CPTCoordinateY], end[CPTCoordinateY]);
maximumValueForYAxis = MAX(start[CPTCoordinateY], end[CPTCoordinateY]);
// now adjust the plot range and axes
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(minimumValueForXAxis)
length:CPTDecimalFromDouble(maximumValueForXAxis - minimumValueForXAxis)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(minimumValueForYAxis)
length:CPTDecimalFromDouble(maximumValueForYAxis - minimumValueForYAxis)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
}
-(IBAction)zoomOut
{
double xval, yval;
minimumValueForXAxis = MAXFLOAT;
maximumValueForXAxis = -MAXFLOAT;
minimumValueForYAxis = MAXFLOAT;
maximumValueForYAxis = -MAXFLOAT;
// get the ful range min and max values
for ( NSDictionary *xyValues in dataPoints ) {
xval = [[xyValues valueForKey:@"x"] doubleValue];
minimumValueForXAxis = fmin(xval, minimumValueForXAxis);
maximumValueForXAxis = fmax(xval, maximumValueForXAxis);
yval = [[xyValues valueForKey:@"y"] doubleValue];
minimumValueForYAxis = fmin(yval, minimumValueForYAxis);
maximumValueForYAxis = fmax(yval, maximumValueForYAxis);
}
minimumValueForXAxis = floor(minimumValueForXAxis / majorIntervalLengthForX) * majorIntervalLengthForX;
minimumValueForYAxis = floor(minimumValueForYAxis / majorIntervalLengthForY) * majorIntervalLengthForY;
// now adjust the plot range and axes
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(minimumValueForXAxis)
length:CPTDecimalFromDouble(ceil( (maximumValueForXAxis - minimumValueForXAxis) / majorIntervalLengthForX ) * majorIntervalLengthForX)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(minimumValueForYAxis)
length:CPTDecimalFromDouble(ceil( (maximumValueForYAxis - minimumValueForYAxis) / majorIntervalLengthForY ) * majorIntervalLengthForY)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyFixedInterval;
axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyFixedInterval;
}
#pragma mark -
#pragma mark PDF / image export
-(IBAction)exportToPDF:(id)sender;
{
NSSavePanel *pdfSavingDialog = [NSSavePanel savePanel];
[pdfSavingDialog setAllowedFileTypes:[NSArray arrayWithObject:@"pdf"]];
if ( [pdfSavingDialog runModal] == NSOKButton ) {
NSData *dataForPDF = [graph dataForPDFRepresentationOfLayer];
[dataForPDF writeToURL:[pdfSavingDialog URL] atomically:NO];
}
}
-(IBAction)exportToPNG:(id)sender;
{
NSSavePanel *pngSavingDialog = [NSSavePanel savePanel];
[pngSavingDialog setAllowedFileTypes:[NSArray arrayWithObject:@"png"]];
if ( [pngSavingDialog runModal] == NSOKButton ) {
NSImage *image = [graph imageOfLayer];
NSData *tiffData = [image TIFFRepresentation];
NSBitmapImageRep *tiffRep = [NSBitmapImageRep imageRepWithData:tiffData];
NSData *pngData = [tiffRep representationUsingType:NSPNGFileType properties:nil];
[pngData writeToURL:[pngSavingDialog URL] atomically:NO];
}
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [dataPoints count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSString *key = (fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y");
NSNumber *num = [[dataPoints objectAtIndex:index] valueForKey:key];
return num;
}
#pragma mark -
#pragma mark Plot Space Delegate Methods
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(id)event atPoint:(CGPoint)interactionPoint
{
if ( zoomAnnotation ) {
CPTPlotArea *plotArea = graph.plotAreaFrame.plotArea;
CGRect plotBounds = plotArea.bounds;
// convert the dragStart and dragEnd values to plot coordinates
CGPoint dragStartInPlotArea = [graph convertPoint:dragStart toLayer:plotArea];
CGPoint dragEndInPlotArea = [graph convertPoint:interactionPoint toLayer:plotArea];
// create the dragrect from dragStart to the current location
CGFloat endX = MAX( MIN( dragEndInPlotArea.x, CGRectGetMaxX(plotBounds) ), CGRectGetMinX(plotBounds) );
CGFloat endY = MAX( MIN( dragEndInPlotArea.y, CGRectGetMaxY(plotBounds) ), CGRectGetMinY(plotBounds) );
CGRect borderRect = CGRectMake( dragStartInPlotArea.x, dragStartInPlotArea.y,
(endX - dragStartInPlotArea.x),
(endY - dragStartInPlotArea.y) );
zoomAnnotation.contentAnchorPoint = CGPointMake(dragEndInPlotArea.x >= dragStartInPlotArea.x ? 0.0 : 1.0,
dragEndInPlotArea.y >= dragStartInPlotArea.y ? 0.0 : 1.0);
zoomAnnotation.contentLayer.frame = borderRect;
}
return NO;
}
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event atPoint:(CGPoint)interactionPoint
{
if ( !zoomAnnotation ) {
dragStart = interactionPoint;
CPTPlotArea *plotArea = graph.plotAreaFrame.plotArea;
CGPoint dragStartInPlotArea = [graph convertPoint:dragStart toLayer:plotArea];
if ( CGRectContainsPoint(plotArea.bounds, dragStartInPlotArea) ) {
// create the zoom rectangle
// first a bordered layer to draw the zoomrect
CPTBorderedLayer *zoomRectangleLayer = [[[CPTBorderedLayer alloc] initWithFrame:CGRectNull] autorelease];
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor darkGrayColor];
lineStyle.lineWidth = 1.0;
zoomRectangleLayer.borderLineStyle = lineStyle;
CPTColor *transparentFillColor = [[CPTColor blueColor] colorWithAlphaComponent:0.2];
zoomRectangleLayer.fill = [CPTFill fillWithColor:transparentFillColor];
double start[2];
[graph.defaultPlotSpace doublePrecisionPlotPoint:start forPlotAreaViewPoint:dragStartInPlotArea];
NSArray *anchorPoint = [NSArray arrayWithObjects:
[NSNumber numberWithDouble:start[CPTCoordinateX]],
[NSNumber numberWithDouble:start[CPTCoordinateY]],
nil];
// now create the annotation
zoomAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
zoomAnnotation.contentLayer = zoomRectangleLayer;
[graph.plotAreaFrame.plotArea addAnnotation:zoomAnnotation];
}
}
return NO;
}
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceUpEvent:(id)event atPoint:(CGPoint)interactionPoint
{
if ( zoomAnnotation ) {
dragEnd = interactionPoint;
// double-click to completely zoom out
if ( [event clickCount] == 2 ) {
CPTPlotArea *plotArea = graph.plotAreaFrame.plotArea;
CGPoint dragEndInPlotArea = [graph convertPoint:interactionPoint toLayer:plotArea];
if ( CGRectContainsPoint(plotArea.bounds, dragEndInPlotArea) ) {
[self zoomOut];
}
}
else if ( !CGPointEqualToPoint(dragStart, dragEnd) ) {
// no accidental drag, so zoom in
[self zoomIn];
}
// and we're done with the drag
[graph.plotAreaFrame.plotArea removeAnnotation:zoomAnnotation];
[zoomAnnotation release];
zoomAnnotation = nil;
dragStart = CGPointZero;
dragEnd = CGPointZero;
}
return NO;
}
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceCancelledEvent:(id)event atPoint:(CGPoint)interactionPoint
{
if ( zoomAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:zoomAnnotation];
[zoomAnnotation release];
zoomAnnotation = nil;
dragStart = CGPointZero;
dragEnd = CGPointZero;
}
return NO;
}
@end