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 |
|---|---|---|---|---|---|
//
// GTMHTTPServerTest.m
//
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <netinet/in.h>
#import <sys/socket.h>
#import <unistd.h>
#import "GTMSenTestCase.h"
#import "GTMUnitTestDevLog.h"
#import "GTMHTTPServer.h"
#import "GTMRegex.h"
@interface GTMHTTPServerTest : GTMTestCase {
NSData *fetchedData_;
}
@end
@interface GTMHTTPServerTest (PrivateMethods)
- (NSData *)fetchFromPort:(unsigned short)port
payload:(NSString *)payload
chunkSize:(NSUInteger)chunkSize;
- (NSFileHandle *)fileHandleSendingToPort:(unsigned short)port
payload:(NSString *)payload
chunkSize:(NSUInteger)chunkSize;
- (void)readFinished:(NSNotification *)notification;
@end
// helper class
@interface TestServerDelegate : NSObject {
NSMutableArray *requests_;
NSMutableArray *responses_;
}
+ (id)testServerDelegate;
- (NSUInteger)requestCount;
- (GTMHTTPRequestMessage *)popRequest;
- (void)pushResponse:(GTMHTTPResponseMessage *)message;
@end
// helper that throws while handling its request
@interface TestThrowingServerDelegate : TestServerDelegate
// since this method ALWAYS throws, we can mark it as noreturn
- (GTMHTTPResponseMessage *)httpServer:(GTMHTTPServer *)server
handleRequest:(GTMHTTPRequestMessage *)request __attribute__ ((noreturn));
@end
// The timings used for waiting for replies
const NSTimeInterval kGiveUpInterval = 5.0;
const NSTimeInterval kRunLoopInterval = 0.01;
// the size we break writes up into to test the reading code and how long to
// wait between writes.
const NSUInteger kSendChunkSize = 12;
const NSTimeInterval kSendChunkInterval = 0.05;
// ----------------------------------------------------------------------------
@implementation GTMHTTPServerTest
- (void)testInit {
// bad delegates
[GTMUnitTestDevLog expectString:@"missing delegate"];
STAssertNil([[GTMHTTPServer alloc] init], nil);
[GTMUnitTestDevLog expectString:@"missing delegate"];
STAssertNil([[GTMHTTPServer alloc] initWithDelegate:nil], nil);
TestServerDelegate *delegate = [TestServerDelegate testServerDelegate];
STAssertNotNil(delegate, nil);
GTMHTTPServer *server =
[[[GTMHTTPServer alloc] initWithDelegate:delegate] autorelease];
STAssertNotNil(server, nil);
// some attributes
STAssertTrue([server delegate] == delegate, nil);
[server setLocalhostOnly:NO];
STAssertFalse([server localhostOnly], nil);
[server setLocalhostOnly:YES];
STAssertTrue([server localhostOnly], nil);
STAssertEquals([server port], (uint16_t)0, nil);
[server setPort:8080];
STAssertEquals([server port], (uint16_t)8080, nil);
[server setPort:80];
STAssertEquals([server port], (uint16_t)80, nil);
// description (atleast 10 chars)
STAssertGreaterThan([[server description] length], (NSUInteger)10, nil);
}
- (void)testStartStop {
TestServerDelegate *delegate1 = [TestServerDelegate testServerDelegate];
STAssertNotNil(delegate1, nil);
GTMHTTPServer *server1 =
[[[GTMHTTPServer alloc] initWithDelegate:delegate1] autorelease];
STAssertNotNil(server1, nil);
NSError *error = nil;
STAssertTrue([server1 start:&error], @"failed to start (error=%@)", error);
STAssertNil(error, @"error: %@", error);
STAssertGreaterThanOrEqual([server1 port], (uint16_t)1024,
@"how'd we get a reserved port?");
TestServerDelegate *delegate2 = [TestServerDelegate testServerDelegate];
STAssertNotNil(delegate2, nil);
GTMHTTPServer *server2 =
[[[GTMHTTPServer alloc] initWithDelegate:delegate2] autorelease];
STAssertNotNil(server2, nil);
// try the reserved port
[server2 setPort:666];
error = nil;
STAssertFalse([server2 start:&error], nil);
STAssertNotNil(error, nil);
STAssertEqualObjects([error domain], kGTMHTTPServerErrorDomain, nil);
STAssertEquals([error code], (NSInteger)kGTMHTTPServerBindFailedError,
@"port should have been reserved");
// try the same port
[server2 setPort:[server1 port]];
error = nil;
STAssertFalse([server2 start:&error], nil);
STAssertNotNil(error, nil);
STAssertEqualObjects([error domain], kGTMHTTPServerErrorDomain, nil);
STAssertEquals([error code], (NSInteger)kGTMHTTPServerBindFailedError,
@"port should have been in use");
// try a random port again so we really start (prove two can run at once)
[server2 setPort:0];
error = nil;
STAssertTrue([server2 start:&error], @"failed to start (error=%@)", error);
STAssertNil(error, @"error: %@", error);
// shut them down
[server1 stop];
[server2 stop];
}
- (void)testRequests {
TestServerDelegate *delegate = [TestServerDelegate testServerDelegate];
STAssertNotNil(delegate, nil);
GTMHTTPServer *server =
[[[GTMHTTPServer alloc] initWithDelegate:delegate] autorelease];
STAssertNotNil(server, nil);
NSError *error = nil;
STAssertTrue([server start:&error], @"failed to start (error=%@)", error);
STAssertNil(error, @"error: %@", error);
// a request to test all the fields of a request object
NSString *payload =
@"PUT /some/server/path HTTP/1.0\r\n"
@"Content-Length: 16\r\n"
@"Custom-Header: Custom_Value\r\n"
@"\r\n"
@"this is the body";
NSData *reply =
[self fetchFromPort:[server port] payload:payload chunkSize:kSendChunkSize];
STAssertNotNil(reply, nil);
GTMHTTPRequestMessage *request = [delegate popRequest];
STAssertEqualObjects([request version], @"HTTP/1.0", nil);
STAssertEqualObjects([[request URL] absoluteString], @"/some/server/path", nil);
STAssertEqualObjects([request method], @"PUT", nil);
STAssertEqualObjects([request body],
[@"this is the body" dataUsingEncoding:NSUTF8StringEncoding],
nil);
NSDictionary *allHeaders = [request allHeaderFieldValues];
STAssertNotNil(allHeaders, nil);
STAssertEquals([allHeaders count], (NSUInteger)2, nil);
STAssertEqualObjects([allHeaders objectForKey:@"Content-Length"],
@"16", nil);
STAssertEqualObjects([allHeaders objectForKey:@"Custom-Header"],
@"Custom_Value", nil);
STAssertGreaterThan([[request description] length], (NSUInteger)10, nil);
// test different request types (in simple form)
typedef struct {
NSString *method;
NSString *url;
} TestData;
TestData data[] = {
{ @"GET", @"/foo/bar" },
{ @"HEAD", @"/foo/baz" },
{ @"POST", @"/foo" },
{ @"PUT", @"/foo/spam" },
{ @"DELETE", @"/fooby/doo" },
{ @"TRACE", @"/something.html" },
{ @"CONNECT", @"/spam" },
{ @"OPTIONS", @"/wee/doggies" },
};
for (size_t i = 0; i < sizeof(data) / sizeof(TestData); i++) {
payload = [NSString stringWithFormat:@"%@ %@ HTTP/1.0\r\n\r\n",
data[i].method, data[i].url];
STAssertNotNil(payload, nil);
reply = [self fetchFromPort:[server port]
payload:payload
chunkSize:kSendChunkSize];
STAssertNotNil(reply, // just want a reply in this test
@"failed of method %@", data[i].method);
request = [delegate popRequest];
STAssertEqualObjects([[request URL] absoluteString], data[i].url,
@"urls didn't match for index %d", i);
STAssertEqualObjects([request method], data[i].method,
@"methods didn't match for index %d", i);
}
[server stop];
}
- (void)testResponses {
// some quick init tests for invalid things
STAssertNil([[GTMHTTPResponseMessage alloc] init], nil);
STAssertNil([GTMHTTPResponseMessage responseWithBody:nil
contentType:nil
statusCode:99],
nil);
STAssertNil([GTMHTTPResponseMessage responseWithBody:nil
contentType:nil
statusCode:602],
nil);
TestServerDelegate *delegate = [TestServerDelegate testServerDelegate];
STAssertNotNil(delegate, nil);
GTMHTTPServer *server =
[[[GTMHTTPServer alloc] initWithDelegate:delegate] autorelease];
STAssertNotNil(server, nil);
NSError *error = nil;
STAssertTrue([server start:&error], @"failed to start (error=%@)", error);
STAssertNil(error, @"error: %@", error);
// test the html helper
GTMHTTPResponseMessage *expectedResponse =
[GTMHTTPResponseMessage responseWithHTMLString:@"Success!"];
STAssertNotNil(expectedResponse, nil);
STAssertGreaterThan([[expectedResponse description] length],
(NSUInteger)0, nil);
[delegate pushResponse:expectedResponse];
NSData *responseData = [self fetchFromPort:[server port]
payload:@"GET /foo HTTP/1.0\r\n\r\n"
chunkSize:kSendChunkSize];
STAssertNotNil(responseData, nil);
NSString *responseString =
[[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding] autorelease];
STAssertNotNil(responseString, nil);
STAssertTrue([responseString hasPrefix:@"HTTP/1.0 200 OK"], nil);
STAssertTrue([responseString hasSuffix:@"Success!"], @"should end w/ our data");
STAssertNotEquals([responseString rangeOfString:@"Content-Length: 8"].location,
(NSUInteger)NSNotFound, nil);
STAssertNotEquals([responseString rangeOfString:@"Content-Type: text/html; charset=UTF-8"].location,
(NSUInteger)NSNotFound, nil);
// test the plain code response
expectedResponse = [GTMHTTPResponseMessage emptyResponseWithCode:299];
STAssertNotNil(expectedResponse, nil);
STAssertGreaterThan([[expectedResponse description] length],
(NSUInteger)0, nil);
[delegate pushResponse:expectedResponse];
responseData = [self fetchFromPort:[server port]
payload:@"GET /foo HTTP/1.0\r\n\r\n"
chunkSize:kSendChunkSize];
STAssertNotNil(responseData, nil);
responseString =
[[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding] autorelease];
STAssertNotNil(responseString, nil);
STAssertTrue([responseString hasPrefix:@"HTTP/1.0 299 "], nil);
STAssertNotEquals([responseString rangeOfString:@"Content-Length: 0"].location,
(NSUInteger)NSNotFound, nil);
STAssertNotEquals([responseString rangeOfString:@"Content-Type: text/html"].location,
(NSUInteger)NSNotFound, nil);
// test the general api w/ extra header add
expectedResponse =
[GTMHTTPResponseMessage responseWithBody:[@"FOO" dataUsingEncoding:NSUTF8StringEncoding]
contentType:@"some/type"
statusCode:298];
STAssertNotNil(expectedResponse, nil);
STAssertGreaterThan([[expectedResponse description] length],
(NSUInteger)0, nil);
[expectedResponse setValue:@"Custom_Value"
forHeaderField:@"Custom-Header"];
[expectedResponse setValue:nil
forHeaderField:@"Custom-Header2"];
[delegate pushResponse:expectedResponse];
responseData = [self fetchFromPort:[server port]
payload:@"GET /foo HTTP/1.0\r\n\r\n"
chunkSize:kSendChunkSize];
STAssertNotNil(responseData, nil);
responseString =
[[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding] autorelease];
STAssertNotNil(responseString, nil);
STAssertTrue([responseString hasPrefix:@"HTTP/1.0 298"], nil);
STAssertTrue([responseString hasSuffix:@"FOO"], @"should end w/ our data");
STAssertNotEquals([responseString rangeOfString:@"Content-Length: 3"].location,
(NSUInteger)NSNotFound, nil);
STAssertNotEquals([responseString rangeOfString:@"Content-Type: some/type"].location,
(NSUInteger)NSNotFound, nil);
STAssertNotEquals([responseString rangeOfString:@"Custom-Header: Custom_Value"].location,
(NSUInteger)NSNotFound, nil);
STAssertNotEquals([responseString rangeOfString:@"Custom-Header2: "].location,
(NSUInteger)NSNotFound, nil);
[server stop];
}
- (void)testRequstEdgeCases {
// test all the odd things about requests
TestServerDelegate *delegate = [TestServerDelegate testServerDelegate];
STAssertNotNil(delegate, nil);
GTMHTTPServer *server =
[[[GTMHTTPServer alloc] initWithDelegate:delegate] autorelease];
STAssertNotNil(server, nil);
NSError *error = nil;
STAssertTrue([server start:&error], @"failed to start (error=%@)", error);
STAssertNil(error, @"error: %@", error);
// extra data (ie-pipelining)
NSString *payload =
@"GET /some/server/path HTTP/1.0\r\n"
@"\r\n"
@"GET /some/server/path/too HTTP/1.0\r\n"
@"\r\n";
// don't chunk this, we want to make sure both requests get to our server
[GTMUnitTestDevLog expectString:@"Got 38 extra bytes on http request, "
"ignoring them"];
NSData *reply =
[self fetchFromPort:[server port] payload:payload chunkSize:0];
STAssertNotNil(reply, nil);
STAssertEquals([delegate requestCount], (NSUInteger)1, nil);
// close w/o full request
{
// local pool so we can force our handle to close
NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
NSFileHandle *handle =
[self fileHandleSendingToPort:[server port]
payload:@"GET /some/server/path HTTP/"
chunkSize:kSendChunkSize];
STAssertNotNil(handle, nil);
// spin the run loop so reads the start of the request
NSDate* loopIntervalDate =
[NSDate dateWithTimeIntervalSinceNow:kRunLoopInterval];
[[NSRunLoop currentRunLoop] runUntilDate:loopIntervalDate];
// make sure we see the request at this point
STAssertEquals([server activeRequestCount], (NSUInteger)1,
@"should have started the request by now");
// drop the pool to close the connection
[localPool release];
// spin the run loop so it should see the close
loopIntervalDate = [NSDate dateWithTimeIntervalSinceNow:kRunLoopInterval];
[[NSRunLoop currentRunLoop] runUntilDate:loopIntervalDate];
// make sure we didn't get a request (1 is from test before) and make sure
// we don't have some in flight.
STAssertEquals([delegate requestCount], (NSUInteger)1,
@"shouldn't have gotten another request");
STAssertEquals([server activeRequestCount], (NSUInteger)0,
@"should have cleaned up the pending connection");
}
}
- (void)testExceptionDuringRequest {
TestServerDelegate *delegate = [TestThrowingServerDelegate testServerDelegate];
STAssertNotNil(delegate, nil);
GTMHTTPServer *server =
[[[GTMHTTPServer alloc] initWithDelegate:delegate] autorelease];
STAssertNotNil(server, nil);
NSError *error = nil;
STAssertTrue([server start:&error], @"failed to start (error=%@)", error);
STAssertNil(error, @"error: %@", error);
[GTMUnitTestDevLog expectString:@"Exception trying to handle http request: "
"To test our handling"];
NSData *responseData = [self fetchFromPort:[server port]
payload:@"GET /foo HTTP/1.0\r\n\r\n"
chunkSize:kSendChunkSize];
STAssertNotNil(responseData, nil);
STAssertEquals([responseData length], (NSUInteger)0, nil);
STAssertEquals([delegate requestCount], (NSUInteger)1, nil);
STAssertEquals([server activeRequestCount], (NSUInteger)0, nil);
}
@end
// ----------------------------------------------------------------------------
@implementation GTMHTTPServerTest (PrivateMethods)
- (NSData *)fetchFromPort:(unsigned short)port
payload:(NSString *)payload
chunkSize:(NSUInteger)chunkSize {
fetchedData_ = nil;
NSFileHandle *handle = [self fileHandleSendingToPort:port
payload:payload
chunkSize:chunkSize];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(readFinished:)
name:NSFileHandleReadToEndOfFileCompletionNotification
object:handle];
[handle readToEndOfFileInBackgroundAndNotify];
// wait for our reply
NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:kGiveUpInterval];
while (!fetchedData_ && [giveUpDate timeIntervalSinceNow] > 0) {
NSDate* loopIntervalDate =
[NSDate dateWithTimeIntervalSinceNow:kRunLoopInterval];
[[NSRunLoop currentRunLoop] runUntilDate:loopIntervalDate];
}
[center removeObserver:self
name:NSFileHandleReadToEndOfFileCompletionNotification
object:handle];
NSData *result = [fetchedData_ autorelease];
fetchedData_ = nil;
return result;
}
- (NSFileHandle *)fileHandleSendingToPort:(unsigned short)port
payload:(NSString *)payload
chunkSize:(NSUInteger)chunkSize {
int fd = socket(AF_INET, SOCK_STREAM, 0);
STAssertGreaterThan(fd, 0, @"failed to create socket");
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(0x7F000001);
int connectResult =
connect(fd, (struct sockaddr*)(&addr), (socklen_t)sizeof(addr));
STAssertEquals(connectResult, 0, nil);
NSFileHandle *handle =
[[[NSFileHandle alloc] initWithFileDescriptor:fd
closeOnDealloc:YES] autorelease];
STAssertNotNil(handle, nil);
NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
// we can send in one block or in chunked mode
if (chunkSize > 0) {
// we don't write the data in one large block, instead of write it out
// in bits to help test the data collection code.
NSUInteger length = [payloadData length];
for (NSUInteger x = 0 ; x < length ; x += chunkSize) {
NSUInteger dataChunkSize = length - x;
if (dataChunkSize > chunkSize) {
dataChunkSize = chunkSize;
}
NSData *dataChunk
= [payloadData subdataWithRange:NSMakeRange(x, dataChunkSize)];
[handle writeData:dataChunk];
// delay after all but the last chunk to give it time to be read.
if ((x + chunkSize) < length) {
NSDate* loopIntervalDate =
[NSDate dateWithTimeIntervalSinceNow:kSendChunkInterval];
[[NSRunLoop currentRunLoop] runUntilDate:loopIntervalDate];
}
}
} else {
[handle writeData:payloadData];
}
return handle;
}
- (void)readFinished:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
fetchedData_ =
[[userInfo objectForKey:NSFileHandleNotificationDataItem] retain];
}
@end
// ----------------------------------------------------------------------------
@implementation TestServerDelegate
- (id)init {
self = [super init];
if (self) {
requests_ = [[NSMutableArray alloc] init];
responses_ = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
[requests_ release];
[responses_ release];
[super dealloc];
}
+ (id)testServerDelegate {
return [[[[self class] alloc] init] autorelease];
}
- (NSUInteger)requestCount {
return [requests_ count];
}
- (GTMHTTPRequestMessage *)popRequest {
GTMHTTPRequestMessage *result = [[[requests_ lastObject] retain] autorelease];
[requests_ removeLastObject];
return result;
}
- (void)pushResponse:(GTMHTTPResponseMessage *)message {
[responses_ addObject:message];
}
- (GTMHTTPResponseMessage *)httpServer:(GTMHTTPServer *)server
handleRequest:(GTMHTTPRequestMessage *)request {
[requests_ addObject:request];
GTMHTTPResponseMessage *result = nil;
if ([responses_ count] > 0) {
result = [[[responses_ lastObject] retain] autorelease];
[responses_ removeLastObject];
} else {
result = [GTMHTTPResponseMessage responseWithHTMLString:@"success"];
}
return result;
}
@end
// ----------------------------------------------------------------------------
@implementation TestThrowingServerDelegate
- (GTMHTTPResponseMessage *)httpServer:(GTMHTTPServer *)server
handleRequest:(GTMHTTPRequestMessage *)request {
// let the base do its normal work for counts, etc.
[super httpServer:server handleRequest:request];
NSException *exception =
[NSException exceptionWithName:@"InternalTestingException"
reason:@"To test our handling"
userInfo:nil];
@throw exception;
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMHTTPServerTest.m | Objective-C | bsd | 21,453 |
//
// GTMNSString+HTML.h
// Dealing with NSStrings that contain HTML
//
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <Foundation/Foundation.h>
/// Utilities for NSStrings containing HTML
@interface NSString (GTMNSStringHTMLAdditions)
/// Get a string where internal characters that need escaping for HTML are escaped
//
/// For example, '&' become '&'. This will only cover characters from table
/// A.2.2 of http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters
/// which is what you want for a unicode encoded webpage. If you have a ascii
/// or non-encoded webpage, please use stringByEscapingAsciiHTML which will
/// encode all characters.
///
/// For obvious reasons this call is only safe once.
//
// Returns:
// Autoreleased NSString
//
- (NSString *)gtm_stringByEscapingForHTML;
/// Get a string where internal characters that need escaping for HTML are escaped
//
/// For example, '&' become '&'
/// All non-mapped characters (unicode that don't have a &keyword; mapping)
/// will be converted to the appropriate &#xxx; value. If your webpage is
/// unicode encoded (UTF16 or UTF8) use stringByEscapingHTML instead as it is
/// faster, and produces less bloated and more readable HTML (as long as you
/// are using a unicode compliant HTML reader).
///
/// For obvious reasons this call is only safe once.
//
// Returns:
// Autoreleased NSString
//
- (NSString *)gtm_stringByEscapingForAsciiHTML;
/// Get a string where internal characters that are escaped for HTML are unescaped
//
/// For example, '&' becomes '&'
/// Handles   and 2 cases as well
///
// Returns:
// Autoreleased NSString
//
- (NSString *)gtm_stringByUnescapingFromHTML;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+HTML.h | Objective-C | bsd | 2,289 |
//
// GTMStackTrace.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#include <stdlib.h>
#include <dlfcn.h>
#include <mach-o/nlist.h>
#include "GTMStackTrace.h"
// Structure representing a small portion of a stack, starting from the saved
// frame pointer, and continuing through the saved program counter.
struct StackFrame {
void *saved_fp;
#if defined (__ppc__) || defined(__ppc64__)
void *padding;
#endif
void *saved_pc;
};
// __builtin_frame_address(0) is a gcc builtin that returns a pointer to the
// current frame pointer. We then use the frame pointer to walk the stack
// picking off program counters and other saved frame pointers. This works
// great on i386, but PPC requires a little more work because the PC (or link
// register) isn't always stored on the stack.
//
int GTMGetStackProgramCounters(void *outPcs[], int size) {
if (!outPcs || (size < 1)) return 0;
struct StackFrame *fp;
#if defined (__ppc__) || defined(__ppc64__)
outPcs[0] = __builtin_return_address(0);
fp = (struct StackFrame *)__builtin_frame_address(1);
#elif defined (__i386__) || defined(__x86_64__)
fp = (struct StackFrame *)__builtin_frame_address(0);
#else
#error architecture not supported
#endif
int level = 0;
while (level < size) {
if (fp == NULL) {
level--;
break;
}
outPcs[level] = fp->saved_pc;
level++;
fp = (struct StackFrame *)fp->saved_fp;
}
return level;
}
CFStringRef GTMStackTraceCreate(void) {
// The maximum number of stack frames that we will walk. We limit this so
// that super-duper recursive functions (or bugs) don't send us for an
// infinite loop.
static const int kMaxStackTraceDepth = 100;
void *pcs[kMaxStackTraceDepth];
int depth = kMaxStackTraceDepth;
depth = GTMGetStackProgramCounters(pcs, depth);
CFMutableStringRef trace = CFStringCreateMutable(kCFAllocatorDefault, 0);
for (int i = 0; i < depth; i++) {
Dl_info info = { NULL, NULL, NULL, NULL };
dladdr(pcs[i], &info);
const char *symbol = info.dli_sname;
const char *fname = info.dli_fname;
CFStringAppendFormat(trace, NULL,
CFSTR("#%-2d 0x%08lx %s () [%s]\n"),
i, pcs[i],
(symbol ? symbol : "??"),
(fname ? fname : "??"));
}
return trace;
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMStackTrace.c | C | bsd | 2,914 |
//
// NSAppleEventDescriptor+Foundation.h
//
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// A category for dealing with NSAppleEventDescriptors and NSArrays.
@interface NSAppleEventDescriptor (GTMAppleEventDescriptorArrayAdditions)
// Used to register the types you know how to convert into
// NSAppleEventDescriptors.
// See examples in NSAppleEventDescriptor+String, NSAppleEventDescriptor+Number
// etc.
// Args:
// selector - selector to call for any of the types in |types|
// types - an std c array of types of length |count|
// count - number of types in |types|
+ (void)gtm_registerSelector:(SEL)selector
forTypes:(DescType*)types
count:(NSUInteger)count;
// Returns an NSObject for any NSAppleEventDescriptor
// Uses types registerd by registerSelector:forTypes:count: to determine
// what type of object to create. If it doesn't know a type, it attempts
// to return [self stringValue].
- (id)gtm_objectValue;
// Return an NSArray for an AEList
// Returns nil on failure.
- (NSArray*)gtm_arrayValue;
// Return an NSDictionary for an AERecord
// Returns nil on failure.
- (NSDictionary*)gtm_dictionaryValue;
// Return an NSNull for a desc of typeNull
// Returns nil on failure.
- (NSNull*)gtm_nullValue;
// Return a NSAppleEventDescriptor for a double value.
+ (NSAppleEventDescriptor*)gtm_descriptorWithDouble:(double)real;
// Return a NSAppleEventDescriptor for a float value.
+ (NSAppleEventDescriptor*)gtm_descriptorWithFloat:(float)real;
// Return a NSAppleEventDescriptor for a CGFloat value.
+ (NSAppleEventDescriptor*)gtm_descriptorWithCGFloat:(CGFloat)real;
// Attempt to extract a double value. Returns NAN on error.
- (double)gtm_doubleValue;
// Attempt to extract a float value. Returns NAN on error.
- (float)gtm_floatValue;
// Attempt to extract a CGFloat value. Returns NAN on error.
- (CGFloat)gtm_cgFloatValue;
// Attempt to extract a NSNumber. Returns nil on error.
- (NSNumber*)gtm_numberValue;
@end
@interface NSObject (GTMAppleEventDescriptorObjectAdditions)
// A informal protocol that objects can override to return appleEventDescriptors
// for their type. The default is to return [self description] rolled up
// in an NSAppleEventDescriptor. Built in support for:
// NSArray, NSDictionary, NSNull, NSString, NSNumber and NSProcessInfo
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor;
@end
@interface NSAppleEventDescriptor (GTMAppleEventDescriptorAdditions)
// Allows you to send events.
// Returns YES if send was successful.
- (BOOL)gtm_sendEventWithMode:(AESendMode)mode
timeOut:(NSTimeInterval)timeout
reply:(NSAppleEventDescriptor**)reply;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleEventDescriptor+Foundation.h | Objective-C | bsd | 3,317 |
//
// GTMNSEnumerator+Filter.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMNSEnumerator+Filter.h"
#import "GTMDebugSelectorValidation.h"
#import "GTMDefines.h"
#if GTM_IPHONE_SDK
#import <objc/message.h>
#import <objc/runtime.h>
#else
#import <objc/objc-runtime.h>
#endif
// a private subclass of NSEnumerator that does all the work.
// public interface just returns one of these.
// This top level class contains all the additional boilerplate. Specific
// behavior is in the subclasses.
@interface GTMEnumeratorPrivateBase : NSEnumerator {
@protected
NSEnumerator *base_; // STRONG
SEL operation_; // either a predicate or a transform depending on context.
id other_; // STRONG, may be nil
}
@end
@interface GTMEnumeratorPrivateBase (SubclassesMustProvide)
- (BOOL)filterObject:(id)obj returning:(id *)resultp;
@end
@implementation GTMEnumeratorPrivateBase
- (id)initWithBase:(NSEnumerator *)base
sel:(SEL)filter
object:(id)optionalOther {
self = [super init];
if (self) {
// someone would have to subclass or directly create an object of this
// class, and this class is private to this impl.
_GTMDevAssert(base, @"can't initWithBase: a nil base enumerator");
base_ = [base retain];
operation_ = filter;
other_ = [optionalOther retain];
}
return self;
}
// we don't provide an init because this base class is private to this
// impl, and no one would be able to create it (if they do, they get whatever
// they happens...).
- (void)dealloc {
[base_ release];
[other_ release];
[super dealloc];
}
- (id)nextObject {
for (id obj = [base_ nextObject]; obj; obj = [base_ nextObject]) {
id result = nil;
if ([self filterObject:obj returning:&result]) {
return result;
}
}
return nil;
}
@end
// a transformer, for each item in the enumerator, returns a f(item).
@interface GTMEnumeratorTransformer : GTMEnumeratorPrivateBase
@end
@implementation GTMEnumeratorTransformer
- (BOOL)filterObject:(id)obj returning:(id *)resultp {
*resultp = [obj performSelector:operation_ withObject:other_];
return nil != *resultp;
}
@end
// a transformer, for each item in the enumerator, returns a f(item).
// a target transformer swaps the target and the argument.
@interface GTMEnumeratorTargetTransformer : GTMEnumeratorPrivateBase
@end
@implementation GTMEnumeratorTargetTransformer
- (BOOL)filterObject:(id)obj returning:(id *)resultp {
*resultp = [other_ performSelector:operation_ withObject:obj];
return nil != *resultp;
}
@end
// a filter, for each item in the enumerator, if(f(item)) { returns item. }
@interface GTMEnumeratorFilter : GTMEnumeratorPrivateBase
@end
@implementation GTMEnumeratorFilter
// We must take care here, since Intel leaves junk in high bytes of return register
// for predicates that return BOOL.
// For details see:
// http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_23.html
// and
// http://www.red-sweater.com/blog/320/abusing-objective-c-with-class#comment-83187
- (BOOL)filterObject:(id)obj returning:(id *)resultp {
*resultp = obj;
return ((BOOL (*)(id, SEL, id))objc_msgSend)(obj, operation_, other_);
}
@end
// a target filter, for each item in the enumerator, if(f(item)) { returns item. }
// a target transformer swaps the target and the argument.
@interface GTMEnumeratorTargetFilter : GTMEnumeratorPrivateBase
@end
@implementation GTMEnumeratorTargetFilter
// We must take care here, since Intel leaves junk in high bytes of return register
// for predicates that return BOOL.
// For details see:
// http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_23.html
// and
// http://www.red-sweater.com/blog/320/abusing-objective-c-with-class#comment-83187
- (BOOL)filterObject:(id)obj returning:(id *)resultp {
*resultp = obj;
return ((BOOL (*)(id, SEL, id))objc_msgSend)(other_, operation_, obj);
}
@end
@implementation NSEnumerator (GTMEnumeratorFilterAdditions)
- (NSEnumerator *)gtm_filteredEnumeratorByMakingEachObjectPerformSelector:(SEL)selector
withObject:(id)argument {
return [[[GTMEnumeratorFilter alloc] initWithBase:self
sel:selector
object:argument] autorelease];
}
- (NSEnumerator *)gtm_enumeratorByMakingEachObjectPerformSelector:(SEL)selector
withObject:(id)argument {
return [[[GTMEnumeratorTransformer alloc] initWithBase:self
sel:selector
object:argument] autorelease];
}
- (NSEnumerator *)gtm_filteredEnumeratorByTarget:(id)target
performOnEachSelector:(SEL)selector {
// make sure the object impls this selector taking an object as an arg.
GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(target, selector,
@encode(BOOL),
@encode(id),
NULL);
return [[[GTMEnumeratorTargetFilter alloc] initWithBase:self
sel:selector
object:target] autorelease];
}
- (NSEnumerator *)gtm_enumeratorByTarget:(id)target
performOnEachSelector:(SEL)selector {
// make sure the object impls this selector taking an object as an arg.
GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(target, selector,
@encode(id),
@encode(id),
NULL);
return [[[GTMEnumeratorTargetTransformer alloc] initWithBase:self
sel:selector
object:target] autorelease];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSEnumerator+Filter.m | Objective-C | bsd | 6,804 |
//
// GTMBase64Test.m
//
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMBase64.h"
#include <stdlib.h> // for randiom/srandomdev
static void FillWithRandom(char *data, NSUInteger len) {
char *max = data + len;
for ( ; data < max ; ++data) {
*data = random() & 0xFF;
}
}
static BOOL NoEqualChar(NSData *data) {
const char *scan = [data bytes];
const char *max = scan + [data length];
for ( ; scan < max ; ++scan) {
if (*scan == '=') {
return NO;
}
}
return YES;
}
@interface GTMBase64Test : GTMTestCase
@end
@implementation GTMBase64Test
- (void)setUp {
// seed random from /dev/random
srandomdev();
}
- (void)testBase64 {
// generate a range of sizes w/ random content
for (int x = 1 ; x < 1024 ; ++x) {
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:x];
FillWithRandom([data mutableBytes], [data length]);
// w/ *Bytes apis
NSData *encoded = [GTMBase64 encodeBytes:[data bytes] length:[data length]];
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Bytes apis should be a multiple of 4");
NSData *dataPrime = [GTMBase64 decodeBytes:[encoded bytes]
length:[encoded length]];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Bytes apis");
// w/ *Data apis
encoded = [GTMBase64 encodeData:data];
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Data apis should be a multiple of 4");
dataPrime = [GTMBase64 decodeData:encoded];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Data apis");
// Bytes to String and back
NSString *encodedString = [GTMBase64 stringByEncodingBytes:[data bytes]
length:[data length]];
STAssertEquals(([encodedString length] % 4), (NSUInteger)0,
@"encoded size for Bytes to Strings should be a multiple of 4");
dataPrime = [GTMBase64 decodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Bytes to Strings");
// Data to String and back
encodedString = [GTMBase64 stringByEncodingData:data];
STAssertEquals(([encodedString length] % 4), (NSUInteger)0,
@"encoded size for Data to Strings should be a multiple of 4");
dataPrime = [GTMBase64 decodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Bytes to Strings");
}
{
// now test all byte values
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:256];
unsigned char *scan = (unsigned char*)[data mutableBytes];
for (int x = 0 ; x <= 255 ; ++x) {
*scan++ = x;
}
// w/ *Bytes apis
NSData *encoded = [GTMBase64 encodeBytes:[data bytes] length:[data length]];
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Bytes apis should be a multiple of 4");
NSData *dataPrime = [GTMBase64 decodeBytes:[encoded bytes]
length:[encoded length]];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Bytes apis");
// w/ *Data apis
encoded = [GTMBase64 encodeData:data];
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Data apis should be a multiple of 4");
dataPrime = [GTMBase64 decodeData:encoded];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Data apis");
// Bytes to String and back
NSString *encodedString = [GTMBase64 stringByEncodingBytes:[data bytes]
length:[data length]];
STAssertEquals(([encodedString length] % 4), (NSUInteger)0,
@"encoded size for Bytes to Strings should be a multiple of 4");
dataPrime = [GTMBase64 decodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Bytes to Strings");
// Data to String and back
encodedString = [GTMBase64 stringByEncodingData:data];
STAssertEquals(([encodedString length] % 4), (NSUInteger)0,
@"encoded size for Data to Strings should be a multiple of 4");
dataPrime = [GTMBase64 decodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Data to Strings");
}
{
// test w/ a mix of spacing characters
// generate some data, encode it, and add spaces
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:253]; // should get some padding chars on the end
FillWithRandom([data mutableBytes], [data length]);
NSString *encodedString = [GTMBase64 stringByEncodingData:data];
NSMutableString *encodedAndSpaced =
[[encodedString mutableCopy] autorelease];
NSString *spaces[] = { @"\t", @"\n", @"\r", @" " };
const NSUInteger numSpaces = sizeof(spaces) / sizeof(NSString*);
for (int x = 0 ; x < 512 ; ++x) {
NSUInteger offset = random() % ([encodedAndSpaced length] + 1);
[encodedAndSpaced insertString:spaces[random() % numSpaces]
atIndex:offset];
}
// we'll need it as data for apis
NSData *encodedAsData =
[encodedAndSpaced dataUsingEncoding:NSASCIIStringEncoding];
STAssertNotNil(encodedAsData, @"failed to extract from string");
STAssertEquals([encodedAsData length], [encodedAndSpaced length],
@"lengths for encoded string and data didn't match?");
// all the decode modes
NSData *dataPrime = [GTMBase64 decodeData:encodedAsData];
STAssertEqualObjects(data, dataPrime,
@"failed Data decode w/ spaces");
dataPrime = [GTMBase64 decodeBytes:[encodedAsData bytes]
length:[encodedAsData length]];
STAssertEqualObjects(data, dataPrime,
@"failed Bytes decode w/ spaces");
dataPrime = [GTMBase64 decodeString:encodedAndSpaced];
STAssertEqualObjects(data, dataPrime,
@"failed String decode w/ spaces");
}
}
- (void)testWebSafeBase64 {
// loop to test w/ and w/o padding
for (int paddedLoop = 0; paddedLoop < 2 ; ++paddedLoop) {
BOOL padded = (paddedLoop == 1);
// generate a range of sizes w/ random content
for (int x = 1 ; x < 1024 ; ++x) {
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:x];
FillWithRandom([data mutableBytes], [data length]);
// w/ *Bytes apis
NSData *encoded = [GTMBase64 webSafeEncodeBytes:[data bytes]
length:[data length]
padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Bytes apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via *Bytes apis had a base64 padding char");
}
NSData *dataPrime = [GTMBase64 webSafeDecodeBytes:[encoded bytes]
length:[encoded length]];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Bytes apis");
// w/ *Data apis
encoded = [GTMBase64 webSafeEncodeData:data padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Data apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via *Data apis had a base64 padding char");
}
dataPrime = [GTMBase64 webSafeDecodeData:encoded];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Data apis");
// Bytes to String and back
NSString *encodedString =
[GTMBase64 stringByWebSafeEncodingBytes:[data bytes]
length:[data length]
padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Bytes apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via Bytes to Strings had a base64 padding char");
}
dataPrime = [GTMBase64 webSafeDecodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Bytes to Strings");
// Data to String and back
encodedString =
[GTMBase64 stringByWebSafeEncodingData:data padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Data apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via Data to Strings had a base64 padding char");
}
dataPrime = [GTMBase64 webSafeDecodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Data to Strings");
}
{
// now test all byte values
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:256];
unsigned char *scan = (unsigned char*)[data mutableBytes];
for (int x = 0 ; x <= 255 ; ++x) {
*scan++ = x;
}
// w/ *Bytes apis
NSData *encoded =
[GTMBase64 webSafeEncodeBytes:[data bytes]
length:[data length]
padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Bytes apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via *Bytes apis had a base64 padding char");
}
NSData *dataPrime = [GTMBase64 webSafeDecodeBytes:[encoded bytes]
length:[encoded length]];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Bytes apis");
// w/ *Data apis
encoded = [GTMBase64 webSafeEncodeData:data padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Data apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via *Data apis had a base64 padding char");
}
dataPrime = [GTMBase64 webSafeDecodeData:encoded];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip via *Data apis");
// Bytes to String and back
NSString *encodedString =
[GTMBase64 stringByWebSafeEncodingBytes:[data bytes]
length:[data length]
padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Bytes apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via Bytes to Strings had a base64 padding char");
}
dataPrime = [GTMBase64 webSafeDecodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Bytes to Strings");
// Data to String and back
encodedString =
[GTMBase64 stringByWebSafeEncodingData:data padded:padded];
if (padded) {
STAssertEquals(([encoded length] % 4), (NSUInteger)0,
@"encoded size via *Data apis should be a multiple of 4");
} else {
STAssertTrue(NoEqualChar(encoded),
@"encoded via Data to Strings had a base64 padding char");
}
dataPrime = [GTMBase64 webSafeDecodeString:encodedString];
STAssertEqualObjects(data, dataPrime,
@"failed to round trip for Data to Strings");
}
{
// test w/ a mix of spacing characters
// generate some data, encode it, and add spaces
NSMutableData *data = [NSMutableData data];
STAssertNotNil(data, @"failed to alloc data block");
[data setLength:253]; // should get some padding chars on the end
FillWithRandom([data mutableBytes], [data length]);
NSString *encodedString = [GTMBase64 stringByWebSafeEncodingData:data
padded:padded];
NSMutableString *encodedAndSpaced =
[[encodedString mutableCopy] autorelease];
NSString *spaces[] = { @"\t", @"\n", @"\r", @" " };
const NSUInteger numSpaces = sizeof(spaces) / sizeof(NSString*);
for (int x = 0 ; x < 512 ; ++x) {
NSUInteger offset = random() % ([encodedAndSpaced length] + 1);
[encodedAndSpaced insertString:spaces[random() % numSpaces]
atIndex:offset];
}
// we'll need it as data for apis
NSData *encodedAsData =
[encodedAndSpaced dataUsingEncoding:NSASCIIStringEncoding];
STAssertNotNil(encodedAsData, @"failed to extract from string");
STAssertEquals([encodedAsData length], [encodedAndSpaced length],
@"lengths for encoded string and data didn't match?");
// all the decode modes
NSData *dataPrime = [GTMBase64 webSafeDecodeData:encodedAsData];
STAssertEqualObjects(data, dataPrime,
@"failed Data decode w/ spaces");
dataPrime = [GTMBase64 webSafeDecodeBytes:[encodedAsData bytes]
length:[encodedAsData length]];
STAssertEqualObjects(data, dataPrime,
@"failed Bytes decode w/ spaces");
dataPrime = [GTMBase64 webSafeDecodeString:encodedAndSpaced];
STAssertEqualObjects(data, dataPrime,
@"failed String decode w/ spaces");
}
} // paddedLoop
}
- (void)testErrors {
const int something = 0;
NSString *nonAscString = [NSString stringWithUTF8String:"This test ©™®๒०᠐٧"];
STAssertNil([GTMBase64 encodeData:nil], @"it worked?");
STAssertNil([GTMBase64 decodeData:nil], @"it worked?");
STAssertNil([GTMBase64 encodeBytes:NULL length:10], @"it worked?");
STAssertNil([GTMBase64 encodeBytes:&something length:0], @"it worked?");
STAssertNil([GTMBase64 decodeBytes:NULL length:10], @"it worked?");
STAssertNil([GTMBase64 decodeBytes:&something length:0], @"it worked?");
STAssertNil([GTMBase64 stringByEncodingData:nil], @"it worked?");
STAssertNil([GTMBase64 stringByEncodingBytes:NULL length:10], @"it worked?");
STAssertNil([GTMBase64 stringByEncodingBytes:&something length:0], @"it worked?");
STAssertNil([GTMBase64 decodeString:nil], @"it worked?");
// test some pads at the end that aren't right
STAssertNil([GTMBase64 decodeString:@"=="], @"it worked?"); // just pads
STAssertNil([GTMBase64 decodeString:@"vw="], @"it worked?"); // missing pad (in state 2)
STAssertNil([GTMBase64 decodeString:@"vw"], @"it worked?"); // missing pad (in state 2)
STAssertNil([GTMBase64 decodeString:@"NNw"], @"it worked?"); // missing pad (in state 3)
STAssertNil([GTMBase64 decodeString:@"vw=v"], @"it worked?"); // missing pad, has something else
STAssertNil([GTMBase64 decodeString:@"v="], @"it worked?"); // missing a needed char, has pad instead
STAssertNil([GTMBase64 decodeString:@"v"], @"it worked?"); // missing a needed char
STAssertNil([GTMBase64 decodeString:@"vw== vw"], @"it worked?");
STAssertNil([GTMBase64 decodeString:nonAscString], @"it worked?");
STAssertNil([GTMBase64 decodeString:@"@@@not valid###"], @"it worked?");
// carefully crafted bad input to make sure we don't overwalk
STAssertNil([GTMBase64 decodeString:@"WD=="], @"it worked?");
STAssertNil([GTMBase64 webSafeEncodeData:nil padded:YES], @"it worked?");
STAssertNil([GTMBase64 webSafeDecodeData:nil], @"it worked?");
STAssertNil([GTMBase64 webSafeEncodeBytes:NULL length:10 padded:YES],
@"it worked?");
STAssertNil([GTMBase64 webSafeEncodeBytes:&something length:0 padded:YES],
@"it worked?");
STAssertNil([GTMBase64 webSafeDecodeBytes:NULL length:10], @"it worked?");
STAssertNil([GTMBase64 webSafeDecodeBytes:&something length:0], @"it worked?");
STAssertNil([GTMBase64 stringByWebSafeEncodingData:nil padded:YES],
@"it worked?");
STAssertNil([GTMBase64 stringByWebSafeEncodingBytes:NULL
length:10
padded:YES],
@"it worked?");
STAssertNil([GTMBase64 stringByWebSafeEncodingBytes:&something
length:0
padded:YES],
@"it worked?");
STAssertNil([GTMBase64 webSafeDecodeString:nil], @"it worked?");
// test some pads at the end that aren't right
STAssertNil([GTMBase64 webSafeDecodeString:@"=="], @"it worked?"); // just pad chars
STAssertNil([GTMBase64 webSafeDecodeString:@"aw="], @"it worked?"); // missing pad
STAssertNil([GTMBase64 webSafeDecodeString:@"aw=a"], @"it worked?"); // missing pad, has something else
STAssertNil([GTMBase64 webSafeDecodeString:@"a"], @"it worked?"); // missing a needed char
STAssertNil([GTMBase64 webSafeDecodeString:@"a="], @"it worked?"); // missing a needed char, has pad instead
STAssertNil([GTMBase64 webSafeDecodeString:@"aw== a"], @"it worked?"); // missing pad
STAssertNil([GTMBase64 webSafeDecodeString:nonAscString], @"it worked?");
STAssertNil([GTMBase64 webSafeDecodeString:@"@@@not valid###"], @"it worked?");
// carefully crafted bad input to make sure we don't overwalk
STAssertNil([GTMBase64 webSafeDecodeString:@"WD=="], @"it worked?");
// make sure our local helper is working right
STAssertFalse(NoEqualChar([NSData dataWithBytes:"aa=zz" length:5]), @"");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMBase64Test.m | Objective-C | bsd | 19,392 |
//
// GTMLogger+ASLTest.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMLogger+ASL.h"
#import "GTMSenTestCase.h"
@interface DummyASLClient : GTMLoggerASLClient
@end
static NSMutableArray *gDummyLog; // weak
@implementation DummyASLClient
- (void)log:(NSString *)msg level:(int)level {
NSString *line = [msg stringByAppendingFormat:@"@%d", level];
[gDummyLog addObject:line];
}
@end
@interface GTMLogger_ASLTest : GTMTestCase
@end
@implementation GTMLogger_ASLTest
- (void)testCreation {
GTMLogger *aslLogger = [GTMLogger standardLoggerWithASL];
STAssertNotNil(aslLogger, nil);
GTMLogASLWriter *writer = [GTMLogASLWriter aslWriter];
STAssertNotNil(writer, nil);
}
- (void)testLogWriter {
gDummyLog = [[[NSMutableArray alloc] init] autorelease];
GTMLogASLWriter *writer = [[[GTMLogASLWriter alloc]
initWithClientClass:[DummyASLClient class]]
autorelease];
STAssertNotNil(writer, nil);
STAssertTrue([gDummyLog count] == 0, nil);
// Log some messages
[writer logMessage:@"unknown" level:kGTMLoggerLevelUnknown];
[writer logMessage:@"debug" level:kGTMLoggerLevelDebug];
[writer logMessage:@"info" level:kGTMLoggerLevelInfo];
[writer logMessage:@"error" level:kGTMLoggerLevelError];
[writer logMessage:@"assert" level:kGTMLoggerLevelAssert];
// Inspect the logged message to make sure they were logged correctly. The
// dummy writer will save the messages w/ @level concatenated. The "level"
// will be the ASL level, not the GTMLogger level. GTMLogASLWriter will log
// all
NSArray *expected = [NSArray arrayWithObjects:
@"unknown@5",
@"debug@5",
@"info@5",
@"error@3",
@"assert@1",
nil];
STAssertEqualObjects(gDummyLog, expected, nil);
gDummyLog = nil;
}
- (void)testASLClient {
GTMLoggerASLClient *client = [[GTMLoggerASLClient alloc] init];
STAssertNotNil(client, nil);
[client release];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMLogger+ASLTest.m | Objective-C | bsd | 2,652 |
//
// GTMNSData+zlib.h
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
/// Helpers for dealing w/ zlib inflate/deflate calls.
@interface NSData (GTMZLibAdditions)
/// Return an autoreleased NSData w/ the result of gzipping the bytes.
//
// Uses the default compression level.
+ (NSData *)gtm_dataByGzippingBytes:(const void *)bytes
length:(NSUInteger)length;
/// Return an autoreleased NSData w/ the result of gzipping the payload of |data|.
//
// Uses the default compression level.
+ (NSData *)gtm_dataByGzippingData:(NSData *)data;
/// Return an autoreleased NSData w/ the result of gzipping the bytes using |level| compression level.
//
// |level| can be 1-9, any other values will be clipped to that range.
+ (NSData *)gtm_dataByGzippingBytes:(const void *)bytes
length:(NSUInteger)length
compressionLevel:(int)level;
/// Return an autoreleased NSData w/ the result of gzipping the payload of |data| using |level| compression level.
+ (NSData *)gtm_dataByGzippingData:(NSData *)data
compressionLevel:(int)level;
// NOTE: deflate is *NOT* gzip. deflate is a "zlib" stream. pick which one
// you really want to create. (the inflate api will handle either)
/// Return an autoreleased NSData w/ the result of deflating the bytes.
//
// Uses the default compression level.
+ (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes
length:(NSUInteger)length;
/// Return an autoreleased NSData w/ the result of deflating the payload of |data|.
//
// Uses the default compression level.
+ (NSData *)gtm_dataByDeflatingData:(NSData *)data;
/// Return an autoreleased NSData w/ the result of deflating the bytes using |level| compression level.
//
// |level| can be 1-9, any other values will be clipped to that range.
+ (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes
length:(NSUInteger)length
compressionLevel:(int)level;
/// Return an autoreleased NSData w/ the result of deflating the payload of |data| using |level| compression level.
+ (NSData *)gtm_dataByDeflatingData:(NSData *)data
compressionLevel:(int)level;
/// Return an autoreleased NSData w/ the result of decompressing the bytes.
//
// The bytes to decompress can be zlib or gzip payloads.
+ (NSData *)gtm_dataByInflatingBytes:(const void *)bytes
length:(NSUInteger)length;
/// Return an autoreleased NSData w/ the result of decompressing the payload of |data|.
//
// The data to decompress can be zlib or gzip payloads.
+ (NSData *)gtm_dataByInflatingData:(NSData *)data;
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSData+zlib.h | Objective-C | bsd | 3,310 |
//
// NSAppleScript+Handler.m
//
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <Carbon/Carbon.h>
#import "GTMNSAppleScript+Handler.h"
#import "GTMNSAppleEventDescriptor+Foundation.h"
#import "GTMNSAppleEventDescriptor+Handler.h"
#import "GTMFourCharCode.h"
#import "GTMMethodCheck.h"
// Some private methods that we need to call
@interface NSAppleScript (NSPrivate)
+ (ComponentInstance)_defaultScriptingComponent;
- (OSAID) _compiledScriptID;
- (id)_initWithData:(NSData*)data error:(NSDictionary**)error;
@end
@interface NSMethodSignature (NSPrivate)
+ (id)signatureWithObjCTypes:(const char *)fp8;
@end
@implementation NSAppleScript(GTMAppleScriptHandlerAdditions)
GTM_METHOD_CHECK(NSAppleEventDescriptor, gtm_descriptorWithPositionalHandler:parametersArray:); // COV_NF_LINE
GTM_METHOD_CHECK(NSAppleEventDescriptor, gtm_descriptorWithLabeledHandler:labels:parameters:count:); // COV_NF_LINE
GTM_METHOD_CHECK(NSAppleEventDescriptor, gtm_registerSelector:forTypes:count:); // COV_NF_LINE
+ (void)load {
DescType types[] = {
typeScript
};
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_scriptValue)
forTypes:types
count:sizeof(types)/sizeof(DescType)];
DescType types2[] = {
'evnt' // No type code for this one
};
[NSAppleEventDescriptor gtm_registerSelector:@selector(gtm_eventValue)
forTypes:types2
count:sizeof(types2)/sizeof(DescType)];
[pool release];
}
- (OSAID)gtm_realIDAndComponent:(ComponentInstance*)component {
if (![self isCompiled]) {
NSDictionary *error;
if (![self compileAndReturnError:&error]) {
_GTMDevLog(@"Unable to compile script: %@ %@", self, error);
return kOSANullScript;
}
}
OSAID genericID = [self _compiledScriptID];
ComponentInstance genericComponent = [NSAppleScript _defaultScriptingComponent];
OSAError err = OSAGenericToRealID(genericComponent, &genericID, component);
if (err) {
_GTMDevLog(@"Unable to get real id script: %@ %@", self, err); // COV_NF_LINE
genericID = kOSANullScript; // COV_NF_LINE
}
return genericID;
}
- (NSAppleEventDescriptor*)gtm_executePositionalHandler:(NSString*)handler
parameters:(NSArray*)params
error:(NSDictionary**)error {
NSAppleEventDescriptor *event
= [NSAppleEventDescriptor gtm_descriptorWithPositionalHandler:handler
parametersArray:params];
return [self executeAppleEvent:event error:error];
}
- (NSAppleEventDescriptor*)gtm_executeLabeledHandler:(NSString*)handler
labels:(AEKeyword*)labels
parameters:(id*)params
count:(NSUInteger)count
error:(NSDictionary **)error {
NSAppleEventDescriptor *event
= [NSAppleEventDescriptor gtm_descriptorWithLabeledHandler:handler
labels:labels
parameters:params
count:count];
return [self executeAppleEvent:event error:error];
}
- (NSSet*)gtm_handlers {
AEDescList names = { typeNull, NULL };
NSArray *array = nil;
ComponentInstance component;
OSAID osaID = [self gtm_realIDAndComponent:&component];
OSAError err = OSAGetHandlerNames(component, kOSAModeNull, osaID, &names);
if (!err) {
NSAppleEventDescriptor *desc
= [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&names] autorelease];
array = [desc gtm_objectValue];
}
if (err) {
_GTMDevLog(@"Error getting handlers: %d", err);
}
return [NSSet setWithArray:array];
}
- (NSSet*)gtm_properties {
AEDescList names = { typeNull, NULL };
NSArray *array = nil;
ComponentInstance component;
OSAID osaID = [self gtm_realIDAndComponent:&component];
OSAError err = OSAGetPropertyNames(component, kOSAModeNull, osaID, &names);
if (!err) {
NSAppleEventDescriptor *desc
= [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&names] autorelease];
array = [desc gtm_objectValue];
}
if (err) {
_GTMDevLog(@"Error getting properties: %d", err);
}
return [NSSet setWithArray:array];
}
- (BOOL)gtm_setValue:(id)value forProperty:(NSString*)property {
BOOL wasGood = NO;
NSAppleEventDescriptor *desc = [value gtm_appleEventDescriptor];
NSAppleEventDescriptor *propertyName = [property gtm_appleEventDescriptor];
OSAError error = paramErr;
if (desc && propertyName) {
OSAID valueID = kOSANullScript;
ComponentInstance component;
OSAID scriptID = [self gtm_realIDAndComponent:&component];
error = OSACoerceFromDesc(component,
[desc aeDesc],
kOSAModeNull,
&valueID);
if (!error) {
error = OSASetProperty(component, kOSAModeNull,
scriptID, [propertyName aeDesc], valueID);
if (!error) {
wasGood = YES;
}
}
}
if (!wasGood) {
_GTMDevLog(@"Unable to setValue:%@ forProperty:%@ from %@ (%d)",
value, property, self, error);
}
return wasGood;
}
- (id)gtm_valueForProperty:(NSString*)property {
id value = nil;
NSAppleEventDescriptor *propertyName = [property gtm_appleEventDescriptor];
OSAError error = paramErr;
if (propertyName) {
ComponentInstance component;
OSAID scriptID = [self gtm_realIDAndComponent:&component];
OSAID valueID = kOSANullScript;
error = OSAGetProperty(component,
kOSAModeNull,
scriptID,
[propertyName aeDesc],
&valueID);
if (!error) {
AEDesc aeDesc;
error = OSACoerceToDesc(component,
valueID,
typeWildCard,
kOSAModeNull,
&aeDesc);
if (!error) {
NSAppleEventDescriptor *desc
= [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&aeDesc] autorelease];
value = [desc gtm_objectValue];
}
}
}
if (error) {
_GTMDevLog(@"Unable to get valueForProperty:%@ from %@ (%d)",
property, self, error);
}
return value;
}
- (NSAppleEventDescriptor*)gtm_appleEventDescriptor {
ComponentInstance component;
OSAID osaID = [self gtm_realIDAndComponent:&component];
AEDesc result = { typeNull, NULL };
NSAppleEventDescriptor *desc = nil;
OSAError err = OSACoerceToDesc(component,
osaID,
typeScript,
kOSAModeNull,
&result);
if (!err) {
desc = [[[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&result] autorelease];
} else {
_GTMDevLog(@"Unable to coerce script %d", err); // COV_NF_LINE
}
return desc;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
if (!signature) {
NSMutableString *types = [NSMutableString stringWithString:@"@@:"];
NSString *selName = NSStringFromSelector(aSelector);
NSArray *selArray = [selName componentsSeparatedByString:@":"];
NSUInteger count = [selArray count];
for (NSUInteger i = 1; i < count; i++) {
[types appendString:@"@"];
}
signature = [NSMethodSignature signatureWithObjCTypes:[types UTF8String]];
}
return signature;
}
- (void)forwardInvocation:(NSInvocation *)invocation {
SEL sel = [invocation selector];
NSMutableString *handlerName = [NSStringFromSelector(sel) mutableCopy];
NSUInteger handlerOrigLength = [handlerName length];
[handlerName replaceOccurrencesOfString:@":"
withString:@""
options:0
range:NSMakeRange(0,handlerOrigLength)];
NSUInteger argCount = handlerOrigLength - [handlerName length];
NSMutableArray *args = [NSMutableArray arrayWithCapacity:argCount];
for (NSUInteger i = 0; i < argCount; ++i) {
id arg;
// +2 to ignore _sel and _cmd
[invocation getArgument:&arg atIndex:i + 2];
[args addObject:arg];
}
NSDictionary *error = nil;
NSAppleEventDescriptor *desc = [self gtm_executePositionalHandler:handlerName
parameters:args
error:&error];
if ([[invocation methodSignature] methodReturnLength] > 0) {
id returnValue = [desc gtm_objectValue];
[invocation setReturnValue:&returnValue];
}
}
@end
@implementation NSAppleEventDescriptor(GMAppleEventDescriptorScriptAdditions)
- (NSAppleScript*)gtm_scriptValue {
NSDictionary *error;
NSAppleScript *script = [[[NSAppleScript alloc] _initWithData:[self data]
error:&error] autorelease];
if (!script) {
_GTMDevLog(@"Unable to create script: %@", error); // COV_NF_LINE
}
return script;
}
- (NSString*)gtm_eventValue {
struct AEEventRecordStruct {
AEEventClass eventClass;
AEEventID eventID;
};
NSData *data = [self data];
const struct AEEventRecordStruct *record
= (const struct AEEventRecordStruct*)[data bytes];
NSString *eClass = [GTMFourCharCode stringWithFourCharCode:record->eventClass];
NSString *eID = [GTMFourCharCode stringWithFourCharCode:record->eventID];
return [eClass stringByAppendingString:eID];
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSAppleScript+Handler.m | Objective-C | bsd | 10,505 |
//
// GTMNSFileManager+PathTest.m
//
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMNSFileManager+Path.h"
@interface GTMNSFileManager_PathTest : GTMTestCase {
NSString *baseDir_;
}
@end
@implementation GTMNSFileManager_PathTest
- (void)setUp {
// make a directory to scribble in
baseDir_ =
[[NSTemporaryDirectory()
stringByAppendingPathComponent:@"GTMNSFileManager_PathTest"] retain];
if (baseDir_) {
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:baseDir_] &&
![fm createDirectoryAtPath:baseDir_ attributes:nil]) {
// COV_NF_START
// if the dir exists or we failed to create it, drop the baseDir_
[baseDir_ release];
baseDir_ = nil;
// COV_NF_END
}
}
}
- (void)tearDown {
if (baseDir_) {
// clean up our directory
NSFileManager *fm = [NSFileManager defaultManager];
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
NSError *error = nil;
[fm removeItemAtPath:baseDir_ error:&error];
STAssertNil(error,
@"Unable to delete %@: %@", baseDir_, [error description]);
#else
[fm removeFileAtPath:baseDir_ handler:nil];
#endif
[baseDir_ release];
baseDir_ = nil;
}
}
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
- (void)testCreateFullPathToDirectoryAttributes {
STAssertNotNil(baseDir_, @"setUp failed");
NSString *testPath =
[baseDir_ stringByAppendingPathComponent:@"/foo/bar/baz"];
STAssertNotNil(testPath, nil);
NSFileManager *fm = [NSFileManager defaultManager];
STAssertFalse([fm fileExistsAtPath:testPath],
@"You must delete '%@' before running this test", testPath);
STAssertFalse([fm gtm_createFullPathToDirectory:nil attributes:nil],
@"didn't fail on nil input");
STAssertTrue([fm gtm_createFullPathToDirectory:testPath attributes:nil],
@"Failed to create nested testPath");
STAssertTrue([fm gtm_createFullPathToDirectory:testPath attributes:nil],
@"Failed to succeed on second create of testPath");
NSString *pathToFail = [@"/etc" stringByAppendingPathComponent:testPath];
STAssertFalse([fm gtm_createFullPathToDirectory:pathToFail attributes:nil],
@"We were allowed to create a dir in '/etc'?!");
STAssertFalse([fm gtm_createFullPathToDirectory:nil attributes:nil],
@"Should have failed when passed (nil)");
}
#endif // MAC_OS_X_VERSION_MIN_REQUIRED < 1050
- (void)testfilePathsWithExtensionsInDirectory {
STAssertNotNil(baseDir_, @"setUp failed");
NSFileManager *fm = [NSFileManager defaultManager];
NSString *bogusPath = @"/some/place/that/does/not/exist";
// --------------------------------------------------------------------------
// test fail cases first
// single
STAssertNil([fm gtm_filePathsWithExtension:nil inDirectory:nil],
@"shouldn't have gotten anything for nil dir");
STAssertNil([fm gtm_filePathsWithExtension:@"txt" inDirectory:nil],
@"shouldn't have gotten anything for nil dir");
STAssertNil([fm gtm_filePathsWithExtension:@"txt" inDirectory:bogusPath],
@"shouldn't have gotten anything for a bogus dir");
// array
STAssertNil([fm gtm_filePathsWithExtensions:nil inDirectory:nil],
@"shouldn't have gotten anything for nil dir");
STAssertNil([fm gtm_filePathsWithExtensions:[NSArray array] inDirectory:nil],
@"shouldn't have gotten anything for nil dir");
STAssertNil([fm gtm_filePathsWithExtensions:[NSArray arrayWithObject:@"txt"]
inDirectory:nil],
@"shouldn't have gotten anything for nil dir");
STAssertNil([fm gtm_filePathsWithExtensions:[NSArray arrayWithObject:@"txt"]
inDirectory:bogusPath],
@"shouldn't have gotten anything for a bogus dir");
// --------------------------------------------------------------------------
// create some test data
NSString *testDirs[] = {
@"", @"/foo", // mave a subdir to make sure we don't match w/in it
};
NSString *testFiles[] = {
@"a.txt", @"b.txt", @"c.rtf", @"d.m",
};
for (size_t i = 0; i < sizeof(testDirs) / sizeof(NSString*); i++) {
NSString *testDir = nil;
if ([testDirs[i] length]) {
testDir = [baseDir_ stringByAppendingPathComponent:testDirs[i]];
STAssertTrue([fm createDirectoryAtPath:testDir attributes:nil], nil);
} else {
testDir = baseDir_;
}
for (size_t j = 0; j < sizeof(testFiles) / sizeof(NSString*); j++) {
NSString *testFile = [testDir stringByAppendingPathComponent:testFiles[j]];
STAssertTrue([@"test" writeToFile:testFile atomically:YES], nil);
}
}
// build set of the top level items
NSMutableArray *allFiles = [NSMutableArray array];
for (size_t i = 0; i < sizeof(testDirs) / sizeof(NSString*); i++) {
if ([testDirs[i] length]) {
NSString *testDir = [baseDir_ stringByAppendingPathComponent:testDirs[i]];
[allFiles addObject:testDir];
}
}
for (size_t j = 0; j < sizeof(testFiles) / sizeof(NSString*); j++) {
NSString *testFile = [baseDir_ stringByAppendingPathComponent:testFiles[j]];
[allFiles addObject:testFile];
}
NSArray *matches = nil;
NSArray *expectedMatches = nil;
NSArray *extensions = nil;
// NOTE: we do all compares w/ sets so order doesn't matter
// --------------------------------------------------------------------------
// test match all
// single
matches = [fm gtm_filePathsWithExtension:nil inDirectory:baseDir_];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:allFiles],
@"didn't get all files for nil extension");
matches = [fm gtm_filePathsWithExtension:@"" inDirectory:baseDir_];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:allFiles],
@"didn't get all files for nil extension");
// array
matches = [fm gtm_filePathsWithExtensions:nil inDirectory:baseDir_];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:allFiles],
@"didn't get all files for nil extension");
matches = [fm gtm_filePathsWithExtensions:[NSArray array]
inDirectory:baseDir_];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:allFiles],
@"didn't get all files for nil extension");
// --------------------------------------------------------------------------
// test match something
// single
extensions = [NSArray arrayWithObject:@"txt"];
matches = [fm gtm_filePathsWithExtension:@"txt" inDirectory:baseDir_];
expectedMatches = [allFiles pathsMatchingExtensions:extensions];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:expectedMatches],
@"didn't get expected files");
// array
matches = [fm gtm_filePathsWithExtensions:extensions inDirectory:baseDir_];
expectedMatches = [allFiles pathsMatchingExtensions:extensions];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:expectedMatches],
@"didn't get expected files");
extensions = [NSArray arrayWithObjects:@"txt", @"rtf", @"xyz", nil];
matches = [fm gtm_filePathsWithExtensions:extensions inDirectory:baseDir_];
expectedMatches = [allFiles pathsMatchingExtensions:extensions];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:expectedMatches],
@"didn't get expected files");
// --------------------------------------------------------------------------
// test match nothing
// single
extensions = [NSArray arrayWithObject:@"xyz"];
matches = [fm gtm_filePathsWithExtension:@"xyz" inDirectory:baseDir_];
expectedMatches = [allFiles pathsMatchingExtensions:extensions];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:expectedMatches],
@"didn't get expected files");
// array
matches = [fm gtm_filePathsWithExtensions:extensions inDirectory:baseDir_];
expectedMatches = [allFiles pathsMatchingExtensions:extensions];
STAssertEqualObjects([NSSet setWithArray:matches],
[NSSet setWithArray:expectedMatches],
@"didn't get expected files");
// --------------------------------------------------------------------------
// test match an empty dir
// create the empty dir
NSString *emptyDir = [baseDir_ stringByAppendingPathComponent:@"emptyDir"];
STAssertTrue([fm createDirectoryAtPath:emptyDir attributes:nil], nil);
// single
matches = [fm gtm_filePathsWithExtension:@"txt" inDirectory:emptyDir];
STAssertEqualObjects([NSSet setWithArray:matches], [NSSet set],
@"expected empty dir");
// array
matches = [fm gtm_filePathsWithExtensions:[NSArray arrayWithObject:@"txt"]
inDirectory:emptyDir];
STAssertEqualObjects([NSSet setWithArray:matches], [NSSet set],
@"expected empty dir");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSFileManager+PathTest.m | Objective-C | bsd | 9,889 |
//
// GTMHTTPFetcherTest.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMHTTPFetcher.h"
#import "GTMTestHTTPServer.h"
@interface GTMHTTPFetcherTest : GTMTestCase {
// these ivars are checked after fetches, and are reset by resetFetchResponse
NSData *fetchedData_;
NSError *fetcherError_;
NSInteger fetchedStatus_;
NSURLResponse *fetchedResponse_;
NSMutableURLRequest *fetchedRequest_;
// setup/teardown ivars
NSMutableDictionary *fetchHistory_;
GTMTestHTTPServer *testServer_;
}
@end
@interface GTMHTTPFetcherTest (PrivateMethods)
- (GTMHTTPFetcher *)doFetchWithURLString:(NSString *)urlString
cachingDatedData:(BOOL)doCaching;
- (GTMHTTPFetcher *)doFetchWithURLString:(NSString *)urlString
cachingDatedData:(BOOL)doCaching
retrySelector:(SEL)retrySel
maxRetryInterval:(NSTimeInterval)maxRetryInterval
userData:(id)userData;
- (NSString *)fileURLStringToTestFileName:(NSString *)name;
- (BOOL)countRetriesFetcher:(GTMHTTPFetcher *)fetcher
willRetry:(BOOL)suggestedWillRetry
forError:(NSError *)error;
- (BOOL)fixRequestFetcher:(GTMHTTPFetcher *)fetcher
willRetry:(BOOL)suggestedWillRetry
forError:(NSError *)error;
- (void)testFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data;
- (void)testFetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error;
@end
@implementation GTMHTTPFetcherTest
static const NSTimeInterval kRunLoopInterval = 0.01;
// The bogus-fetch test can take >10s to pass. Pick something way higher
// to avoid failing.
static const NSTimeInterval kGiveUpInterval = 60.0; // bail on the test if 60 seconds elapse
static NSString *const kValidFileName = @"GTMHTTPFetcherTestPage.html";
- (void)setUp {
fetchHistory_ = [[NSMutableDictionary alloc] init];
NSBundle *testBundle = [NSBundle bundleForClass:[self class]];
STAssertNotNil(testBundle, nil);
NSString *docRoot = [testBundle pathForResource:@"GTMHTTPFetcherTestPage"
ofType:@"html"];
docRoot = [docRoot stringByDeletingLastPathComponent];
STAssertNotNil(docRoot, nil);
testServer_ = [[GTMTestHTTPServer alloc] initWithDocRoot:docRoot];
STAssertNotNil(testServer_, @"failed to create a testing server");
}
- (void)resetFetchResponse {
[fetchedData_ release];
fetchedData_ = nil;
[fetcherError_ release];
fetcherError_ = nil;
[fetchedRequest_ release];
fetchedRequest_ = nil;
[fetchedResponse_ release];
fetchedResponse_ = nil;
fetchedStatus_ = 0;
}
- (void)tearDown {
[testServer_ release];
testServer_ = nil;
[self resetFetchResponse];
[fetchHistory_ release];
fetchHistory_ = nil;
}
- (void)testValidFetch {
NSString *urlString = [self fileURLStringToTestFileName:kValidFileName];
[self doFetchWithURLString:urlString cachingDatedData:YES];
STAssertNotNil(fetchedData_,
@"failed to fetch data, status:%ld error:%@, URL:%@",
(long)fetchedStatus_, fetcherError_, urlString);
STAssertNotNil(fetchedResponse_,
@"failed to get fetch response, status:%ld error:%@",
(long)fetchedStatus_, fetcherError_);
STAssertNotNil(fetchedRequest_, @"failed to get fetch request, URL %@",
urlString);
STAssertNil(fetcherError_, @"fetching data gave error: %@", fetcherError_);
STAssertEquals(fetchedStatus_, (NSInteger)200,
@"fetching data expected status 200, instead got %ld, for URL %@",
(long)fetchedStatus_, urlString);
// no cookies should be sent with our first request
NSDictionary *headers = [fetchedRequest_ allHTTPHeaderFields];
NSString *cookiesSent = [headers objectForKey:@"Cookie"];
STAssertNil(cookiesSent, @"Cookies sent unexpectedly: %@", cookiesSent);
// cookies should have been set by the response; specifically, TestCookie
// should be set to the name of the file requested
NSDictionary *responseHeaders;
responseHeaders = [(NSHTTPURLResponse *)fetchedResponse_ allHeaderFields];
NSString *cookiesSetString = [responseHeaders objectForKey:@"Set-Cookie"];
NSString *cookieExpected = [NSString stringWithFormat:@"TestCookie=%@",
kValidFileName];
STAssertEqualObjects(cookiesSetString, cookieExpected, @"Unexpected cookie");
// make a copy of the fetched data to compare with our next fetch from the
// cache
NSData *originalFetchedData = [[fetchedData_ copy] autorelease];
// Now fetch again so the "If modified since" header will be set (because
// we're calling setFetchHistory: below) and caching ON, and verify that we
// got a good data from the cache, along with a "Not modified" status
[self resetFetchResponse];
[self doFetchWithURLString:urlString cachingDatedData:YES];
STAssertEqualObjects(fetchedData_, originalFetchedData,
@"cache data mismatch");
STAssertNotNil(fetchedData_,
@"failed to fetch data, status:%ld error:%@, URL:%@",
(long)fetchedStatus_, fetcherError_, urlString);
STAssertNotNil(fetchedResponse_,
@"failed to get fetch response, status:%;d error:%@",
(long)fetchedStatus_, fetcherError_);
STAssertNotNil(fetchedRequest_, @"failed to get fetch request, URL %@",
urlString);
STAssertNil(fetcherError_, @"fetching data gave error: %@", fetcherError_);
STAssertEquals(fetchedStatus_, (NSInteger)kGTMHTTPFetcherStatusNotModified, // 304
@"fetching data expected status 304, instead got %ld, for URL %@",
(long)fetchedStatus_, urlString);
// the TestCookie set previously should be sent with this request
cookiesSent = [[fetchedRequest_ allHTTPHeaderFields] objectForKey:@"Cookie"];
STAssertEqualObjects(cookiesSent, cookieExpected, @"Cookie not sent");
// Now fetch twice without caching enabled, and verify that we got a
// "Not modified" status, along with a non-nil but empty NSData (which
// is normal for that status code)
[self resetFetchResponse];
[fetchHistory_ removeAllObjects];
[self doFetchWithURLString:urlString cachingDatedData:NO];
STAssertEqualObjects(fetchedData_, originalFetchedData,
@"cache data mismatch");
[self resetFetchResponse];
[self doFetchWithURLString:urlString cachingDatedData:NO];
STAssertNotNil(fetchedData_, @"");
STAssertEquals([fetchedData_ length], (NSUInteger)0, @"unexpected data");
STAssertEquals(fetchedStatus_, (NSInteger)kGTMHTTPFetcherStatusNotModified,
@"fetching data expected status 304, instead got %d", fetchedStatus_);
STAssertNil(fetcherError_, @"unexpected error: %@", fetcherError_);
}
- (void)testBogusFetch {
// fetch a live, invalid URL
NSString *badURLString = @"http://localhost:86/";
[self doFetchWithURLString:badURLString cachingDatedData:NO];
const int kServiceUnavailableStatus = 503;
if (fetchedStatus_ == kServiceUnavailableStatus) {
// some proxies give a "service unavailable" error for bogus fetches
} else {
if (fetchedData_) {
NSString *str = [[[NSString alloc] initWithData:fetchedData_
encoding:NSUTF8StringEncoding] autorelease];
STAssertNil(fetchedData_, @"fetched unexpected data: %@", str);
}
STAssertNotNil(fetcherError_, @"failed to receive fetching error");
STAssertEquals(fetchedStatus_, (NSInteger)0,
@"fetching data expected no status from no response, instead got %d",
fetchedStatus_);
}
// fetch with a specific status code from our http server
[self resetFetchResponse];
NSString *invalidWebPageFile =
[kValidFileName stringByAppendingString:@"?status=400"];
NSString *statusUrlString =
[self fileURLStringToTestFileName:invalidWebPageFile];
[self doFetchWithURLString:statusUrlString cachingDatedData:NO];
STAssertNotNil(fetchedData_, @"fetch lacked data with error info");
STAssertNil(fetcherError_, @"expected bad status but got an error");
STAssertEquals(fetchedStatus_, (NSInteger)400,
@"unexpected status, error=%@", fetcherError_);
}
- (void)testRetryFetches {
GTMHTTPFetcher *fetcher;
NSString *invalidFile = [kValidFileName stringByAppendingString:@"?status=503"];
NSString *urlString = [self fileURLStringToTestFileName:invalidFile];
SEL countRetriesSel = @selector(countRetriesFetcher:willRetry:forError:);
SEL fixRequestSel = @selector(fixRequestFetcher:willRetry:forError:);
//
// test: retry until timeout, then expect failure with status message
//
NSNumber *lotsOfRetriesNumber = [NSNumber numberWithInt:1000];
fetcher= [self doFetchWithURLString:urlString
cachingDatedData:NO
retrySelector:countRetriesSel
maxRetryInterval:5.0 // retry intervals of 1, 2, 4
userData:lotsOfRetriesNumber];
STAssertNotNil(fetchedData_, @"error data is expected");
STAssertEquals(fetchedStatus_, (NSInteger)503, nil);
STAssertEquals([fetcher retryCount], 3U, @"retry count unexpected");
//
// test: retry twice, then give up
//
[self resetFetchResponse];
NSNumber *twoRetriesNumber = [NSNumber numberWithInt:2];
fetcher= [self doFetchWithURLString:urlString
cachingDatedData:NO
retrySelector:countRetriesSel
maxRetryInterval:10.0 // retry intervals of 1, 2, 4, 8
userData:twoRetriesNumber];
STAssertNotNil(fetchedData_, @"error data is expected");
STAssertEquals(fetchedStatus_, (NSInteger)503, nil);
STAssertEquals([fetcher retryCount], 2U, @"retry count unexpected");
//
// test: retry, making the request succeed on the first retry
// by fixing the URL
//
[self resetFetchResponse];
fetcher= [self doFetchWithURLString:urlString
cachingDatedData:NO
retrySelector:fixRequestSel
maxRetryInterval:30.0 // should only retry once due to selector
userData:lotsOfRetriesNumber];
STAssertNotNil(fetchedData_, @"data is expected");
STAssertEquals(fetchedStatus_, (NSInteger)200, nil);
STAssertEquals([fetcher retryCount], 1U, @"retry count unexpected");
}
#pragma mark -
- (GTMHTTPFetcher *)doFetchWithURLString:(NSString *)urlString
cachingDatedData:(BOOL)doCaching {
return [self doFetchWithURLString:(NSString *)urlString
cachingDatedData:(BOOL)doCaching
retrySelector:nil
maxRetryInterval:0
userData:nil];
}
- (GTMHTTPFetcher *)doFetchWithURLString:(NSString *)urlString
cachingDatedData:(BOOL)doCaching
retrySelector:(SEL)retrySel
maxRetryInterval:(NSTimeInterval)maxRetryInterval
userData:(id)userData {
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *req = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:kGiveUpInterval];
GTMHTTPFetcher *fetcher = [GTMHTTPFetcher httpFetcherWithRequest:req];
STAssertNotNil(fetcher, @"Failed to allocate fetcher");
// setting the fetch history will add the "If-modified-since" header
// to repeat requests
[fetcher setFetchHistory:fetchHistory_];
if (doCaching != [fetcher shouldCacheDatedData]) {
// only set the value when it changes since setting it to nil clears out
// some of the state and our tests need the state between some non caching
// fetches.
[fetcher setShouldCacheDatedData:doCaching];
}
if (retrySel) {
[fetcher setIsRetryEnabled:YES];
[fetcher setRetrySelector:retrySel];
[fetcher setMaxRetryInterval:maxRetryInterval];
[fetcher setUserData:userData];
// we force a minimum retry interval for unit testing; otherwise,
// we'd have no idea how many retries will occur before the max
// retry interval occurs, since the minimum would be random
[fetcher setMinRetryInterval:1.0];
}
BOOL isFetching =
[fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(testFetcher:finishedWithData:)
didFailSelector:@selector(testFetcher:failedWithError:)];
STAssertTrue(isFetching, @"Begin fetch failed");
if (isFetching) {
// Give time for the fetch to happen, but give up if 10 seconds elapse with
// no response
NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:kGiveUpInterval];
while ((!fetchedData_ && !fetcherError_) &&
[giveUpDate timeIntervalSinceNow] > 0) {
NSDate* loopIntervalDate =
[NSDate dateWithTimeIntervalSinceNow:kRunLoopInterval];
[[NSRunLoop currentRunLoop] runUntilDate:loopIntervalDate];
}
}
return fetcher;
}
- (NSString *)fileURLStringToTestFileName:(NSString *)name {
// we need to create http URLs referring to the desired
// resource to be found by the python http server running locally
// return a localhost:port URL for the test file
NSString *urlString = [NSString stringWithFormat:@"http://localhost:%d/%@",
[testServer_ port], name];
// we exclude the "?status=" that would indicate that the URL
// should cause a retryable error
NSRange range = [name rangeOfString:@"?status="];
if (range.length > 0) {
name = [name substringToIndex:range.location];
}
// we exclude the ".auth" extension that would indicate that the URL
// should be tested with authentication
if ([[name pathExtension] isEqual:@"auth"]) {
name = [name stringByDeletingPathExtension];
}
// just for sanity, let's make sure we see the file locally, so
// we can expect the Python http server to find it too
NSBundle *testBundle = [NSBundle bundleForClass:[self class]];
STAssertNotNil(testBundle, nil);
NSString *filePath =
[testBundle pathForResource:[name stringByDeletingPathExtension]
ofType:[name pathExtension]];
STAssertNotNil(filePath, nil);
return urlString;
}
- (void)testFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data {
fetchedData_ = [data copy];
fetchedStatus_ = [fetcher statusCode]; // this implicitly tests that the fetcher has kept the response
fetchedRequest_ = [[fetcher request] retain];
fetchedResponse_ = [[fetcher response] retain];
}
- (void)testFetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error {
// if it's a status error, don't hang onto the error, just the status/data
if ([[error domain] isEqual:kGTMHTTPFetcherStatusDomain]) {
fetchedData_ = [[[error userInfo] objectForKey:kGTMHTTPFetcherStatusDataKey] copy];
fetchedStatus_ = [error code]; // this implicitly tests that the fetcher has kept the response
} else {
fetcherError_ = [error retain];
fetchedStatus_ = [fetcher statusCode];
}
}
// Selector for allowing up to N retries, where N is an NSNumber in the
// fetcher's userData
- (BOOL)countRetriesFetcher:(GTMHTTPFetcher *)fetcher
willRetry:(BOOL)suggestedWillRetry
forError:(NSError *)error {
int count = [fetcher retryCount];
int allowedRetryCount = [[fetcher userData] intValue];
BOOL shouldRetry = (count < allowedRetryCount);
STAssertEquals([fetcher nextRetryInterval], pow(2.0, [fetcher retryCount]),
@"unexpected next retry interval (expected %f, was %f)",
pow(2.0, [fetcher retryCount]),
[fetcher nextRetryInterval]);
return shouldRetry;
}
// Selector for retrying and changing the request to one that will succeed
- (BOOL)fixRequestFetcher:(GTMHTTPFetcher *)fetcher
willRetry:(BOOL)suggestedWillRetry
forError:(NSError *)error {
STAssertEquals([fetcher nextRetryInterval], pow(2.0, [fetcher retryCount]),
@"unexpected next retry interval (expected %f, was %f)",
pow(2.0, [fetcher retryCount]),
[fetcher nextRetryInterval]);
// fix it - change the request to a URL which does not have a status value
NSString *urlString = [self fileURLStringToTestFileName:kValidFileName];
NSURL *url = [NSURL URLWithString:urlString];
[fetcher setRequest:[NSURLRequest requestWithURL:url]];
return YES; // do the retry fetch; it should succeed now
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMHTTPFetcherTest.m | Objective-C | bsd | 17,466 |
//
// GTMNSString+XML.h
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <Foundation/Foundation.h>
/// Utilities for NSStrings containing XML
@interface NSString (GTMNSStringXMLAdditions)
/// Get a string where characters that need escaping for XML are escaped and invalid characters removed
//
/// This call escapes '&', '<, '>', '\'', '"' per the xml spec and removes all
/// invalid characters as defined by Section 2.2 of the xml spec.
///
/// For obvious reasons this call is only safe once.
//
// Returns:
// Autoreleased NSString
//
- (NSString *)gtm_stringBySanitizingAndEscapingForXML;
/// Get a string where characters that invalid characters per the XML spec have been removed
//
/// This call removes all invalid characters as defined by Section 2.2 of the
/// xml spec. If you are writing XML yourself, you probably was to use the
/// above api (gtm_stringBySanitizingAndEscapingForXML) so any entities also
/// get escaped.
//
// Returns:
// Autoreleased NSString
//
- (NSString *)gtm_stringBySanitizingToXMLSpec;
// There is no stringByUnescapingFromXML because the XML parser will do this.
// The above api is here just incase you need to create XML yourself.
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSString+XML.h | Objective-C | bsd | 1,765 |
//
// GTMRegexTest.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMRegex.h"
#import "GTMUnitTestDevLog.h"
//
// NOTE:
//
// We don't really test any of the pattern matching since that's testing
// libregex, we just want to test our wrapper.
//
@interface GTMRegexTest : GTMTestCase
@end
@interface NSString_GTMRegexAdditions : GTMTestCase
@end
@implementation GTMRegexTest
- (void)testEscapedPatternForString {
STAssertEqualStrings([GTMRegex escapedPatternForString:@"abcdefghijklmnopqrstuvwxyz0123456789"],
@"abcdefghijklmnopqrstuvwxyz0123456789",
nil);
STAssertEqualStrings([GTMRegex escapedPatternForString:@"^.[$()|*+?{\\"],
@"\\^\\.\\[\\$\\(\\)\\|\\*\\+\\?\\{\\\\",
nil);
STAssertEqualStrings([GTMRegex escapedPatternForString:@"a^b.c[d$e(f)g|h*i+j?k{l\\m"],
@"a\\^b\\.c\\[d\\$e\\(f\\)g\\|h\\*i\\+j\\?k\\{l\\\\m",
nil);
STAssertNil([GTMRegex escapedPatternForString:nil], nil);
STAssertEqualStrings([GTMRegex escapedPatternForString:@""], @"", nil);
}
- (void)testInit {
// fail cases
STAssertNil([[[GTMRegex alloc] init] autorelease], nil);
STAssertNil([[[GTMRegex alloc] initWithPattern:nil] autorelease], nil);
STAssertNil([[[GTMRegex alloc] initWithPattern:nil
options:kGTMRegexOptionIgnoreCase] autorelease], nil);
[GTMUnitTestDevLog expectString:@"Invalid pattern \"(.\", error: \"parentheses not balanced\""];
STAssertNil([[[GTMRegex alloc] initWithPattern:@"(."] autorelease], nil);
[GTMUnitTestDevLog expectString:@"Invalid pattern \"(.\", error: \"parentheses not balanced\""];
STAssertNil([[[GTMRegex alloc] initWithPattern:@"(."
options:kGTMRegexOptionIgnoreCase] autorelease], nil);
// fail cases w/ error param
NSError *error = nil;
STAssertNil([[[GTMRegex alloc] initWithPattern:nil
options:kGTMRegexOptionIgnoreCase
withError:&error] autorelease], nil);
STAssertNil(error, @"no pattern, shouldn't get error object");
STAssertNil([[[GTMRegex alloc] initWithPattern:@"(."
options:kGTMRegexOptionIgnoreCase
withError:&error] autorelease], nil);
STAssertNotNil(error, nil);
STAssertEqualObjects([error domain], kGTMRegexErrorDomain, nil);
STAssertEquals([error code], (NSInteger)kGTMRegexPatternParseFailedError, nil);
NSDictionary *userInfo = [error userInfo];
STAssertNotNil(userInfo, @"failed to get userInfo from error");
STAssertEqualObjects([userInfo objectForKey:kGTMRegexPatternErrorPattern], @"(.", nil);
STAssertNotNil([userInfo objectForKey:kGTMRegexPatternErrorErrorString], nil);
// basic pattern w/ options
STAssertNotNil([[[GTMRegex alloc] initWithPattern:@"(.*)"] autorelease], nil);
STAssertNotNil([[[GTMRegex alloc] initWithPattern:@"(.*)"
options:0] autorelease], nil);
STAssertNotNil([[[GTMRegex alloc] initWithPattern:@"(.*)"
options:kGTMRegexOptionIgnoreCase] autorelease], nil);
error = nil;
STAssertNotNil([[[GTMRegex alloc] initWithPattern:@"(.*)"
options:kGTMRegexOptionIgnoreCase
withError:&error] autorelease], nil);
STAssertNil(error, @"shouldn't have been any error");
// fail cases (helper)
STAssertNil([GTMRegex regexWithPattern:nil], nil);
STAssertNil([GTMRegex regexWithPattern:nil
options:0], nil);
[GTMUnitTestDevLog expectString:@"Invalid pattern \"(.\", error: \"parentheses not balanced\""];
STAssertNil([GTMRegex regexWithPattern:@"(."], nil);
[GTMUnitTestDevLog expectString:@"Invalid pattern \"(.\", error: \"parentheses not balanced\""];
STAssertNil([GTMRegex regexWithPattern:@"(."
options:0], nil);
// fail cases (helper) w/ error param
STAssertNil([GTMRegex regexWithPattern:nil
options:kGTMRegexOptionIgnoreCase
withError:&error], nil);
STAssertNil(error, @"no pattern, shouldn't get error object");
STAssertNil([GTMRegex regexWithPattern:@"(."
options:kGTMRegexOptionIgnoreCase
withError:&error], nil);
STAssertNotNil(error, nil);
STAssertEqualObjects([error domain], kGTMRegexErrorDomain, nil);
STAssertEquals([error code], (NSInteger)kGTMRegexPatternParseFailedError, nil);
userInfo = [error userInfo];
STAssertNotNil(userInfo, @"failed to get userInfo from error");
STAssertEqualObjects([userInfo objectForKey:kGTMRegexPatternErrorPattern], @"(.", nil);
STAssertNotNil([userInfo objectForKey:kGTMRegexPatternErrorErrorString], nil);
// basic pattern w/ options (helper)
STAssertNotNil([GTMRegex regexWithPattern:@"(.*)"], nil);
STAssertNotNil([GTMRegex regexWithPattern:@"(.*)"
options:0], nil);
STAssertNotNil([GTMRegex regexWithPattern:@"(.*)"
options:kGTMRegexOptionIgnoreCase], nil);
error = nil;
STAssertNotNil([GTMRegex regexWithPattern:@"(.*)"
options:kGTMRegexOptionIgnoreCase
withError:&error], nil);
STAssertNil(error, @"shouldn't have been any error");
// not really a test on GTMRegex, but make sure we block attempts to directly
// alloc/init a GTMRegexStringSegment.
STAssertThrowsSpecificNamed([[[GTMRegexStringSegment alloc] init] autorelease],
NSException, NSInvalidArgumentException,
@"shouldn't have been able to alloc/init a GTMRegexStringSegment");
}
- (void)testOptions {
NSString *testString = @"aaa AAA\nbbb BBB\n aaa aAa\n bbb BbB";
// default options
GTMRegex *regex = [GTMRegex regexWithPattern:@"a+"];
STAssertNotNil(regex, nil);
NSEnumerator *enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa"
GTMRegexStringSegment *seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
// " AAA\nbbb BBB\n "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @" AAA\nbbb BBB\n ", nil);
// "aaa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
// " "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @" ", nil);
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "A"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"A", nil);
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "\n bbb BbB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\n bbb BbB", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// kGTMRegexOptionIgnoreCase
regex = [GTMRegex regexWithPattern:@"a+" options:kGTMRegexOptionIgnoreCase];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
// " "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @" ", nil);
// "AAA"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"AAA", nil);
// "\nbbb BBB\n "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\nbbb BBB\n ", nil);
// "aaa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
// " "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @" ", nil);
// "aAa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aAa", nil);
// "\n bbb BbB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\n bbb BbB", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// defaults w/ '^'
regex = [GTMRegex regexWithPattern:@"^a+"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
// " AAA\nbbb BBB\n aaa aAa\n bbb BbB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @" AAA\nbbb BBB\n aaa aAa\n bbb BbB", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// defaults w/ '$'
regex = [GTMRegex regexWithPattern:@"B+$"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa AAA\nbbb "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa AAA\nbbb ", nil);
// "BBB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"BBB", nil);
// "\n aaa aAa\n bbb Bb"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\n aaa aAa\n bbb Bb", nil);
// "B"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"B", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// kGTMRegexOptionIgnoreCase w/ '$'
regex = [GTMRegex regexWithPattern:@"B+$"
options:kGTMRegexOptionIgnoreCase];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa AAA\nbbb "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa AAA\nbbb ", nil);
// "BBB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"BBB", nil);
// "\n aaa aAa\n bbb "
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\n aaa aAa\n bbb ", nil);
// "BbB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"BbB", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test w/ kGTMRegexOptionSupressNewlineSupport and \n in the string
regex = [GTMRegex regexWithPattern:@"a.*b" options:kGTMRegexOptionSupressNewlineSupport];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa AAA\nbbb BBB\n aaa aAa\n bbb Bb"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa AAA\nbbb BBB\n aaa aAa\n bbb Bb", nil);
// "B"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"B", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test w/o kGTMRegexOptionSupressNewlineSupport and \n in the string
// (this is no match since it '.' can't match the '\n')
regex = [GTMRegex regexWithPattern:@"a.*b"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa AAA\nbbb BBB\n aaa aAa\n bbb BbB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa AAA\nbbb BBB\n aaa aAa\n bbb BbB", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// kGTMRegexOptionSupressNewlineSupport w/ '^'
regex = [GTMRegex regexWithPattern:@"^a+" options:kGTMRegexOptionSupressNewlineSupport];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
// " AAA\nbbb BBB\n aaa aAa\n bbb BbB"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @" AAA\nbbb BBB\n aaa aAa\n bbb BbB", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// kGTMRegexOptionSupressNewlineSupport w/ '$'
regex = [GTMRegex regexWithPattern:@"B+$" options:kGTMRegexOptionSupressNewlineSupport];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:testString];
STAssertNotNil(enumerator, nil);
// "aaa AAA\nbbb BBB\n aaa aAa\n bbb Bb"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa AAA\nbbb BBB\n aaa aAa\n bbb Bb", nil);
// "B"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"B", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
}
- (void)testSubPatternCount {
STAssertEquals((NSUInteger)0, [[GTMRegex regexWithPattern:@".*"] subPatternCount], nil);
STAssertEquals((NSUInteger)1, [[GTMRegex regexWithPattern:@"(.*)"] subPatternCount], nil);
STAssertEquals((NSUInteger)1, [[GTMRegex regexWithPattern:@"[fo]*(.*)[bar]*"] subPatternCount], nil);
STAssertEquals((NSUInteger)3, [[GTMRegex regexWithPattern:@"([fo]*)(.*)([bar]*)"] subPatternCount], nil);
STAssertEquals((NSUInteger)7, [[GTMRegex regexWithPattern:@"(([bar]*)|([fo]*))(.*)(([bar]*)|([fo]*))"] subPatternCount], nil);
}
- (void)testMatchesString {
// simple pattern
GTMRegex *regex = [GTMRegex regexWithPattern:@"foo.*bar"];
STAssertNotNil(regex, nil);
STAssertTrue([regex matchesString:@"foobar"], nil);
STAssertTrue([regex matchesString:@"foobydoo spambar"], nil);
STAssertFalse([regex matchesString:@"zzfoobarzz"], nil);
STAssertFalse([regex matchesString:@"zzfoobydoo spambarzz"], nil);
STAssertFalse([regex matchesString:@"abcdef"], nil);
STAssertFalse([regex matchesString:@""], nil);
STAssertFalse([regex matchesString:nil], nil);
// pattern w/ sub patterns
regex = [GTMRegex regexWithPattern:@"(foo)(.*)(bar)"];
STAssertNotNil(regex, nil);
STAssertTrue([regex matchesString:@"foobar"], nil);
STAssertTrue([regex matchesString:@"foobydoo spambar"], nil);
STAssertFalse([regex matchesString:@"zzfoobarzz"], nil);
STAssertFalse([regex matchesString:@"zzfoobydoo spambarzz"], nil);
STAssertFalse([regex matchesString:@"abcdef"], nil);
STAssertFalse([regex matchesString:@""], nil);
STAssertFalse([regex matchesString:nil], nil);
}
- (void)testSubPatternsOfString {
GTMRegex *regex = [GTMRegex regexWithPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNotNil(regex, nil);
STAssertEquals((NSUInteger)5, [regex subPatternCount], nil);
NSArray *subPatterns = [regex subPatternsOfString:@"foooooobaz"];
STAssertNotNil(subPatterns, nil);
STAssertEquals((NSUInteger)6, [subPatterns count], nil);
STAssertEqualStrings(@"foooooobaz", [subPatterns objectAtIndex:0], nil);
STAssertEqualStrings(@"foooooo", [subPatterns objectAtIndex:1], nil);
STAssertEqualStrings(@"ooooo", [subPatterns objectAtIndex:2], nil);
STAssertEqualStrings(@"baz", [subPatterns objectAtIndex:3], nil);
STAssertEqualObjects([NSNull null], [subPatterns objectAtIndex:4], nil);
STAssertEqualStrings(@"baz", [subPatterns objectAtIndex:5], nil);
// not there
subPatterns = [regex subPatternsOfString:@"aaa"];
STAssertNil(subPatterns, nil);
// not extra stuff on either end
subPatterns = [regex subPatternsOfString:@"ZZZfoooooobaz"];
STAssertNil(subPatterns, nil);
subPatterns = [regex subPatternsOfString:@"foooooobazZZZ"];
STAssertNil(subPatterns, nil);
subPatterns = [regex subPatternsOfString:@"ZZZfoooooobazZZZ"];
STAssertNil(subPatterns, nil);
}
- (void)testFirstSubStringMatchedInString {
// simple pattern
GTMRegex *regex = [GTMRegex regexWithPattern:@"foo.*bar"];
STAssertNotNil(regex, nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"foobar"],
@"foobar", nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"foobydoo spambar"],
@"foobydoo spambar", nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"zzfoobarzz"],
@"foobar", nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"zzfoobydoo spambarzz"],
@"foobydoo spambar", nil);
STAssertNil([regex firstSubStringMatchedInString:@"abcdef"], nil);
STAssertNil([regex firstSubStringMatchedInString:@""], nil);
// pattern w/ sub patterns
regex = [GTMRegex regexWithPattern:@"(foo)(.*)(bar)"];
STAssertNotNil(regex, nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"foobar"],
@"foobar", nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"foobydoo spambar"],
@"foobydoo spambar", nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"zzfoobarzz"],
@"foobar", nil);
STAssertEqualStrings([regex firstSubStringMatchedInString:@"zzfoobydoo spambarzz"],
@"foobydoo spambar", nil);
STAssertNil([regex firstSubStringMatchedInString:@"abcdef"], nil);
STAssertNil([regex firstSubStringMatchedInString:@""], nil);
}
- (void)testMatchesSubStringInString {
// simple pattern
GTMRegex *regex = [GTMRegex regexWithPattern:@"foo.*bar"];
STAssertNotNil(regex, nil);
STAssertTrue([regex matchesSubStringInString:@"foobar"], nil);
STAssertTrue([regex matchesSubStringInString:@"foobydoo spambar"], nil);
STAssertTrue([regex matchesSubStringInString:@"zzfoobarzz"], nil);
STAssertTrue([regex matchesSubStringInString:@"zzfoobydoo spambarzz"], nil);
STAssertFalse([regex matchesSubStringInString:@"abcdef"], nil);
STAssertFalse([regex matchesSubStringInString:@""], nil);
// pattern w/ sub patterns
regex = [GTMRegex regexWithPattern:@"(foo)(.*)(bar)"];
STAssertNotNil(regex, nil);
STAssertTrue([regex matchesSubStringInString:@"foobar"], nil);
STAssertTrue([regex matchesSubStringInString:@"foobydoo spambar"], nil);
STAssertTrue([regex matchesSubStringInString:@"zzfoobarzz"], nil);
STAssertTrue([regex matchesSubStringInString:@"zzfoobydoo spambarzz"], nil);
STAssertFalse([regex matchesSubStringInString:@"abcdef"], nil);
STAssertFalse([regex matchesSubStringInString:@""], nil);
}
- (void)testSegmentEnumeratorForString {
GTMRegex *regex = [GTMRegex regexWithPattern:@"foo+ba+r"];
STAssertNotNil(regex, nil);
// test odd input
NSEnumerator *enumerator = [regex segmentEnumeratorForString:@""];
STAssertNotNil(enumerator, nil);
enumerator = [regex segmentEnumeratorForString:nil];
STAssertNil(enumerator, nil);
// on w/ the normal tests
enumerator = [regex segmentEnumeratorForString:@"afoobarbfooobaarfoobarzz"];
STAssertNotNil(enumerator, nil);
// "a"
GTMRegexStringSegment *seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "b"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"b", nil);
// "fooobaar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"fooobaar", nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "zz"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"zz", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test no match
enumerator = [regex segmentEnumeratorForString:@"aaa"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test only match
enumerator = [regex segmentEnumeratorForString:@"foobar"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// now test the saved sub segments
regex = [GTMRegex regexWithPattern:@"(foo)((bar)|(baz))"];
STAssertNotNil(regex, nil);
STAssertEquals((NSUInteger)4, [regex subPatternCount], nil);
enumerator = [regex segmentEnumeratorForString:@"foobarxxfoobaz"];
STAssertNotNil(enumerator, nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"bar", nil);
STAssertEqualStrings([seg subPatternString:3], @"bar", nil);
STAssertNil([seg subPatternString:4], nil); // nothing matched "(baz)"
STAssertNil([seg subPatternString:5], nil);
// "xx"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"xx", nil);
STAssertEqualStrings([seg subPatternString:0], @"xx", nil);
STAssertNil([seg subPatternString:1], nil);
// "foobaz"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"baz", nil);
STAssertNil([seg subPatternString:3], nil); // (nothing matched "(bar)"
STAssertEqualStrings([seg subPatternString:4], @"baz", nil);
STAssertNil([seg subPatternString:5], nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test all objects
regex = [GTMRegex regexWithPattern:@"foo+ba+r"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:@"afoobarbfooobaarfoobarzz"];
STAssertNotNil(enumerator, nil);
NSArray *allSegments = [enumerator allObjects];
STAssertNotNil(allSegments, nil);
STAssertEquals((NSUInteger)6, [allSegments count], nil);
// test we are getting the flags right for newline
regex = [GTMRegex regexWithPattern:@"^a"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:@"aa\naa"];
STAssertNotNil(enumerator, nil);
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "a\n"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a\n", nil);
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test we are getting the flags right for newline, part 2
regex = [GTMRegex regexWithPattern:@"^a*$"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:@"aa\naa\nbb\naa"];
STAssertNotNil(enumerator, nil);
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// "\n"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\n", nil);
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// "\nbb\n"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"\nbb\n", nil);
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// make sure the enum cleans up if not walked to the end
regex = [GTMRegex regexWithPattern:@"b+"];
STAssertNotNil(regex, nil);
enumerator = [regex segmentEnumeratorForString:@"aabbcc"];
STAssertNotNil(enumerator, nil);
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// and done w/o walking the rest
}
- (void)testMatchSegmentEnumeratorForString {
GTMRegex *regex = [GTMRegex regexWithPattern:@"foo+ba+r"];
STAssertNotNil(regex, nil);
// test odd input
NSEnumerator *enumerator = [regex matchSegmentEnumeratorForString:@""];
STAssertNotNil(enumerator, nil);
enumerator = [regex matchSegmentEnumeratorForString:nil];
STAssertNil(enumerator, nil);
// on w/ the normal tests
enumerator = [regex matchSegmentEnumeratorForString:@"afoobarbfooobaarfoobarzz"];
STAssertNotNil(enumerator, nil);
// "a" - skipped
// "foobar"
GTMRegexStringSegment *seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "b" - skipped
// "fooobaar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"fooobaar", nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "zz" - skipped
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test no match
enumerator = [regex matchSegmentEnumeratorForString:@"aaa"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil); // should have gotten nothing
// test only match
enumerator = [regex matchSegmentEnumeratorForString:@"foobar"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// now test the saved sub segments
regex = [GTMRegex regexWithPattern:@"(foo)((bar)|(baz))"];
STAssertNotNil(regex, nil);
STAssertEquals((NSUInteger)4, [regex subPatternCount], nil);
enumerator = [regex matchSegmentEnumeratorForString:@"foobarxxfoobaz"];
STAssertNotNil(enumerator, nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"bar", nil);
STAssertEqualStrings([seg subPatternString:3], @"bar", nil);
STAssertNil([seg subPatternString:4], nil); // nothing matched "(baz)"
STAssertNil([seg subPatternString:5], nil);
// "xx" - skipped
// "foobaz"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"baz", nil);
STAssertNil([seg subPatternString:3], nil); // (nothing matched "(bar)"
STAssertEqualStrings([seg subPatternString:4], @"baz", nil);
STAssertNil([seg subPatternString:5], nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test all objects
regex = [GTMRegex regexWithPattern:@"foo+ba+r"];
STAssertNotNil(regex, nil);
enumerator = [regex matchSegmentEnumeratorForString:@"afoobarbfooobaarfoobarzz"];
STAssertNotNil(enumerator, nil);
NSArray *allSegments = [enumerator allObjects];
STAssertNotNil(allSegments, nil);
STAssertEquals((NSUInteger)3, [allSegments count], nil);
// test we are getting the flags right for newline
regex = [GTMRegex regexWithPattern:@"^a"];
STAssertNotNil(regex, nil);
enumerator = [regex matchSegmentEnumeratorForString:@"aa\naa"];
STAssertNotNil(enumerator, nil);
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "a\n" - skipped
// "a"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "a" - skipped
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test we are getting the flags right for newline, part 2
regex = [GTMRegex regexWithPattern:@"^a*$"];
STAssertNotNil(regex, nil);
enumerator = [regex matchSegmentEnumeratorForString:@"aa\naa\nbb\naa"];
STAssertNotNil(enumerator, nil);
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// "\n" - skipped
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// "\nbb\n" - skipped
// "aa"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aa", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
}
- (void)testStringByReplacingMatchesInStringWithReplacement {
GTMRegex *regex = [GTMRegex regexWithPattern:@"(foo)(.*)(bar)"];
STAssertNotNil(regex, nil);
// the basics
STAssertEqualStrings(@"weeZbarZbydoo spamZfooZdoggies",
[regex stringByReplacingMatchesInString:@"weefoobydoo spambardoggies"
withReplacement:@"Z\\3Z\\2Z\\1Z"],
nil);
// nil/empty replacement
STAssertEqualStrings(@"weedoggies",
[regex stringByReplacingMatchesInString:@"weefoobydoo spambardoggies"
withReplacement:nil],
nil);
STAssertEqualStrings(@"weedoggies",
[regex stringByReplacingMatchesInString:@"weefoobydoo spambardoggies"
withReplacement:@""],
nil);
STAssertEqualStrings(@"",
[regex stringByReplacingMatchesInString:@""
withReplacement:@"abc"],
nil);
STAssertNil([regex stringByReplacingMatchesInString:nil
withReplacement:@"abc"],
nil);
// use optional and invale subexpression parts to confirm that works
regex = [GTMRegex regexWithPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNotNil(regex, nil);
STAssertEqualStrings(@"aaa baz bar bar foo baz aaa",
[regex stringByReplacingMatchesInString:@"aaa foooooobaz fooobar bar foo baz aaa"
withReplacement:@"\\4\\5"],
nil);
STAssertEqualStrings(@"aaa ZZZ ZZZ bar foo baz aaa",
[regex stringByReplacingMatchesInString:@"aaa foooooobaz fooobar bar foo baz aaa"
withReplacement:@"Z\\10Z\\12Z"],
nil);
// test slashes in replacement that aren't part of the subpattern reference
regex = [GTMRegex regexWithPattern:@"a+"];
STAssertNotNil(regex, nil);
STAssertEqualStrings(@"z\\\\0 \\\\a \\\\\\\\0z",
[regex stringByReplacingMatchesInString:@"zaz"
withReplacement:@"\\\\0 \\\\\\0 \\\\\\\\0"],
nil);
STAssertEqualStrings(@"z\\\\a \\\\\\\\0 \\\\\\\\az",
[regex stringByReplacingMatchesInString:@"zaz"
withReplacement:@"\\\\\\0 \\\\\\\\0 \\\\\\\\\\0"],
nil);
STAssertEqualStrings(@"z\\\\\\\\0 \\\\\\\\a \\\\\\\\\\\\0z",
[regex stringByReplacingMatchesInString:@"zaz"
withReplacement:@"\\\\\\\\0 \\\\\\\\\\0 \\\\\\\\\\\\0"],
nil);
}
- (void)testDescriptions {
// default options
GTMRegex *regex = [GTMRegex regexWithPattern:@"a+"];
STAssertNotNil(regex, nil);
STAssertGreaterThan([[regex description] length], (NSUInteger)10,
@"failed to get a reasonable description for regex");
// enumerator
NSEnumerator *enumerator = [regex segmentEnumeratorForString:@"aaabbbccc"];
STAssertNotNil(enumerator, nil);
STAssertGreaterThan([[enumerator description] length], (NSUInteger)10,
@"failed to get a reasonable description for regex enumerator");
// string segment
GTMRegexStringSegment *seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertGreaterThan([[seg description] length], (NSUInteger)10,
@"failed to get a reasonable description for regex string segment");
// regex w/ other options
regex = [GTMRegex regexWithPattern:@"a+"
options:(kGTMRegexOptionIgnoreCase | kGTMRegexOptionSupressNewlineSupport)];
STAssertNotNil(regex, nil);
STAssertGreaterThan([[regex description] length], (NSUInteger)10,
@"failed to get a reasonable description for regex w/ options");
}
@end
@implementation NSString_GTMRegexAdditions
// Only partial tests to test that the call get through correctly since the
// above really tests them.
- (void)testMatchesPattern {
// simple pattern
STAssertTrue([@"foobar" gtm_matchesPattern:@"foo.*bar"], nil);
STAssertTrue([@"foobydoo spambar" gtm_matchesPattern:@"foo.*bar"], nil);
STAssertFalse([@"zzfoobarzz" gtm_matchesPattern:@"foo.*bar"], nil);
STAssertFalse([@"zzfoobydoo spambarzz" gtm_matchesPattern:@"foo.*bar"], nil);
STAssertFalse([@"abcdef" gtm_matchesPattern:@"foo.*bar"], nil);
STAssertFalse([@"" gtm_matchesPattern:@"foo.*bar"], nil);
// pattern w/ sub patterns
STAssertTrue([@"foobar" gtm_matchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertTrue([@"foobydoo spambar" gtm_matchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertFalse([@"zzfoobarzz" gtm_matchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertFalse([@"zzfoobydoo spambarzz" gtm_matchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertFalse([@"abcdef" gtm_matchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertFalse([@"" gtm_matchesPattern:@"(foo)(.*)(bar)"], nil);
}
- (void)testSubPatternsOfPattern {
NSArray *subPatterns = [@"foooooobaz" gtm_subPatternsOfPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNotNil(subPatterns, nil);
STAssertEquals((NSUInteger)6, [subPatterns count], nil);
STAssertEqualStrings(@"foooooobaz", [subPatterns objectAtIndex:0], nil);
STAssertEqualStrings(@"foooooo", [subPatterns objectAtIndex:1], nil);
STAssertEqualStrings(@"ooooo", [subPatterns objectAtIndex:2], nil);
STAssertEqualStrings(@"baz", [subPatterns objectAtIndex:3], nil);
STAssertEqualObjects([NSNull null], [subPatterns objectAtIndex:4], nil);
STAssertEqualStrings(@"baz", [subPatterns objectAtIndex:5], nil);
// not there
subPatterns = [@"aaa" gtm_subPatternsOfPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNil(subPatterns, nil);
// not extra stuff on either end
subPatterns = [@"ZZZfoooooobaz" gtm_subPatternsOfPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNil(subPatterns, nil);
subPatterns = [@"foooooobazZZZ" gtm_subPatternsOfPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNil(subPatterns, nil);
subPatterns = [@"ZZZfoooooobazZZZ" gtm_subPatternsOfPattern:@"(fo(o+))((bar)|(baz))"];
STAssertNil(subPatterns, nil);
}
- (void)testFirstSubStringMatchedByPattern {
// simple pattern
STAssertEqualStrings([@"foobar" gtm_firstSubStringMatchedByPattern:@"foo.*bar"],
@"foobar", nil);
STAssertEqualStrings([@"foobydoo spambar" gtm_firstSubStringMatchedByPattern:@"foo.*bar"],
@"foobydoo spambar", nil);
STAssertEqualStrings([@"zzfoobarzz" gtm_firstSubStringMatchedByPattern:@"foo.*bar"],
@"foobar", nil);
STAssertEqualStrings([@"zzfoobydoo spambarzz" gtm_firstSubStringMatchedByPattern:@"foo.*bar"],
@"foobydoo spambar", nil);
STAssertNil([@"abcdef" gtm_firstSubStringMatchedByPattern:@"foo.*bar"], nil);
STAssertNil([@"" gtm_firstSubStringMatchedByPattern:@"foo.*bar"], nil);
// pattern w/ sub patterns
STAssertEqualStrings([@"foobar" gtm_firstSubStringMatchedByPattern:@"(foo)(.*)(bar)"],
@"foobar", nil);
STAssertEqualStrings([@"foobydoo spambar" gtm_firstSubStringMatchedByPattern:@"(foo)(.*)(bar)"],
@"foobydoo spambar", nil);
STAssertEqualStrings([@"zzfoobarzz" gtm_firstSubStringMatchedByPattern:@"(foo)(.*)(bar)"],
@"foobar", nil);
STAssertEqualStrings([@"zzfoobydoo spambarzz" gtm_firstSubStringMatchedByPattern:@"(foo)(.*)(bar)"],
@"foobydoo spambar", nil);
STAssertNil([@"abcdef" gtm_firstSubStringMatchedByPattern:@"(foo)(.*)(bar)"], nil);
STAssertNil([@"" gtm_firstSubStringMatchedByPattern:@"(foo)(.*)(bar)"], nil);
}
- (void)testSubStringMatchesPattern {
// simple pattern
STAssertTrue([@"foobar" gtm_subStringMatchesPattern:@"foo.*bar"], nil);
STAssertTrue([@"foobydoo spambar" gtm_subStringMatchesPattern:@"foo.*bar"], nil);
STAssertTrue([@"zzfoobarzz" gtm_subStringMatchesPattern:@"foo.*bar"], nil);
STAssertTrue([@"zzfoobydoo spambarzz" gtm_subStringMatchesPattern:@"foo.*bar"], nil);
STAssertFalse([@"abcdef" gtm_subStringMatchesPattern:@"foo.*bar"], nil);
STAssertFalse([@"" gtm_subStringMatchesPattern:@"foo.*bar"], nil);
// pattern w/ sub patterns
STAssertTrue([@"foobar" gtm_subStringMatchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertTrue([@"foobydoo spambar" gtm_subStringMatchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertTrue([@"zzfoobarzz" gtm_subStringMatchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertTrue([@"zzfoobydoo spambarzz" gtm_subStringMatchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertFalse([@"abcdef" gtm_subStringMatchesPattern:@"(foo)(.*)(bar)"], nil);
STAssertFalse([@"" gtm_subStringMatchesPattern:@"(foo)(.*)(bar)"], nil);
}
- (void)testSegmentEnumeratorForPattern {
NSEnumerator *enumerator =
[@"afoobarbfooobaarfoobarzz" gtm_segmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
// "a"
GTMRegexStringSegment *seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"a", nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "b"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"b", nil);
// "fooobaar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"fooobaar", nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "zz"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"zz", nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test no match
enumerator = [@"aaa" gtm_segmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"aaa", nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test only match
enumerator = [@"foobar" gtm_segmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// now test the saved sub segments
enumerator =
[@"foobarxxfoobaz" gtm_segmentEnumeratorForPattern:@"(foo)((bar)|(baz))"];
STAssertNotNil(enumerator, nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"bar", nil);
STAssertEqualStrings([seg subPatternString:3], @"bar", nil);
STAssertNil([seg subPatternString:4], nil); // nothing matched "(baz)"
STAssertNil([seg subPatternString:5], nil);
// "xx"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertFalse([seg isMatch], nil);
STAssertEqualStrings([seg string], @"xx", nil);
STAssertEqualStrings([seg subPatternString:0], @"xx", nil);
STAssertNil([seg subPatternString:1], nil);
// "foobaz"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"baz", nil);
STAssertNil([seg subPatternString:3], nil); // (nothing matched "(bar)"
STAssertEqualStrings([seg subPatternString:4], @"baz", nil);
STAssertNil([seg subPatternString:5], nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test all objects
enumerator = [@"afoobarbfooobaarfoobarzz" gtm_segmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
NSArray *allSegments = [enumerator allObjects];
STAssertNotNil(allSegments, nil);
STAssertEquals((NSUInteger)6, [allSegments count], nil);
}
- (void)testMatchSegmentEnumeratorForPattern {
NSEnumerator *enumerator =
[@"afoobarbfooobaarfoobarzz" gtm_matchSegmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
// "a" - skipped
// "foobar"
GTMRegexStringSegment *seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "b" - skipped
// "fooobaar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"fooobaar", nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
// "zz" - skipped
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test no match
enumerator = [@"aaa" gtm_matchSegmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test only match
enumerator = [@"foobar" gtm_matchSegmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// now test the saved sub segments
enumerator =
[@"foobarxxfoobaz" gtm_matchSegmentEnumeratorForPattern:@"(foo)((bar)|(baz))"];
STAssertNotNil(enumerator, nil);
// "foobar"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobar", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"bar", nil);
STAssertEqualStrings([seg subPatternString:3], @"bar", nil);
STAssertNil([seg subPatternString:4], nil); // nothing matched "(baz)"
STAssertNil([seg subPatternString:5], nil);
// "xx" - skipped
// "foobaz"
seg = [enumerator nextObject];
STAssertNotNil(seg, nil);
STAssertTrue([seg isMatch], nil);
STAssertEqualStrings([seg string], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:0], @"foobaz", nil);
STAssertEqualStrings([seg subPatternString:1], @"foo", nil);
STAssertEqualStrings([seg subPatternString:2], @"baz", nil);
STAssertNil([seg subPatternString:3], nil); // (nothing matched "(bar)"
STAssertEqualStrings([seg subPatternString:4], @"baz", nil);
STAssertNil([seg subPatternString:5], nil);
// (end)
seg = [enumerator nextObject];
STAssertNil(seg, nil);
// test all objects
enumerator = [@"afoobarbfooobaarfoobarzz" gtm_matchSegmentEnumeratorForPattern:@"foo+ba+r"];
STAssertNotNil(enumerator, nil);
NSArray *allSegments = [enumerator allObjects];
STAssertNotNil(allSegments, nil);
STAssertEquals((NSUInteger)3, [allSegments count], nil);
}
- (void)testAllSubstringsMatchedByPattern {
NSArray *segments =
[@"afoobarbfooobaarfoobarzz" gtm_allSubstringsMatchedByPattern:@"foo+ba+r"];
STAssertNotNil(segments, nil);
STAssertEquals((NSUInteger)3, [segments count], nil);
STAssertEqualStrings([segments objectAtIndex:0], @"foobar", nil);
STAssertEqualStrings([segments objectAtIndex:1], @"fooobaar", nil);
STAssertEqualStrings([segments objectAtIndex:2], @"foobar", nil);
// test no match
segments = [@"aaa" gtm_allSubstringsMatchedByPattern:@"foo+ba+r"];
STAssertNotNil(segments, nil);
STAssertEquals((NSUInteger)0, [segments count], nil);
// test only match
segments = [@"foobar" gtm_allSubstringsMatchedByPattern:@"foo+ba+r"];
STAssertNotNil(segments, nil);
STAssertEquals((NSUInteger)1, [segments count], nil);
STAssertEqualStrings([segments objectAtIndex:0], @"foobar", nil);
}
- (void)testStringByReplacingMatchesOfPatternWithReplacement {
// the basics
STAssertEqualStrings(@"weeZbarZbydoo spamZfooZdoggies",
[@"weefoobydoo spambardoggies" gtm_stringByReplacingMatchesOfPattern:@"(foo)(.*)(bar)"
withReplacement:@"Z\\3Z\\2Z\\1Z"],
nil);
// nil/empty replacement
STAssertEqualStrings(@"weedoggies",
[@"weefoobydoo spambardoggies" gtm_stringByReplacingMatchesOfPattern:@"(foo)(.*)(bar)"
withReplacement:nil],
nil);
STAssertEqualStrings(@"weedoggies",
[@"weefoobydoo spambardoggies" gtm_stringByReplacingMatchesOfPattern:@"(foo)(.*)(bar)"
withReplacement:@""],
nil);
STAssertEqualStrings(@"",
[@"" gtm_stringByReplacingMatchesOfPattern:@"(foo)(.*)(bar)"
withReplacement:@"abc"],
nil);
// use optional and invale subexpression parts to confirm that works
STAssertEqualStrings(@"aaa baz bar bar foo baz aaa",
[@"aaa foooooobaz fooobar bar foo baz aaa" gtm_stringByReplacingMatchesOfPattern:@"(fo(o+))((bar)|(baz))"
withReplacement:@"\\4\\5"],
nil);
STAssertEqualStrings(@"aaa ZZZ ZZZ bar foo baz aaa",
[@"aaa foooooobaz fooobar bar foo baz aaa" gtm_stringByReplacingMatchesOfPattern:@"(fo(o+))((bar)|(baz))"
withReplacement:@"Z\\10Z\\12Z"],
nil);
// test slashes in replacement that aren't part of the subpattern reference
STAssertEqualStrings(@"z\\\\0 \\\\a \\\\\\\\0z",
[@"zaz" gtm_stringByReplacingMatchesOfPattern:@"a+"
withReplacement:@"\\\\0 \\\\\\0 \\\\\\\\0"],
nil);
STAssertEqualStrings(@"z\\\\a \\\\\\\\0 \\\\\\\\az",
[@"zaz" gtm_stringByReplacingMatchesOfPattern:@"a+"
withReplacement:@"\\\\\\0 \\\\\\\\0 \\\\\\\\\\0"],
nil);
STAssertEqualStrings(@"z\\\\\\\\0 \\\\\\\\a \\\\\\\\\\\\0z",
[@"zaz" gtm_stringByReplacingMatchesOfPattern:@"a+"
withReplacement:@"\\\\\\\\0 \\\\\\\\\\0 \\\\\\\\\\\\0"],
nil);
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMRegexTest.m | Objective-C | bsd | 51,838 |
//
// GTMStackTraceTest.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <SenTestingKit/SenTestingKit.h>
#import <Foundation/Foundation.h>
#import "GTMStackTrace.h"
#import "GTMSenTestCase.h"
@interface GTMStackTraceTest : GTMTestCase
@end
@implementation GTMStackTraceTest
- (void)testStackTraceBasic {
NSString *stacktrace = GTMStackTrace();
NSArray *stacklines = [stacktrace componentsSeparatedByString:@"\n"];
STAssertGreaterThan([stacklines count], (NSUInteger)3,
@"stack trace must have > 3 lines");
STAssertLessThan([stacklines count], (NSUInteger)25,
@"stack trace must have < 25 lines");
NSString *firstFrame = [stacklines objectAtIndex:0];
NSRange range = [firstFrame rangeOfString:@"GTMStackTrace"];
STAssertNotEquals(range.location, (NSUInteger)NSNotFound,
@"First frame should contain GTMStackTrace, stack trace: %@",
stacktrace);
}
- (void)testProgramCountersBasic {
void *pcs[10];
int depth = 10;
depth = GTMGetStackProgramCounters(pcs, depth);
STAssertGreaterThan(depth, 3, @"stack trace must have > 3 lines");
STAssertLessThanOrEqual(depth, 10, @"stack trace must have < 10 lines");
// pcs is an array of program counters from the stack. pcs[0] should match
// the call into GTMGetStackProgramCounters, which is tough for us to check.
// However, we can verify that pcs[1] is equal to our current return address
// for our current function.
void *current_pc = __builtin_return_address(0);
STAssertEquals(pcs[1], current_pc, @"pcs[1] should equal the current PC");
}
- (void)testProgramCountersMore {
void *pcs0[0];
int depth0 = 0;
depth0 = GTMGetStackProgramCounters(pcs0, depth0);
STAssertEquals(depth0, 0, @"stack trace must have 0 lines");
void *pcs1[1];
int depth1 = 1;
depth1 = GTMGetStackProgramCounters(pcs1, depth1);
STAssertEquals(depth1, 1, @"stack trace must have 1 lines");
void *pcs2[2];
int depth2 = 2;
depth2 = GTMGetStackProgramCounters(pcs2, depth2);
STAssertEquals(depth2, 2, @"stack trace must have 2 lines");
void *current_pc = __builtin_return_address(0);
STAssertEquals(pcs2[1], current_pc, @"pcs[1] should equal the current PC");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMStackTraceTest.m | Objective-C | bsd | 2,815 |
//
// GTMSystemVersionTest.m
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMSystemVersion.h"
@interface GTMSystemVersionTest : GTMTestCase
@end
@implementation GTMSystemVersionTest
- (void)testBasics {
long major;
long minor;
long bugFix;
[GTMSystemVersion getMajor:nil minor:nil bugFix:nil];
[GTMSystemVersion getMajor:&major minor:&minor bugFix:&bugFix];
#if GTM_IPHONE_SDK
STAssertTrue(major >= 2 && minor >= 0 && bugFix >= 0, nil);
#else
STAssertTrue(major >= 10 && minor >= 3 && bugFix >= 0, nil);
BOOL isPanther = (major == 10) && (minor == 3);
BOOL isTiger = (major == 10) && (minor == 4);
BOOL isLeopard = (major == 10) && (minor == 5);
BOOL isLater = (major > 10) || ((major == 10) && (minor > 5));
STAssertEquals([GTMSystemVersion isPanther], isPanther, nil);
STAssertEquals([GTMSystemVersion isPantherOrGreater],
(BOOL)(isPanther || isTiger || isLeopard || isLater), nil);
STAssertEquals([GTMSystemVersion isTiger], isTiger, nil);
STAssertEquals([GTMSystemVersion isTigerOrGreater],
(BOOL)(isTiger || isLeopard || isLater), nil);
STAssertEquals([GTMSystemVersion isLeopard], isLeopard, nil);
STAssertEquals([GTMSystemVersion isLeopardOrGreater],
(BOOL)(isLeopard || isLater), nil);
#endif
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMSystemVersionTest.m | Objective-C | bsd | 1,901 |
//
// GTMLogger.h
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
// Key Abstractions
// ----------------
//
// This file declares multiple classes and protocols that are used by the
// GTMLogger logging system. The 4 main abstractions used in this file are the
// following:
//
// * logger (GTMLogger) - The main logging class that users interact with. It
// has methods for logging at different levels and uses a log writer, a log
// formatter, and a log filter to get the job done.
//
// * log writer (GTMLogWriter) - Writes a given string to some log file, where
// a "log file" can be a physical file on disk, a POST over HTTP to some URL,
// or even some in-memory structure (e.g., a ring buffer).
//
// * log formatter (GTMLogFormatter) - Given a format string and arguments as
// a va_list, returns a single formatted NSString. A "formatted string" could
// be a string with the date prepended, a string with values in a CSV format,
// or even a string of XML.
//
// * log filter (GTMLogFilter) - Given a formatted log message as an NSString
// and the level at which the message is to be logged, this class will decide
// whether the given message should be logged or not. This is a flexible way
// to filter out messages logged at a certain level, messages that contain
// certain text, or filter nothing out at all. This gives the caller the
// flexibility to dynamically enable debug logging in Release builds.
//
// This file also declares some classes to handle the common log writer, log
// formatter, and log filter cases. Callers can also create their own writers,
// formatters, and filters and they can even build them on top of the ones
// declared here. Keep in mind that your custom writer/formatter/filter may be
// called from multiple threads, so it must be thread-safe.
#import <Foundation/Foundation.h>
#import "GTMDefines.h"
// Predeclaration of used protocols that are declared later in this file.
@protocol GTMLogWriter, GTMLogFormatter, GTMLogFilter;
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
#define CHECK_FORMAT_NSSTRING(a, b) __attribute__((format(__NSString__, a, b)))
#else
#define CHECK_FORMAT_NSSTRING(a, b)
#endif
// GTMLogger
//
// GTMLogger is the primary user-facing class for an object-oriented logging
// system. It is built on the concept of log formatters (GTMLogFormatter), log
// writers (GTMLogWriter), and log filters (GTMLogFilter). When a message is
// sent to a GTMLogger to log a message, the message is formatted using the log
// formatter, then the log filter is consulted to see if the message should be
// logged, and if so, the message is sent to the log writer to be written out.
//
// GTMLogger is intended to be a flexible and thread-safe logging solution. Its
// flexibility comes from the fact that GTMLogger instances can be customized
// with user defined formatters, filters, and writers. And these writers,
// filters, and formatters can be combined, stacked, and customized in arbitrary
// ways to suit the needs at hand. For example, multiple writers can be used at
// the same time, and a GTMLogger instance can even be used as another
// GTMLogger's writer. This allows for arbitrarily deep logging trees.
//
// A standard GTMLogger uses a writer that sends messages to standard out, a
// formatter that smacks a timestamp and a few other bits of interesting
// information on the message, and a filter that filters out debug messages from
// release builds. Using the standard log settings, a log message will look like
// the following:
//
// 2007-12-30 10:29:24.177 myapp[4588/0xa07d0f60] [lvl=1] foo=<Foo: 0x123>
//
// The output contains the date and time of the log message, the name of the
// process followed by its process ID/thread ID, the log level at which the
// message was logged (in the previous example the level was 1:
// kGTMLoggerLevelDebug), and finally, the user-specified log message itself (in
// this case, the log message was @"foo=%@", foo).
//
// Multiple instances of GTMLogger can be created, each configured their own
// way. Though GTMLogger is not a singleton (in the GoF sense), it does provide
// access to a shared (i.e., globally accessible) GTMLogger instance. This makes
// it convenient for all code in a process to use the same GTMLogger instance.
// The shared GTMLogger instance can also be configured in an arbitrary, and
// these configuration changes will affect all code that logs through the shared
// instance.
//
// Log Levels
// ----------
// GTMLogger has 3 different log levels: Debug, Info, and Error. GTMLogger
// doesn't take any special action based on the log level; it simply forwards
// this information on to formatters, filters, and writers, each of which may
// optionally take action based on the level. Since log level filtering is
// performed at runtime, log messages are typically not filtered out at compile
// time. The exception to this rule is that calls to the GTMLoggerDebug() macro
// *ARE* filtered out of non-DEBUG builds. This is to be backwards compatible
// with behavior that many developers are currently used to. Note that this
// means that GTMLoggerDebug(@"hi") will be compiled out of Release builds, but
// [[GTMLogger sharedLogger] logDebug:@"hi"] will NOT be compiled out.
//
// Standard loggers are created with the GTMLogLevelFilter log filter, which
// filters out certain log messages based on log level, and some other settings.
//
// In addition to the -logDebug:, -logInfo:, and -logError: methods defined on
// GTMLogger itself, there are also C macros that make usage of the shared
// GTMLogger instance very convenient. These macros are:
//
// GTMLoggerDebug(...)
// GTMLoggerInfo(...)
// GTMLoggerError(...)
//
// Again, a notable feature of these macros is that GTMLogDebug() calls *will be
// compiled out of non-DEBUG builds*.
//
// Standard Loggers
// ----------------
// GTMLogger has the concept of "standard loggers". A standard logger is simply
// a logger that is pre-configured with some standard/common writer, formatter,
// and filter combination. Standard loggers are created using the creation
// methods beginning with "standard". The alternative to a standard logger is a
// regular logger, which will send messages to stdout, with no special
// formatting, and no filtering.
//
// How do I use GTMLogger?
// ----------------------
// The typical way you will want to use GTMLogger is to simply use the
// GTMLogger*() macros for logging from code. That way we can easily make
// changes to the GTMLogger class and simply update the macros accordingly. Only
// your application startup code (perhaps, somewhere in main()) should use the
// GTMLogger class directly in order to configure the shared logger, which all
// of the code using the macros will be using. Again, this is just the typical
// situation.
//
// To be complete, there are cases where you may want to use GTMLogger directly,
// or even create separate GTMLogger instances for some reason. That's fine,
// too.
//
// Examples
// --------
// The following show some common GTMLogger use cases.
//
// 1. You want to log something as simply as possible. Also, this call will only
// appear in debug builds. In non-DEBUG builds it will be completely removed.
//
// GTMLoggerDebug(@"foo = %@", foo);
//
// 2. The previous example is similar to the following. The major difference is
// that the previous call (example 1) will be compiled out of Release builds
// but this statement will not be compiled out.
//
// [[GTMLogger sharedLogger] logDebug:@"foo = %@", foo];
//
// 3. Send all logging output from the shared logger to a file. We do this by
// creating an NSFileHandle for writing associated with a file, and setting
// that file handle as the logger's writer.
//
// NSFileHandle *f = [NSFileHandle fileHandleForWritingAtPath:@"/tmp/f.log"
// create:YES];
// [[GTMLogger sharedLogger] setWriter:f];
// GTMLoggerError(@"hi"); // This will be sent to /tmp/f.log
//
// 4. Create a new GTMLogger that will log to a file. This example differs from
// the previous one because here we create a new GTMLogger that is different
// from the shared logger.
//
// GTMLogger *logger = [GTMLogger standardLoggerWithPath:@"/tmp/temp.log"];
// [logger logInfo:@"hi temp log file"];
//
// 5. Create a logger that writes to stdout and does NOT do any formatting to
// the log message. This might be useful, for example, when writing a help
// screen for a command-line tool to standard output.
//
// GTMLogger *logger = [GTMLogger logger];
// [logger logInfo:@"%@ version 0.1 usage", progName];
//
// 6. Send log output to stdout AND to a log file. The trick here is that
// NSArrays function as composite log writers, which means when an array is
// set as the log writer, it forwards all logging messages to all of its
// contained GTMLogWriters.
//
// // Create array of GTMLogWriters
// NSArray *writers = [NSArray arrayWithObjects:
// [NSFileHandle fileHandleForWritingAtPath:@"/tmp/f.log" create:YES],
// [NSFileHandle fileHandleWithStandardOutput], nil];
//
// GTMLogger *logger = [GTMLogger standardLogger];
// [logger setWriter:writers];
// [logger logInfo:@"hi"]; // Output goes to stdout and /tmp/f.log
//
// For futher details on log writers, formatters, and filters, see the
// documentation below.
//
// NOTE: GTMLogger is application level logging. By default it does nothing
// with _GTMDevLog/_GTMDevAssert (see GTMDefines.h). An application can choose
// to bridge _GTMDevLog/_GTMDevAssert to GTMLogger by providing macro
// definitions in its prefix header (see GTMDefines.h for how one would do
// that).
//
@interface GTMLogger : NSObject {
@private
id<GTMLogWriter> writer_;
id<GTMLogFormatter> formatter_;
id<GTMLogFilter> filter_;
}
//
// Accessors for the shared logger instance
//
// Returns a shared/global standard GTMLogger instance. Callers should typically
// use this method to get a GTMLogger instance, unless they explicitly want
// their own instance to configure for their own needs. This is the only method
// that returns a shared instance; all the rest return new GTMLogger instances.
+ (id)sharedLogger;
// Sets the shared logger instance to |logger|. Future calls to +sharedLogger
// will return |logger| instead.
+ (void)setSharedLogger:(GTMLogger *)logger;
//
// Creation methods
//
// Returns a new autoreleased GTMLogger instance that will log to stdout, using
// the GTMLogStandardFormatter, and the GTMLogLevelFilter filter.
+ (id)standardLogger;
// Same as +standardLogger, but logs to stderr.
+ (id)standardLoggerWithStderr;
// Returns a new standard GTMLogger instance with a log writer that will
// write to the file at |path|, and will use the GTMLogStandardFormatter and
// GTMLogLevelFilter classes. If |path| does not exist, it will be created.
+ (id)standardLoggerWithPath:(NSString *)path;
// Returns an autoreleased GTMLogger instance that will use the specified
// |writer|, |formatter|, and |filter|.
+ (id)loggerWithWriter:(id<GTMLogWriter>)writer
formatter:(id<GTMLogFormatter>)formatter
filter:(id<GTMLogFilter>)filter;
// Returns an autoreleased GTMLogger instance that logs to stdout, with the
// basic formatter, and no filter. The returned logger differs from the logger
// returned by +standardLogger because this one does not do any filtering and
// does not do any special log formatting; this is the difference between a
// "regular" logger and a "standard" logger.
+ (id)logger;
// Designated initializer. This method returns a GTMLogger initialized with the
// specified |writer|, |formatter|, and |filter|. See the setter methods below
// for what values will be used if nil is passed for a parameter.
- (id)initWithWriter:(id<GTMLogWriter>)writer
formatter:(id<GTMLogFormatter>)formatter
filter:(id<GTMLogFilter>)filter;
//
// Logging methods
//
// Logs a message at the debug level (kGTMLoggerLevelDebug).
- (void)logDebug:(NSString *)fmt, ... CHECK_FORMAT_NSSTRING(1, 2);
// Logs a message at the info level (kGTMLoggerLevelInfo).
- (void)logInfo:(NSString *)fmt, ... CHECK_FORMAT_NSSTRING(1, 2);
// Logs a message at the error level (kGTMLoggerLevelError).
- (void)logError:(NSString *)fmt, ... CHECK_FORMAT_NSSTRING(1, 2);
// Logs a message at the assert level (kGTMLoggerLevelAssert).
- (void)logAssert:(NSString *)fmt, ... CHECK_FORMAT_NSSTRING(1, 2);
//
// Accessors
//
// Accessor methods for the log writer. If the log writer is set to nil,
// [NSFileHandle fileHandleWithStandardOutput] is used.
- (id<GTMLogWriter>)writer;
- (void)setWriter:(id<GTMLogWriter>)writer;
// Accessor methods for the log formatter. If the log formatter is set to nil,
// GTMLogBasicFormatter is used. This formatter will format log messages in a
// plain printf style.
- (id<GTMLogFormatter>)formatter;
- (void)setFormatter:(id<GTMLogFormatter>)formatter;
// Accessor methods for the log filter. If the log filter is set to nil,
// GTMLogNoFilter is used, which allows all log messages through.
- (id<GTMLogFilter>)filter;
- (void)setFilter:(id<GTMLogFilter>)filter;
@end // GTMLogger
// Helper functions that are used by the convenience GTMLogger*() macros that
// enable the logging of function names.
@interface GTMLogger (GTMLoggerMacroHelpers)
- (void)logFuncDebug:(const char *)func msg:(NSString *)fmt, ...
CHECK_FORMAT_NSSTRING(2, 3);
- (void)logFuncInfo:(const char *)func msg:(NSString *)fmt, ...
CHECK_FORMAT_NSSTRING(2, 3);
- (void)logFuncError:(const char *)func msg:(NSString *)fmt, ...
CHECK_FORMAT_NSSTRING(2, 3);
- (void)logFuncAssert:(const char *)func msg:(NSString *)fmt, ...
CHECK_FORMAT_NSSTRING(2, 3);
@end // GTMLoggerMacroHelpers
// Convenience macros that log to the shared GTMLogger instance. These macros
// are how users should typically log to GTMLogger. Notice that GTMLoggerDebug()
// calls will be compiled out of non-Debug builds.
#define GTMLoggerDebug(...) \
[[GTMLogger sharedLogger] logFuncDebug:__func__ msg:__VA_ARGS__]
#define GTMLoggerInfo(...) \
[[GTMLogger sharedLogger] logFuncInfo:__func__ msg:__VA_ARGS__]
#define GTMLoggerError(...) \
[[GTMLogger sharedLogger] logFuncError:__func__ msg:__VA_ARGS__]
#define GTMLoggerAssert(...) \
[[GTMLogger sharedLogger] logFuncAssert:__func__ msg:__VA_ARGS__]
// If we're not in a debug build, remove the GTMLoggerDebug statements. This
// makes calls to GTMLoggerDebug "compile out" of Release builds
#ifndef DEBUG
#undef GTMLoggerDebug
#define GTMLoggerDebug(...) do {} while(0)
#endif
// Log levels.
typedef enum {
kGTMLoggerLevelUnknown,
kGTMLoggerLevelDebug,
kGTMLoggerLevelInfo,
kGTMLoggerLevelError,
kGTMLoggerLevelAssert,
} GTMLoggerLevel;
//
// Log Writers
//
// Protocol to be implemented by a GTMLogWriter instance.
@protocol GTMLogWriter <NSObject>
// Writes the given log message to where the log writer is configured to write.
- (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level;
@end // GTMLogWriter
// Simple category on NSFileHandle that makes NSFileHandles valid log writers.
// This is convenient because something like, say, +fileHandleWithStandardError
// now becomes a valid log writer. Log messages are written to the file handle
// with a newline appended.
@interface NSFileHandle (GTMFileHandleLogWriter) <GTMLogWriter>
// Opens the file at |path| in append mode, and creates the file with |mode|
// if it didn't previously exist.
+ (id)fileHandleForLoggingAtPath:(NSString *)path mode:(mode_t)mode;
@end // NSFileHandle
// This category makes NSArray a GTMLogWriter that can be composed of other
// GTMLogWriters. This is the classic Composite GoF design pattern. When the
// GTMLogWriter -logMessage:level: message is sent to the array, the array
// forwards the message to all of its elements that implement the GTMLogWriter
// protocol.
//
// This is useful in situations where you would like to send log output to
// multiple log writers at the same time. Simply create an NSArray of the log
// writers you wish to use, then set the array as the "writer" for your
// GTMLogger instance.
@interface NSArray (GTMArrayCompositeLogWriter) <GTMLogWriter>
@end // GTMArrayCompositeLogWriter
// This category adapts the GTMLogger interface so that it can be used as a log
// writer; it's an "adapter" in the GoF Adapter pattern sense.
//
// This is useful when you want to configure a logger to log to a specific
// writer with a specific formatter and/or filter. But you want to also compose
// that with a different log writer that may have its own formatter and/or
// filter.
@interface GTMLogger (GTMLoggerLogWriter) <GTMLogWriter>
@end // GTMLoggerLogWriter
//
// Log Formatters
//
// Protocol to be implemented by a GTMLogFormatter instance.
@protocol GTMLogFormatter <NSObject>
// Returns a formatted string using the format specified in |fmt| and the va
// args specified in |args|.
- (NSString *)stringForFunc:(NSString *)func
withFormat:(NSString *)fmt
valist:(va_list)args
level:(GTMLoggerLevel)level;
@end // GTMLogFormatter
// A basic log formatter that formats a string the same way that NSLog (or
// printf) would. It does not do anything fancy, nor does it add any data of its
// own.
@interface GTMLogBasicFormatter : NSObject <GTMLogFormatter>
@end // GTMLogBasicFormatter
// A log formatter that formats the log string like the basic formatter, but
// also prepends a timestamp and some basic process info to the message, as
// shown in the following sample output.
// 2007-12-30 10:29:24.177 myapp[4588/0xa07d0f60] [lvl=1] log mesage here
@interface GTMLogStandardFormatter : GTMLogBasicFormatter {
@private
NSDateFormatter *dateFormatter_; // yyyy-MM-dd HH:mm:ss.SSS
NSString *pname_;
pid_t pid_;
}
@end // GTMLogStandardFormatter
//
// Log Filters
//
// Protocol to be imlemented by a GTMLogFilter instance.
@protocol GTMLogFilter <NSObject>
// Returns YES if |msg| at |level| should be filtered out; NO otherwise.
- (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level;
@end // GTMLogFilter
// A log filter that filters messages at the kGTMLoggerLevelDebug level out of
// non-debug builds. Messages at the kGTMLoggerLevelInfo level are also filtered
// out of non-debug builds unless GTMVerboseLogging is set in the environment or
// the processes's defaults. Messages at the kGTMLoggerLevelError level are
// never filtered.
@interface GTMLogLevelFilter : NSObject <GTMLogFilter>
@end // GTMLogLevelFilter
// A simple log filter that does NOT filter anything out;
// -filterAllowsMessage:level will always return YES. This can be a convenient
// way to enable debug-level logging in release builds (if you so desire).
@interface GTMLogNoFilter : NSObject <GTMLogFilter>
@end // GTMLogNoFilter
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMLogger.h | Objective-C | bsd | 19,633 |
//
// GTMNSDictionary+URLArgumentsTest.m
//
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMNSDictionary+URLArguments.h"
#import "GTMDefines.h"
@interface GTMNSDictionary_URLArgumentsTest : GTMTestCase
@end
@implementation GTMNSDictionary_URLArgumentsTest
- (void)testArgumentsString {
STAssertEqualObjects([[NSDictionary dictionary] gtm_httpArgumentsString], @"",
@"- empty dictionary should give an empty string");
STAssertEqualObjects([[NSDictionary dictionaryWithObject:@"123" forKey:@"abc"] gtm_httpArgumentsString],
@"abc=123",
@"- simple one-pair dictionary should work");
NSDictionary* arguments = [NSDictionary dictionaryWithObjectsAndKeys:
@"1+1!=3 & 2*6/3=4", @"complex",
@"specialkey", @"a+b",
nil];
NSString* argumentString = [arguments gtm_httpArgumentsString];
// check for individual pieces since order is not guaranteed
NSString* component1 = @"a%2Bb=specialkey";
NSString* component2 = @"complex=1%2B1%21%3D3%20%26%202%2A6%2F3%3D4";
STAssertNotEquals([argumentString rangeOfString:component1].location, (NSUInteger)NSNotFound,
@"- '%@' not found in '%@'", component1, argumentString);
STAssertNotEquals([argumentString rangeOfString:component2].location, (NSUInteger)NSNotFound,
@"- '%@' not found in '%@'", component2, argumentString);
STAssertNotEquals([argumentString rangeOfString:@"&"].location, (NSUInteger)NSNotFound,
@"- special characters should be escaped");
STAssertNotEquals([argumentString characterAtIndex:0], (unichar)'&',
@"- there should be no & at the beginning of the string");
STAssertNotEquals([argumentString characterAtIndex:([argumentString length] - 1)], (unichar)'&',
@"- there should be no & at the end of the string");
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/Foundation/GTMNSDictionary+URLArgumentsTest.m | Objective-C | bsd | 2,584 |
//
// GTMDebugSelectorValidation.h
//
// This file should only be included within an implimation file. In any
// function that takes an object and selector to invoke, you should call:
//
// GTMAssertSelectorNilOrImplementedWithArguments(obj, sel, @encode(arg1type), ..., NULL)
// or
// GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(obj, sel, @encode(returnType), @encode(arg1type), ..., NULL)
//
// This will then validate that the selector is defined and using the right
// type(s), this can help catch errors much earlier then waiting for the
// selector to actually fire (and in the case of error selectors, might never
// really be tested until in the field).
//
// Copyright 2007-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#if DEBUG
#import <stdarg.h>
#import "GTMDefines.h"
static void GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(id obj, SEL sel, const char *retType, ...) {
// verify that the object's selector is implemented with the proper
// number and type of arguments
va_list argList;
va_start(argList, retType);
if (obj && sel) {
// check that the selector is implemented
_GTMDevAssert([obj respondsToSelector:sel],
@"\"%@\" selector \"%@\" is unimplemented or misnamed",
NSStringFromClass([obj class]),
NSStringFromSelector(sel));
const char *expectedArgType;
NSUInteger argCount = 2; // skip self and _cmd
NSMethodSignature *sig = [obj methodSignatureForSelector:sel];
// check that each expected argument is present and of the correct type
while ((expectedArgType = va_arg(argList, const char*)) != 0) {
if ([sig numberOfArguments] > argCount) {
const char *foundArgType = [sig getArgumentTypeAtIndex:argCount];
_GTMDevAssert(0 == strncmp(foundArgType, expectedArgType, strlen(expectedArgType)),
@"\"%@\" selector \"%@\" argument %d should be type %s",
NSStringFromClass([obj class]),
NSStringFromSelector(sel),
(argCount - 2),
expectedArgType);
}
argCount++;
}
// check that the proper number of arguments are present in the selector
_GTMDevAssert(argCount == [sig numberOfArguments],
@"\"%@\" selector \"%@\" should have %d arguments",
NSStringFromClass([obj class]),
NSStringFromSelector(sel),
(argCount - 2));
// if asked, validate the return type
if (retType && (strcmp("gtm_skip_return_test", retType) != 0)) {
const char *foundRetType = [sig methodReturnType];
_GTMDevAssert(0 == strncmp(foundRetType, retType, strlen(retType)),
@"\"%@\" selector \"%@\" return type should be type %s",
NSStringFromClass([obj class]),
NSStringFromSelector(sel),
retType);
}
}
va_end(argList);
}
#define GTMAssertSelectorNilOrImplementedWithArguments(obj, sel, ...) \
GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments((obj), (sel), "gtm_skip_return_test", __VA_ARGS__)
#else // DEBUG
// make it go away if not debug
#define GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(obj, sel, retType, ...) do { } while (0)
#define GTMAssertSelectorNilOrImplementedWithArguments(obj, sel, ...) do { } while (0)
#endif // DEBUG
| 08iteng-ipad | systemtests/google-toolbox-for-mac/DebugUtils/GTMDebugSelectorValidation.h | Objective-C | bsd | 4,023 |
//
// GTMMethodCheck.m
//
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
// Don't want any of this in release builds
#ifdef DEBUG
#import "GTMDefines.h"
#import "GTMMethodCheck.h"
#import "GTMObjC2Runtime.h"
#import <dlfcn.h>
// Checks to see if the cls passed in (or one of it's superclasses) conforms
// to NSObject protocol. Inheriting from NSObject is the easiest way to do this
// but not all classes (i.e. NSProxy) inherit from NSObject. Also, some classes
// inherit from Object instead of NSObject which is fine, and we'll count as
// conforming to NSObject for our needs.
static BOOL ConformsToNSObjectProtocol(Class cls) {
// If we get nil, obviously doesn't conform.
if (!cls) return NO;
const char *className = class_getName(cls);
if (!className) return NO;
// We're going to assume that all Apple classes will work
// (and aren't being checked)
// Note to apple: why doesn't obj-c have real namespaces instead of two
// letter hacks? If you name your own classes starting with NS this won't
// work for you.
// Some classes (like _NSZombie) start with _NS.
// On Leopard we have to look for CFObject as well.
// On iPhone we check Object as well
if ((strncmp(className, "NS", 2) == 0)
|| (strncmp(className, "_NS", 3) == 0)
|| (strcmp(className, "CFObject") == 0)
#if GTM_IPHONE_SDK
|| (strcmp(className, "Object") == 0)
#endif
) {
return YES;
}
// iPhone SDK does not define the |Object| class, so we instead test for the
// |NSObject| class.
#if GTM_IPHONE_SDK
// Iterate through all the protocols |cls| supports looking for NSObject.
if (cls == [NSObject class]
|| class_conformsToProtocol(cls, @protocol(NSObject))) {
return YES;
}
#else
// Iterate through all the protocols |cls| supports looking for NSObject.
if (cls == [Object class]
|| class_conformsToProtocol(cls, @protocol(NSObject))) {
return YES;
}
#endif
// Recursively check the superclasses.
return ConformsToNSObjectProtocol(class_getSuperclass(cls));
}
void GTMMethodCheckMethodChecker(void) {
// Run through all the classes looking for class methods that are
// prefixed with xxGMMethodCheckMethod. If it finds one, it calls it.
// See GTMMethodCheck.h to see what it does.
int numClasses = 0;
int newNumClasses = objc_getClassList(NULL, 0);
int i;
Class *classes = NULL;
while (numClasses < newNumClasses) {
numClasses = newNumClasses;
classes = realloc(classes, sizeof(Class) * numClasses);
_GTMDevAssert(classes, @"Unable to allocate memory for classes");
newNumClasses = objc_getClassList(classes, numClasses);
}
for (i = 0; i < numClasses; ++i) {
Class cls = classes[i];
// Since we are directly calling objc_msgSend, we need to conform to
// @protocol(NSObject), or else we will tumble into a _objc_msgForward
// recursive loop when we try and call a function by name.
if (!ConformsToNSObjectProtocol(cls)) {
// COV_NF_START
_GTMDevLog(@"GTMMethodCheckMethodChecker: Class %s does not conform to "
"@protocol(NSObject), so won't be checked",
class_getName(cls));
continue;
// COV_NF_END
}
// Since we are looking for a class method (+xxGMMethodCheckMethod...)
// we need to query the isa pointer to see what methods it support, but
// send the method (if it's supported) to the class itself.
unsigned int count;
Class metaClass = objc_getMetaClass(class_getName(cls));
Method *methods = class_copyMethodList(metaClass, &count);
unsigned int j;
for (j = 0; j < count; ++j) {
SEL selector = method_getName(methods[j]);
const char *name = sel_getName(selector);
if (strstr(name, "xxGTMMethodCheckMethod") == name) {
// Check to make sure that the method we are checking comes
// from the same image that we are in. Since GTMMethodCheckMethodChecker
// is not exported, we should always find the copy in our local
// image. We compare the address of it's image with the address of
// the image which implements the method we want to check. If
// they match we continue. This does two things:
// a) minimizes the amount of calls we make to the xxxGTMMethodCheck
// methods. They should only be called once.
// b) prevents initializers for various classes being called too early
Dl_info methodCheckerInfo;
if (!dladdr(GTMMethodCheckMethodChecker,
&methodCheckerInfo)) {
// COV_NF_START
// Don't know how to force this case in a unittest.
// Certainly hope we never see it.
_GTMDevLog(@"GTMMethodCheckMethodChecker: Unable to get dladdr info "
"for GTMMethodCheckMethodChecker while introspecting +[%@ %@]]",
class_getName(cls), name);
continue;
// COV_NF_END
}
Dl_info methodInfo;
if (!dladdr(method_getImplementation(methods[j]),
&methodInfo)) {
// COV_NF_START
// Don't know how to force this case in a unittest
// Certainly hope we never see it.
_GTMDevLog(@"GTMMethodCheckMethodChecker: Unable to get dladdr info "
"for %@ while introspecting +[%@ %@]]", name,
class_getName(cls), name);
continue;
// COV_NF_END
}
if (methodCheckerInfo.dli_fbase == methodInfo.dli_fbase) {
objc_msgSend(cls, selector);
}
}
}
if (methods) {
free(methods);
}
}
if (classes) {
free(classes);
}
}
#endif // DEBUG
| 08iteng-ipad | systemtests/google-toolbox-for-mac/DebugUtils/GTMMethodCheck.m | Objective-C | bsd | 6,257 |
//
// GTMMethodCheck.h
//
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import <Foundation/Foundation.h>
#import <stdio.h>
#import <sysexits.h>
/// A macro for enforcing debug time checks to make sure all required methods are linked in
//
// When using categories, it can be very easy to forget to include the
// implementation of a category.
// Let's say you had a class foo that depended on method bar of class baz, and
// method bar was implemented as a member of a category.
// You could add the following code:
// @implementation foo
// GTM_METHOD_CHECK(baz, bar)
// @end
// and the code would check to make sure baz was implemented just before main
// was called. This works for both dynamic libraries, and executables.
//
// Classes (or one of their superclasses) being checked must conform to the
// NSObject protocol. We will check this, and spit out a warning if a class does
// not conform to NSObject.
//
// This is not compiled into release builds.
#ifdef DEBUG
#ifdef __cplusplus
extern "C" {
#endif
// If you get an error for GTMMethodCheckMethodChecker not being defined,
// you need to link in GTMMethodCheck.m. We keep it hidden so that we can have
// it living in several separate images without conflict.
// Functions with the ((constructor)) attribute are called after all +loads
// have been called. See "Initializing Objective-C Classes" in
// http://developer.apple.com/documentation/DeveloperTools/Conceptual/DynamicLibraries/Articles/DynamicLibraryDesignGuidelines.html#//apple_ref/doc/uid/TP40002013-DontLinkElementID_20
__attribute__ ((constructor, visibility("hidden"))) void GTMMethodCheckMethodChecker(void);
#ifdef __cplusplus
};
#endif
// This is the "magic".
// A) we need a multi layer define here so that the stupid preprocessor
// expands __LINE__ out the way we want it. We need LINE so that each of
// out GTM_METHOD_CHECKs generates a unique class method for the class.
#define GTM_METHOD_CHECK(class, method) GTM_METHOD_CHECK_INNER(class, method, __LINE__)
#define GTM_METHOD_CHECK_INNER(class, method, line) GTM_METHOD_CHECK_INNER_INNER(class, method, line)
// B) Create up a class method called xxGMethodCheckMethod+class+line that the
// GTMMethodCheckMethodChecker function can look for and call. We
// look for GTMMethodCheckMethodChecker to enforce linkage of
// GTMMethodCheck.m.
#define GTM_METHOD_CHECK_INNER_INNER(class, method, line) \
+ (void)xxGMMethodCheckMethod ## class ## line { \
void (*addr)() = GTMMethodCheckMethodChecker; \
if (addr && ![class instancesRespondToSelector:@selector(method)] \
&& ![class respondsToSelector:@selector(method)]) { \
fprintf(stderr, "%s:%d: error: We need method '%s' to be linked in for class '%s'\n", \
__FILE__, line, #method, #class); \
exit(EX_SOFTWARE); \
} \
}
#else // !DEBUG
// Do nothing in debug
#define GTM_METHOD_CHECK(class, method)
#endif // DEBUG
| 08iteng-ipad | systemtests/google-toolbox-for-mac/DebugUtils/GTMMethodCheck.h | Objective-C | bsd | 3,493 |
//
// GTMDevLog.m
//
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#include "GTMUnitTestDevLog.h"
// This is the logging function that is called by default when building
// GTMFramework. If it can find GTMUnitTestDevLog class it will use it,
// otherwise it falls onto NSLog.
void _GTMUnittestDevLog(NSString *format, ...) {
Class devLogClass = NSClassFromString(@"GTMUnitTestDevLog");
va_list argList;
va_start(argList, format);
if (devLogClass) {
[devLogClass log:format args:argList];
} else {
NSLogv(format, argList);
}
va_end(argList);
}
| 08iteng-ipad | systemtests/google-toolbox-for-mac/DebugUtils/GTMDevLog.m | Objective-C | bsd | 1,126 |
//
// GTMMethodCheckTest.m
// Copyright 2006-2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#import "GTMSenTestCase.h"
#import "GTMMethodCheck.h"
static BOOL gTestCheckVar = NO;
@interface GTMMethodCheckTest : GTMTestCase
+ (void)GTMMethodCheckTestClassMethod;
@end
@implementation GTMMethodCheckTest
GTM_METHOD_CHECK(GTMMethodCheckTest, GTMMethodCheckTestMethod); // COV_NF_LINE
GTM_METHOD_CHECK(GTMMethodCheckTest, GTMMethodCheckTestClassMethod); // COV_NF_LINE
- (void)GTMMethodCheckTestMethod {
}
+ (void)GTMMethodCheckTestClassMethod {
}
+ (void)xxGTMMethodCheckMethodTestCheck {
// This gets called because of its special name by GMMethodCheck
// Look at the Macros in GMMethodCheck.h for details.
gTestCheckVar = YES;
}
- (void)testGTMMethodCheck {
#ifdef DEBUG
// GTMMethodCheck only runs in debug
STAssertTrue(gTestCheckVar, @"Should be true");
#endif
}
@end
| 08iteng-ipad | systemtests/google-toolbox-for-mac/DebugUtils/GTMMethodCheckTest.m | Objective-C | bsd | 1,430 |
#!/bin/sh
# BuildAllSDKs.sh
#
# This script builds both the Tiger and Leopard versions of the requested
# target in the current basic config (debug, release, debug-gcov). This script
# should be run from the same directory as the GTM Xcode project file.
#
# Copyright 2006-2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
PROJECT_TARGET="$1"
XCODEBUILD="${DEVELOPER_BIN_DIR}/xcodebuild"
REQUESTED_BUILD_STYLE=$(echo "${BUILD_STYLE}" | sed "s/.*OrLater-\(.*\)/\1/")
# See if we were told to clean instead of build.
PROJECT_ACTION="build"
if [ "${ACTION}" == "clean" ]; then
PROJECT_ACTION="clean"
fi
# helper for doing a build
function doIt {
local myProject=$1
local myTarget=$2
local myConfig=$3
echo "note: Starting ${PROJECT_ACTION} of ${myTarget} from ${myProject} in ${myConfig}"
${XCODEBUILD} -project "${myProject}" \
-target "${myTarget}" \
-configuration "${myConfig}" \
"${PROJECT_ACTION}"
buildResult=$?
if [ $buildResult -ne 0 ]; then
echo "Error: ** ${PROJECT_ACTION} Failed **"
exit $buildResult
fi
echo "note: Done ${PROJECT_ACTION}"
}
# now build tiger and then leopard
doIt GTM.xcodeproj "${PROJECT_TARGET}" "TigerOrLater-${REQUESTED_BUILD_STYLE}"
doIt GTM.xcodeproj "${PROJECT_TARGET}" "LeopardOrLater-${REQUESTED_BUILD_STYLE}"
# TODO(iphone if right tool chain?)
| 08iteng-ipad | systemtests/google-toolbox-for-mac/BuildScripts/BuildAllSDKs.sh | Shell | bsd | 1,839 |
//
// GTMDefines.h
//
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
// ============================================================================
// ----------------------------------------------------------------------------
// CPP symbols that can be overridden in a prefix to control how the toolbox
// is compiled.
// ----------------------------------------------------------------------------
// GTMHTTPFetcher will support logging by default but only hook its input
// stream support for logging when requested. You can control the inclusion of
// the code by providing your own definitions for these w/in a prefix header.
//
#ifndef GTM_HTTPFETCHER_ENABLE_LOGGING
# define GTM_HTTPFETCHER_ENABLE_LOGGING 1
#endif // GTM_HTTPFETCHER_ENABLE_LOGGING
#ifndef GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
# define GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING 0
#endif // GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
// Give ourselves a consistent way to do inlines. Apple's macros even use
// a few different actual definitions, so we're based off of the foundation
// one.
#if !defined(GTM_INLINE)
#if defined (__GNUC__) && (__GNUC__ == 4)
#define GTM_INLINE static __inline__ __attribute__((always_inline))
#else
#define GTM_INLINE static __inline__
#endif
#endif
// Give ourselves a consistent way of doing externs that links up nicely
// when mixing objc and objc++
#if !defined (GTM_EXTERN)
#if defined __cplusplus
#define GTM_EXTERN extern "C"
#else
#define GTM_EXTERN extern
#endif
#endif
// Give ourselves a consistent way of exporting things if we have visibility
// set to hidden.
#if !defined (GTM_EXPORT)
#define GTM_EXPORT __attribute__((visibility("default")))
#endif
// _GTMDevLog & _GTMDevAssert
//
// _GTMDevLog & _GTMDevAssert are meant to be a very lightweight shell for
// developer level errors. This implementation simply macros to NSLog/NSAssert.
// It is not intended to be a general logging/reporting system.
//
// Please see http://code.google.com/p/google-toolbox-for-mac/wiki/DevLogNAssert
// for a little more background on the usage of these macros.
//
// _GTMDevLog log some error/problem in debug builds
// _GTMDevAssert assert if conditon isn't met w/in a method/function
// in all builds.
//
// To replace this system, just provide different macro definitions in your
// prefix header. Remember, any implementation you provide *must* be thread
// safe since this could be called by anything in what ever situtation it has
// been placed in.
//
// We only define the simple macros if nothing else has defined this.
#ifndef _GTMDevLog
#ifdef DEBUG
#define _GTMDevLog(...) NSLog(__VA_ARGS__)
#else
#define _GTMDevLog(...) do { } while (0)
#endif
#endif // _GTMDevLog
// Declared here so that it can easily be used for logging tracking if
// necessary. See GTMUnitTestDevLog.h for details.
@class NSString;
extern void _GTMUnittestDevLog(NSString *format, ...);
#ifndef _GTMDevAssert
// we directly invoke the NSAssert handler so we can pass on the varargs
// (NSAssert doesn't have a macro we can use that takes varargs)
#if !defined(NS_BLOCK_ASSERTIONS)
#define _GTMDevAssert(condition, ...) \
do { \
if (!(condition)) { \
[[NSAssertionHandler currentHandler] \
handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__] \
file:[NSString stringWithCString:__FILE__] \
lineNumber:__LINE__ \
description:__VA_ARGS__]; \
} \
} while(0)
#else // !defined(NS_BLOCK_ASSERTIONS)
#define _GTMDevAssert(condition, ...) do { } while (0)
#endif // !defined(NS_BLOCK_ASSERTIONS)
#endif // _GTMDevAssert
// _GTMCompileAssert
// _GTMCompileAssert is an assert that is meant to fire at compile time if you
// want to check things at compile instead of runtime. For example if you
// want to check that a wchar is 4 bytes instead of 2 you would use
// _GTMCompileAssert(sizeof(wchar_t) == 4, wchar_t_is_4_bytes_on_OS_X)
// Note that the second "arg" is not in quotes, and must be a valid processor
// symbol in it's own right (no spaces, punctuation etc).
// Wrapping this in an #ifndef allows external groups to define their own
// compile time assert scheme.
#ifndef _GTMCompileAssert
// We got this technique from here:
// http://unixjunkie.blogspot.com/2007/10/better-compile-time-asserts_29.html
#define _GTMCompileAssertSymbolInner(line, msg) _GTMCOMPILEASSERT ## line ## __ ## msg
#define _GTMCompileAssertSymbol(line, msg) _GTMCompileAssertSymbolInner(line, msg)
#define _GTMCompileAssert(test, msg) \
typedef char _GTMCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ]
#endif // _GTMCompileAssert
// Macro to allow fast enumeration when building for 10.5 or later, and
// reliance on NSEnumerator for 10.4. Remember, NSDictionary w/ FastEnumeration
// does keys, so pick the right thing, nothing is done on the FastEnumeration
// side to be sure you're getting what you wanted.
#ifndef GTM_FOREACH_OBJECT
#if TARGET_OS_IPHONE || (GTM_MAC_OS_X_VERSION_MINIMUM_REQUIRED >= MAC_OS_X_VERSION_10_5)
#define GTM_FOREACH_ENUMEREE(element, enumeration) \
for (element in enumeration)
#define GTM_FOREACH_OBJECT(element, collection) \
for (element in collection)
#define GTM_FOREACH_KEY(element, collection) \
for (element in collection)
#else
#define GTM_FOREACH_ENUMEREE(element, enumeration) \
for (NSEnumerator *_ ## element ## _enum = enumeration; \
(element = [_ ## element ## _enum nextObject]) != nil; )
#define GTM_FOREACH_OBJECT(element, collection) \
GTM_FOREACH_ENUMEREE(element, [collection objectEnumerator])
#define GTM_FOREACH_KEY(element, collection) \
GTM_FOREACH_ENUMEREE(element, [collection keyEnumerator])
#endif
#endif
// ============================================================================
// ----------------------------------------------------------------------------
// CPP symbols defined based on the project settings so the GTM code has
// simple things to test against w/o scattering the knowledge of project
// setting through all the code.
// ----------------------------------------------------------------------------
// Provide a single constant CPP symbol that all of GTM uses for ifdefing
// iPhone code.
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE // iPhone SDK
// For iPhone specific stuff
#define GTM_IPHONE_SDK 1
#else
// For MacOS specific stuff
#define GTM_MACOS_SDK 1
#endif
// To simplify support for 64bit (and Leopard in general), we provide the type
// defines for non Leopard SDKs
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
// NSInteger/NSUInteger and Max/Mins
#ifndef NSINTEGER_DEFINED
#if __LP64__ || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
#define NSIntegerMax LONG_MAX
#define NSIntegerMin LONG_MIN
#define NSUIntegerMax ULONG_MAX
#define NSINTEGER_DEFINED 1
#endif // NSINTEGER_DEFINED
// CGFloat
#ifndef CGFLOAT_DEFINED
#if defined(__LP64__) && __LP64__
// This really is an untested path (64bit on Tiger?)
typedef double CGFloat;
#define CGFLOAT_MIN DBL_MIN
#define CGFLOAT_MAX DBL_MAX
#define CGFLOAT_IS_DOUBLE 1
#else /* !defined(__LP64__) || !__LP64__ */
typedef float CGFloat;
#define CGFLOAT_MIN FLT_MIN
#define CGFLOAT_MAX FLT_MAX
#define CGFLOAT_IS_DOUBLE 0
#endif /* !defined(__LP64__) || !__LP64__ */
#define CGFLOAT_DEFINED 1
#endif // CGFLOAT_DEFINED
#endif // MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
| 08iteng-ipad | systemtests/google-toolbox-for-mac/GTMDefines.h | Objective-C | bsd | 8,593 |
#import <Cocoa/Cocoa.h>
#import "CorePlotQCPlugIn.h"
@interface CPBarPlotPlugIn : CorePlotQCPlugIn<CPBarPlotDataSource> {
}
@property(assign) double inputBaseValue;
@property(assign) double inputBarWidth;
@property(assign) double inputBarOffset;
@property(assign) BOOL inputHorizontalBars;
-(CPFill *) barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSNumber *)index;
@end
| 08iteng-ipad | QCPlugin/CPBarPlotPlugin.h | Objective-C | bsd | 381 |
#import "CPBarPlotPlugIn.h"
@implementation CPBarPlotPlugIn
/*
NOTE: It seems that QC plugins don't inherit dynamic input ports which is
why all of the accessor declarations are duplicated here
*/
/*
Accessor for the output image
*/
@dynamic outputImage;
/*
Dynamic accessors for the static PlugIn inputs
*/
@dynamic inputPixelsWide, inputPixelsHigh;
@dynamic inputPlotAreaColor;
@dynamic inputAxisColor, inputAxisLineWidth, inputAxisMinorTickWidth, inputAxisMajorTickWidth, inputAxisMajorTickLength, inputAxisMinorTickLength;
@dynamic inputMajorGridLineWidth, inputMinorGridLineWidth;
@dynamic inputXMin, inputXMax, inputYMin, inputYMax;
@dynamic inputXMajorIntervals, inputYMajorIntervals, inputXMinorIntervals, inputYMinorIntervals;
/*
Bar plot special accessors
*/
@dynamic inputBaseValue, inputBarOffset, inputBarWidth, inputHorizontalBars;
+ (NSDictionary*) attributes
{
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Core Plot Bar Chart", QCPlugInAttributeNameKey,
@"Bar chart", QCPlugInAttributeDescriptionKey,
nil];
}
+ (NSDictionary*) attributesForPropertyPortWithKey:(NSString*)key
{
// A few additional ports for the bar plot chart type ...
if ([key isEqualToString:@"inputBarWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Bar Width", QCPortAttributeNameKey,
[NSNumber numberWithFloat:1.0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeMinimumValueKey,
nil];
if ([key isEqualToString:@"inputBarOffset"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Bar Offset", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.5], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputBaseValue"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Base Value", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputHorizontalBars"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Horizontal Bars", QCPortAttributeNameKey,
[NSNumber numberWithBool:NO], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputXMin"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"X Range Min", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputXMax"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"X Range Max", QCPortAttributeNameKey,
[NSNumber numberWithFloat:5.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputYMin"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Y Range Min", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputYMax"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Y Range Max", QCPortAttributeNameKey,
[NSNumber numberWithFloat:5.0], QCPortAttributeDefaultValueKey,
nil];
return [super attributesForPropertyPortWithKey:key];
}
- (void) addPlotWithIndex:(NSUInteger)index
{
// Create input ports for the new plot
[self addInputPortWithType:QCPortTypeStructure
forKey:[NSString stringWithFormat:@"plotNumbers%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Values %i", index+1], QCPortAttributeNameKey,
QCPortTypeStructure, QCPortAttributeTypeKey,
nil]];
[self addInputPortWithType:QCPortTypeColor
forKey:[NSString stringWithFormat:@"plotDataLineColor%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Plot Line Color %i", index+1], QCPortAttributeNameKey,
QCPortTypeColor, QCPortAttributeTypeKey,
[self defaultColorForPlot:index alpha:1.0], QCPortAttributeDefaultValueKey,
nil]];
[self addInputPortWithType:QCPortTypeColor
forKey:[NSString stringWithFormat:@"plotFillColor%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Plot Fill Color %i", index+1], QCPortAttributeNameKey,
QCPortTypeColor, QCPortAttributeTypeKey,
[self defaultColorForPlot:index alpha:0.25], QCPortAttributeDefaultValueKey,
nil]];
[self addInputPortWithType:QCPortTypeNumber
forKey:[NSString stringWithFormat:@"plotDataLineWidth%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Plot Line Width %i", index+1], QCPortAttributeNameKey,
QCPortTypeNumber, QCPortAttributeTypeKey,
[NSNumber numberWithInt:1.0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeMinimumValueKey,
nil]];
// Add the new plot to the graph
CPBarPlot *barPlot = [CPBarPlot tubularBarPlotWithColor:[CPColor greenColor] horizontalBars:NO];
barPlot.identifier = [NSString stringWithFormat:@"Bar Plot %i", index+1];
barPlot.dataSource = self;
[graph addPlot:barPlot];
}
- (void) removePlots:(NSUInteger)count
{
// Clean up a deleted plot
for (int i = numberOfPlots; i > numberOfPlots-count; i--)
{
[self removeInputPortForKey:[NSString stringWithFormat:@"plotNumbers%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotDataLineColor%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotFillColor%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotDataLineWidth%i", i-1]];
[graph removePlot:[[graph allPlots] lastObject]];
}
}
- (BOOL) configurePlots
{
// The pixel width of a single plot unit (1..2) along the x axis of the plot
double count = (double)[[graph allPlots] count];
double unitWidth = graph.plotAreaFrame.bounds.size.width / (self.inputXMax - self.inputXMin);
double barWidth = self.inputBarWidth*unitWidth/count;
// Configure scatter plots for active plot inputs
for (CPBarPlot* plot in [graph allPlots])
{
int index = [[graph allPlots] indexOfObject:plot];
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineColor = [CPColor colorWithCGColor:[self dataLineColor:index]];
lineStyle.lineWidth = [self dataLineWidth:index];
plot.lineStyle = lineStyle;
plot.baseValue = CPDecimalFromDouble(self.inputBaseValue);
plot.barWidth = barWidth;
plot.barOffset = self.inputBarOffset;
plot.barsAreHorizontal = self.inputHorizontalBars;
plot.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:[self areaFillColor:index]]];
[plot reloadData];
}
return YES;
}
#pragma mark -
#pragma markData source methods
-(CPFill *) barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSNumber *)index
{
return nil;
}
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:plot];
NSString *key = [NSString stringWithFormat:@"plotNumbers%i", plotIndex];
if (![self valueForInputKey:key])
return 0;
return [[self valueForInputKey:key] count];
}
- (NSArray *)numbersForPlot:(CPBarPlot *)plot field:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:plot];
NSString *key = [NSString stringWithFormat:@"plotNumbers%i", plotIndex];
if (![self valueForInputKey:key])
return nil;
NSDictionary *dict = [self valueForInputKey:key];
NSMutableArray *array = [NSMutableArray array];
if (fieldEnum == CPBarPlotFieldBarLocation)
{
// Calculate horizontal position of bar - nth bar index + barWidth*plotIndex + 0.5
float xpos;
float plotCount = [[graph allPlots] count];
for (int i = 0; i < [[dict allKeys] count]; i++)
{
xpos = (float)i + (float)plotIndex/(plotCount);
[array addObject:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", xpos]]];
}
}
else
{
for (int i = 0; i < [[dict allKeys] count]; i++)
{
[array addObject:[NSDecimalNumber decimalNumberWithString:[[dict valueForKey:[NSString stringWithFormat:@"%i", i]] stringValue]]];
}
}
return array;
}
@end
| 08iteng-ipad | QCPlugin/CPBarPlotPlugin.m | Objective-C | bsd | 8,137 |
#import <Cocoa/Cocoa.h>
#import "CorePlotQCPlugIn.h"
@interface CPScatterPlotPlugIn : CorePlotQCPlugIn {
}
@end
| 08iteng-ipad | QCPlugin/CPScatterPlotPlugin.h | Objective-C | bsd | 114 |
#import "CPScatterPlotPlugIn.h"
@implementation CPScatterPlotPlugIn
/*
NOTE: It seems that QC plugins don't inherit dynamic input ports which is
why all of the accessor declarations are duplicated here
*/
/*
Accessor for the output image
*/
@dynamic outputImage;
/*
Dynamic accessors for the static PlugIn inputs
*/
@dynamic inputPixelsWide, inputPixelsHigh;
@dynamic inputPlotAreaColor;
@dynamic inputAxisColor, inputAxisLineWidth, inputAxisMinorTickWidth, inputAxisMajorTickWidth, inputAxisMajorTickLength, inputAxisMinorTickLength;
@dynamic inputMajorGridLineWidth, inputMinorGridLineWidth;
@dynamic inputXMin, inputXMax, inputYMin, inputYMax;
@dynamic inputXMajorIntervals, inputYMajorIntervals, inputXMinorIntervals, inputYMinorIntervals;
+ (NSDictionary*) attributes
{
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Core Plot Scatter Plot", QCPlugInAttributeNameKey,
@"Scatter plot", QCPlugInAttributeDescriptionKey,
nil];
}
- (void) addPlotWithIndex:(NSUInteger)index
{
// Create input ports for the new plot
[self addInputPortWithType:QCPortTypeStructure
forKey:[NSString stringWithFormat:@"plotXNumbers%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"X Values %i", index+1], QCPortAttributeNameKey,
QCPortTypeStructure, QCPortAttributeTypeKey,
nil]];
[self addInputPortWithType:QCPortTypeStructure
forKey:[NSString stringWithFormat:@"plotYNumbers%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Y Values %i", index+1], QCPortAttributeNameKey,
QCPortTypeStructure, QCPortAttributeTypeKey,
nil]];
[self addInputPortWithType:QCPortTypeColor
forKey:[NSString stringWithFormat:@"plotDataLineColor%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Plot Line Color %i", index+1], QCPortAttributeNameKey,
QCPortTypeColor, QCPortAttributeTypeKey,
[self defaultColorForPlot:index alpha:1.0], QCPortAttributeDefaultValueKey,
nil]];
[self addInputPortWithType:QCPortTypeColor
forKey:[NSString stringWithFormat:@"plotFillColor%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Plot Fill Color %i", index+1], QCPortAttributeNameKey,
QCPortTypeColor, QCPortAttributeTypeKey,
[self defaultColorForPlot:index alpha:0.25], QCPortAttributeDefaultValueKey,
nil]];
[self addInputPortWithType:QCPortTypeNumber
forKey:[NSString stringWithFormat:@"plotDataLineWidth%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Plot Line Width %i", index+1], QCPortAttributeNameKey,
QCPortTypeNumber, QCPortAttributeTypeKey,
[NSNumber numberWithInt:1.0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeMinimumValueKey,
nil]];
[self addInputPortWithType:QCPortTypeIndex
forKey:[NSString stringWithFormat:@"plotDataSymbols%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Data Symbols %i", index+1], QCPortAttributeNameKey,
QCPortTypeIndex, QCPortAttributeTypeKey,
[NSArray arrayWithObjects:@"Empty", @"Circle", @"Triangle", @"Square", @"Plus", @"Star", @"Diamond", @"Pentagon", @"Hexagon", @"Dash", @"Snow", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithInt:0], QCPortAttributeDefaultValueKey,
[NSNumber numberWithInt:0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithInt:10], QCPortAttributeMaximumValueKey,
nil]];
[self addInputPortWithType:QCPortTypeColor
forKey:[NSString stringWithFormat:@"plotDataSymbolColor%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Data Symbol Color %i", index+1], QCPortAttributeNameKey,
QCPortTypeColor, QCPortAttributeTypeKey,
[self defaultColorForPlot:index alpha:0.25], QCPortAttributeDefaultValueKey,
nil]];
// Add the new plot to the graph
CPScatterPlot *scatterPlot = [[[CPScatterPlot alloc] init] autorelease];
scatterPlot.identifier = [NSString stringWithFormat:@"Data Source Plot %i", index+1];
// Line Style
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineWidth = 3.f;
lineStyle.lineColor = [CPColor colorWithCGColor:[self defaultColorForPlot:index alpha:1.0]];
scatterPlot.dataLineStyle = lineStyle;
scatterPlot.areaFill = [CPFill fillWithColor:[CPColor colorWithCGColor:[self defaultColorForPlot:index alpha:0.25]]];
scatterPlot.dataSource = self;
[graph addPlot:scatterPlot];
}
- (void) removePlots:(NSUInteger)count
{
// Clean up a deleted plot
for (int i = numberOfPlots; i > numberOfPlots-count; i--)
{
[self removeInputPortForKey:[NSString stringWithFormat:@"plotXNumbers%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotYNumbers%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotDataLineColor%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotFillColor%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotDataLineWidth%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotDataSymbols%i", i-1]];
[self removeInputPortForKey:[NSString stringWithFormat:@"plotDataSymbolColor%i", i-1]];
[graph removePlot:[[graph allPlots] lastObject]];
}
}
- (CPPlotSymbol *) plotSymbol:(NSUInteger)index
{
NSString *key = [NSString stringWithFormat:@"plotDataSymbols%i", index];
NSUInteger value = [[self valueForInputKey:key] unsignedIntValue];
switch (value) {
case 1:
return [CPPlotSymbol ellipsePlotSymbol];
case 2:
return [CPPlotSymbol trianglePlotSymbol];
case 3:
return [CPPlotSymbol rectanglePlotSymbol];
case 4:
return [CPPlotSymbol plusPlotSymbol];
case 5:
return [CPPlotSymbol starPlotSymbol];
case 6:
return [CPPlotSymbol diamondPlotSymbol];
case 7:
return [CPPlotSymbol pentagonPlotSymbol];
case 8:
return [CPPlotSymbol hexagonPlotSymbol];
case 9:
return [CPPlotSymbol dashPlotSymbol];
case 10:
return [CPPlotSymbol snowPlotSymbol];
default:
return nil;
}
}
- (CGColorRef) dataSymbolColor:(NSUInteger)index
{
NSString *key = [NSString stringWithFormat:@"plotDataSymbolColor%i", index];
return (CGColorRef)[self valueForInputKey:key];
}
- (BOOL) configurePlots
{
// Adjust the plots configuration using the QC input ports
for (CPScatterPlot* plot in [graph allPlots])
{
int index = [[graph allPlots] indexOfObject:plot];
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineColor = [CPColor colorWithCGColor:[self dataLineColor:index]];
lineStyle.lineWidth = [self dataLineWidth:index];
plot.dataLineStyle = lineStyle;
lineStyle.lineColor = [CPColor colorWithCGColor:[self dataSymbolColor:index]];
plot.plotSymbol = [self plotSymbol:index];
plot.plotSymbol.lineStyle = lineStyle;
plot.plotSymbol.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:[self dataSymbolColor:index]]];
plot.plotSymbol.size = CGSizeMake(10.0, 10.0);
plot.areaFill = [CPFill fillWithColor:[CPColor colorWithCGColor:[self areaFillColor:index]]];
plot.areaBaseValue = CPDecimalFromFloat(MAX(self.inputYMin, MIN(self.inputYMax, 0.0)));
[plot reloadData];
}
return YES;
}
#pragma mark -
#pragma markData source methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:plot];
NSString *xKey = [NSString stringWithFormat:@"plotXNumbers%i", plotIndex];
NSString *yKey = [NSString stringWithFormat:@"plotYNumbers%i", plotIndex];
if (![self valueForInputKey:xKey] || ![self valueForInputKey:yKey])
return 0;
else if ([[self valueForInputKey:xKey] count] != [[self valueForInputKey:yKey] count])
return 0;
return [[self valueForInputKey:xKey] count];
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:plot];
NSString *xKey = [NSString stringWithFormat:@"plotXNumbers%i", plotIndex];
NSString *yKey = [NSString stringWithFormat:@"plotYNumbers%i", plotIndex];
if (![self valueForInputKey:xKey] || ![self valueForInputKey:yKey])
return nil;
else if ([[self valueForInputKey:xKey] count] != [[self valueForInputKey:yKey] count])
return nil;
NSString *key = (fieldEnum == CPScatterPlotFieldX) ? xKey : yKey;
NSDictionary *dict = [self valueForInputKey:key];
NSString *dictionaryKey = [NSString stringWithFormat:@"%i", index];
NSNumber *number = [dict valueForKey:dictionaryKey];
if (number == nil)
{
NSLog(@"No value for key: %@", dictionaryKey);
NSLog(@"Dict: %@", dict);
}
return number;
}
@end
| 08iteng-ipad | QCPlugin/CPScatterPlotPlugin.m | Objective-C | bsd | 9,045 |
#import <OpenGL/CGLMacro.h>
#import "CorePlotQCPlugIn.h"
#define kQCPlugIn_Name @"CorePlotQCPlugIn"
#define kQCPlugIn_Description @"CorePlotQCPlugIn base plugin."
// Draws the string "ERROR" in the given context in big red letters
void drawErrorText(CGContextRef context, CGRect rect)
{
// :'(
CGContextSaveGState(context);
float w, h;
w = rect.size.width;
h = rect.size.height;
CGContextSelectFont (context, "Verdana", h/4, kCGEncodingMacRoman);
CGContextSetTextDrawingMode (context, kCGTextFillStroke);
CGContextSetRGBFillColor (context, 1, 0, 0, 0.5);
CGContextSetRGBStrokeColor (context, 0, 0, 0, 1);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
// Compute the width of the text
CGPoint r0 = CGContextGetTextPosition(context);
CGContextSetTextDrawingMode(context, kCGTextInvisible);
CGContextShowText(context, "ERROR", 5); // 10
CGPoint r1 = CGContextGetTextPosition(context);
float width = r1.x - r0.x;
float height = h/3;
float x = rect.origin.x + rect.size.width/2.0 - width/2.0;
float y = rect.origin.y + rect.size.height/2.0 - height/2.0;
CGContextSetTextDrawingMode(context, kCGTextFillStroke);
CGContextShowTextAtPoint (context, x, y, "ERROR", 5);
CGContextRestoreGState(context);
}
@implementation CorePlotQCPlugIn
// TODO: Make the port accessors dynamic, that way certain inputs can be removed based on settings and subclasses won't need the @dynamic declarations
/*
Accessor for the output image
*/
@dynamic outputImage;
/*
Dynamic accessors for the static PlugIn inputs
*/
@dynamic inputPixelsWide, inputPixelsHigh;
@dynamic inputPlotAreaColor;
@dynamic inputAxisColor, inputAxisLineWidth, inputAxisMinorTickWidth, inputAxisMajorTickWidth, inputAxisMajorTickLength, inputAxisMinorTickLength;
@dynamic inputMajorGridLineWidth, inputMinorGridLineWidth;
@dynamic inputXMin, inputXMax, inputYMin, inputYMax;
@dynamic inputXMajorIntervals, inputYMajorIntervals, inputXMinorIntervals, inputYMinorIntervals;
/*
Synthesized accessors for internal PlugIn settings
*/
@synthesize numberOfPlots;
+ (NSDictionary*) attributes
{
/*
Return a dictionary of attributes describing the plug-in (QCPlugInAttributeNameKey, QCPlugInAttributeDescriptionKey...).
*/
return [NSDictionary dictionaryWithObjectsAndKeys:
kQCPlugIn_Name, QCPlugInAttributeNameKey,
kQCPlugIn_Description, QCPlugInAttributeDescriptionKey,
nil];
}
+ (QCPlugInExecutionMode) executionMode
{
/*
Return the execution mode of the plug-in: kQCPlugInExecutionModeProvider, kQCPlugInExecutionModeProcessor, or kQCPlugInExecutionModeConsumer.
*/
return kQCPlugInExecutionModeProcessor;
}
+ (QCPlugInTimeMode) timeMode
{
/*
Return the time dependency mode of the plug-in: kQCPlugInTimeModeNone, kQCPlugInTimeModeIdle or kQCPlugInTimeModeTimeBase.
*/
return kQCPlugInTimeModeNone;
}
- (id) init
{
if (self = [super init])
{
/*
Allocate any permanent resource required by the plug-in.
*/
[self createGraph];
numberOfPlots = 0;
[self setNumberOfPlots:1];
imageData = nil;
imageProvider = nil;
bitmapContext = nil;
}
return self;
}
- (void) finalize
{
/*
Release any non garbage collected resources created in -init.
*/
[super finalize];
}
- (void) dealloc
{
/*
Release any resources created in -init.
*/
[self freeResources];
[super dealloc];
}
- (void) freeImageResources
{
if (bitmapContext)
{
CGContextRelease(bitmapContext);
bitmapContext = nil;
}
if (imageData)
{
free(imageData);
imageData = nil;
}
}
- (void) freeResources
{
[self freeImageResources];
if (graph)
{
[graph release];
graph = nil;
}
}
- (QCPlugInViewController*) createViewController
{
/*
Return a new QCPlugInViewController to edit the internal settings of this plug-in instance.
You can return a subclass of QCPlugInViewController if necessary.
*/
return [[QCPlugInViewController alloc] initWithPlugIn:self viewNibName:@"Settings"];
}
#pragma mark -
#pragma markInput and output port configuration
+ (NSArray*) sortedPropertyPortKeys
{
return [NSArray arrayWithObjects:
@"inputPixelsWide",
@"inputPixelsHigh",
@"inputPlotAreaColor",
@"inputAxisColor",
@"inputAxisLineWidth",
@"inputXMin",
@"inputXMax",
@"inputYMin",
@"inputYMax",
@"inputXMajorIntervals",
@"inputYMajorIntervals",
@"inputAxisMajorTickLength",
@"inputAxisMajorTickWidth",
@"inputXMinorIntervals",
@"inputYMinorIntervals",
@"inputAxisMinorTickLength",
@"inputAxisMinorTickWidth",
nil];
}
+ (NSDictionary*) attributesForPropertyPortWithKey:(NSString*)key
{
/*
Specify the optional attributes for property based ports (QCPortAttributeNameKey, QCPortAttributeDefaultValueKey...).
*/
if ([key isEqualToString:@"inputXMin"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"X Range Min", QCPortAttributeNameKey,
[NSNumber numberWithFloat:-1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputXMax"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"X Range Max", QCPortAttributeNameKey,
[NSNumber numberWithFloat:1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputYMin"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Y Range Min", QCPortAttributeNameKey,
[NSNumber numberWithFloat:-1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputYMax"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Y Range Max", QCPortAttributeNameKey,
[NSNumber numberWithFloat:1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputXMajorIntervals"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"X Major Intervals", QCPortAttributeNameKey,
[NSNumber numberWithFloat:4], QCPortAttributeDefaultValueKey,
[NSNumber numberWithFloat:0], QCPortAttributeMinimumValueKey,
nil];
if ([key isEqualToString:@"inputYMajorIntervals"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Y Major Intervals", QCPortAttributeNameKey,
[NSNumber numberWithFloat:4], QCPortAttributeDefaultValueKey,
[NSNumber numberWithFloat:0], QCPortAttributeMinimumValueKey,
nil];
if ([key isEqualToString:@"inputXMinorIntervals"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"X Minor Intervals", QCPortAttributeNameKey,
[NSNumber numberWithInt:1], QCPortAttributeDefaultValueKey,
[NSNumber numberWithInt:0], QCPortAttributeMinimumValueKey,
nil];
if ([key isEqualToString:@"inputYMinorIntervals"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Y Minor Intervals", QCPortAttributeNameKey,
[NSNumber numberWithInt:1], QCPortAttributeDefaultValueKey,
[NSNumber numberWithInt:0], QCPortAttributeMinimumValueKey,
nil];
if ([key isEqualToString:@"inputAxisColor"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Axis Color", QCPortAttributeNameKey,
[(id)CGColorCreateGenericRGB(1.0, 1.0, 1.0, 1.0) autorelease], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputAxisLineWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Axis Line Width", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputAxisMajorTickWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Major Tick Width", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:2.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputAxisMinorTickWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Minor Tick Width", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputAxisMajorTickLength"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Major Tick Length", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:10.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputAxisMinorTickLength"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Minor Tick Length", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:3.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputMajorGridLineWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Major Grid Line Width", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:1.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputMinorGridLineWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Minor Grid Line Width", QCPortAttributeNameKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithDouble:0.0], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputPlotAreaColor"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Plot Area Color", QCPortAttributeNameKey,
[(id)CGColorCreateGenericRGB(0.0, 0.0, 0.0, 0.4) autorelease], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputPixelsWide"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Pixels Wide", QCPortAttributeNameKey,
[NSNumber numberWithInt:1], QCPortAttributeMinimumValueKey,
[NSNumber numberWithInt:512], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"inputPixelsHigh"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Pixels High", QCPortAttributeNameKey,
[NSNumber numberWithInt:1], QCPortAttributeMinimumValueKey,
[NSNumber numberWithInt:512], QCPortAttributeDefaultValueKey,
nil];
if ([key isEqualToString:@"outputImage"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Image", QCPortAttributeNameKey,
nil];
return nil;
}
#pragma mark -
#pragma mark Graph configuration
- (void) createGraph
{
if (!graph)
{
// Create graph from theme
CPTheme *theme = [CPTheme themeNamed:kCPPlainBlackTheme];
graph = (CPXYGraph *)[theme newGraph];
// Setup scatter plot space
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)];
// Axes
CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(0.5);
x.minorTicksPerInterval = 2;
CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromFloat(0.5);
y.minorTicksPerInterval = 5;
}
}
- (CGColorRef) defaultColorForPlot:(NSUInteger)index alpha:(float)alpha
{
CGColorRef color;
switch (index) {
case 0:
color = CGColorCreateGenericRGB(1.0, 0.0, 0.0, alpha);
break;
case 1:
color = CGColorCreateGenericRGB(0.0, 1.0, 0.0, alpha);
break;
case 2:
color = CGColorCreateGenericRGB(0.0, 0.0, 1.0, alpha);
break;
case 3:
color = CGColorCreateGenericRGB(1.0, 1.0, 0.0, alpha);
break;
case 4:
color = CGColorCreateGenericRGB(1.0, 0.0, 1.0, alpha);
break;
case 5:
color = CGColorCreateGenericRGB(0.0, 1.0, 1.0, alpha);
break;
default:
color = CGColorCreateGenericRGB(1.0, 0.0, 0.0, alpha);
break;
}
[(id)color autorelease];
return color;
}
- (void) addPlots:(NSUInteger)count
{
for (int i = 0; i < count; i++)
[self addPlotWithIndex:i+numberOfPlots];
}
- (BOOL) configureAxis
{
CPColor *axisColor = [CPColor colorWithCGColor:self.inputAxisColor];
CPXYAxisSet *set = (CPXYAxisSet *)graph.axisSet;
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineColor = axisColor;
lineStyle.lineWidth = self.inputAxisLineWidth;
set.xAxis.axisLineStyle = lineStyle;
set.yAxis.axisLineStyle = lineStyle;
lineStyle.lineWidth = self.inputAxisMajorTickWidth;
set.xAxis.majorTickLineStyle = lineStyle;
set.yAxis.majorTickLineStyle = lineStyle;
lineStyle.lineWidth = self.inputAxisMinorTickWidth;
set.xAxis.minorTickLineStyle = lineStyle;
set.yAxis.minorTickLineStyle = lineStyle;
CPMutableTextStyle *textStyle = [CPMutableTextStyle textStyle];
textStyle.color = axisColor;
set.xAxis.labelTextStyle = textStyle;
double xrange = self.inputXMax - self.inputXMin;
set.xAxis.majorIntervalLength = CPDecimalFromDouble(xrange / (self.inputXMajorIntervals));
set.xAxis.minorTicksPerInterval = self.inputXMinorIntervals;
double yrange = self.inputYMax - self.inputYMin;
set.yAxis.majorIntervalLength = CPDecimalFromDouble(yrange / (self.inputYMajorIntervals));
set.yAxis.minorTicksPerInterval = self.inputYMinorIntervals;
set.xAxis.minorTickLength = self.inputAxisMinorTickLength;
set.yAxis.minorTickLength = self.inputAxisMinorTickLength;
set.xAxis.majorTickLength = self.inputAxisMajorTickLength;
set.yAxis.majorTickLength = self.inputAxisMajorTickLength;
if ([self didValueForInputKeyChange:@"inputMajorGridLineWidth"] || [self didValueForInputKeyChange:@"inputAxisColor"])
{
CPMutableLineStyle *majorGridLineStyle = nil;
if (self.inputMajorGridLineWidth == 0.0)
majorGridLineStyle = nil;
else
{
majorGridLineStyle = [CPMutableLineStyle lineStyle];
majorGridLineStyle.lineColor = [CPColor colorWithCGColor:self.inputAxisColor];
majorGridLineStyle.lineWidth = self.inputMajorGridLineWidth;
}
set.xAxis.majorGridLineStyle = majorGridLineStyle;
set.yAxis.majorGridLineStyle = majorGridLineStyle;
}
if ([self didValueForInputKeyChange:@"inputMinorGridLineWidth"] || [self didValueForInputKeyChange:@"inputAxisColor"])
{
CPMutableLineStyle *minorGridLineStyle;
if (self.inputMinorGridLineWidth == 0.0)
minorGridLineStyle = nil;
else
{
minorGridLineStyle = [CPMutableLineStyle lineStyle];
minorGridLineStyle.lineColor = [CPColor colorWithCGColor:self.inputAxisColor];
minorGridLineStyle.lineWidth = self.inputMinorGridLineWidth;
}
set.xAxis.minorGridLineStyle = minorGridLineStyle;
set.yAxis.minorGridLineStyle = minorGridLineStyle;
}
return YES;
}
- (CGColorRef) dataLineColor:(NSUInteger)index
{
NSString *key = [NSString stringWithFormat:@"plotDataLineColor%i", index];
return (CGColorRef)[self valueForInputKey:key];
}
- (CGFloat) dataLineWidth:(NSUInteger)index
{
NSString *key = [NSString stringWithFormat:@"plotDataLineWidth%i", index];
return [[self valueForInputKey:key] floatValue];
}
- (CGColorRef) areaFillColor:(NSUInteger)index
{
NSString *key = [NSString stringWithFormat:@"plotFillColor%i", index];
return (CGColorRef)[self valueForInputKey:key];
}
- (CGImageRef) areaFillImage:(NSUInteger)index
{
NSString *key = [NSString stringWithFormat:@"plotFillImage%i", index];
id<QCPlugInInputImageSource> img = [self valueForInputKey:key];
if (!img)
return nil;
#if __BIG_ENDIAN__
NSString *pixelFormat = QCPlugInPixelFormatARGB8;
#else
NSString *pixelFormat = QCPlugInPixelFormatBGRA8;
#endif
[img lockBufferRepresentationWithPixelFormat:pixelFormat colorSpace:CGColorSpaceCreateDeviceRGB() forBounds:[img imageBounds]];
void *baseAddress = (void *)[img bufferBaseAddress];
NSUInteger pixelsWide = [img bufferPixelsWide];
NSUInteger pixelsHigh = [img bufferPixelsHigh];
NSUInteger bitsPerComponent = 8;
NSUInteger bytesPerRow = [img bufferBytesPerRow];
CGColorSpaceRef colorSpace = [img bufferColorSpace];
CGContextRef imgContext = CGBitmapContextCreate(baseAddress,
pixelsWide,
pixelsHigh,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaNoneSkipLast);
CGImageRef imageRef = CGBitmapContextCreateImage(imgContext);
[img unlockBufferRepresentation];
CGContextRelease(imgContext);
return imageRef;
}
static void _BufferReleaseCallback(const void* address, void* context)
{
// Don't do anything. We release the buffer manually when it's recreated or during dealloc
}
- (void) createImageResourcesWithContext:(id<QCPlugInContext>)context
{
// Create a CG bitmap for drawing. The image data is released when QC calls _BufferReleaseCallback
CGSize boundsSize = graph.bounds.size;
NSUInteger bitsPerComponent = 8;
NSUInteger rowBytes = (NSInteger)boundsSize.width * 4;
if(rowBytes % 16)
rowBytes = ((rowBytes / 16) + 1) * 16;
if (!imageData)
{
imageData = valloc( rowBytes * boundsSize.height );
bitmapContext = CGBitmapContextCreate(imageData,
boundsSize.width,
boundsSize.height,
bitsPerComponent,
rowBytes,
[context colorSpace],
kCGImageAlphaPremultipliedFirst);
}
if (!imageData)
{
NSLog(@"Couldn't allocate memory for image data");
return;
}
if (!bitmapContext)
{
free(imageData);
imageData = nil;
NSLog(@"Couldn't create bitmap context");
return;
}
if(rowBytes % 16)
rowBytes = ((rowBytes / 16) + 1) * 16;
// Note: I don't have a PPC to test on so this may or may not cause some color issues
#if __BIG_ENDIAN__
imageProvider = [context outputImageProviderFromBufferWithPixelFormat:QCPlugInPixelFormatBGRA8
pixelsWide:(NSInteger)boundsSize.width
pixelsHigh:(NSInteger)boundsSize.height
baseAddress:imageData
bytesPerRow:rowBytes
releaseCallback:_BufferReleaseCallback
releaseContext:NULL
colorSpace:[context colorSpace]
shouldColorMatch:YES];
#else
imageProvider = [context outputImageProviderFromBufferWithPixelFormat:QCPlugInPixelFormatARGB8
pixelsWide:(NSInteger)boundsSize.width
pixelsHigh:(NSInteger)boundsSize.height
baseAddress:imageData
bytesPerRow:rowBytes
releaseCallback:_BufferReleaseCallback
releaseContext:NULL
colorSpace:[context colorSpace]
shouldColorMatch:YES];
#endif
}
#pragma mark -
#pragma markData source methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
return 0;
}
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
return [NSNumber numberWithInt:0];
}
#pragma mark -
#pragma markMethods for dealing with plugin keys
- (void) setNumberOfPlots:(NSUInteger)number
{
number = MAX(1, number);
if (number > numberOfPlots)
[self addPlots:number - numberOfPlots];
else
[self removePlots:numberOfPlots - number];
numberOfPlots = number;
}
+ (NSArray*) plugInKeys
{
return [NSArray arrayWithObjects:
@"numberOfPlots",
nil];
}
- (id) serializedValueForKey:(NSString*)key;
{
/*
Provide custom serialization for the plug-in internal settings that are not values complying to the <NSCoding> protocol.
The return object must be nil or a PList compatible i.e. NSString, NSNumber, NSDate, NSData, NSArray or NSDictionary.
*/
if ([key isEqualToString:@"numberOfPlots"])
return [NSNumber numberWithInt:self.numberOfPlots];
else
return [super serializedValueForKey:key];
}
- (void) setSerializedValue:(id)serializedValue forKey:(NSString*)key
{
/*
Provide deserialization for the plug-in internal settings that were custom serialized in -serializedValueForKey.
Deserialize the value, then call [self setValue:value forKey:key] to set the corresponding internal setting of the plug-in instance to that deserialized value.
*/
if ([key isEqualToString:@"numberOfPlots"])
[self setNumberOfPlots:MAX(1, [serializedValue intValue])];
else
[super setSerializedValue:serializedValue forKey:key];
}
#pragma mark -
#pragma mark Subclass methods
- (void) addPlotWithIndex:(NSUInteger)index
{
/*
Subclasses should override this method to create their own ports, plots, and add the plots to the graph
*/
}
- (void) removePlots:(NSUInteger)count
{
/*
Subclasses should override this method to remove plots and their ports
*/
}
- (BOOL) configurePlots
{
/*
Subclasses sjpi;d override this method to configure the plots (i.e., by using values from the input ports)
*/
return YES;
}
- (BOOL) configureGraph
{
/*
Subclasses can override this method to configure the graph (i.e., by using values from the input ports)
*/
// Configure the graph area
CGRect frame = CGRectMake(0.0, 0.0, MAX(1, self.inputPixelsWide), MAX(1, self.inputPixelsHigh));
[graph setBounds:frame];
graph.paddingLeft = 0.0;
graph.paddingRight = 0.0;
graph.paddingTop = 0.0;
graph.paddingBottom = 0.0;
// Perform some sanity checks. If there is a configuration error set the error flag so that a message is displayed
if (self.inputXMax <= self.inputXMin || self.inputYMax <= self.inputYMin)
return NO;
[graph layoutSublayers];
[graph layoutIfNeeded];
graph.fill = nil;
graph.plotAreaFrame.fill = [CPFill fillWithColor:[CPColor colorWithCGColor:self.inputPlotAreaColor]];
if (self.inputAxisLineWidth > 0.0)
{
CPMutableLineStyle *lineStyle = [CPMutableLineStyle lineStyle];
lineStyle.lineWidth = self.inputAxisLineWidth;
lineStyle.lineColor = [CPColor colorWithCGColor:self.inputAxisColor];
graph.plotAreaFrame.borderLineStyle = lineStyle;
}
else {
graph.plotAreaFrame.borderLineStyle = nil;
}
// Configure the plot space and axis sets
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(self.inputXMin) length:CPDecimalFromFloat(self.inputXMax-self.inputXMin)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(self.inputYMin) length:CPDecimalFromFloat(self.inputYMax-self.inputYMin)];
[self configureAxis];
[graph layoutSublayers];
[graph setNeedsDisplay];
return YES;
}
@end
@implementation CorePlotQCPlugIn (Execution)
- (BOOL) execute:(id<QCPlugInContext>)context atTime:(NSTimeInterval)time withArguments:(NSDictionary*)arguments
{
// Configure the plot for drawing
configurationCheck = [self configureGraph];
// If the output image dimensions change recreate the image resources
if ([self didValueForInputKeyChange:@"inputPixelsWide"] || [self didValueForInputKeyChange:@"inputPixelsHigh"] || !imageProvider)
[self freeImageResources];
// Verifies that the image data + bitmap context are valid
[self createImageResourcesWithContext:context];
// Draw the plot ...
CGSize boundsSize = graph.bounds.size;
CGContextClearRect(bitmapContext, CGRectMake(0.0f, 0.0f, boundsSize.width, boundsSize.height));
CGContextSetRGBFillColor(bitmapContext, 0.0, 0.0, 0.0, 0.0);
CGContextFillRect(bitmapContext, CGRectMake(0, 0, boundsSize.width, boundsSize.height));
CGContextSetAllowsAntialiasing(bitmapContext, true);
if (configurationCheck)
{
[self configurePlots];
[graph recursivelyRenderInContext:bitmapContext];
}
else
{
drawErrorText(bitmapContext, CGRectMake(0, 0, self.inputPixelsWide, self.inputPixelsHigh));
}
//CGContextSetAllowsAntialiasing(bitmapContext, false);
CGContextFlush(bitmapContext);
// ... and put it on the output port
self.outputImage = imageProvider;
return YES;
}
@end
| 08iteng-ipad | QCPlugin/CorePlotQCPlugin.m | Objective-C | bsd | 23,605 |
#import <Quartz/Quartz.h>
#import <CorePlot/CorePlot.h>
@interface CorePlotQCPlugIn : QCPlugIn <CPPlotDataSource>
{
NSUInteger numberOfPlots;
BOOL configurationCheck;
void *imageData;
CGContextRef bitmapContext;
id<QCPlugInOutputImageProvider> imageProvider;
CPGraph *graph;
}
/*
Declare here the Obj-C 2.0 properties to be used as input and output ports for the plug-in e.g.
@property double inputFoo;
@property(assign) NSString* outputBar;
You can access their values in the appropriate plug-in methods using self.inputFoo or self.inputBar
*/
@property(assign) id<QCPlugInOutputImageProvider> outputImage;
@property(assign) NSUInteger numberOfPlots;
@property(assign) NSUInteger inputPixelsWide;
@property(assign) NSUInteger inputPixelsHigh;
@property(assign) CGColorRef inputPlotAreaColor;
@property(assign) CGColorRef inputAxisColor;
@property(assign) double inputAxisLineWidth;
@property(assign) double inputAxisMajorTickWidth;
@property(assign) double inputAxisMinorTickWidth;
@property(assign) double inputAxisMajorTickLength;
@property(assign) double inputAxisMinorTickLength;
@property(assign) double inputMajorGridLineWidth;
@property(assign) double inputMinorGridLineWidth;
@property(assign) NSUInteger inputXMajorIntervals;
@property(assign) NSUInteger inputYMajorIntervals;
@property(assign) NSUInteger inputXMinorIntervals;
@property(assign) NSUInteger inputYMinorIntervals;
@property(assign) double inputXMin;
@property(assign) double inputXMax;
@property(assign) double inputYMin;
@property(assign) double inputYMax;
- (void) createGraph;
- (void) addPlots:(NSUInteger)count;
- (void) addPlotWithIndex:(NSUInteger)index;
- (void) removePlots:(NSUInteger)count;
- (BOOL) configureGraph;
- (BOOL) configurePlots;
- (BOOL) configureAxis;
- (NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot;
- (CGColorRef) defaultColorForPlot:(NSUInteger)index alpha:(float)alpha;
- (void) freeResources;
- (CGColorRef) dataLineColor:(NSUInteger)index;
- (CGFloat) dataLineWidth:(NSUInteger)index;
- (CGColorRef) areaFillColor:(NSUInteger)index;
- (CGImageRef) areaFillImage:(NSUInteger)index;
@end
| 08iteng-ipad | QCPlugin/CorePlotQCPlugin.h | Objective-C | bsd | 2,118 |
#import "CPPieChartPlugin.h"
@implementation CPPieChartPlugIn
/*
NOTE: It seems that QC plugins don't inherit dynamic input ports which is
why all of the accessor declarations are duplicated here
*/
/*
Accessor for the output image
*/
@dynamic outputImage;
/*
Dynamic accessors for the static PlugIn inputs
*/
@dynamic inputPixelsWide, inputPixelsHigh;
@dynamic inputAxisLineWidth, inputAxisColor;
@dynamic inputPlotAreaColor, inputBorderColor, inputBorderWidth;
@dynamic inputLabelColor;
/*
Pie chart special accessors
*/
@dynamic inputPieRadius, inputSliceLabelOffset, inputStartAngle, inputSliceDirection;
+ (NSDictionary*) attributes
{
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Core Plot Pie Chart", QCPlugInAttributeNameKey,
@"Pie chart", QCPlugInAttributeDescriptionKey,
nil];
}
- (double) inputXMax { return 1.0; }
- (double) inputXMin { return -1.0; }
- (double) inputYMax { return 1.0; }
- (double) inputYMin { return -1.0; }
// Pie charts only support one layer so we override the createViewController method (to hide the number of charts button)
- (QCPlugInViewController*) createViewController
{
return nil;
}
+ (NSArray*) sortedPropertyPortKeys
{
NSArray *pieChartPropertyPortKeys = [NSArray arrayWithObjects:@"inputPieRadius", @"inputSliceLabelOffset", @"inputStartAngle", @"inputSliceDirection", @"inputBorderColor", @"inputBorderWidth", nil];
return [[super sortedPropertyPortKeys] arrayByAddingObjectsFromArray:pieChartPropertyPortKeys];
}
+ (NSDictionary*) attributesForPropertyPortWithKey:(NSString*)key
{
// A few additional ports for the pie chart type ...
if ([key isEqualToString:@"inputPieRadius"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Pie Radius", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithFloat:0.75], QCPortAttributeDefaultValueKey,
nil];
else if ([key isEqualToString:@"inputSliceLabelOffset"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Label Offset", QCPortAttributeNameKey,
[NSNumber numberWithFloat:20.0], QCPortAttributeDefaultValueKey,
nil];
else if ([key isEqualToString:@"inputStartAngle"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Start Angle", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeDefaultValueKey,
nil];
else if ([key isEqualToString:@"inputSliceDirection"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Slice Direction", QCPortAttributeNameKey,
[NSNumber numberWithInt:1], QCPortAttributeMaximumValueKey,
[NSArray arrayWithObjects:@"Clockwise", @"Counter-Clockwise", nil], QCPortAttributeMenuItemsKey,
[NSNumber numberWithInt:0], QCPortAttributeDefaultValueKey,
nil];
else if ([key isEqualToString:@"inputBorderWidth"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Border Width", QCPortAttributeNameKey,
[NSNumber numberWithFloat:0.0], QCPortAttributeMinimumValueKey,
[NSNumber numberWithFloat:1.0], QCPortAttributeDefaultValueKey,
nil];
else if ([key isEqualToString:@"inputBorderColor"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Border Color", QCPortAttributeNameKey,
[(id)CGColorCreateGenericGray(0.0, 1.0) autorelease], QCPortAttributeDefaultValueKey,
nil];
else if ([key isEqualToString:@"inputLabelColor"])
return [NSDictionary dictionaryWithObjectsAndKeys:
@"Label Color", QCPortAttributeNameKey,
[(id)CGColorCreateGenericGray(1.0, 1.0) autorelease], QCPortAttributeDefaultValueKey,
nil];
else
return [super attributesForPropertyPortWithKey:key];
}
- (void) addPlotWithIndex:(NSUInteger)index
{
if (index == 0)
{
[self addInputPortWithType:QCPortTypeStructure
forKey:[NSString stringWithFormat:@"plotNumbers%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Data Values", index+1], QCPortAttributeNameKey,
QCPortTypeStructure, QCPortAttributeTypeKey,
nil]];
[self addInputPortWithType:QCPortTypeStructure
forKey:[NSString stringWithFormat:@"plotLabels%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Data Labels", index+1], QCPortAttributeNameKey,
QCPortTypeStructure, QCPortAttributeTypeKey,
nil]];
// TODO: add support for used defined fill colors. As of now we use a single color
// multiplied against the 'default' pie chart colors
[self addInputPortWithType:QCPortTypeColor
forKey:[NSString stringWithFormat:@"plotFillColor%i", index]
withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"Primary Fill Color", index+1], QCPortAttributeNameKey,
QCPortTypeColor, QCPortAttributeTypeKey,
[(id)CGColorCreateGenericGray(1.0, 1.0) autorelease], QCPortAttributeDefaultValueKey,
nil]];
// Add the new plot to the graph
CPPieChart *pieChart = [[[CPPieChart alloc] init] autorelease];
pieChart.identifier = [NSString stringWithFormat:@"Pie Chart %i", index+1];
pieChart.dataSource = self;
[graph addPlot:pieChart];
}
}
#pragma mark -
#pragma markGraph configuration
- (void) createGraph
{
if (!graph)
{
// Create graph from theme
CPTheme *theme = [CPTheme themeNamed:kCPPlainWhiteTheme];
graph = (CPXYGraph *)[theme newGraph];
graph.axisSet = nil;
}
}
- (BOOL) configureAxis
{
// We use no axis for the pie chart
graph.axisSet = nil;
graph.plotAreaFrame.plotArea.borderLineStyle = nil;
return YES;
}
- (BOOL) configurePlots
{
// Configure the pie chart
for (CPPieChart* pieChart in [graph allPlots])
{
pieChart.plotArea.borderLineStyle = nil;
pieChart.pieRadius = self.inputPieRadius*MIN(self.inputPixelsWide, self.inputPixelsHigh)/2.0;
pieChart.sliceLabelOffset = self.inputSliceLabelOffset;
pieChart.startAngle = self.inputStartAngle*M_PI/180.0; // QC typically works in degrees
pieChart.centerAnchor = CGPointMake(0.5, 0.5);
pieChart.sliceDirection = (self.inputSliceDirection == 0) ? CPPieDirectionClockwise : CPPieDirectionCounterClockwise;
if (self.inputBorderWidth > 0.0)
{
CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle];
borderLineStyle.lineWidth = self.inputBorderWidth;
borderLineStyle.lineColor = [CPColor colorWithCGColor:self.inputBorderColor];
borderLineStyle.lineCap = kCGLineCapSquare;
borderLineStyle.lineJoin = kCGLineJoinBevel;
pieChart.borderLineStyle = borderLineStyle;
}
else {
pieChart.borderLineStyle = nil;
}
[pieChart reloadData];
}
return YES;
}
#pragma mark -
#pragma markData source methods
-(NSUInteger)numberOfRecordsForPlot:(CPPlot *)plot
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:plot];
NSString *key = [NSString stringWithFormat:@"plotNumbers%i", plotIndex];
if (![self valueForInputKey:key])
return 0;
return [[self valueForInputKey:key] count];
}
- (NSNumber *) numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:plot];
NSString *key = [NSString stringWithFormat:@"plotNumbers%i", plotIndex];
if (![self valueForInputKey:key])
return nil;
NSDictionary *dict = [self valueForInputKey:key];
return [NSDecimalNumber decimalNumberWithString:[[dict valueForKey:[NSString stringWithFormat:@"%i", index]] stringValue]];
}
- (CPFill *) sliceFillForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index
{
CGColorRef plotFillColor = [[CPPieChart defaultPieSliceColorForIndex:index] cgColor];
CGColorRef inputFillColor = [self areaFillColor:0];
const CGFloat *plotColorComponents = CGColorGetComponents(plotFillColor);
const CGFloat *inputColorComponents = CGColorGetComponents(inputFillColor);
CGColorRef fillColor = CGColorCreateGenericRGB(plotColorComponents[0]*inputColorComponents[0],
plotColorComponents[1]*inputColorComponents[1],
plotColorComponents[2]*inputColorComponents[2],
plotColorComponents[3]*inputColorComponents[3]);
CPColor *fillCPColor = [CPColor colorWithCGColor:fillColor];
CGColorRelease(fillColor);
return [[(CPFill *)[CPFill alloc] initWithColor:fillCPColor] autorelease];
}
- (CPTextLayer *) sliceLabelForPieChart:(CPPieChart *)pieChart recordIndex:(NSUInteger)index
{
NSUInteger plotIndex = [[graph allPlots] indexOfObject:pieChart];
NSString *key = [NSString stringWithFormat:@"plotLabels%i", plotIndex];
if (![self valueForInputKey:key])
return nil;
NSDictionary *dict = [self valueForInputKey:key];
NSString *label = [dict valueForKey:[NSString stringWithFormat:@"%i", index]];
CPTextLayer *layer = [[[CPTextLayer alloc] initWithText:label] autorelease];
[layer sizeToFit];
CPMutableTextStyle *style = [CPMutableTextStyle textStyle];
style.color = [CPColor colorWithCGColor:self.inputLabelColor];
layer.textStyle = style;
return layer;
}
@end
| 08iteng-ipad | QCPlugin/CPPieChartPlugin.m | Objective-C | bsd | 9,036 |
#import <Cocoa/Cocoa.h>
#import "CorePlotQCPlugIn.h"
@interface CPPieChartPlugIn : CorePlotQCPlugIn <CPPieChartDataSource> {
}
@property (assign) double inputPieRadius;
@property (assign) double inputSliceLabelOffset;
@property (assign) double inputStartAngle;
@property (assign) NSUInteger inputSliceDirection;
@property (assign) double inputBorderWidth;
@property (assign) CGColorRef inputBorderColor;
@property (assign) CGColorRef inputLabelColor;
@end
| 08iteng-ipad | QCPlugin/CPPieChartPlugin.h | Objective-C | bsd | 459 |
#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 | framework/TestResources/checkformisalignedlayers.d | DTrace | bsd | 263 |
provider CorePlot {
probe layer_position_change(char *, int, int, int, int);
}; | 08iteng-ipad | framework/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 | framework/main-cocoatouch.m | Objective-C | bsd | 312 |
#import "CPPlatformSpecificCategories.h"
@implementation CPColor(CPPlatformSpecificColorExtensions)
/** @property uiColor
* @brief Gets the color value as a UIColor.
**/
@dynamic uiColor;
-(UIColor *)uiColor
{
return [UIColor colorWithCGColor:self.cgColor];
}
@end
#pragma mark -
@implementation CPLayer(CPPlatformSpecificLayerExtensions)
/** @brief Gets an image of the layer contents.
* @return A native image representation of the layer content.
**/
-(CPNativeImage *)imageOfLayer
{
UIGraphicsBeginImageContext(self.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetAllowsAntialiasing(context, true);
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[self layoutAndRenderInContext:context];
CPNativeImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
CGContextSetAllowsAntialiasing(context, false);
CGContextRestoreGState(context);
UIGraphicsEndImageContext();
return layerImage;
}
@end
#pragma mark -
@implementation NSNumber(CPPlatformSpecificNumberExtensions)
/** @brief Returns a Boolean value that indicates whether the receiver is less than another given number.
* @param other The other number to compare to the receiver.
* @return YES if the receiver is less than other, otherwise NO.
**/
-(BOOL)isLessThan:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedAscending );
}
/** @brief Returns a Boolean value that indicates whether the receiver is less than or equal to another given number.
* @param other The other number to compare to the receiver.
* @return YES if the receiver is less than or equal to other, otherwise NO.
**/
-(BOOL)isLessThanOrEqualTo:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedSame || [self compare:other] == NSOrderedAscending );
}
/** @brief Returns a Boolean value that indicates whether the receiver is greater than another given number.
* @param other The other number to compare to the receiver.
* @return YES if the receiver is greater than other, otherwise NO.
**/
-(BOOL)isGreaterThan:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedDescending );
}
/** @brief Returns a Boolean value that indicates whether the receiver is greater than or equal to another given number.
* @param other The other number to compare to the receiver.
* @return YES if the receiver is greater than or equal to other, otherwise NO.
**/
-(BOOL)isGreaterThanOrEqualTo:(NSNumber *)other
{
return ( [self compare:other] == NSOrderedSame || [self compare:other] == NSOrderedDescending );
}
@end
| 08iteng-ipad | framework/iPhoneOnly/CPPlatformSpecificCategories.m | Objective-C | bsd | 2,664 |
#import "CPTextStyle.h"
#import "CPTextStylePlatformSpecific.h"
#import "CPPlatformSpecificCategories.h"
#import "CPPlatformSpecificFunctions.h"
#import "CPColor.h"
@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)sizeWithTextStyle:(CPTextStyle *)style
{
UIFont *theFont = [UIFont fontWithName:style.fontName size:style.fontSize];
CGSize textSize = [self sizeWithFont:theFont];
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 withTextStyle:(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:point withFont:theFont];
CGContextRestoreGState(context);
CPPopCGContext();
}
@end
| 08iteng-ipad | framework/iPhoneOnly/CPTextStylePlatformSpecific.m | Objective-C | bsd | 1,431 |
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef UIImage CPNativeImage;
| 08iteng-ipad | framework/iPhoneOnly/CPPlatformSpecificDefines.h | Objective-C | bsd | 91 |
#import <UIKit/UIKit.h>
@class CPGraph;
@interface CPGraphHostingView : UIView {
@protected
CPGraph *hostedGraph;
BOOL collapsesLayers;
BOOL allowPinchScaling;
id pinchGestureRecognizer;
}
@property (nonatomic, readwrite, retain) CPGraph *hostedGraph;
@property (nonatomic, readwrite, assign) BOOL collapsesLayers;
@property (nonatomic, readwrite, assign) BOOL allowPinchScaling;
@end
| 08iteng-ipad | framework/iPhoneOnly/CPGraphHostingView.h | Objective-C | bsd | 400 |
#import "CPGraphHostingView.h"
#import "CPGraph.h"
#import "CPPlotAreaFrame.h"
#import "CPPlotArea.h"
#import "CPPlotSpace.h"
/** @brief A container view for displaying a CPGraph.
**/
@implementation CPGraphHostingView
/** @property hostedGraph
* @brief The CPLayer hosted inside this view.
**/
@synthesize hostedGraph;
/** @property collapsesLayers
* @brief Whether view draws all graph layers into a single layer.
* Collapsing layers may improve performance in some cases.
**/
@synthesize collapsesLayers;
/** @property allowPinchScaling
* @brief Whether a pinch will trigger plot space scaling.
* Default is YES. This causes gesture recognizers to be added to identify pinches.
**/
@synthesize allowPinchScaling;
+(Class)layerClass
{
return [CALayer class];
}
-(void)commonInit
{
hostedGraph = nil;
collapsesLayers = NO;
self.backgroundColor = [UIColor clearColor];
self.allowPinchScaling = YES;
// This undoes the normal coordinate space inversion that UIViews apply to their layers
self.layer.sublayerTransform = CATransform3DMakeScale(1.0, -1.0, 1.0);
}
-(id)initWithFrame:(CGRect)frame
{
if ( (self = [super initWithFrame:frame]) ) {
[self commonInit];
}
return self;
}
// On the iPhone, the init method is not called when loading from a XIB
-(void)awakeFromNib
{
[self commonInit];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[hostedGraph 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];
if (!collapsesLayers) {
pointOfTouch = [self.layer convertPoint:pointOfTouch toLayer:hostedGraph];
} else {
pointOfTouch.y = self.frame.size.height - pointOfTouch.y;
}
[hostedGraph pointingDeviceDownEvent:event atPoint:pointOfTouch];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
{
CGPoint pointOfTouch = [[[event touchesForView:self] anyObject] locationInView:self];
if (!collapsesLayers) {
pointOfTouch = [self.layer convertPoint:pointOfTouch toLayer:hostedGraph];
} else {
pointOfTouch.y = self.frame.size.height - pointOfTouch.y;
}
[hostedGraph pointingDeviceDraggedEvent:event atPoint:pointOfTouch];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint pointOfTouch = [[[event touchesForView:self] anyObject] locationInView:self];
if (!collapsesLayers) {
pointOfTouch = [self.layer convertPoint:pointOfTouch toLayer:hostedGraph];
} else {
pointOfTouch.y = self.frame.size.height - pointOfTouch.y;
}
[hostedGraph pointingDeviceUpEvent:event atPoint:pointOfTouch];
}
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[hostedGraph pointingDeviceCancelledEvent:event];
}
#pragma mark -
#pragma mark Gestures
-(void)setAllowPinchScaling:(BOOL)yn
{
if ( allowPinchScaling != yn ) {
allowPinchScaling = yn;
if ( allowPinchScaling ) {
// Register for pinches
Class pinchClass = NSClassFromString(@"UIPinchGestureRecognizer");
if ( pinchClass ) {
pinchGestureRecognizer = [[pinchClass alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
[self addGestureRecognizer:pinchGestureRecognizer];
[pinchGestureRecognizer release];
}
}
else {
if ( pinchGestureRecognizer ) [self removeGestureRecognizer:pinchGestureRecognizer];
pinchGestureRecognizer = nil;
}
}
}
-(void)handlePinchGesture:(id)aPinchGestureRecognizer
{
CGPoint interactionPoint = [aPinchGestureRecognizer locationInView:self];
if ( !collapsesLayers )
interactionPoint = [self.layer convertPoint:interactionPoint toLayer:hostedGraph];
else
interactionPoint.y = self.frame.size.height-interactionPoint.y;
CGPoint pointInPlotArea = [hostedGraph convertPoint:interactionPoint toLayer:hostedGraph.plotAreaFrame.plotArea];
for ( CPPlotSpace *space in hostedGraph.allPlotSpaces ) {
[space scaleBy:[[pinchGestureRecognizer valueForKey:@"scale"] floatValue] aboutPoint:pointInPlotArea];
}
[pinchGestureRecognizer setScale:1.0f];
}
#pragma mark -
#pragma mark Drawing
-(void)drawRect:(CGRect)rect
{
if ( !collapsesLayers ) return;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1, -1);
hostedGraph.frame = self.bounds;
[hostedGraph layoutAndRenderInContext:context];
}
-(void)graphNeedsRedraw:(NSNotification *)notification
{
[self setNeedsDisplay];
}
#pragma mark -
#pragma mark Accessors
-(void)updateNotifications
{
if ( collapsesLayers ) {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if ( hostedGraph ) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(graphNeedsRedraw:) name:CPGraphNeedsRedrawNotification object:hostedGraph];
}
}
}
-(void)setHostedGraph:(CPGraph *)newLayer
{
if (newLayer == hostedGraph) return;
[hostedGraph removeFromSuperlayer];
[hostedGraph release];
hostedGraph = [newLayer retain];
if ( !collapsesLayers ) {
hostedGraph.frame = self.layer.bounds;
[self.layer addSublayer:hostedGraph];
}
else {
[self setNeedsDisplay];
}
[self updateNotifications];
}
-(void)setCollapsesLayers:(BOOL)yn
{
if ( yn != collapsesLayers ) {
collapsesLayers = yn;
if ( !collapsesLayers )
[self.layer addSublayer:hostedGraph];
else {
[hostedGraph removeFromSuperlayer];
[self setNeedsDisplay];
}
[self updateNotifications];
}
}
-(void)setFrame:(CGRect)newFrame
{
[super setFrame:newFrame];
if ( !collapsesLayers )
hostedGraph.frame = self.bounds;
else
[self setNeedsDisplay];
}
-(void)setBounds:(CGRect)newBounds
{
[super setBounds:newBounds];
if ( collapsesLayers ) [self setNeedsDisplay];
}
@end
| 08iteng-ipad | framework/iPhoneOnly/CPGraphHostingView.m | Objective-C | bsd | 6,266 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
/// @file
#if __cplusplus
extern "C" {
#endif
/// @name Graphics Context Save Stack
/// @{
void CPPushCGContext(CGContextRef context);
void CPPopCGContext(void);
/// @}
/// @name Graphics Context
/// @{
CGContextRef CPGetCurrentContext(void);
/// @}
#if __cplusplus
}
#endif
| 08iteng-ipad | framework/iPhoneOnly/CPPlatformSpecificFunctions.h | Objective-C | bsd | 349 |
#import <Foundation/Foundation.h>
| 08iteng-ipad | framework/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();
}
CGContextRef CPGetCurrentContext(void)
{
return UIGraphicsGetCurrentContext();
}
| 08iteng-ipad | framework/iPhoneOnly/CPPlatformSpecificFunctions.m | Objective-C | bsd | 325 |
#import <UIKit/UIKit.h>
#import "CPColor.h"
#import "CPLayer.h"
#import "CPPlatformSpecificDefines.h"
/** @category CPColor(CPPlatformSpecificColorExtensions)
* @brief Platform-specific extensions to CPColor.
**/
@interface CPColor(CPPlatformSpecificColorExtensions)
@property (nonatomic, readonly, retain) UIColor *uiColor;
@end
/** @category CPLayer(CPPlatformSpecificLayerExtensions)
* @brief Platform-specific extensions to CPLayer.
**/
@interface CPLayer(CPPlatformSpecificLayerExtensions)
/// @name Images
/// @{
-(CPNativeImage *)imageOfLayer;
/// @}
@end
/** @category NSNumber(CPPlatformSpecificNumberExtensions)
* @brief Platform-specific extensions to NSNumber.
**/
@interface NSNumber(CPPlatformSpecificNumberExtensions)
-(BOOL)isLessThan:(NSNumber *)other;
-(BOOL)isLessThanOrEqualTo:(NSNumber *)other;
-(BOOL)isGreaterThan:(NSNumber *)other;
-(BOOL)isGreaterThanOrEqualTo:(NSNumber *)other;
@end
| 08iteng-ipad | framework/iPhoneOnly/CPPlatformSpecificCategories.h | Objective-C | bsd | 926 |
//
// 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 | framework/main.m | Objective-C | bsd | 584 |
#import "CPAnnotation.h"
#import "CPAnnotationHostLayer.h"
#import "CPAxis.h"
#import "CPAxisLabel.h"
#import "CPAxisLabelGroup.h"
#import "CPAxisSet.h"
#import "CPAxisTitle.h"
#import "CPBarPlot.h"
#import "CPBorderedLayer.h"
#import "CPColor.h"
#import "CPColorSpace.h"
#import "CPConstrainedPosition.h"
#import "CPDarkGradientTheme.h"
#import "CPDefinitions.h"
#import "CPExceptions.h"
#import "CPFill.h"
#import "CPGradient.h"
#import "CPGraph.h"
#import "CPGraphHostingView.h"
#import "CPGridLines.h"
#import "CPImage.h"
#import "CPLayer.h"
#import "CPLayerAnnotation.h"
#import "CPLayoutManager.h"
#import "CPLimitBand.h"
#import "CPLineStyle.h"
#import "CPMutableLineStyle.h"
#import "CPMutableNumericData.h"
#import "CPMutableNumericData+TypeConversion.h"
#import "CPMutableTextStyle.h"
#import "CPNumericData.h"
#import "CPNumericData+TypeConversion.h"
#import "CPNumericDataType.h"
#import "CPPieChart.h"
#import "CPPlainBlackTheme.h"
#import "CPPlainWhiteTheme.h"
#import "CPPlatformSpecificDefines.h"
#import "CPPlatformSpecificFunctions.h"
#import "CPPlatformSpecificCategories.h"
#import "CPPathExtensions.h"
#import "CPPlot.h"
#import "CPPlotArea.h"
#import "CPPlotAreaFrame.h"
#import "CPPlotGroup.h"
#import "CPPlotRange.h"
#import "CPPlotSpace.h"
#import "CPPlotSpaceAnnotation.h"
#import "CPPlotSymbol.h"
#import "CPPolarPlotSpace.h"
#import "CPRangePlot.h"
#import "CPResponder.h"
#import "CPScatterPlot.h"
#import "CPSlateTheme.h"
#import "CPSlateTheme.h"
#import "CPStocksTheme.h"
#import "CPTextLayer.h"
#import "CPTextStyle.h"
#import "CPTheme.h"
#import "CPTimeFormatter.h"
#import "CPTradingRangePlot.h"
#import "CPUtilities.h"
#import "CPXYAxis.h"
#import "CPXYAxisSet.h"
#import "CPXYGraph.h"
#import "CPXYPlotSpace.h"
#import "CPXYTheme.h"
| 08iteng-ipad | framework/CorePlot-CocoaTouch.h | Objective-C | bsd | 1,769 |
#import <CorePlot/CPAnnotation.h>
#import <CorePlot/CPAnnotationHostLayer.h>
#import <CorePlot/CPAxis.h>
#import <CorePlot/CPAxisLabel.h>
#import <CorePlot/CPAxisLabelGroup.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/CPConstrainedPosition.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/CPGridLines.h>
#import <CorePlot/CPImage.h>
#import <CorePlot/CPLayer.h>
#import <CorePlot/CPLayerAnnotation.h>
#import <CorePlot/CPLayoutManager.h>
#import <CorePlot/CPLimitBand.h>
#import <CorePlot/CPLineStyle.h>
#import <CorePlot/CPMutableLineStyle.h>
#import <CorePlot/CPMutableNumericData.h>
#import <CorePlot/CPMutableNumericData+TypeConversion.h>
#import <CorePlot/CPMutableTextStyle.h>
#import <CorePlot/CPNumericDataType.h>
#import <CorePlot/CPNumericData.h>
#import <CorePlot/CPNumericData+TypeConversion.h>
#import <CorePlot/CPPieChart.h>
#import <CorePlot/CPPlainBlackTheme.h>
#import <CorePlot/CPPlainWhiteTheme.h>
#import <CorePlot/CPPlatformSpecificDefines.h>
#import <CorePlot/CPPlatformSpecificFunctions.h>
#import <CorePlot/CPPlatformSpecificCategories.h>
#import <CorePlot/CPPathExtensions.h>
#import <CorePlot/CPPlot.h>
#import <CorePlot/CPPlotArea.h>
#import <CorePlot/CPPlotAreaFrame.h>
#import <CorePlot/CPPlotGroup.h>
#import <CorePlot/CPPlotRange.h>
#import <CorePlot/CPPlotSpace.h>
#import <CorePlot/CPPlotSpaceAnnotation.h>
#import <CorePlot/CPPlotSymbol.h>
#import <CorePlot/CPPolarPlotSpace.h>
#import <CorePlot/CPRangePlot.h>
#import <CorePlot/CPResponder.h>
#import <CorePlot/CPScatterPlot.h>
#import <CorePlot/CPSlateTheme.h>
#import <CorePlot/CPStocksTheme.h>
#import <CorePlot/CPTextLayer.h>
#import <CorePlot/CPTextStyle.h>
#import <CorePlot/CPTradingRangePlot.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 | framework/CorePlot.h | Objective-C | bsd | 2,382 |
#import <AppKit/AppKit.h>
#import "CPPlatformSpecificCategories.h"
#import "CPUtilities.h"
@implementation CPLayer(CPPlatformSpecificLayerExtensions)
/** @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.0, 0.0, boundsSize.width, boundsSize.height));
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldSmoothFonts(context, false);
[self layoutAndRenderInContext:context];
CGContextFlush(context);
NSImage *image = [[NSImage alloc] initWithSize:NSSizeFromCGSize(boundsSize)];
[image addRepresentation:layerImage];
[layerImage release];
return [image autorelease];
}
@end
#pragma mark -
@implementation CPColor(CPPlatformSpecificColorExtensions)
/** @property nsColor
* @brief Gets the color value as an NSColor.
**/
@dynamic nsColor;
-(NSColor *)nsColor
{
return [NSColor colorWithCIColor:[CIColor colorWithCGColor:self.cgColor]];
}
@end
| 08iteng-ipad | framework/MacOnly/CPPlatformSpecificCategories.m | Objective-C | bsd | 1,541 |
#import "CPMutableTextStyle.h"
#import "CPTextStylePlatformSpecific.h"
#import "CPPlatformSpecificCategories.h"
#import "CPPlatformSpecificFunctions.h"
@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)sizeWithTextStyle:(CPMutableTextStyle *)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 withTextStyle:(CPMutableTextStyle *)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 | framework/MacOnly/CPTextStylePlatformSpecific.m | Objective-C | bsd | 1,777 |
#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 | framework/MacOnly/CPPlatformSpecificDefines.h | Objective-C | bsd | 384 |
#import <Cocoa/Cocoa.h>
@class CPLayer;
@interface CPLayerHostingView : NSView {
@private
CPLayer *hostedLayer;
}
@property (nonatomic, readwrite, retain) CPLayer *hostedLayer;
@end
| 08iteng-ipad | framework/MacOnly/CPLayerHostingView.h | Objective-C | bsd | 188 |
#import <Foundation/Foundation.h>
@interface CPDecimalNumberValueTransformer : NSValueTransformer {
}
@end
| 08iteng-ipad | framework/MacOnly/CPDecimalNumberValueTransformer.h | Objective-C | bsd | 112 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import "CPDefinitions.h"
/// @file
#if __cplusplus
extern "C" {
#endif
/// @name Graphics Context Save Stack
/// @{
void CPPushCGContext(CGContextRef context);
void CPPopCGContext(void);
/// @}
/// @name Graphics Context
/// @{
CGContextRef CPGetCurrentContext(void);
/// @}
/// @name Color Conversion
/// @{
CGColorRef CPNewCGColorFromNSColor(NSColor *nsColor);
CPRGBAColor CPRGBAColorFromNSColor(NSColor *nsColor);
/// @}
#if __cplusplus
}
#endif
| 08iteng-ipad | framework/MacOnly/CPPlatformSpecificFunctions.h | Objective-C | bsd | 524 |
#import <Foundation/Foundation.h>
| 08iteng-ipad | framework/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 Context
/** @brief Get the default graphics context
**/
CGContextRef CPGetCurrentContext(void)
{
return [[NSGraphicsContext currentContext] graphicsPort];
}
#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 | framework/MacOnly/CPPlatformSpecificFunctions.m | Objective-C | bsd | 2,302 |
#import "CPLayerHostingView.h"
#import "CPLayer.h"
/** @brief A container view for displaying a CPLayer.
**/
@implementation CPLayerHostingView
/** @property hostedLayer
* @brief The CPLayer hosted inside this view.
**/
@synthesize hostedLayer;
-(id)initWithFrame:(NSRect)frame
{
if (self = [super initWithFrame:frame]) {
hostedLayer = nil;
CPLayer *mainLayer = [(CPLayer *)[CPLayer alloc] initWithFrame:NSRectToCGRect(frame)];
self.layer = mainLayer;
[mainLayer release];
}
return self;
}
-(void)dealloc
{
[hostedLayer removeFromSuperlayer];
[hostedLayer release];
[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]);
CGPoint pointInHostedLayer = [self.layer convertPoint:pointOfMouseDown toLayer:hostedLayer];
[hostedLayer pointingDeviceDownEvent:theEvent atPoint:pointInHostedLayer];
}
-(void)mouseDragged:(NSEvent *)theEvent
{
CGPoint pointOfMouseDrag = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow] fromView:nil]);
CGPoint pointInHostedLayer = [self.layer convertPoint:pointOfMouseDrag toLayer:hostedLayer];
[hostedLayer pointingDeviceDraggedEvent:theEvent atPoint:pointInHostedLayer];
}
-(void)mouseUp:(NSEvent *)theEvent
{
CGPoint pointOfMouseUp = NSPointToCGPoint([self convertPoint:[theEvent locationInWindow] fromView:nil]);
CGPoint pointInHostedLayer = [self.layer convertPoint:pointOfMouseUp toLayer:hostedLayer];
[hostedLayer pointingDeviceUpEvent:theEvent atPoint:pointInHostedLayer];
}
#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 | framework/MacOnly/CPLayerHostingView.m | Objective-C | bsd | 2,041 |
#import <AppKit/AppKit.h>
#import <QuartzCore/QuartzCore.h>
#import "CPLayer.h"
#import "CPColor.h"
/** @category CPLayer(CPPlatformSpecificLayerExtensions)
* @brief Platform-specific extensions to CPLayer.
**/
@interface CPLayer(CPPlatformSpecificLayerExtensions)
/// @name Images
/// @{
-(CPNativeImage *)imageOfLayer;
/// @}
@end
/** @category CPColor(CPPlatformSpecificColorExtensions)
* @brief Platform-specific extensions to CPColor.
**/
@interface CPColor(CPPlatformSpecificColorExtensions)
@property (nonatomic, readonly, retain) NSColor *nsColor;
@end
| 08iteng-ipad | framework/MacOnly/CPPlatformSpecificCategories.h | Objective-C | bsd | 571 |
#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 | framework/MacOnly/CPDecimalNumberValueTransformer.m | Objective-C | bsd | 488 |
#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;
/** @property tileAnchoredToContext
* @brief Anchor the tiled image to the context origin?
*
* If YES, the origin of the tiled image is anchored to the origin of the drawing context.
* If NO, the origin of the tiled image is set to the orgin of rectangle passed to
* <code>drawInRect:inContext:</code>.
* The default value is YES.
* If <code>tiled</code> is NO, this property has no effect.
**/
@synthesize tileAnchoredToContext;
#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;
tileAnchoredToContext = YES;
}
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];
}
-(void)finalize
{
CGImageRelease(image);
[super finalize];
}
-(id)copyWithZone:(NSZone *)zone
{
CPImage *copy = [[[self class] allocWithZone:zone] init];
copy->image = CGImageCreateCopy(self.image);
copy->tiled = self->tiled;
copy->tileAnchoredToContext = self->tileAnchoredToContext;
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)newImage
{
if ( newImage != image ) {
CGImageRetain(newImage);
CGImageRelease(image);
image = newImage;
}
}
#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
{
CGImageRef theImage = self.image;
if ( theImage ) {
if ( self.isTiled ) {
CGContextSaveGState(context);
CGContextClipToRect(context, *(CGRect *)&rect);
if ( !self.tileAnchoredToContext ) {
CGContextTranslateCTM(context, rect.origin.x, rect.origin.y);
}
CGRect imageBounds = CGRectMake(0.0, 0.0, (CGFloat)CGImageGetWidth(theImage), (CGFloat)CGImageGetHeight(theImage));
CGContextDrawTiledImage(context, imageBounds, theImage);
CGContextRestoreGState(context);
} else {
CGContextDrawImage(context, rect, theImage);
}
}
}
@end
| 08iteng-ipad | framework/Source/CPImage.m | Objective-C | bsd | 4,603 |
#import <Foundation/Foundation.h>
#import "CPAnnotationHostLayer.h"
@class CPLineStyle;
@class CPFill;
@interface CPBorderedLayer : CPAnnotationHostLayer {
@private
CPLineStyle *borderLineStyle;
CPFill *fill;
}
@property (nonatomic, readwrite, copy) CPLineStyle *borderLineStyle;
@property (nonatomic, readwrite, copy) CPFill *fill;
@end
| 08iteng-ipad | framework/Source/CPBorderedLayer.h | Objective-C | bsd | 347 |
#import "CPLayer.h"
#import "CPTextStyle.h"
/// @file
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
/// @{
-(CGSize)sizeThatFits;
-(void)sizeToFit;
/// @}
@end
| 08iteng-ipad | framework/Source/CPTextLayer.h | Objective-C | bsd | 573 |
#import "NSDecimalNumberExtensions.h"
@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 | framework/Source/NSDecimalNumberExtensions.m | Objective-C | bsd | 507 |
#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];
CGColorSpaceRelease(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];
}
-(void)finalize
{
CGColorSpaceRelease(cgColorSpace);
[super finalize];
}
#pragma mark -
#pragma mark Accessors
-(void)setCGColorSpace:(CGColorSpaceRef)newSpace
{
if ( newSpace != cgColorSpace ) {
CGColorSpaceRelease(cgColorSpace);
CGColorSpaceRetain(newSpace);
cgColorSpace = newSpace;
}
}
@end
| 08iteng-ipad | framework/Source/CPColorSpace.m | Objective-C | bsd | 2,089 |
#import "CPExceptions.h"
#import "CPGraph.h"
#import "CPMutableNumericData.h"
#import "CPMutableNumericData+TypeConversion.h"
#import "CPNumericData.h"
#import "CPNumericData+TypeConversion.h"
#import "CPPlot.h"
#import "CPPlotArea.h"
#import "CPPlotAreaFrame.h"
#import "CPPlotRange.h"
#import "CPPlotSpace.h"
#import "CPPlotSpaceAnnotation.h"
#import "CPTextLayer.h"
#import "NSNumberExtensions.h"
#import "CPUtilities.h"
/** @cond */
@interface CPPlot()
@property (nonatomic, readwrite, assign) BOOL dataNeedsReloading;
@property (nonatomic, readwrite, retain) NSMutableDictionary *cachedData;
@property (nonatomic, readwrite, assign) BOOL needsRelabel;
@property (nonatomic, readwrite, assign) BOOL labelFormatterChanged;
@property (nonatomic, readwrite, assign) NSRange labelIndexRange;
@property (nonatomic, readwrite, retain) NSMutableArray *labelAnnotations;
@property (nonatomic, readwrite, assign) NSUInteger cachedDataCount;
-(CPMutableNumericData *)numericDataForNumbers:(id)numbers;
-(void)setCachedDataType:(CPNumericDataType)newDataType;
-(void)updateContentAnchorForLabel:(CPPlotSpaceAnnotation *)label;
@end
/** @endcond */
#pragma mark -
/** @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 plotArea
* @brief The plot area for the plot.
**/
@dynamic plotArea;
/** @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;
/** @property cachedDataCount
* @brief The number of data points stored in the cache.
**/
@synthesize cachedDataCount;
/** @property doublePrecisionCache
* @brief If YES, the cache holds data of type 'double', otherwise it holds NSNumber.
**/
@dynamic doublePrecisionCache;
/** @property cachePrecision
* @brief The numeric precision used to cache the plot data and perform all plot calculations. Defaults to CPPlotCachePrecisionAuto.
**/
@synthesize cachePrecision;
/** @property doubleDataType
* @brief The CPNumericDataType used to cache plot data as <code>double</code>.
**/
@dynamic doubleDataType;
/** @property decimalDataType
* @brief The CPNumericDataType used to cache plot data as NSDecimal.
**/
@dynamic decimalDataType;
/** @property needsRelabel
* @brief If YES, the plot needs to be relabeled before the layer content is drawn.
**/
@synthesize needsRelabel;
/** @property labelOffset
* @brief The distance that labels should be offset from their anchor points. The direction of the offset is defined by subclasses.
**/
@synthesize labelOffset;
/** @property labelRotation
* @brief The rotation of the data labels in radians.
* Set this property to <code>M_PI/2.0</code> to have labels read up the screen, for example.
**/
@synthesize labelRotation;
/** @property labelField
* @brief The plot field identifier of the data field used to generate automatic labels.
**/
@synthesize labelField;
/** @property labelTextStyle
* @brief The text style used to draw the data labels.
* Set this property to <code>nil</code> to hide the data labels.
**/
@synthesize labelTextStyle;
/** @property labelFormatter
* @brief The number formatter used to format the data labels.
* Set this property to <code>nil</code> to hide the data labels.
* 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 (e.g., "Jan 10, 2010").
* The CPTimeFormatter is useful for this purpose.
**/
@synthesize labelFormatter;
@synthesize labelFormatterChanged;
@synthesize labelIndexRange;
@synthesize labelAnnotations;
#pragma mark -
#pragma mark init/dealloc
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
cachedData = [[NSMutableDictionary alloc] initWithCapacity:5];
cachedDataCount = 0;
cachePrecision = CPPlotCachePrecisionAuto;
dataSource = nil;
identifier = nil;
plotSpace = nil;
dataNeedsReloading = NO;
needsRelabel = YES;
labelOffset = 0.0;
labelRotation = 0.0;
labelField = 0;
labelTextStyle = nil;
labelFormatter = nil;
labelFormatterChanged = YES;
labelIndexRange = NSMakeRange(0, 0);
labelAnnotations = nil;
self.masksToBounds = YES;
self.needsDisplayOnBoundsChange = YES;
}
return self;
}
-(id)initWithLayer:(id)layer
{
if ( self = [super initWithLayer:layer] ) {
CPPlot *theLayer = (CPPlot *)layer;
cachedData = [theLayer->cachedData retain];
cachedDataCount = theLayer->cachedDataCount;
cachePrecision = theLayer->cachePrecision;
dataSource = theLayer->dataSource;
identifier = [theLayer->identifier retain];
plotSpace = [theLayer->plotSpace retain];
dataNeedsReloading = theLayer->dataNeedsReloading;
needsRelabel = theLayer->needsRelabel;
labelOffset = theLayer->labelOffset;
labelRotation = theLayer->labelRotation;
labelField = theLayer->labelField;
labelTextStyle = [theLayer->labelTextStyle retain];
labelFormatter = [theLayer->labelFormatter retain];
labelFormatterChanged = theLayer->labelFormatterChanged;
labelIndexRange = theLayer->labelIndexRange;
labelAnnotations = [theLayer->labelAnnotations retain];
}
return self;
}
-(void)dealloc
{
[cachedData release];
[identifier release];
[plotSpace release];
[labelTextStyle release];
[labelFormatter release];
[labelAnnotations release];
[super dealloc];
}
#pragma mark -
#pragma mark Bindings
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
-(Class)valueClassForBinding:(NSString *)binding
{
return [NSArray class];
}
#endif
#pragma mark -
#pragma mark Drawing
-(void)drawInContext:(CGContextRef)theContext
{
[self reloadDataIfNeeded];
[super drawInContext:theContext];
}
#pragma mark -
#pragma mark Layout
+(CGFloat)defaultZPosition
{
return CPDefaultZPositionPlot;
}
-(void)layoutSublayers
{
[self relabel];
[super layoutSublayers];
}
#pragma mark -
#pragma mark Data Source
/** @brief Marks the receiver as needing the data source reloaded before the content is next drawn.
**/
-(void)setDataNeedsReloading
{
self.dataNeedsReloading = YES;
}
/** @brief Reload all plot data from the data source immediately.
**/
-(void)reloadData
{
[self.cachedData removeAllObjects];
self.cachedDataCount = 0;
[self reloadDataInIndexRange:NSMakeRange(0, [self.dataSource numberOfRecordsForPlot:self])];
}
/** @brief Reload plot data from the data source only if the data cache is out of date.
**/
-(void)reloadDataIfNeeded
{
if ( self.dataNeedsReloading ) {
[self reloadData];
}
}
/** @brief Reload plot data in the given index range from the data source immediately.
* @param indexRange The index range to load.
**/
-(void)reloadDataInIndexRange:(NSRange)indexRange
{
NSParameterAssert(NSMaxRange(indexRange) <= [self.dataSource numberOfRecordsForPlot:self]);
self.dataNeedsReloading = NO;
[self relabelIndexRange:indexRange];
}
/** @brief Insert records into the plot data cache at the given index.
* @param index The starting index of the new records.
* @param numberOfRecords The number of records to insert.
**/
-(void)insertDataAtIndex:(NSUInteger)index numberOfRecords:(NSUInteger)numberOfRecords
{
NSParameterAssert(index <= self.cachedDataCount);
for ( CPMutableNumericData *numericData in [self.cachedData allValues] ) {
size_t sampleSize = numericData.sampleBytes;
size_t length = sampleSize * numberOfRecords;
[(NSMutableData *)numericData.data increaseLengthBy:length];
void *start = [numericData samplePointer:index];
size_t bytesToMove = numericData.data.length - (index + numberOfRecords) * sampleSize;
if ( bytesToMove > 0 ) {
memmove(start + length, start, bytesToMove);
}
}
self.cachedDataCount += numberOfRecords;
[self reloadDataInIndexRange:NSMakeRange(index, self.cachedDataCount - index)];
}
/** @brief Delete records in the given index range from the plot data cache.
* @param indexRange The index range of the data records to remove.
**/
-(void)deleteDataInIndexRange:(NSRange)indexRange
{
NSParameterAssert(NSMaxRange(indexRange) <= self.cachedDataCount);
for ( CPMutableNumericData *numericData in [self.cachedData allValues] ) {
size_t sampleSize = numericData.sampleBytes;
void *start = [numericData samplePointer:indexRange.location];
size_t length = sampleSize * indexRange.length;
size_t bytesToMove = numericData.data.length - (indexRange.location + indexRange.length) * sampleSize;
if ( bytesToMove > 0 ) {
memmove(start, start + length, bytesToMove);
}
NSMutableData *dataBuffer = (NSMutableData *)numericData.data;
dataBuffer.length -= length;
}
self.cachedDataCount -= indexRange.length;
[self relabelIndexRange:NSMakeRange(indexRange.location, self.cachedDataCount - indexRange.location)];
[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.
**/
-(id)numbersFromDataSourceForField:(NSUInteger)fieldEnum recordIndexRange:(NSRange)indexRange
{
id numbers; // can be CPNumericData, NSArray, or NSData
id <CPPlotDataSource> theDataSource = self.dataSource;
if ( theDataSource ) {
if ( [theDataSource respondsToSelector:@selector(dataForPlot:field:recordIndexRange:)] ) {
numbers = [theDataSource dataForPlot:self field:fieldEnum recordIndexRange:indexRange];
}
else if ( [theDataSource respondsToSelector:@selector(doublesForPlot:field:recordIndexRange:)] ) {
numbers = [NSMutableData dataWithLength:sizeof(double)*indexRange.length];
double *fieldValues = [numbers mutableBytes];
double *doubleValues = [theDataSource doublesForPlot:self field:fieldEnum recordIndexRange:indexRange];
memcpy( fieldValues, doubleValues, sizeof(double)*indexRange.length );
}
else if ( [theDataSource respondsToSelector:@selector(numbersForPlot:field:recordIndexRange:)] ) {
numbers = [NSArray arrayWithArray:[theDataSource numbersForPlot:self field:fieldEnum recordIndexRange:indexRange]];
}
else if ( [theDataSource respondsToSelector:@selector(doubleForPlot:field:recordIndex:)] ) {
NSUInteger recordIndex;
NSMutableData *fieldData = [NSMutableData dataWithLength:sizeof(double)*indexRange.length];
double *fieldValues = [fieldData mutableBytes];
for ( recordIndex = indexRange.location; recordIndex < indexRange.location + indexRange.length; ++recordIndex ) {
double number = [theDataSource doubleForPlot:self field:fieldEnum recordIndex:recordIndex];
*fieldValues++ = number;
}
numbers = fieldData;
}
else {
BOOL respondsToSingleValueSelector = [theDataSource 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 = [theDataSource numberForPlot:self field:fieldEnum recordIndex:recordIndex];
if ( number ) {
[fieldValues addObject:number];
}
else {
[fieldValues addObject:[NSNull null]];
}
}
else {
[fieldValues addObject:[NSDecimalNumber zero]];
}
}
numbers = fieldValues;
}
}
else {
numbers = [NSArray array];
}
return numbers;
}
#pragma mark -
#pragma mark Data Caching
/** @brief Copies an array of numbers to the cache.
* @param numbers An array of numbers to cache. Can be a CPNumericData, NSArray, or NSData (NSData is assumed to be a c-style array of type <code>double</code>).
* @param fieldEnum The field enumerator identifying the field.
**/
-(void)cacheNumbers:(id)numbers forField:(NSUInteger)fieldEnum
{
NSNumber *cacheKey = [NSNumber numberWithUnsignedInteger:fieldEnum];
if ( numbers ) {
CPMutableNumericData *mutableNumbers = [self numericDataForNumbers:numbers];
NSUInteger sampleCount = mutableNumbers.numberOfSamples;
if ( sampleCount > 0 ) {
[self.cachedData setObject:mutableNumbers forKey:cacheKey];
}
else {
[self.cachedData removeObjectForKey:cacheKey];
}
self.cachedDataCount = sampleCount;
switch ( self.cachePrecision ) {
case CPPlotCachePrecisionAuto:
[self setCachedDataType:mutableNumbers.dataType];
break;
case CPPlotCachePrecisionDouble:
[self setCachedDataType:self.doubleDataType];
break;
case CPPlotCachePrecisionDecimal:
[self setCachedDataType:self.decimalDataType];
break;
}
}
else {
[self.cachedData removeObjectForKey:cacheKey];
self.cachedDataCount = 0;
}
self.needsRelabel = YES;
[self setNeedsDisplay];
}
/** @brief Copies an array of numbers to replace a part of the cache.
* @param numbers An array of numbers to cache. Can be a CPNumericData, NSArray, or NSData (NSData is assumed to be a c-style array of type <code>double</code>).
* @param fieldEnum The field enumerator identifying the field.
* @param index The index of the first data point to replace.
**/
-(void)cacheNumbers:(id)numbers forField:(NSUInteger)fieldEnum atRecordIndex:(NSUInteger)index
{
if ( numbers ) {
CPMutableNumericData *mutableNumbers = [self numericDataForNumbers:numbers];
NSUInteger sampleCount = mutableNumbers.numberOfSamples;
if ( sampleCount > 0 ) {
// Ensure the new data is the same type as the cache
switch ( self.cachePrecision ) {
case CPPlotCachePrecisionAuto:
[self setCachedDataType:mutableNumbers.dataType];
break;
case CPPlotCachePrecisionDouble: {
CPNumericDataType newType = self.doubleDataType;
[self setCachedDataType:newType];
mutableNumbers.dataType = newType;
}
break;
case CPPlotCachePrecisionDecimal: {
CPNumericDataType newType = self.decimalDataType;
[self setCachedDataType:newType];
mutableNumbers.dataType = newType;
}
break;
}
// Ensure the data cache exists and is the right size
NSNumber *cacheKey = [NSNumber numberWithUnsignedInteger:fieldEnum];
CPMutableNumericData *cachedNumbers = [self.cachedData objectForKey:cacheKey];
if ( !cachedNumbers ) {
cachedNumbers = [CPMutableNumericData numericDataWithData:[NSData data]
dataType:mutableNumbers.dataType
shape:nil];
[self.cachedData setObject:cachedNumbers forKey:cacheKey];
}
NSUInteger numberOfRecords = [self.dataSource numberOfRecordsForPlot:self];
((NSMutableData *)cachedNumbers.data).length = numberOfRecords * cachedNumbers.sampleBytes;
// Update the cache
self.cachedDataCount = numberOfRecords;
NSUInteger startByte = index * cachedNumbers.sampleBytes;
void *cachePtr = cachedNumbers.mutableBytes + startByte;
size_t numberOfBytes = MIN(mutableNumbers.data.length, cachedNumbers.data.length - startByte);
memcpy(cachePtr, mutableNumbers.bytes, numberOfBytes);
[self relabelIndexRange:NSMakeRange(index, sampleCount)];
}
[self setNeedsDisplay];
}
}
-(CPMutableNumericData *)numericDataForNumbers:(id)numbers
{
CPMutableNumericData *mutableNumbers = nil;
CPNumericDataType loadedDataType;
if ( [numbers isKindOfClass:[CPNumericData class]] ) {
mutableNumbers = [numbers mutableCopy];
// ensure the numeric data is in a supported format; default to double if not already NSDecimal
if ( !CPDataTypeEqualToDataType(mutableNumbers.dataType, self.decimalDataType) ) {
mutableNumbers.dataType = self.doubleDataType;
}
}
else if ( [numbers isKindOfClass:[NSData class]] ) {
loadedDataType = self.doubleDataType;
mutableNumbers = [[CPMutableNumericData alloc] initWithData:numbers dataType:loadedDataType shape:nil];
}
else if ( [numbers isKindOfClass:[NSArray class]] ) {
if ( ((NSArray *)numbers).count == 0 ) {
loadedDataType = self.doubleDataType;
}
else if ( [[(NSArray *)numbers objectAtIndex:0] isKindOfClass:[NSDecimalNumber class]] ) {
loadedDataType = self.decimalDataType;
} else {
loadedDataType = self.doubleDataType;
}
mutableNumbers = [[CPMutableNumericData alloc] initWithArray:numbers dataType:loadedDataType shape:nil];
}
else {
[NSException raise:CPException format:@"Unsupported number array format"];
}
return [mutableNumbers autorelease];
}
-(BOOL)doublePrecisionCache
{
BOOL result = NO;
switch ( self.cachePrecision ) {
case CPPlotCachePrecisionAuto: {
NSArray *cachedObjects = [self.cachedData allValues];
if ( cachedObjects.count > 0 ) {
result = CPDataTypeEqualToDataType(((CPMutableNumericData *)[cachedObjects objectAtIndex:0]).dataType, self.doubleDataType);
}
}
break;
case CPPlotCachePrecisionDouble:
result = YES;
break;
default:
// not double precision
break;
}
return result;
}
/** @brief Retrieves an array of numbers from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @return The array of cached numbers.
**/
-(CPMutableNumericData *)cachedNumbersForField:(NSUInteger)fieldEnum
{
return [self.cachedData objectForKey:[NSNumber numberWithUnsignedInteger:fieldEnum]];
}
/** @brief Retrieves a single number from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @param index The index of the desired data value.
* @return The cached number.
**/
-(NSNumber *)cachedNumberForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
CPMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
return [numbers sampleValue:index];
}
/** @brief Retrieves a single number from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @param index The index of the desired data value.
* @return The cached number or NAN if no data is cached for the requested field.
**/
-(double)cachedDoubleForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
CPMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
if ( numbers ) {
switch ( numbers.dataTypeFormat ) {
case CPFloatingPointDataType: {
double *doubleNumber = (double *)[numbers samplePointer:index];
return *doubleNumber;
}
break;
case CPDecimalDataType: {
NSDecimal *decimalNumber = (NSDecimal *)[numbers samplePointer:index];
return CPDecimalDoubleValue(*decimalNumber);
}
break;
default:
[NSException raise:CPException format:@"Unsupported data type format"];
break;
}
}
return NAN;
}
/** @brief Retrieves a single number from the cache.
* @param fieldEnum The field enumerator identifying the field.
* @param index The index of the desired data value.
* @return The cached number or NAN if no data is cached for the requested field.
**/
-(NSDecimal)cachedDecimalForField:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
CPMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
if ( numbers ) {
switch ( numbers.dataTypeFormat ) {
case CPFloatingPointDataType: {
double *doubleNumber = (double *)[numbers samplePointer:index];
return CPDecimalFromDouble(*doubleNumber);
}
break;
case CPDecimalDataType: {
NSDecimal *decimalNumber = (NSDecimal *)[numbers samplePointer:index];
return *decimalNumber;
}
break;
default:
[NSException raise:CPException format:@"Unsupported data type format"];
break;
}
}
return CPDecimalNaN();
}
-(void)setCachedDataType:(CPNumericDataType)newDataType
{
for ( CPMutableNumericData *numericData in [self.cachedData allValues] ) {
numericData.dataType = newDataType;
}
}
-(CPNumericDataType)doubleDataType
{
return CPDataType(CPFloatingPointDataType, sizeof(double), CFByteOrderGetCurrent());
}
-(CPNumericDataType)decimalDataType
{
return CPDataType(CPDecimalDataType, sizeof(NSDecimal), CFByteOrderGetCurrent());
}
#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];
CPMutableNumericData *numbers = [self cachedNumbersForField:fieldEnum];
CPPlotRange *range = nil;
if ( numbers.numberOfSamples > 0 ) {
NSMutableArray *numberArray = [[numbers sampleArray] mutableCopy];
[numberArray removeObject:[NSNull null]];
[numberArray removeObject:[NSDecimalNumber notANumber]];
if ( numberArray.count > 0 ) {
NSNumber *min = [numberArray valueForKeyPath:@"@min.self"];
NSNumber *max = [numberArray valueForKeyPath:@"@max.self"];
NSDecimal length = CPDecimalSubtract([max decimalValue], [min decimalValue]);
range = [CPPlotRange plotRangeWithLocation:[min decimalValue] length:length];
}
[numberArray release];
}
return range;
}
/** @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 = nil;
for ( NSNumber *field in fields ) {
CPPlotRange *currentRange = [self plotRangeForField:field.unsignedIntValue];
if ( !unionRange )
unionRange = currentRange;
else
[unionRange unionPlotRange:[self plotRangeForField:field.unsignedIntValue]];
}
return unionRange;
}
#pragma mark -
#pragma mark Data Labels
/** @brief Marks the receiver as needing to update the labels before the content is next drawn.
**/
-(void)setNeedsRelabel
{
self.labelIndexRange = NSMakeRange(0, self.cachedDataCount);
self.needsRelabel = YES;
}
/** @brief Updates the data labels.
**/
-(void)relabel
{
if ( !self.needsRelabel ) return;
self.needsRelabel = NO;
id <CPPlotDataSource> theDataSource = self.dataSource;
CPMutableTextStyle *dataLabelTextStyle = self.labelTextStyle;
NSNumberFormatter *dataLabelFormatter = self.labelFormatter;
BOOL dataSourceProvidesLabels = [theDataSource respondsToSelector:@selector(dataLabelForPlot:recordIndex:)];
BOOL plotProvidesLabels = dataLabelTextStyle && dataLabelFormatter;
if ( !dataSourceProvidesLabels && !plotProvidesLabels ) {
Class annotationClass = [CPAnnotation class];
for ( CPAnnotation *annotation in self.labelAnnotations) {
if ( [annotation isKindOfClass:annotationClass] ) {
[self removeAnnotation:annotation];
}
}
self.labelAnnotations = nil;
return;
}
NSUInteger sampleCount = self.cachedDataCount;
NSRange indexRange = self.labelIndexRange;
NSUInteger maxIndex = NSMaxRange(indexRange);
if ( !self.labelAnnotations ) {
self.labelAnnotations = [NSMutableArray arrayWithCapacity:sampleCount];
}
CPPlotSpace *thePlotSpace = self.plotSpace;
CGFloat theRotation = self.labelRotation;
NSMutableArray *labelArray = self.labelAnnotations;
NSUInteger oldLabelCount = labelArray.count;
Class nullClass = [NSNull class];
CPMutableNumericData *labelFieldDataCache = [self cachedNumbersForField:self.labelField];
for ( NSUInteger i = indexRange.location; i < maxIndex; i++ ) {
CPLayer *newLabelLayer = nil;
NSNumber *dataValue = [labelFieldDataCache sampleValue:i];
if ( isnan([dataValue doubleValue]) ) {
newLabelLayer = nil;
}
else {
if ( dataSourceProvidesLabels ) {
newLabelLayer = [[theDataSource dataLabelForPlot:self recordIndex:i] retain];
}
if ( !newLabelLayer && plotProvidesLabels ) {
NSString *labelString = [dataLabelFormatter stringForObjectValue:dataValue];
newLabelLayer = [[CPTextLayer alloc] initWithText:labelString style:dataLabelTextStyle];
}
if ( [newLabelLayer isKindOfClass:nullClass] ) {
[newLabelLayer release];
newLabelLayer = nil;
}
}
CPPlotSpaceAnnotation *labelAnnotation;
if ( i < oldLabelCount ) {
labelAnnotation = [labelArray objectAtIndex:i];
}
else {
labelAnnotation = [[CPPlotSpaceAnnotation alloc] initWithPlotSpace:thePlotSpace anchorPlotPoint:nil];
[labelArray addObject:labelAnnotation];
[self addAnnotation:labelAnnotation];
[labelAnnotation release];
}
labelAnnotation.contentLayer = newLabelLayer;
labelAnnotation.rotation = theRotation;
[self positionLabelAnnotation:labelAnnotation forIndex:i];
[self updateContentAnchorForLabel:labelAnnotation];
[newLabelLayer release];
}
// remove labels that are no longer needed
Class annotationClass = [CPAnnotation class];
while ( labelArray.count > sampleCount ) {
CPAnnotation *oldAnnotation = [labelArray objectAtIndex:labelArray.count - 1];
if ( [oldAnnotation isKindOfClass:annotationClass] ) {
[self removeAnnotation:oldAnnotation];
}
[labelArray removeLastObject];
}
}
/** @brief Sets the labelIndexRange and informs the receiver that it needs to relabel.
* @param indexRange The new indexRange for the labels.
*
* @todo Needs more documentation.
**/
-(void)relabelIndexRange:(NSRange)indexRange
{
self.labelIndexRange = indexRange;
self.needsRelabel = YES;
}
-(void)updateContentAnchorForLabel:(CPPlotSpaceAnnotation *)label
{
CGPoint displacement = label.displacement;
if ( CGPointEqualToPoint(displacement, CGPointZero) ) {
displacement.y = 1.0; // put the label above the data point if zero displacement
}
double angle = M_PI + atan2(displacement.y, displacement.x) - label.rotation;
double newAnchorX = cos(angle);
double newAnchorY = sin(angle);
if ( ABS(newAnchorX) <= ABS(newAnchorY) ) {
newAnchorX /= ABS(newAnchorY);
newAnchorY = signbit(newAnchorY) ? -1.0 : 1.0;
}
else {
newAnchorY /= ABS(newAnchorX);
newAnchorX = signbit(newAnchorX) ? -1.0 : 1.0;
}
label.contentAnchorPoint = CGPointMake((newAnchorX + 1.0) / 2.0, (newAnchorY + 1.0) / 2.0);
}
#pragma mark -
#pragma mark Accessors
-(void)setDataSource:(id <CPPlotDataSource>)newSource
{
if ( newSource != dataSource ) {
dataSource = newSource;
[self setDataNeedsReloading];
}
}
-(void)setDataNeedsReloading:(BOOL)newDataNeedsReloading
{
if ( newDataNeedsReloading != dataNeedsReloading ) {
dataNeedsReloading = newDataNeedsReloading;
if ( dataNeedsReloading ) {
[self setNeedsDisplay];
}
}
}
-(CPPlotArea *)plotArea
{
return self.graph.plotAreaFrame.plotArea;
}
-(void)setNeedsRelabel:(BOOL)newNeedsRelabel
{
if ( newNeedsRelabel != needsRelabel ) {
needsRelabel = newNeedsRelabel;
if ( needsRelabel ) {
[self setNeedsLayout];
}
}
}
-(void)setLabelTextStyle:(CPMutableTextStyle *)newStyle
{
if ( newStyle != labelTextStyle ) {
[labelTextStyle release];
labelTextStyle = [newStyle copy];
if ( labelTextStyle && !self.labelFormatter ) {
NSNumberFormatter *newFormatter = [[NSNumberFormatter alloc] init];
newFormatter.minimumIntegerDigits = 1;
newFormatter.maximumFractionDigits = 1;
newFormatter.minimumFractionDigits = 1;
self.labelFormatter = newFormatter;
[newFormatter release];
}
self.needsRelabel = YES;
}
}
-(void)setLabelOffset:(CGFloat)newOffset
{
if ( newOffset != labelOffset ) {
labelOffset = newOffset;
self.needsRelabel = YES;
}
}
-(void)setLabelRotation:(CGFloat)newRotation
{
if ( newRotation != labelRotation ) {
labelRotation = newRotation;
self.needsRelabel = YES;
}
}
-(void)setLabelFormatter:(NSNumberFormatter *)newTickLabelFormatter
{
if ( newTickLabelFormatter != labelFormatter ) {
[labelFormatter release];
labelFormatter = [newTickLabelFormatter retain];
self.labelFormatterChanged = YES;
self.needsRelabel = YES;
}
}
-(void)setCachePrecision:(CPPlotCachePrecision)newPrecision
{
if ( newPrecision != cachePrecision ) {
cachePrecision = newPrecision;
switch ( cachePrecision ) {
case CPPlotCachePrecisionAuto:
// don't change data already in the cache
break;
case CPPlotCachePrecisionDouble:
[self setCachedDataType:self.doubleDataType];
break;
case CPPlotCachePrecisionDecimal:
[self setCachedDataType:self.decimalDataType];
break;
default:
[NSException raise:NSInvalidArgumentException format:@"Invalid cache precision"];
break;
}
}
}
@end
#pragma mark -
@implementation CPPlot(AbstractMethods)
#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 Labels
/** @brief Adjusts the position of the data label annotation for the plot point at the given index.
* @param label The annotation for the data label.
* @param index The data index for the label.
**/
-(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index
{
// do nothing--implementation provided by subclasses
}
@end
| 08iteng-ipad | framework/Source/CPPlot.m | Objective-C | bsd | 30,313 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
/// @file
#if __cplusplus
extern "C" {
#endif
CGPathRef CreateRoundedRectPath(CGRect rect, CGFloat cornerRadius);
void AddRoundedRectPath(CGContextRef context, CGRect rect, CGFloat cornerRadius);
#if __cplusplus
}
#endif
| 08iteng-ipad | framework/Source/CPPathExtensions.h | Objective-C | bsd | 294 |
#import "CPAxis.h"
#import "CPAxisLabel.h"
#import "CPAxisLabelGroup.h"
#import "CPAxisSet.h"
#import "CPAxisTitle.h"
#import "CPColor.h"
#import "CPExceptions.h"
#import "CPFill.h"
#import "CPGradient.h"
#import "CPGridLineGroup.h"
#import "CPGridLines.h"
#import "CPImage.h"
#import "CPLimitBand.h"
#import "CPLineStyle.h"
#import "CPPlotRange.h"
#import "CPPlotSpace.h"
#import "CPPlotArea.h"
#import "CPTextLayer.h"
#import "CPUtilities.h"
#import "CPPlatformSpecificCategories.h"
#import "CPUtilities.h"
#import "NSDecimalNumberExtensions.h"
/** @cond */
@interface CPAxis ()
@property (nonatomic, readwrite, assign) BOOL needsRelabel;
@property (nonatomic, readwrite, assign) __weak CPGridLines *minorGridLines;
@property (nonatomic, readwrite, assign) __weak CPGridLines *majorGridLines;
@property (nonatomic, readwrite, assign) BOOL labelFormatterChanged;
@property (nonatomic, readwrite, retain) NSMutableArray *mutableBackgroundLimitBands;
-(void)generateFixedIntervalMajorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations;
-(void)autoGenerateMajorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations;
-(NSSet *)filteredTickLocations:(NSSet *)allLocations;
-(void)updateAxisLabelsAtLocations:(NSSet *)locations useMajorAxisLabels:(BOOL)useMajorAxisLabels labelAlignment:(CPAlignment)theLabelAlignment labelOffset:(CGFloat)theLabelOffset labelRotation:(CGFloat)theLabelRotation textStyle:(CPTextStyle *)theLabelTextStyle labelFormatter:(NSNumberFormatter *)theLabelFormatter;
@end
/** @endcond */
#pragma mark -
/** @brief An abstract axis class.
**/
@implementation 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 labelingOrigin
* @brief The origin used for axis labels.
* The default value is 0. It is only used when the axis labeling
* policy is CPAxisLabelingPolicyFixedInterval. The origin is
* a reference point used to being labeling. Labels are added
* at the origin, as well as at fixed intervals above and below
* the origin.
**/
@synthesize labelingOrigin;
/** @property tickDirection
* @brief The tick direction.
* The direction is given as the sign that ticks extend along
* the axis (e.g., positive, or negative).
**/
@synthesize tickDirection;
/** @property visibleRange
* @brief The plot range over which the axis and ticks are visible.
* Use this to restrict an axis to less than the full plot area width.
* Set to nil for no restriction.
**/
@synthesize visibleRange;
/** @property gridLinesRange
* @brief The plot range over which the grid lines are visible.
* Note that this range applies to the orthogonal coordinate, not
* the axis coordinate itself.
* Set to nil for no restriction.
**/
@synthesize gridLinesRange;
// Title
/** @property titleTextStyle
* @brief The text style used to draw the axis title text.
**/
@synthesize titleTextStyle;
/** @property axisTitle
* @brief The axis title.
* If nil, no title is drawn.
**/
@synthesize axisTitle;
/** @property titleOffset
* @brief The offset distance between the axis title and the axis line.
**/
@synthesize titleOffset;
/** @property title
* @brief A convenience property for setting the text title of the axis.
**/
@synthesize title;
/** @property titleLocation
* @brief The position along the axis where the axis title should be centered.
* If NaN, the <code>defaultTitleLocation</code> will be used.
**/
@dynamic titleLocation;
/** @property defaultTitleLocation
* @brief The position along the axis where the axis title should be centered
* if <code>titleLocation</code> is NaN.
**/
@dynamic defaultTitleLocation;
// Plot space
/** @property plotSpace
* @brief The plot space for the axis.
**/
@synthesize plotSpace;
// Labels
/** @property labelingPolicy
* @brief The axis labeling policy.
**/
@synthesize labelingPolicy;
/** @property labelOffset
* @brief The offset distance between the tick marks and labels.
**/
@synthesize labelOffset;
/** @property minorTickLabelOffset
* @brief The offset distance between the minor tick marks and labels.
**/
@synthesize minorTickLabelOffset;
/** @property labelRotation
* @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 labelRotation;
/** @property minorTickLabelRotation
* @brief The rotation of the axis minor tick labels in radians.
* Set this property to M_PI/2.0 to have labels read up the screen, for example.
**/
@synthesize minorTickLabelRotation;
/** @property labelAlignment
* @brief The alignment of the axis label with respect to the tick mark.
**/
@synthesize labelAlignment;
/** @property minorTickLabelAlignment
* @brief The alignment of the axis label with respect to the tick mark.
**/
@synthesize minorTickLabelAlignment;
/** @property labelTextStyle
* @brief The text style used to draw the label text.
**/
@synthesize labelTextStyle;
/** @property minorTickLabelTextStyle
* @brief The text style used to draw the label text of minor tick labels.
**/
@synthesize minorTickLabelTextStyle;
/** @property labelFormatter
* @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 (e.g., "Jan 10, 2010").
* The CPTimeFormatter is useful for this purpose.
**/
@synthesize labelFormatter;
/** @property minorTickLabelFormatter
* @brief The number formatter used to format the label text of minor ticks.
* 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 (e.g., "Jan 10, 2010").
* The CPTimeFormatter is useful for this purpose.
**/
@synthesize minorTickLabelFormatter;
@synthesize labelFormatterChanged;
/** @property axisLabels
* @brief The set of axis labels.
**/
@synthesize axisLabels;
/** @property minorTickAxisLabels
* @brief The set of minor tick axis labels.
**/
@synthesize minorTickAxisLabels;
/** @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;
// 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;
// Background Bands
/** @property alternatingBandFills
* @brief An array of two or more fills to be drawn between successive major tick marks.
*
* When initializing the fills, provide an NSArray containing any combinination of CPFill,
* CPColor, CPGradient, and/or CPImage objects. Blank (transparent) bands can be created
* by using [NSNull null] in place of some of the CPFill objects.
**/
@synthesize alternatingBandFills;
/** @property backgroundLimitBands
* @brief An array of CPLimitBand objects.
*
* The limit bands are drawn on top of the alternating band fills.
**/
@dynamic backgroundLimitBands;
@synthesize mutableBackgroundLimitBands;
// Layers
/** @property separateLayers
* @brief Use separate layers for drawing grid lines?
*
* If NO, the default, the major and minor grid lines are drawn in layers shared with other axes.
* If YES, the grid lines are drawn in their own layers.
**/
@synthesize separateLayers;
/** @property plotArea
* @brief The plot area that the axis belongs to.
**/
@synthesize plotArea;
/** @property minorGridLines
* @brief The layer that draws the minor grid lines.
**/
@synthesize minorGridLines;
/** @property majorGridLines
* @brief The layer that draws the major grid lines.
**/
@synthesize majorGridLines;
/** @property axisSet
* @brief The axis set that the axis belongs to.
**/
@dynamic axisSet;
#pragma mark -
#pragma mark Init/Dealloc
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
plotSpace = nil;
majorTickLocations = [[NSSet set] retain];
minorTickLocations = [[NSSet set] retain];
preferredNumberOfMajorTicks = 5;
minorTickLength = 3.0;
majorTickLength = 5.0;
labelOffset = 2.0;
minorTickLabelOffset = 2.0;
labelRotation = 0.0;
minorTickLabelRotation = 0.0;
labelAlignment = CPAlignmentCenter;
minorTickLabelAlignment = CPAlignmentCenter;
title = nil;
titleOffset = 30.0;
axisLineStyle = [[CPLineStyle alloc] init];
majorTickLineStyle = [[CPLineStyle alloc] init];
minorTickLineStyle = [[CPLineStyle alloc] init];
majorGridLineStyle = nil;
minorGridLineStyle = nil;
labelingOrigin = [[NSDecimalNumber zero] decimalValue];
majorIntervalLength = [[NSDecimalNumber one] decimalValue];
minorTicksPerInterval = 1;
coordinate = CPCoordinateX;
labelingPolicy = CPAxisLabelingPolicyFixedInterval;
labelTextStyle = [[CPTextStyle alloc] init];
NSNumberFormatter *newFormatter = [[NSNumberFormatter alloc] init];
newFormatter.minimumIntegerDigits = 1;
newFormatter.maximumFractionDigits = 1;
newFormatter.minimumFractionDigits = 1;
labelFormatter = newFormatter;
minorTickLabelTextStyle = [[CPTextStyle alloc] init];
minorTickLabelFormatter = nil;
labelFormatterChanged = YES;
axisLabels = [[NSSet set] retain];
minorTickAxisLabels = [[NSSet set] retain];
tickDirection = CPSignNone;
axisTitle = nil;
titleTextStyle = [[CPTextStyle alloc] init];
titleLocation = CPDecimalNaN();
needsRelabel = YES;
labelExclusionRanges = nil;
plotArea = nil;
separateLayers = NO;
alternatingBandFills = nil;
mutableBackgroundLimitBands = nil;
minorGridLines = nil;
majorGridLines = nil;
self.needsDisplayOnBoundsChange = YES;
}
return self;
}
-(id)initWithLayer:(id)layer
{
if ( self = [super initWithLayer:layer] ) {
CPAxis *theLayer = (CPAxis *)layer;
plotSpace = [theLayer->plotSpace retain];
majorTickLocations = [theLayer->majorTickLocations retain];
minorTickLocations = [theLayer->minorTickLocations retain];
preferredNumberOfMajorTicks = theLayer->preferredNumberOfMajorTicks;
minorTickLength = theLayer->minorTickLength;
majorTickLength = theLayer->majorTickLength;
labelOffset = theLayer->labelOffset;
minorTickLabelOffset = theLayer->labelOffset;
labelRotation = theLayer->labelRotation;
minorTickLabelRotation = theLayer->labelRotation;
labelAlignment = theLayer->labelAlignment;
minorTickLabelAlignment = theLayer->labelAlignment;
title = [theLayer->title retain];
titleOffset = theLayer->titleOffset;
axisLineStyle = [theLayer->axisLineStyle retain];
majorTickLineStyle = [theLayer->majorTickLineStyle retain];
minorTickLineStyle = [theLayer->minorTickLineStyle retain];
majorGridLineStyle = [theLayer->majorGridLineStyle retain];
minorGridLineStyle = [theLayer->minorGridLineStyle retain];
labelingOrigin = theLayer->labelingOrigin;
majorIntervalLength = theLayer->majorIntervalLength;
minorTicksPerInterval = theLayer->minorTicksPerInterval;
coordinate = theLayer->coordinate;
labelingPolicy = theLayer->labelingPolicy;
labelFormatter = [theLayer->labelFormatter retain];
minorTickLabelFormatter = [theLayer->minorTickLabelFormatter retain];
axisLabels = [theLayer->axisLabels retain];
minorTickAxisLabels = [theLayer->minorTickAxisLabels retain];
tickDirection = theLayer->tickDirection;
labelTextStyle = [theLayer->labelTextStyle retain];
minorTickLabelTextStyle = [theLayer->minorTickLabelTextStyle retain];
axisTitle = [theLayer->axisTitle retain];
titleTextStyle = [theLayer->titleTextStyle retain];
titleLocation = theLayer->titleLocation;
needsRelabel = theLayer->needsRelabel;
labelExclusionRanges = [theLayer->labelExclusionRanges retain];
plotArea = theLayer->plotArea;
separateLayers = theLayer->separateLayers;
visibleRange = [theLayer->visibleRange retain];
gridLinesRange = [theLayer->gridLinesRange retain];
alternatingBandFills = [theLayer->alternatingBandFills retain];
mutableBackgroundLimitBands = [theLayer->mutableBackgroundLimitBands retain];
minorGridLines = theLayer->minorGridLines;
majorGridLines = theLayer->majorGridLines;
}
return self;
}
-(void)dealloc
{
self.plotArea = nil; // update layers
[plotSpace release];
[majorTickLocations release];
[minorTickLocations release];
[title release];
[axisLineStyle release];
[majorTickLineStyle release];
[minorTickLineStyle release];
[majorGridLineStyle release];
[minorGridLineStyle release];
[labelFormatter release];
[minorTickLabelFormatter release];
[axisLabels release];
[minorTickAxisLabels release];
[labelTextStyle release];
[minorTickLabelTextStyle release];
[axisTitle release];
[titleTextStyle release];
[labelExclusionRanges release];
[visibleRange release];
[gridLinesRange release];
[alternatingBandFills release];
[mutableBackgroundLimitBands release];
[super dealloc];
}
#pragma mark -
#pragma mark Ticks
-(void)generateFixedIntervalMajorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations
{
NSMutableSet *majorLocations = [NSMutableSet set];
NSMutableSet *minorLocations = [NSMutableSet set];
NSDecimal zero = CPDecimalFromInteger(0);
NSDecimal majorInterval = self.majorIntervalLength;
if ( CPDecimalGreaterThan(majorInterval, zero) ) {
CPPlotRange *range = [[self.plotSpace plotRangeForCoordinate:self.coordinate] copy];
if ( range ) {
CPPlotRange *theVisibleRange = self.visibleRange;
if ( theVisibleRange ) {
[range intersectionPlotRange:theVisibleRange];
}
NSDecimal rangeMin = range.minLimit;
NSDecimal rangeMax = range.maxLimit;
NSDecimal minorInterval;
NSUInteger minorTickCount = self.minorTicksPerInterval;
if ( minorTickCount > 0 ) {
minorInterval = CPDecimalDivide(majorInterval, CPDecimalFromUnsignedInteger(self.minorTicksPerInterval + 1));
}
else {
minorInterval = zero;
}
// Set starting coord--should be the smallest value >= rangeMin that is a whole multiple of majorInterval away from the labelingOrigin
NSDecimal coord = CPDecimalDivide(CPDecimalSubtract(rangeMin, self.labelingOrigin), majorInterval);
NSDecimalRound(&coord, &coord, 0, NSRoundUp);
coord = CPDecimalAdd(CPDecimalMultiply(coord, majorInterval), self.labelingOrigin);
// Set minor ticks between the starting point and rangeMin
if ( minorTickCount > 0 ) {
NSDecimal minorCoord = CPDecimalSubtract(coord, minorInterval);
for ( NSUInteger minorTickIndex = 0; minorTickIndex < minorTickCount; minorTickIndex++ ) {
if ( CPDecimalLessThan(minorCoord, rangeMin) ) break;
[minorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:minorCoord]];
minorCoord = CPDecimalSubtract(minorCoord, minorInterval);
}
}
// Set tick locations
while ( CPDecimalLessThanOrEqualTo(coord, rangeMax) ) {
// Major tick
[majorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:coord]];
// Minor ticks
if ( minorTickCount > 0 ) {
NSDecimal minorCoord = CPDecimalAdd(coord, minorInterval);
for ( NSUInteger minorTickIndex = 0; minorTickIndex < minorTickCount; minorTickIndex++ ) {
if ( CPDecimalGreaterThan(minorCoord, rangeMax) ) break;
[minorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:minorCoord]];
minorCoord = CPDecimalAdd(minorCoord, minorInterval);
}
}
coord = CPDecimalAdd(coord, majorInterval);
}
}
[range release];
}
*newMajorLocations = majorLocations;
*newMinorLocations = minorLocations;
}
-(void)autoGenerateMajorTickLocations:(NSSet **)newMajorLocations minorTickLocations:(NSSet **)newMinorLocations
{
// cache some values
CPPlotRange *range = [[self.plotSpace plotRangeForCoordinate:self.coordinate] copy];
CPPlotRange *theVisibleRange = self.visibleRange;
if ( theVisibleRange ) {
[range intersectionPlotRange:theVisibleRange];
}
NSUInteger numTicks = self.preferredNumberOfMajorTicks;
NSUInteger minorTicks = self.minorTicksPerInterval;
double length = range.lengthDouble;
// Create sets for locations
NSMutableSet *majorLocations = [NSMutableSet set];
NSMutableSet *minorLocations = [NSMutableSet set];
// Filter troublesome values and return empty sets
if ( length > 0 && numTicks > 0 ) {
// Determine interval value
double roughInterval = length / numTicks;
double exponentValue = pow( 10.0, floor(log10(fabs(roughInterval))) );
double interval = exponentValue * round(roughInterval / exponentValue);
// Determine minor interval
double minorInterval = interval / (minorTicks + 1);
// Calculate actual range limits
double minLimit = range.minLimitDouble;
double maxLimit = range.maxLimitDouble;
// Determine the initial and final major indexes for the actual visible range
NSInteger initialIndex = floor(minLimit / interval); // can be negative
NSInteger finalIndex = ceil(maxLimit / interval); // can be negative
// Iterate through the indexes with visible ticks and build the locations sets
for ( NSInteger i = initialIndex; i <= finalIndex; i++ ) {
double pointLocation = i * interval;
for ( NSUInteger j = 0; j < minorTicks; j++ ) {
double minorPointLocation = pointLocation + minorInterval * (j + 1);
if ( minorPointLocation < minLimit ) continue;
if ( minorPointLocation > maxLimit ) continue;
[minorLocations addObject:[NSDecimalNumber numberWithDouble:minorPointLocation]];
}
if ( pointLocation < minLimit ) continue;
if ( pointLocation > maxLimit ) continue;
[majorLocations addObject:[NSDecimalNumber numberWithDouble:pointLocation]];
}
}
[range release];
// Return tick locations sets
*newMajorLocations = majorLocations;
*newMinorLocations = minorLocations;
}
-(NSSet *)filteredTickLocations:(NSSet *)allLocations
{
NSArray *exclusionRanges = self.labelExclusionRanges;
if ( exclusionRanges ) {
NSMutableSet *filteredLocations = [allLocations mutableCopy];
for ( CPPlotRange *range in exclusionRanges ) {
for ( NSDecimalNumber *location in allLocations ) {
if ( [range contains:[location decimalValue]] ) {
[filteredLocations removeObject:location];
}
}
}
return [filteredLocations autorelease];
}
else {
return allLocations;
}
}
/** @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 filtered 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 filtered set.
**/
-(NSSet *)filteredMinorTickLocations:(NSSet *)allLocations
{
return [self filteredTickLocations:allLocations];
}
#pragma mark -
#pragma mark Labels
/** @brief Updates the set of axis labels using the given locations.
* Existing axis label objects and content layers are reused where possible.
* @param locations A set of NSDecimalNumber label locations.
**/
-(void)updateAxisLabelsAtLocations:(NSSet *)locations useMajorAxisLabels:(BOOL)useMajorAxisLabels labelAlignment:(CPAlignment)theLabelAlignment labelOffset:(CGFloat)theLabelOffset labelRotation:(CGFloat)theLabelRotation textStyle:(CPTextStyle *)theLabelTextStyle labelFormatter:(NSNumberFormatter *)theLabelFormatter;
{
if ( [self.delegate respondsToSelector:@selector(axis:shouldUpdateAxisLabelsAtLocations:)] ) {
BOOL shouldContinue = [self.delegate axis:self shouldUpdateAxisLabelsAtLocations:locations];
if ( !shouldContinue ) return;
}
if ( locations.count == 0 || !theLabelTextStyle || !theLabelFormatter ) {
if (useMajorAxisLabels) {
self.axisLabels = nil;
} else {
self.minorTickAxisLabels = nil;
}
return;
}
CGFloat offset = theLabelOffset;
switch ( self.tickDirection ) {
case CPSignNone:
offset += self.majorTickLength / 2.0;
break;
case CPSignPositive:
case CPSignNegative:
offset += self.majorTickLength;
break;
}
[self.plotArea setAxisSetLayersForType:CPGraphLayerTypeAxisLabels];
NSMutableSet *oldAxisLabels;
if (useMajorAxisLabels) {
oldAxisLabels = [self.axisLabels mutableCopy];
} else {
oldAxisLabels = [self.minorTickAxisLabels mutableCopy];
}
NSMutableSet *newAxisLabels = [[NSMutableSet alloc] initWithCapacity:locations.count];
CPAxisLabel *blankLabel = [[CPAxisLabel alloc] initWithText:nil textStyle:nil];
CPAxisLabelGroup *axisLabelGroup = self.plotArea.axisLabelGroup;
CALayer *lastLayer = nil;
CPPlotArea *thePlotArea = self.plotArea;
BOOL theLabelFormatterChanged = self.labelFormatterChanged;
CPSign theTickDirection = self.tickDirection;
CPCoordinate orthogonalCoordinate = CPOrthogonalCoordinate(self.coordinate);
for ( NSDecimalNumber *tickLocation in locations ) {
CPAxisLabel *newAxisLabel;
BOOL needsNewContentLayer = NO;
// reuse axis labels where possible--will prevent flicker when updating layers
blankLabel.tickLocation = [tickLocation decimalValue];
CPAxisLabel *oldAxisLabel = [oldAxisLabels member:blankLabel];
if ( oldAxisLabel ) {
newAxisLabel = [oldAxisLabel retain];
}
else {
newAxisLabel = [[CPAxisLabel alloc] initWithText:nil textStyle:nil];
newAxisLabel.tickLocation = [tickLocation decimalValue];
needsNewContentLayer = YES;
}
newAxisLabel.rotation = theLabelRotation;
newAxisLabel.offset = offset;
newAxisLabel.alignment = theLabelAlignment;
if ( needsNewContentLayer || theLabelFormatterChanged ) {
NSString *labelString = [theLabelFormatter stringForObjectValue:tickLocation];
CPTextLayer *newLabelLayer = [[CPTextLayer alloc] initWithText:labelString style:theLabelTextStyle];
[oldAxisLabel.contentLayer removeFromSuperlayer];
newAxisLabel.contentLayer = newLabelLayer;
if ( lastLayer ) {
[axisLabelGroup insertSublayer:newLabelLayer below:lastLayer];
}
else {
[axisLabelGroup insertSublayer:newLabelLayer atIndex:[thePlotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisLabels]];
}
[newLabelLayer release];
CGPoint tickBasePoint = [self viewPointForCoordinateDecimalNumber:newAxisLabel.tickLocation];
[newAxisLabel positionRelativeToViewPoint:tickBasePoint forCoordinate:orthogonalCoordinate inDirection:theTickDirection];
}
lastLayer = newAxisLabel.contentLayer;
[newAxisLabels addObject:newAxisLabel];
[newAxisLabel release];
}
[blankLabel release];
// remove old labels that are not needed any more from the layer hierarchy
[oldAxisLabels minusSet:newAxisLabels];
for ( CPAxisLabel *label in oldAxisLabels ) {
[label.contentLayer removeFromSuperlayer];
}
[oldAxisLabels release];
// do not use accessor because we've already updated the layer hierarchy
if (useMajorAxisLabels) {
[axisLabels release];
axisLabels = newAxisLabels;
} else {
[minorTickAxisLabels release];
minorTickAxisLabels = newAxisLabels;
}
[self setNeedsLayout];
self.labelFormatterChanged = NO;
}
/** @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;
}
NSSet *newMajorLocations = nil;
NSSet *newMinorLocations = nil;
switch ( self.labelingPolicy ) {
case CPAxisLabelingPolicyNone:
case CPAxisLabelingPolicyLocationsProvided:
// Locations are set by user
break;
case CPAxisLabelingPolicyFixedInterval:
[self generateFixedIntervalMajorTickLocations:&newMajorLocations minorTickLocations:&newMinorLocations];
break;
case CPAxisLabelingPolicyAutomatic:
[self autoGenerateMajorTickLocations:&newMajorLocations minorTickLocations:&newMinorLocations];
break;
case CPAxisLabelingPolicyLogarithmic:
// TODO: logarithmic labeling policy
break;
}
switch ( self.labelingPolicy ) {
case CPAxisLabelingPolicyNone:
case CPAxisLabelingPolicyLocationsProvided:
// Locations are set by user--no filtering required
break;
default:
// Filter and set tick locations
self.majorTickLocations = [self filteredMajorTickLocations:newMajorLocations];
self.minorTickLocations = [self filteredMinorTickLocations:newMinorLocations];
}
if ( self.labelingPolicy != CPAxisLabelingPolicyNone ) {
// Label ticks
[self updateAxisLabelsAtLocations:self.majorTickLocations useMajorAxisLabels:YES labelAlignment:self.labelAlignment labelOffset: self.labelOffset labelRotation:self.labelRotation textStyle:self.labelTextStyle labelFormatter:self.labelFormatter];
if (self.minorTickLabelFormatter) {
[self updateAxisLabelsAtLocations:self.minorTickLocations useMajorAxisLabels:NO labelAlignment:self.minorTickLabelAlignment labelOffset: self.minorTickLabelOffset labelRotation:self.minorTickLabelRotation textStyle:self.minorTickLabelTextStyle labelFormatter:self.minorTickLabelFormatter];
}
}
self.needsRelabel = NO;
if ( self.alternatingBandFills.count > 0 ) {
[self.plotArea setNeedsDisplay];
}
[self.delegate axisDidRelabel:self];
}
#pragma mark -
#pragma mark Titles
-(NSDecimal)defaultTitleLocation
{
return CPDecimalNaN();
}
#pragma mark -
#pragma mark Layout
+(CGFloat)defaultZPosition
{
return CPDefaultZPositionAxis;
}
-(void)layoutSublayers
{
for ( CPAxisLabel *label in self.axisLabels ) {
CGPoint tickBasePoint = [self viewPointForCoordinateDecimalNumber:label.tickLocation];
[label positionRelativeToViewPoint:tickBasePoint forCoordinate:CPOrthogonalCoordinate(self.coordinate) inDirection:self.tickDirection];
}
for ( CPAxisLabel *label in self.minorTickAxisLabels ) {
CGPoint tickBasePoint = [self viewPointForCoordinateDecimalNumber:label.tickLocation];
[label positionRelativeToViewPoint:tickBasePoint forCoordinate:CPOrthogonalCoordinate(self.coordinate) inDirection:self.tickDirection];
}
[self.axisTitle positionRelativeToViewPoint:[self viewPointForCoordinateDecimalNumber:self.titleLocation] forCoordinate:CPOrthogonalCoordinate(self.coordinate) inDirection:self.tickDirection];
}
#pragma mark -
#pragma mark Background Bands
/** @brief Add a background limit band.
* @param limitBand The new limit band.
**/
-(void)addBackgroundLimitBand:(CPLimitBand *)limitBand
{
if ( limitBand ) {
if ( !self.mutableBackgroundLimitBands ) {
self.mutableBackgroundLimitBands = [NSMutableArray array];
}
[self.mutableBackgroundLimitBands addObject:limitBand];
[self.plotArea setNeedsDisplay];
}
}
/** @brief Remove a background limit band.
* @param limitBand The limit band to be removed.
**/
-(void)removeBackgroundLimitBand:(CPLimitBand *)limitBand
{
if ( limitBand ) {
[self.mutableBackgroundLimitBands removeObject:limitBand];
[self.plotArea setNeedsDisplay];
}
}
#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;
[self.plotArea updateAxisSetLayersForType:CPGraphLayerTypeAxisLabels];
if ( axisLabels ) {
CPAxisLabelGroup *axisLabelGroup = self.plotArea.axisLabelGroup;
CALayer *lastLayer = nil;
for ( CPAxisLabel *label in axisLabels ) {
CPLayer *contentLayer = label.contentLayer;
if ( contentLayer ) {
if ( lastLayer ) {
[axisLabelGroup insertSublayer:contentLayer below:lastLayer];
}
else {
[axisLabelGroup insertSublayer:contentLayer atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisLabels]];
}
lastLayer = contentLayer;
}
}
}
[self setNeedsLayout];
}
}
-(void)setMinorTickAxisLabels:(NSSet *)newLabels
{
if ( newLabels != minorTickAxisLabels ) {
for ( CPAxisLabel *label in minorTickAxisLabels ) {
[label.contentLayer removeFromSuperlayer];
}
[newLabels retain];
[minorTickAxisLabels release];
minorTickAxisLabels = newLabels;
if ( minorTickAxisLabels ) {
CPAxisLabelGroup *axisLabelGroup = self.plotArea.axisLabelGroup;
CALayer *lastLayer = nil;
for ( CPAxisLabel *label in minorTickAxisLabels ) {
CPLayer *contentLayer = label.contentLayer;
if ( contentLayer ) {
if ( lastLayer ) {
[axisLabelGroup insertSublayer:contentLayer below:lastLayer];
}
else {
[axisLabelGroup insertSublayer:contentLayer atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisLabels]];
}
lastLayer = contentLayer;
}
}
}
[self setNeedsLayout];
}
}
-(void)setLabelTextStyle:(CPTextStyle *)newStyle
{
if ( newStyle != labelTextStyle ) {
[labelTextStyle release];
labelTextStyle = [newStyle copy];
for ( CPAxisLabel *axisLabel in self.axisLabels ) {
CPLayer *contentLayer = axisLabel.contentLayer;
if ( [contentLayer isKindOfClass:[CPTextLayer class]] ) {
[(CPTextLayer *)contentLayer setTextStyle:labelTextStyle];
}
}
[self setNeedsLayout];
}
}
-(void)setMinorTickLabelTextStyle:(CPTextStyle *)newStyle
{
if ( newStyle != minorTickLabelTextStyle ) {
[minorTickLabelTextStyle release];
minorTickLabelTextStyle = [newStyle copy];
[self setNeedsLayout];
}
}
-(void)setAxisTitle:(CPAxisTitle *)newTitle
{
if ( newTitle != axisTitle ) {
[axisTitle.contentLayer removeFromSuperlayer];
[axisTitle release];
axisTitle = [newTitle retain];
[self.plotArea updateAxisSetLayersForType:CPGraphLayerTypeAxisTitles];
if ( axisTitle ) {
axisTitle.offset = self.titleOffset;
CPLayer *contentLayer = axisTitle.contentLayer;
if ( contentLayer ) {
[self.plotArea.axisTitleGroup insertSublayer:contentLayer atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisTitles]];
}
}
[self setNeedsLayout];
}
}
-(CPAxisTitle *)axisTitle
{
if ( axisTitle == nil && title != nil ) {
CPAxisTitle *newTitle = [[CPAxisTitle alloc] initWithText:title textStyle:self.titleTextStyle];
self.axisTitle = newTitle;
[newTitle release];
}
return axisTitle;
}
-(void)setTitleTextStyle:(CPTextStyle *)newStyle
{
if ( newStyle != titleTextStyle ) {
[titleTextStyle release];
titleTextStyle = [newStyle copy];
CPLayer *contentLayer = self.axisTitle.contentLayer;
if ( [contentLayer isKindOfClass:[CPTextLayer class]] ) {
[(CPTextLayer *)contentLayer setTextStyle:titleTextStyle];
}
[self setNeedsLayout];
}
}
-(void)setTitleOffset:(CGFloat)newOffset
{
if ( newOffset != titleOffset ) {
titleOffset = newOffset;
self.axisTitle.offset = titleOffset;
[self setNeedsLayout];
}
}
-(void)setTitle:(NSString *)newTitle
{
if ( newTitle != title ) {
[title release];
title = [newTitle copy];
if ( title == nil ) self.axisTitle = nil;
CPLayer *contentLayer = self.axisTitle.contentLayer;
if ( [contentLayer isKindOfClass:[CPTextLayer class]] ) {
[(CPTextLayer *)contentLayer setText:title];
}
[self setNeedsLayout];
}
}
-(void)setTitleLocation:(NSDecimal)newLocation
{
if ( NSDecimalCompare(&newLocation, &titleLocation) != NSOrderedSame ) {
titleLocation = newLocation;
[self setNeedsLayout];
}
}
-(NSDecimal)titleLocation
{
if ( NSDecimalIsNotANumber(&titleLocation) ) {
return self.defaultTitleLocation;
} else {
return titleLocation;
}
}
-(void)setLabelExclusionRanges:(NSArray *)ranges
{
if ( ranges != labelExclusionRanges ) {
[labelExclusionRanges release];
labelExclusionRanges = [ranges retain];
self.needsRelabel = YES;
}
}
-(void)setNeedsRelabel:(BOOL)newNeedsRelabel
{
if (newNeedsRelabel != needsRelabel) {
needsRelabel = newNeedsRelabel;
if ( needsRelabel ) {
[self setNeedsLayout];
[self setNeedsDisplay];
}
}
}
-(void)setMajorTickLocations:(NSSet *)newLocations
{
if ( newLocations != majorTickLocations ) {
[majorTickLocations release];
majorTickLocations = [newLocations retain];
[self setNeedsDisplay];
if ( self.separateLayers ) {
[self.majorGridLines setNeedsDisplay];
}
else {
[self.plotArea.majorGridLineGroup setNeedsDisplay];
}
self.needsRelabel = YES;
}
}
-(void)setMinorTickLocations:(NSSet *)newLocations
{
if ( newLocations != majorTickLocations ) {
[minorTickLocations release];
minorTickLocations = [newLocations retain];
[self setNeedsDisplay];
if ( self.separateLayers ) {
[self.minorGridLines setNeedsDisplay];
}
else {
[self.plotArea.minorGridLineGroup 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)setLabelOffset:(CGFloat)newOffset
{
if ( newOffset != labelOffset ) {
labelOffset = newOffset;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setMinorTickLabelOffset:(CGFloat)newOffset
{
if ( newOffset != minorTickLabelOffset ) {
minorTickLabelOffset = newOffset;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setLabelRotation:(CGFloat)newRotation
{
if ( newRotation != labelRotation ) {
labelRotation = newRotation;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setMinorTickLabelRotation:(CGFloat)newRotation
{
if ( newRotation != minorTickLabelRotation ) {
minorTickLabelRotation = newRotation;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setLabelAlignment:(CPAlignment)newAlignment
{
if ( newAlignment != labelAlignment ) {
labelAlignment = newAlignment;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setMinorTickLabelAlignment:(CPAlignment)newAlignment
{
if ( newAlignment != minorTickLabelAlignment ) {
minorTickLabelAlignment = newAlignment;
[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)setMajorGridLineStyle:(CPLineStyle *)newLineStyle
{
if ( newLineStyle != majorGridLineStyle ) {
[majorGridLineStyle release];
majorGridLineStyle = [newLineStyle copy];
[self.plotArea updateAxisSetLayersForType:CPGraphLayerTypeMajorGridLines];
if ( majorGridLineStyle ) {
if ( self.separateLayers ) {
if ( !self.majorGridLines ) {
CPGridLines *gridLines = [[CPGridLines alloc] init];
self.majorGridLines = gridLines;
[gridLines release];
}
else {
[self.majorGridLines setNeedsDisplay];
}
}
else {
[self.plotArea.majorGridLineGroup setNeedsDisplay];
}
}
else {
self.majorGridLines = nil;
}
}
}
-(void)setMinorGridLineStyle:(CPLineStyle *)newLineStyle
{
if ( newLineStyle != minorGridLineStyle ) {
[minorGridLineStyle release];
minorGridLineStyle = [newLineStyle copy];
[self.plotArea updateAxisSetLayersForType:CPGraphLayerTypeMinorGridLines];
if ( minorGridLineStyle ) {
if ( self.separateLayers ) {
if ( !self.minorGridLines ) {
CPGridLines *gridLines = [[CPGridLines alloc] init];
self.minorGridLines = gridLines;
[gridLines release];
}
else {
[self.minorGridLines setNeedsDisplay];
}
}
else {
[self.plotArea.minorGridLineGroup setNeedsDisplay];
}
}
else {
self.minorGridLines = nil;
}
}
}
-(void)setLabelingOrigin:(NSDecimal)newLabelingOrigin
{
if ( CPDecimalEquals(labelingOrigin, newLabelingOrigin) ) {
return;
}
labelingOrigin = newLabelingOrigin;
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)setLabelingPolicy:(CPAxisLabelingPolicy)newPolicy
{
if ( newPolicy != labelingPolicy ) {
labelingPolicy = newPolicy;
self.needsRelabel = YES;
}
}
-(void)setLabelFormatter:(NSNumberFormatter *)newTickLabelFormatter
{
if ( newTickLabelFormatter != labelFormatter ) {
[labelFormatter release];
labelFormatter = [newTickLabelFormatter retain];
self.labelFormatterChanged = YES;
self.needsRelabel = YES;
}
}
-(void)setMinorTickLabelFormatter:(NSNumberFormatter *)newMinorTickLabelFormatter
{
if ( newMinorTickLabelFormatter != minorTickLabelFormatter ) {
[minorTickLabelFormatter release];
minorTickLabelFormatter = [newMinorTickLabelFormatter retain];
if (!newMinorTickLabelFormatter) {
for ( CPAxisLabel *label in self.minorTickAxisLabels ) {
[label.contentLayer removeFromSuperlayer];
}
[minorTickAxisLabels release];
minorTickAxisLabels = [[NSSet set] retain];
}
self.labelFormatterChanged = YES;
self.needsRelabel = YES;
}
}
-(void)setTickDirection:(CPSign)newDirection
{
if ( newDirection != tickDirection ) {
tickDirection = newDirection;
[self setNeedsLayout];
self.needsRelabel = YES;
}
}
-(void)setGridLinesRange:(CPPlotRange *)newRange {
if ( newRange != gridLinesRange ) {
[gridLinesRange release];
gridLinesRange = [newRange copy];
if ( self.separateLayers ) {
[self.minorGridLines setNeedsDisplay];
[self.majorGridLines setNeedsDisplay];
}
else {
[self.plotArea.minorGridLineGroup setNeedsDisplay];
[self.plotArea.majorGridLineGroup setNeedsDisplay];
}
}
}
-(void)setPlotArea:(CPPlotArea *)newPlotArea
{
if ( newPlotArea != plotArea ) {
plotArea = newPlotArea;
if ( plotArea ) {
[plotArea updateAxisSetLayersForType:CPGraphLayerTypeMinorGridLines];
CPGridLines *gridLines = self.minorGridLines;
if ( gridLines ) {
[gridLines removeFromSuperlayer];
[plotArea.minorGridLineGroup insertSublayer:gridLines atIndex:[plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeMinorGridLines]];
}
[plotArea updateAxisSetLayersForType:CPGraphLayerTypeMajorGridLines];
gridLines = self.majorGridLines;
if ( gridLines ) {
[gridLines removeFromSuperlayer];
[plotArea.majorGridLineGroup insertSublayer:gridLines atIndex:[plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeMajorGridLines]];
}
[plotArea updateAxisSetLayersForType:CPGraphLayerTypeAxisLabels];
if ( self.axisLabels.count > 0 ) {
CPAxisLabelGroup *axisLabelGroup = self.plotArea.axisLabelGroup;
CALayer *lastLayer = nil;
for ( CPAxisLabel *label in self.axisLabels ) {
CPLayer *contentLayer = label.contentLayer;
if ( contentLayer ) {
[contentLayer removeFromSuperlayer];
if ( lastLayer ) {
[axisLabelGroup insertSublayer:contentLayer below:lastLayer];
}
else {
[axisLabelGroup insertSublayer:contentLayer atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisLabels]];
}
lastLayer = contentLayer;
}
}
}
if ( self.minorTickAxisLabels.count > 0 ) {
CPAxisLabelGroup *axisLabelGroup = self.plotArea.axisLabelGroup;
CALayer *lastLayer = nil;
for ( CPAxisLabel *label in self.minorTickAxisLabels ) {
CPLayer *contentLayer = label.contentLayer;
if ( contentLayer ) {
[contentLayer removeFromSuperlayer];
if ( lastLayer ) {
[axisLabelGroup insertSublayer:contentLayer below:lastLayer];
}
else {
[axisLabelGroup insertSublayer:contentLayer atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisLabels]];
}
lastLayer = contentLayer;
}
}
}
[plotArea updateAxisSetLayersForType:CPGraphLayerTypeAxisTitles];
CPLayer *content = self.axisTitle.contentLayer;
if ( content ) {
[content removeFromSuperlayer];
[plotArea.axisTitleGroup insertSublayer:content atIndex:[plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeAxisTitles]];
}
}
else {
self.minorGridLines = nil;
self.majorGridLines = nil;
for ( CPAxisLabel *label in self.axisLabels ) {
[label.contentLayer removeFromSuperlayer];
}
[self.axisTitle.contentLayer removeFromSuperlayer];
}
}
}
-(void)setVisibleRange:(CPPlotRange *)newRange
{
if ( newRange != visibleRange ) {
[visibleRange release];
visibleRange = [newRange copy];
self.needsRelabel = YES;
}
}
-(void)setSeparateLayers:(BOOL)newSeparateLayers
{
if ( newSeparateLayers != separateLayers ) {
separateLayers = newSeparateLayers;
if ( separateLayers ) {
if ( self.minorGridLineStyle ) {
CPGridLines *gridLines = [[CPGridLines alloc] init];
self.minorGridLines = gridLines;
[gridLines release];
}
if ( self.majorGridLineStyle ) {
CPGridLines *gridLines = [[CPGridLines alloc] init];
self.majorGridLines = gridLines;
[gridLines release];
}
}
else {
self.minorGridLines = nil;
if ( self.minorGridLineStyle ) {
[self.plotArea.minorGridLineGroup setNeedsDisplay];
}
self.majorGridLines = nil;
if ( self.majorGridLineStyle ) {
[self.plotArea.majorGridLineGroup setNeedsDisplay];
}
}
}
}
-(void)setMinorGridLines:(CPGridLines *)newGridLines
{
if ( newGridLines != minorGridLines ) {
[minorGridLines removeFromSuperlayer];
minorGridLines = newGridLines;
if ( minorGridLines ) {
minorGridLines.major = NO;
minorGridLines.axis = self;
[self.plotArea.minorGridLineGroup insertSublayer:minorGridLines atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeMinorGridLines]];
}
}
}
-(void)setMajorGridLines:(CPGridLines *)newGridLines
{
if ( newGridLines != majorGridLines ) {
[majorGridLines removeFromSuperlayer];
majorGridLines = newGridLines;
if ( majorGridLines ) {
majorGridLines.major = YES;
majorGridLines.axis = self;
[self.plotArea.majorGridLineGroup insertSublayer:majorGridLines atIndex:[self.plotArea sublayerIndexForAxis:self layerType:CPGraphLayerTypeMajorGridLines]];
}
}
}
-(void)setAlternatingBandFills:(NSArray *)newFills
{
if ( newFills != alternatingBandFills ) {
[alternatingBandFills release];
BOOL convertFills = NO;
for ( id obj in newFills ) {
if ( obj == [NSNull null] ) {
continue;
}
else if ( [obj isKindOfClass:[CPFill class]] ) {
continue;
}
else {
convertFills = YES;
break;
}
}
if ( convertFills ) {
NSMutableArray *fillArray = [newFills mutableCopy];
NSInteger i = -1;
CPFill *newFill = nil;
for ( id obj in newFills ) {
i++;
if ( obj == [NSNull null] ) {
continue;
}
else if ( [obj isKindOfClass:[CPFill class]] ) {
continue;
}
else if ( [obj isKindOfClass:[CPColor class]] ) {
newFill = [[CPFill alloc] initWithColor:obj];
}
else if ( [obj isKindOfClass:[CPGradient class]] ) {
newFill = [[CPFill alloc] initWithGradient:obj];
}
else if ( [obj isKindOfClass:[CPImage class]] ) {
newFill = [[CPFill alloc] initWithImage:obj];
}
else {
[NSException raise:CPException format:@"Alternating band fills must be one or more of the following: CPFill, CPColor, CPGradient, CPImage, or [NSNull null]."];
}
[fillArray replaceObjectAtIndex:i withObject:newFill];
[newFill release];
}
alternatingBandFills = fillArray;
}
else {
alternatingBandFills = [newFills copy];
}
[self.plotArea setNeedsDisplay];
}
}
-(NSArray *)backgroundLimitBands
{
return [[self.mutableBackgroundLimitBands copy] autorelease];
}
-(CPAxisSet *)axisSet
{
return self.plotArea.axisSet;
}
@end
#pragma mark -
@implementation CPAxis(AbstractMethods)
/** @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 CGPointZero;
}
/** @brief Draws grid lines into the provided graphics context.
* @param context The graphics context to draw into.
* @param major Draw the major grid lines if YES, minor grid lines otherwise.
**/
-(void)drawGridLinesInContext:(CGContextRef)context isMajor:(BOOL)major
{
// do nothing--subclasses must override to do their drawing
}
/** @brief Draws alternating background bands into the provided graphics context.
* @param context The graphics context to draw into.
**/
-(void)drawBackgroundBandsInContext:(CGContextRef)context
{
// do nothing--subclasses must override to do their drawing
}
/** @brief Draws background limit ranges into the provided graphics context.
* @param context The graphics context to draw into.
**/
-(void)drawBackgroundLimitsInContext:(CGContextRef)context
{
// do nothing--subclasses must override to do their drawing
}
@end
| 08iteng-ipad | framework/Source/CPAxis.m | Objective-C | bsd | 48,914 |
#import "CPTestCase.h"
@interface CPThemeTests : CPTestCase {
}
@end
| 08iteng-ipad | framework/Source/CPThemeTests.h | Objective-C | bsd | 72 |
#import "CPLayer.h"
@class CPPlotArea;
@interface CPGridLineGroup : CPLayer {
@private
__weak CPPlotArea *plotArea;
BOOL major;
}
@property (nonatomic, readwrite, assign) __weak CPPlotArea *plotArea;
@property (nonatomic, readwrite) BOOL major;
@end
| 08iteng-ipad | framework/Source/CPGridLineGroup.h | Objective-C | bsd | 256 |
#import "CPMutableTextStyle.h"
#import "CPColor.h"
/** @brief Mutable wrapper for text style properties.
*
* Use this whenever you need to customize the properties of a text style.
**/
@implementation CPMutableTextStyle
/** @property fontSize
* @brief The font size.
**/
@dynamic fontSize;
/** @property fontName
* @brief The font name.
**/
@dynamic fontName;
/** @property color
* @brief The current text color.
**/
@dynamic color;
@end
| 08iteng-ipad | framework/Source/CPMutableTextStyle.m | Objective-C | bsd | 459 |
#import "CPTestCase.h"
@interface CPNumericDataTypeConversionPerformanceTests : CPTestCase {
}
@end
| 08iteng-ipad | framework/Source/CPNumericDataTypeConversionPerformanceTests.h | Objective-C | bsd | 104 |
#import "CPTestCase.h"
@interface CPTextStyleTests : CPTestCase {
}
@end
| 08iteng-ipad | framework/Source/CPTextStyleTests.h | Objective-C | bsd | 76 |
#import "CPMutableNumericDataTypeConversionTests.h"
#import "CPMutableNumericData.h"
#import "CPMutableNumericData+TypeConversion.h"
#import "CPUtilities.h"
static const NSUInteger numberOfSamples = 5;
static const double precision = 1.0e-6;
@implementation CPMutableNumericDataTypeConversionTests
-(void)testFloatToDoubleInPlaceConversion
{
NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(float)];
float *samples = (float *)[data mutableBytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
samples[i] = sinf(i);
}
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:data
dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder())
shape:nil];
numericData.sampleBytes = sizeof(double);
const double *doubleSamples = (const double *)[numericData.data bytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
STAssertEqualsWithAccuracy((double)samples[i], doubleSamples[i], precision, @"(float)%g != (double)%g", samples[i], doubleSamples[i]);
}
[numericData release];
}
-(void)testDoubleToFloatInPlaceConversion
{
NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(double)];
double *samples = (double *)[data mutableBytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
samples[i] = sin(i);
}
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:data
dataType:CPDataType(CPFloatingPointDataType, sizeof(double), NSHostByteOrder())
shape:nil];
numericData.sampleBytes = sizeof(float);
const float *floatSamples = (const float *)[numericData.data bytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
STAssertEqualsWithAccuracy((double)floatSamples[i], samples[i], precision, @"(float)%g != (double)%g", floatSamples[i], samples[i]);
}
[numericData release];
}
-(void)testFloatToIntegerInPlaceConversion
{
NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(float)];
float *samples = (float *)[data mutableBytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
samples[i] = sinf(i) * 1000.0f;
}
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:data
dataType:CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder())
shape:nil];
numericData.dataType = CPDataType(CPIntegerDataType, sizeof(NSInteger), NSHostByteOrder());
const NSInteger *intSamples = (const NSInteger *)[numericData.data bytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
STAssertEqualsWithAccuracy((NSInteger)samples[i], intSamples[i], precision, @"(float)%g != (NSInteger)%ld", samples[i], (long)intSamples[i]);
}
[numericData release];
}
-(void)testIntegerToFloatInPlaceConversion
{
NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(NSInteger)];
NSInteger *samples = (NSInteger *)[data mutableBytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
samples[i] = sin(i) * 1000.0;
}
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:data
dataType:CPDataType(CPIntegerDataType, sizeof(NSInteger), NSHostByteOrder())
shape:nil];
numericData.dataType = CPDataType(CPFloatingPointDataType, sizeof(float), NSHostByteOrder());
const float *floatSamples = (const float *)[numericData.data bytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
STAssertEqualsWithAccuracy(floatSamples[i], (float)samples[i], precision, @"(float)%g != (NSInteger)%ld", floatSamples[i], (long)samples[i]);
}
[numericData release];
}
-(void)testDecimalToDoubleInPlaceConversion
{
NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(NSDecimal)];
NSDecimal *samples = (NSDecimal *)[data mutableBytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
samples[i] = CPDecimalFromDouble(sin(i));
}
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:data
dataType:CPDataType(CPDecimalDataType, sizeof(NSDecimal), NSHostByteOrder())
shape:nil];
numericData.dataType = CPDataType(CPFloatingPointDataType, sizeof(double), NSHostByteOrder());
const double *doubleSamples = (const double *)[numericData.data bytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
STAssertEquals(CPDecimalDoubleValue(samples[i]), doubleSamples[i], @"(NSDecimal)%@ != (double)%g", CPDecimalStringValue(samples[i]), doubleSamples[i]);
}
[numericData release];
}
-(void)testDoubleToDecimalInPlaceConversion
{
NSMutableData *data = [NSMutableData dataWithLength:numberOfSamples * sizeof(double)];
double *samples = (double *)[data mutableBytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
samples[i] = sin(i);
}
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:data
dataType:CPDataType(CPFloatingPointDataType, sizeof(double), NSHostByteOrder())
shape:nil];
numericData.dataType = CPDataType(CPDecimalDataType, sizeof(NSDecimal), NSHostByteOrder());
const NSDecimal *decimalSamples = (const NSDecimal *)[numericData.data bytes];
for ( NSUInteger i = 0; i < numberOfSamples; i++ ) {
STAssertTrue(CPDecimalEquals(decimalSamples[i], CPDecimalFromDouble(samples[i])), @"(NSDecimal)%@ != (double)%g", CPDecimalStringValue(decimalSamples[i]), samples[i]);
}
[numericData release];
}
-(void)testTypeConversionSwapsByteOrderIntegerInPlace
{
CFByteOrder hostByteOrder = CFByteOrderGetCurrent();
CFByteOrder swappedByteOrder = (hostByteOrder == CFByteOrderBigEndian) ? CFByteOrderLittleEndian : CFByteOrderBigEndian;
uint32_t start = 1000;
NSData *startData = [NSData dataWithBytesNoCopy:&start
length:sizeof(uint32_t)
freeWhenDone:NO];
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:startData
dataType:CPDataType(CPUnsignedIntegerDataType, sizeof(uint32_t), hostByteOrder)
shape:nil];
numericData.byteOrder = swappedByteOrder;
uint32_t end = *(const uint32_t *)numericData.bytes;
STAssertEquals(CFSwapInt32(start), end, @"Bytes swapped");
numericData.byteOrder = hostByteOrder;
uint32_t startRoundTrip = *(const uint32_t *)numericData.bytes;
STAssertEquals(start, startRoundTrip, @"Round trip");
[numericData release];
}
-(void)testTypeConversionSwapsByteOrderDoubleInPlace
{
CFByteOrder hostByteOrder = CFByteOrderGetCurrent();
CFByteOrder swappedByteOrder = (hostByteOrder == CFByteOrderBigEndian) ? CFByteOrderLittleEndian : CFByteOrderBigEndian;
double start = 1000.0;
NSData *startData = [NSData dataWithBytesNoCopy:&start
length:sizeof(double)
freeWhenDone:NO];
CPMutableNumericData *numericData = [[CPMutableNumericData alloc] initWithData:startData
dataType:CPDataType(CPFloatingPointDataType, sizeof(double), hostByteOrder)
shape:nil];
numericData.byteOrder = swappedByteOrder;
uint64_t end = *(const uint64_t *)numericData.bytes;
union swap {
double v;
CFSwappedFloat64 sv;
} result;
result.v = start;
STAssertEquals(CFSwapInt64(result.sv.v), end, @"Bytes swapped");
numericData.byteOrder = hostByteOrder;
double startRoundTrip = *(const double *)numericData.bytes;
STAssertEquals(start, startRoundTrip, @"Round trip");
[numericData release];
}
@end
| 08iteng-ipad | framework/Source/CPMutableNumericDataTypeConversionTests.m | Objective-C | bsd | 7,716 |
#import "CPLayoutManager.h"
| 08iteng-ipad | framework/Source/CPLayoutManager.m | Objective-C | bsd | 28 |
#import "CPAxisLabelTests.h"
#import "CPAxisLabel.h"
#import "CPMutableTextStyle.h"
#import "CPFill.h"
#import "CPBorderedLayer.h"
#import "CPColor.h"
#import "CPExceptions.h"
static const double precision = 1.0e-6;
@implementation CPAxisLabelTests
static CGPoint roundPoint(CGPoint position, CGSize contentSize, CGPoint anchor);
static CGPoint roundPoint(CGPoint position, CGSize contentSize, CGPoint anchor)
{
CGPoint newPosition = position;
newPosition.x = round(newPosition.x) - round(contentSize.width * anchor.x) + (contentSize.width * anchor.x);
newPosition.y = round(newPosition.y) - round(contentSize.height * anchor.y) + (contentSize.height * anchor.y);
return newPosition;
}
-(void)testPositionRelativeToViewPointRaisesForInvalidDirection
{
CPAxisLabel *label;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionRelativeToViewPointRaisesForInvalidDirection" textStyle:[CPTextStyle textStyle]];
STAssertThrowsSpecificNamed([label positionRelativeToViewPoint:CGPointZero forCoordinate:CPCoordinateX inDirection:INT_MAX], NSException, NSInvalidArgumentException, @"Should raise NSInvalidArgumentException for invalid direction (type CPSign)");
}
@finally {
[label release];
}
}
-(void)testPositionRelativeToViewPointPositionsForXCoordinate
{
CPAxisLabel *label;
CGFloat start = 100.0;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionRelativeToViewPointPositionsForXCoordinate" textStyle:[CPTextStyle textStyle]];
CPLayer *contentLayer = label.contentLayer;
CGSize contentSize = contentLayer.bounds.size;
label.offset = 20.0;
CGPoint viewPoint = CGPointMake(start, start);
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateX
inDirection:CPSignNone];
CGPoint newPosition = roundPoint(CGPointMake(start-label.offset, start), contentSize, contentLayer.anchorPoint);
STAssertEquals(contentLayer.position, newPosition, @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSPointFromCGPoint(newPosition)));
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.x, (CGFloat)1.0, precision, @"Should anchor at (1.0,0.5)");
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.y, (CGFloat)0.5, precision, @"Should anchor at (1.0,0.5)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateX
inDirection:CPSignNegative];
newPosition = roundPoint(CGPointMake(start-label.offset, start), contentSize, contentLayer.anchorPoint);
STAssertEquals(contentLayer.position, newPosition, @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSPointFromCGPoint(newPosition)));
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.x, (CGFloat)1.0, precision, @"Should anchor at (1.0,0.5)");
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.y, (CGFloat)0.5, precision, @"Should anchor at (1.0,0.5)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateX
inDirection:CPSignPositive];
newPosition = roundPoint(CGPointMake(start+label.offset, start), contentSize, contentLayer.anchorPoint);
STAssertEquals(contentLayer.position, newPosition, @"Should add positive offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSPointFromCGPoint(newPosition)));
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.x, (CGFloat)0.0, precision, @"Should anchor at (0.0,0.5)");
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.y, (CGFloat)0.5, precision, @"Should anchor at (0.0,0.5)");
}
@finally {
[label release];
}
}
-(void)testPositionRelativeToViewPointPositionsForYCoordinate
{
CPAxisLabel *label;
CGFloat start = 100.0;
@try {
label = [[CPAxisLabel alloc] initWithText:@"CPAxisLabelTests-testPositionRelativeToViewPointPositionsForYCoordinate" textStyle:[CPTextStyle textStyle]];
CPLayer *contentLayer = label.contentLayer;
CGSize contentSize = contentLayer.bounds.size;
label.offset = 20.0;
CGPoint viewPoint = CGPointMake(start,start);
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateY
inDirection:CPSignNone];
CGPoint newPosition = roundPoint(CGPointMake(start, start-label.offset), contentSize, contentLayer.anchorPoint);
STAssertEquals(contentLayer.position, newPosition, @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSPointFromCGPoint(newPosition)));
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.x, (CGFloat)0.5, precision, @"Should anchor at (0.5,1.0)");
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.y, (CGFloat)1.0, precision, @"Should anchor at (0.5,1.0)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateY
inDirection:CPSignNegative];
newPosition = roundPoint(CGPointMake(start, start-label.offset), contentSize, contentLayer.anchorPoint);
STAssertEquals(contentLayer.position, newPosition, @"Should add negative offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSPointFromCGPoint(newPosition)));
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.x, (CGFloat)0.5, precision, @"Should anchor at (0.5,1.0)");
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.y, (CGFloat)1.0, precision, @"Should anchor at (0.5,1.0)");
contentLayer.anchorPoint = CGPointZero;
contentLayer.position = CGPointZero;
[label positionRelativeToViewPoint:viewPoint
forCoordinate:CPCoordinateY
inDirection:CPSignPositive];
newPosition = roundPoint(CGPointMake(start, start+label.offset), contentSize, contentLayer.anchorPoint);
STAssertEquals(contentLayer.position, newPosition, @"Should add positive offset, %@ != %@", NSStringFromPoint(NSPointFromCGPoint(contentLayer.position)), NSStringFromPoint(NSPointFromCGPoint(newPosition)));
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.x, (CGFloat)0.5, precision, @"Should anchor at (0.5,0)");
STAssertEqualsWithAccuracy(contentLayer.anchorPoint.y, (CGFloat)0.0, precision, @"Should anchor at (0.5,0)");
}
@finally {
[label release];
}
}
@end
| 08iteng-ipad | framework/Source/CPAxisLabelTests.m | Objective-C | bsd | 7,421 |
#import "CPLayer.h"
@class CPAnnotation;
@interface CPAnnotationHostLayer : CPLayer {
@private
NSMutableArray *mutableAnnotations;
}
@property (nonatomic, readonly, retain) NSArray *annotations;
-(void)addAnnotation:(CPAnnotation *)annotation;
-(void)removeAnnotation:(CPAnnotation *)annotation;
-(void)removeAllAnnotations;
@end
| 08iteng-ipad | framework/Source/CPAnnotationHostLayer.h | Objective-C | bsd | 337 |
#import "CPNumericData.h"
#import "CPMutableNumericData.h"
#import "CPExceptions.h"
/** @cond */
@interface CPMutableNumericData()
-(void)commonInitWithData:(NSData *)newData
dataType:(CPNumericDataType)newDataType
shape:(NSArray *)shapeArray;
@end
/** @endcond */
#pragma mark -
/** @brief An annotated NSMutableData type.
*
* CPNumericData combines a mutable data buffer with information
* about the data (shape, data type, size, etc.).
* The data is assumed to be an array of one or more dimensions
* of a single type of numeric data. Each numeric value in the array,
* which can be more than one byte in size, is referred to as a "sample".
* The structure of this object is similar to the NumPy ndarray
* object.
**/
@implementation CPMutableNumericData
/** @property mutableBytes
* @brief Returns a pointer to the data buffer’s contents.
**/
@dynamic mutableBytes;
/** @property shape
* @brief The shape of the data buffer array.
*
* The shape describes the dimensions of the sample array stored in
* the data buffer. Each entry in the shape array represents the
* size of the corresponding array dimension and should be an unsigned
* integer encoded in an instance of NSNumber.
**/
@dynamic shape;
#pragma mark -
#pragma mark Factory Methods
/** @brief Creates and returns a new CPMutableNumericData instance.
* @param newData The data buffer.
* @param newDataType The type of data stored in the buffer.
* @param shapeArray The shape of the data buffer array.
* @return A new CPMutableNumericData instance.
**/
+(CPMutableNumericData *)numericDataWithData:(NSData *)newData
dataType:(CPNumericDataType)newDataType
shape:(NSArray *)shapeArray
{
return [[[CPMutableNumericData alloc] initWithData:newData
dataType:newDataType
shape:shapeArray]
autorelease];
}
/** @brief Creates and returns a new CPMutableNumericData instance.
* @param newData The data buffer.
* @param newDataTypeString The type of data stored in the buffer.
* @param shapeArray The shape of the data buffer array.
* @return A new CPMutableNumericData instance.
**/
+(CPMutableNumericData *)numericDataWithData:(NSData *)newData
dataTypeString:(NSString *)newDataTypeString
shape:(NSArray *)shapeArray
{
return [[[CPMutableNumericData alloc] initWithData:newData
dataType:CPDataTypeWithDataTypeString(newDataTypeString)
shape:shapeArray]
autorelease];
}
#pragma mark -
#pragma mark Init/Dealloc
/** @brief Initializes a newly allocated CPMutableNumericData object with the provided data. This is the designated initializer.
* @param newData The data buffer.
* @param newDataType The type of data stored in the buffer.
* @param shapeArray The shape of the data buffer array.
* @return The initialized CPMutableNumericData instance.
**/
-(id)initWithData:(NSData *)newData
dataType:(CPNumericDataType)newDataType
shape:(NSArray *)shapeArray
{
if ( self = [super init] ) {
[self commonInitWithData:newData
dataType:newDataType
shape:shapeArray];
}
return self;
}
-(void)commonInitWithData:(NSData *)newData
dataType:(CPNumericDataType)newDataType
shape:(NSArray *)shapeArray
{
NSParameterAssert(CPDataTypeIsSupported(newDataType));
data = [newData mutableCopy];
dataType = newDataType;
if ( shapeArray == nil ) {
shape = [[NSArray arrayWithObject:[NSNumber numberWithUnsignedInteger:self.numberOfSamples]] retain];
}
else {
NSUInteger prod = 1;
for ( NSNumber *cNum in shapeArray ) {
prod *= [cNum unsignedIntegerValue];
}
if ( prod != self.numberOfSamples ) {
[NSException raise:CPNumericDataException
format:@"Shape product (%u) does not match data size (%u)", prod, self.numberOfSamples];
}
shape = [shapeArray copy];
}
}
#pragma mark -
#pragma mark Accessors
-(void *)mutableBytes
{
return [(NSMutableData *)self.data mutableBytes];
}
#pragma mark -
#pragma mark NSMutableCopying
-(id)mutableCopyWithZone:(NSZone *)zone
{
if ( NSShouldRetainWithZone(self, zone)) {
return [self retain];
}
return [[CPMutableNumericData allocWithZone:zone] initWithData:self.data
dataType:self.dataType
shape:self.shape];
}
#pragma mark -
#pragma mark NSCopying
-(id)copyWithZone:(NSZone *)zone
{
return [[[self class] allocWithZone:zone] initWithData:self.data
dataType:self.dataType
shape:self.shape];
}
#pragma mark -
#pragma mark NSCoding
-(void)encodeWithCoder:(NSCoder *)encoder
{
//[super encodeWithCoder:encoder];
if ( [encoder allowsKeyedCoding] ) {
[encoder encodeObject:self.data forKey:@"data"];
CPNumericDataType selfDataType = self.dataType;
[encoder encodeInteger:selfDataType.dataTypeFormat forKey:@"dataType.dataTypeFormat"];
[encoder encodeInteger:selfDataType.sampleBytes forKey:@"dataType.sampleBytes"];
[encoder encodeInteger:selfDataType.byteOrder forKey:@"dataType.byteOrder"];
[encoder encodeObject:self.shape forKey:@"shape"];
}
else {
[encoder encodeObject:self.data];
CPNumericDataType selfDataType = self.dataType;
[encoder encodeValueOfObjCType:@encode(CPDataTypeFormat) at:&(selfDataType.dataTypeFormat)];
[encoder encodeValueOfObjCType:@encode(NSUInteger) at:&(selfDataType.sampleBytes)];
[encoder encodeValueOfObjCType:@encode(CFByteOrder) at:&(selfDataType.byteOrder)];
[encoder encodeObject:self.shape];
}
}
-(id)initWithCoder:(NSCoder *)decoder
{
if ( self = [super init] ) {
NSData *newData;
CPNumericDataType newDataType;
NSArray *shapeArray;
if ( [decoder allowsKeyedCoding] ) {
newData = [decoder decodeObjectForKey:@"data"];
newDataType = CPDataType([decoder decodeIntegerForKey:@"dataType.dataTypeFormat"],
[decoder decodeIntegerForKey:@"dataType.sampleBytes"],
[decoder decodeIntegerForKey:@"dataType.byteOrder"]);
shapeArray = [decoder decodeObjectForKey:@"shape"];
}
else {
newData = [decoder decodeObject];
[decoder decodeValueOfObjCType:@encode(CPDataTypeFormat) at:&(newDataType.dataTypeFormat)];
[decoder decodeValueOfObjCType:@encode(NSUInteger) at:&(newDataType.sampleBytes)];
[decoder decodeValueOfObjCType:@encode(CFByteOrder) at:&(newDataType.byteOrder)];
shapeArray = [decoder decodeObject];
}
[self commonInitWithData:newData dataType:newDataType shape:shapeArray];
}
return self;
}
@end
| 08iteng-ipad | framework/Source/CPMutableNumericData.m | Objective-C | bsd | 6,858 |
#import "CPLayerAnnotation.h"
#import "CPAnnotationHostLayer.h"
#import "CPConstrainedPosition.h"
#import "CPLayer.h"
/** @cond */
@interface CPLayerAnnotation()
@property (nonatomic, readwrite, retain) CPConstrainedPosition *xConstrainedPosition;
@property (nonatomic, readwrite, retain) CPConstrainedPosition *yConstrainedPosition;
-(void)setConstraints;
@end
/** @endcond */
#pragma mark -
/** @brief Positions a content layer relative to some anchor point in a reference layer.
* @todo More documentation needed
**/
@implementation CPLayerAnnotation
/** @property anchorLayer
* @brief The reference layer.
**/
@synthesize anchorLayer;
/** @property rectAnchor
* @brief The anchor position for the annotation.
**/
@synthesize rectAnchor;
@synthesize xConstrainedPosition;
@synthesize yConstrainedPosition;
#pragma mark -
#pragma mark Init/Dealloc
/** @brief Initializes a newly allocated CPLayerAnnotation object with the provided reference layer.
*
* This is the designated initializer. The initialized layer will be anchored to
* CPRectAnchor#CPRectAnchorTop by default.
*
* @param newAnchorLayer The reference layer.
* @return The initialized CPLayerAnnotation object.
**/
-(id)initWithAnchorLayer:(CPLayer *)newAnchorLayer
{
if ( self = [super init] ) {
anchorLayer = newAnchorLayer;
rectAnchor = CPRectAnchorTop;
xConstrainedPosition = nil;
yConstrainedPosition = nil;
[self setConstraints];
}
return self;
}
-(void)dealloc
{
anchorLayer = nil;
[xConstrainedPosition release];
[yConstrainedPosition release];
[super dealloc];
}
#pragma mark -
#pragma mark Layout
-(void)positionContentLayer
{
CPLayer *content = self.contentLayer;
if ( content ) {
CPAnnotationHostLayer *hostLayer = self.annotationHostLayer;
if ( hostLayer ) {
if ( !self.xConstrainedPosition || !self.yConstrainedPosition ) {
[self setConstraints];
}
CGFloat myRotation = self.rotation;
CGPoint anchor = self.contentAnchorPoint;
CPLayer *theAnchorLayer = self.anchorLayer;
CGRect anchorLayerBounds = theAnchorLayer.bounds;
CPConstrainedPosition *xConstraint = self.xConstrainedPosition;
CPConstrainedPosition *yConstraint = self.yConstrainedPosition;
xConstraint.lowerBound = CGRectGetMinX(anchorLayerBounds);
xConstraint.upperBound = CGRectGetMaxX(anchorLayerBounds);
yConstraint.lowerBound = CGRectGetMinY(anchorLayerBounds);
yConstraint.upperBound = CGRectGetMaxY(anchorLayerBounds);
CGPoint referencePoint = CGPointMake(xConstraint.position, yConstraint.position);
CGPoint newPosition = [theAnchorLayer convertPoint:referencePoint toLayer:hostLayer];
CGPoint offset = self.displacement;
newPosition.x = round(newPosition.x + offset.x);
newPosition.y = round(newPosition.y + offset.y);
// Pixel-align the label layer to prevent blurriness
if ( myRotation == 0.0 ) {
CGSize currentSize = content.bounds.size;
newPosition.x = newPosition.x - round(currentSize.width * anchor.x) + (currentSize.width * anchor.x);
newPosition.y = newPosition.y - round(currentSize.height * anchor.y) + (currentSize.height * anchor.y);
}
content.anchorPoint = anchor;
content.position = newPosition;
content.transform = CATransform3DMakeRotation(myRotation, 0.0, 0.0, 1.0);
[content setNeedsDisplay];
}
}
}
#pragma mark -
#pragma mark Constraints
-(void)setConstraints
{
CGRect anchorBounds = self.anchorLayer.bounds;
if ( CGRectIsEmpty(anchorBounds) ) return;
CPAlignment xAlign, yAlign;
switch ( self.rectAnchor ) {
case CPRectAnchorRight:
xAlign = CPAlignmentRight;
yAlign = CPAlignmentMiddle;
break;
case CPRectAnchorTopRight:
xAlign = CPAlignmentRight;
yAlign = CPAlignmentTop;
break;
case CPRectAnchorTop:
xAlign = CPAlignmentCenter;
yAlign = CPAlignmentTop;
break;
case CPRectAnchorTopLeft:
xAlign = CPAlignmentLeft;
yAlign = CPAlignmentTop;
break;
case CPRectAnchorLeft:
xAlign = CPAlignmentLeft;
yAlign = CPAlignmentMiddle;
break;
case CPRectAnchorBottomLeft:
xAlign = CPAlignmentLeft;
yAlign = CPAlignmentBottom;
break;
case CPRectAnchorBottom:
xAlign = CPAlignmentCenter;
yAlign = CPAlignmentBottom;
break;
case CPRectAnchorBottomRight:
xAlign = CPAlignmentRight;
yAlign = CPAlignmentBottom;
break;
case CPRectAnchorCenter:
xAlign = CPAlignmentCenter;
yAlign = CPAlignmentMiddle;
break;
default:
xAlign = CPAlignmentCenter;
yAlign = CPAlignmentMiddle;
break;
}
[xConstrainedPosition release];
xConstrainedPosition = [[CPConstrainedPosition alloc] initWithAlignment:xAlign lowerBound:CGRectGetMinX(anchorBounds) upperBound:CGRectGetMaxX(anchorBounds)];
[yConstrainedPosition release];
yConstrainedPosition = [[CPConstrainedPosition alloc] initWithAlignment:yAlign lowerBound:CGRectGetMinY(anchorBounds) upperBound:CGRectGetMaxY(anchorBounds)];
}
#pragma mark -
#pragma mark Accessors
-(void)setRectAnchor:(CPRectAnchor)newAnchor
{
if ( newAnchor != rectAnchor ) {
rectAnchor = newAnchor;
[self setConstraints];
[self positionContentLayer];
}
}
@end
| 08iteng-ipad | framework/Source/CPLayerAnnotation.m | Objective-C | bsd | 5,546 |
#import <Foundation/Foundation.h>
#import "CPPlot.h"
#import "CPDefinitions.h"
/// @file
@class CPLineStyle;
@class CPMutableNumericData;
@class CPNumericData;
@class CPFill;
@class CPPlotRange;
@class CPColor;
@class CPBarPlot;
@class CPTextLayer;
@class CPTextStyle;
/// @name Binding Identifiers
/// @{
extern NSString * const CPBarPlotBindingBarLocations;
extern NSString * const CPBarPlotBindingBarTips;
extern NSString * const CPBarPlotBindingBarBases;
/// @}
/** @brief Enumeration of bar plot data source field types
**/
typedef enum _CPBarPlotField {
CPBarPlotFieldBarLocation = 2, ///< Bar location on independent coordinate axis.
CPBarPlotFieldBarTip = 3, ///< Bar tip value.
CPBarPlotFieldBarBase = 4 ///< Bar base (if baseValue is nil.)
} CPBarPlotField;
#pragma mark -
/** @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;
/** @brief Gets a bar label for the given bar plot. This method is no longer used.
* @param barPlot The bar plot.
* @param index The data index of interest.
* @return The bar label for the point with the given index.
* If you return nil, the default bar label will be used. If you return an instance of NSNull,
* no label will be shown for the index in question.
* @deprecated This method has been replaced by the CPPlotDataSource::dataLabelForPlot:recordIndex: method and is no longer used.
**/
-(CPTextLayer *)barLabelForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSUInteger)index;
@end
#pragma mark -
/** @brief Bar plot delegate.
**/
@protocol CPBarPlotDelegate <NSObject>
@optional
// @name Point selection
/// @{
/** @brief Informs delegate that a point was touched.
* @param plot The scatter plot.
* @param index Index of touched point
**/
-(void)barPlot:(CPBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index;
/// @}
@end
#pragma mark -
@interface CPBarPlot : CPPlot {
@private
CPLineStyle *lineStyle;
CPFill *fill;
NSDecimal barWidth;
NSDecimal barOffset;
CGFloat barCornerRadius;
NSDecimal baseValue;
BOOL barsAreHorizontal;
BOOL barBasesVary;
BOOL barWidthsAreInViewCoordinates;
CPPlotRange *plotRange;
}
@property (nonatomic, readwrite, assign) BOOL barWidthsAreInViewCoordinates;
@property (nonatomic, readwrite, assign) NSDecimal barWidth;
@property (nonatomic, readwrite, assign) NSDecimal barOffset;
@property (nonatomic, readwrite, assign) CGFloat barCornerRadius;
@property (nonatomic, readwrite, copy) CPLineStyle *lineStyle;
@property (nonatomic, readwrite, copy) CPFill *fill;
@property (nonatomic, readwrite, assign) BOOL barsAreHorizontal;
@property (nonatomic, readwrite, assign) NSDecimal baseValue;
@property (nonatomic, readwrite, assign) BOOL barBasesVary;
@property (nonatomic, readwrite, copy) CPPlotRange *plotRange;
@property (nonatomic, readwrite, assign) CGFloat barLabelOffset;
@property (nonatomic, readwrite, copy) CPTextStyle *barLabelTextStyle;
/// @name Factory Methods
/// @{
+(CPBarPlot *)tubularBarPlotWithColor:(CPColor *)color horizontalBars:(BOOL)horizontal;
/// @}
@end
| 08iteng-ipad | framework/Source/CPBarPlot.h | Objective-C | bsd | 3,409 |
#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, midy);
CGPathAddArcToPoint(path, NULL, minx, miny, midx, miny, cornerRadius);
CGPathAddArcToPoint(path, NULL, maxx, miny, maxx, midy, cornerRadius);
CGPathAddArcToPoint(path, NULL, maxx, maxy, midx, maxy, cornerRadius);
CGPathAddArcToPoint(path, NULL, minx, maxy, minx, midy, 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 | framework/Source/CPPathExtensions.m | Objective-C | bsd | 1,688 |
#import "NSExceptionExtensions.h"
@implementation NSException(CPExtensions)
/** @brief Raises an NSGenericException with the given format and arguments.
* @param fmt The format string using standard printf formatting codes.
**/
+(void)raiseGenericFormat:(NSString*)fmt,...
{
va_list args;
va_start(args, fmt);
[self raise:NSGenericException
format:fmt
arguments:args];
va_end(args);
}
@end
| 08iteng-ipad | framework/Source/NSExceptionExtensions.m | Objective-C | bsd | 409 |
#import <Foundation/Foundation.h>
#import "CPLineStyle.h"
#import "CPFill.h"
#import "CPPlotSymbol.h"
/** @cond */
@interface CPPlotSymbol()
@property (nonatomic, readwrite, assign) CGPathRef cachedSymbolPath;
@property (nonatomic, readwrite, assign) CGLayerRef cachedLayer;
-(CGPathRef)newSymbolPath;
@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;
@dynamic cachedSymbolPath;
@synthesize cachedLayer;
#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;
cachedSymbolPath = NULL;
customSymbolPath = NULL;
usesEvenOddClipRule = NO;
cachedLayer = NULL;
}
return self;
}
-(void)dealloc
{
[lineStyle release];
[fill release];
CGPathRelease(cachedSymbolPath);
CGPathRelease(customSymbolPath);
CGLayerRelease(cachedLayer);
[super dealloc];
}
-(void)finalize
{
CGPathRelease(cachedSymbolPath);
CGPathRelease(customSymbolPath);
CGLayerRelease(cachedLayer);
[super finalize];
}
#pragma mark -
#pragma mark Accessors
-(void)setSize:(CGSize)newSize
{
if ( !CGSizeEqualToSize(newSize, size) ) {
size = newSize;
self.cachedSymbolPath = NULL;
}
}
-(void)setSymbolType:(CPPlotSymbolType)newType
{
if ( newType != symbolType ) {
symbolType = newType;
self.cachedSymbolPath = NULL;
}
}
-(void)setCustomSymbolPath:(CGPathRef)newPath
{
if ( customSymbolPath != newPath ) {
CGPathRelease(customSymbolPath);
customSymbolPath = CGPathRetain(newPath);
self.cachedSymbolPath = NULL;
}
}
-(CGPathRef)cachedSymbolPath
{
if ( !cachedSymbolPath ) {
cachedSymbolPath = [self newSymbolPath];
}
return cachedSymbolPath;
}
-(void)setCachedSymbolPath:(CGPathRef)newPath
{
if ( cachedSymbolPath != newPath ) {
CGPathRelease(cachedSymbolPath);
cachedSymbolPath = CGPathRetain(newPath);
self.cachedLayer = NULL;
}
}
-(void)setCachedLayer:(CGLayerRef)newLayer
{
if ( cachedLayer != newLayer ) {
CGLayerRelease(cachedLayer);
cachedLayer = CGLayerRetain(newLayer);
}
}
#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];
}
#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
{
CGLayerRef theCachedLayer = self.cachedLayer;
if ( !theCachedLayer ) {
const CGFloat symbolMargin = 2.0;
CGSize symbolSize = CGPathGetBoundingBox(self.cachedSymbolPath).size;
CGFloat lineWidth = self.lineStyle.lineWidth;
symbolSize.width += lineWidth + symbolMargin;
symbolSize.height += lineWidth + symbolMargin;
theCachedLayer = CGLayerCreateWithContext(theContext, symbolSize, NULL);
[self renderAsVectorInContext:CGLayerGetContext(theCachedLayer)
atPoint:CGPointMake(symbolSize.width / 2.0, symbolSize.height / 2.0)];
self.cachedLayer = theCachedLayer;
CGLayerRelease(theCachedLayer);
}
if ( theCachedLayer ) {
CGSize layerSize = CGLayerGetSize(theCachedLayer);
CGContextDrawLayerAtPoint(theContext, CGPointMake(center.x - layerSize.width / 2.0, center.y - layerSize.height / 2.0), theCachedLayer);
}
}
-(void)renderAsVectorInContext:(CGContextRef)theContext atPoint:(CGPoint)center
{
CGPathRef theSymbolPath = self.cachedSymbolPath;
if ( theSymbolPath ) {
CPLineStyle *theLineStyle = nil;
CPFill *theFill = nil;
switch ( self.symbolType ) {
case CPPlotSymbolTypeRectangle:
case CPPlotSymbolTypeEllipse:
case CPPlotSymbolTypeDiamond:
case CPPlotSymbolTypeTriangle:
case CPPlotSymbolTypeStar:
case CPPlotSymbolTypePentagon:
case CPPlotSymbolTypeHexagon:
case CPPlotSymbolTypeCustom:
theLineStyle = self.lineStyle;
theFill = self.fill;
break;
case CPPlotSymbolTypeCross:
case CPPlotSymbolTypePlus:
case CPPlotSymbolTypeDash:
case CPPlotSymbolTypeSnow:
theLineStyle = self.lineStyle;
break;
default:
break;
}
if ( theLineStyle || theFill ) {
CGContextSaveGState(theContext);
CGContextTranslateCTM(theContext, center.x, center.y);
if ( theFill ) {
// 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, theSymbolPath);
if ( self.usesEvenOddClipRule ) {
CGContextEOClip(theContext);
}
else {
CGContextClip(theContext);
}
[theFill fillRect:bounds inContext:theContext];
CGContextRestoreGState(theContext);
}
if ( theLineStyle ) {
[theLineStyle setLineStyleInContext:theContext];
CGContextBeginPath(theContext);
CGContextAddPath(theContext, theSymbolPath);
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.
**/
-(CGPathRef)newSymbolPath
{
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);
CGMutablePathRef symbolPath = CGPathCreateMutable();
switch ( self.symbolType ) {
case CPPlotSymbolTypeNone:
// empty path
break;
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: {
CGPathRef customPath = self.customSymbolPath;
if ( customPath ) {
CGRect oldBounds = CGRectNull;
CGAffineTransform scaleTransform = CGAffineTransformIdentity;
oldBounds = CGPathGetBoundingBox(customPath);
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, customPath);
}
}
break;
}
return symbolPath;
}
@end
| 08iteng-ipad | framework/Source/CPPlotSymbol.m | Objective-C | bsd | 17,836 |
#import "CPTestCase.h"
@implementation CPTestCase
@end
| 08iteng-ipad | framework/Source/CPTestCase.m | Objective-C | bsd | 57 |
#import <Foundation/Foundation.h>
#import "CPPlot.h"
#import "CPDefinitions.h"
/// @file
@class CPLineStyle;
@class CPMutableNumericData;
@class CPNumericData;
@class CPTradingRangePlot;
@class CPFill;
/// @name Binding Identifiers
/// @{
extern NSString * const CPTradingRangePlotBindingXValues;
extern NSString * const CPTradingRangePlotBindingOpenValues;
extern NSString * const CPTradingRangePlotBindingHighValues;
extern NSString * const CPTradingRangePlotBindingLowValues;
extern NSString * const CPTradingRangePlotBindingCloseValues;
/// @}
/** @brief Enumeration of Quote plot render style types
**/
typedef enum _CPTradingRangePlotStyle {
CPTradingRangePlotStyleOHLC, ///< OHLC
CPTradingRangePlotStyleCandleStick ///< Candle
} CPTradingRangePlotStyle;
/** @brief Enumeration of Quote plot data source field types
**/
typedef enum _CPTradingRangePlotField {
CPTradingRangePlotFieldX, ///< X values.
CPTradingRangePlotFieldOpen, ///< Open values.
CPTradingRangePlotFieldHigh, ///< High values.
CPTradingRangePlotFieldLow , ///< Low values.
CPTradingRangePlotFieldClose ///< Close values.
} CPTradingRangePlotField;
#pragma mark -
@interface CPTradingRangePlot : CPPlot {
@private
CPLineStyle *lineStyle;
CPFill *increaseFill;
CPFill *decreaseFill;
CPTradingRangePlotStyle plotStyle;
CGFloat barWidth;
CGFloat stickLength;
CGFloat barCornerRadius;
}
@property (nonatomic, readwrite, copy) CPLineStyle *lineStyle;
@property (nonatomic, readwrite, copy) CPFill *increaseFill;
@property (nonatomic, readwrite, copy) CPFill *decreaseFill;
@property (nonatomic, readwrite, assign) CPTradingRangePlotStyle plotStyle;
@property (nonatomic, readwrite, assign) CGFloat barWidth; // In view coordinates
@property (nonatomic, readwrite, assign) CGFloat stickLength; // In view coordinates
@property (nonatomic, readwrite, assign) CGFloat barCornerRadius;
@end
| 08iteng-ipad | framework/Source/CPTradingRangePlot.h | Objective-C | bsd | 1,918 |
#import "CPDerivedXYGraph.h"
/** @brief An empty XY graph class used for testing themes.
**/
@implementation CPDerivedXYGraph
@end
| 08iteng-ipad | framework/Source/CPDerivedXYGraph.m | Objective-C | bsd | 134 |
#import "CPStocksTheme.h"
#import "CPXYGraph.h"
#import "CPColor.h"
#import "CPGradient.h"
#import "CPFill.h"
#import "CPPlotAreaFrame.h"
#import "CPXYPlotSpace.h"
#import "CPUtilities.h"
#import "CPXYAxisSet.h"
#import "CPXYAxis.h"
#import "CPMutableLineStyle.h"
#import "CPMutableTextStyle.h"
#import "CPBorderedLayer.h"
#import "CPExceptions.h"
/** @brief Creates a CPXYGraph instance formatted with a gradient background and white lines.
**/
@implementation CPStocksTheme
+(NSString *)defaultName
{
return kCPStocksTheme;
}
-(void)applyThemeToBackground:(CPXYGraph *)graph
{
graph.fill = [CPFill fillWithColor:[CPColor blackColor]];
}
-(void)applyThemeToPlotArea:(CPPlotAreaFrame *)plotAreaFrame
{
CPGradient *stocksBackgroundGradient = [[[CPGradient alloc] init] autorelease];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.21569 green:0.28627 blue:0.44706 alpha:1.0] atPosition:0.0];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.09412 green:0.17255 blue:0.36078 alpha:1.0] atPosition:0.5];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.05882 green:0.13333 blue:0.33333 alpha:1.0] atPosition:0.5];
stocksBackgroundGradient = [stocksBackgroundGradient addColorStop:[CPColor colorWithComponentRed:0.05882 green:0.13333 blue:0.33333 alpha:1.0] atPosition:1.0];
stocksBackgroundGradient.angle = 270.0;
plotAreaFrame.fill = [CPFill fillWithGradient:stocksBackgroundGradient];
CPMutableLineStyle *borderLineStyle = [CPMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPColor colorWithGenericGray:0.2];
borderLineStyle.lineWidth = 0.0;
plotAreaFrame.borderLineStyle = borderLineStyle;
plotAreaFrame.cornerRadius = 14.0;
}
-(void)applyThemeToAxisSet:(CPXYAxisSet *)axisSet
{
CPMutableLineStyle *majorLineStyle = [CPMutableLineStyle lineStyle];
majorLineStyle.lineCap = kCGLineCapRound;
majorLineStyle.lineColor = [CPColor whiteColor];
majorLineStyle.lineWidth = 3.0;
CPMutableLineStyle *minorLineStyle = [CPMutableLineStyle lineStyle];
minorLineStyle.lineColor = [CPColor whiteColor];
minorLineStyle.lineWidth = 3.0;
CPXYAxis *x = axisSet.xAxis;
CPMutableTextStyle *whiteTextStyle = [[[CPMutableTextStyle alloc] init] autorelease];
whiteTextStyle.color = [CPColor whiteColor];
whiteTextStyle.fontSize = 14.0;
CPMutableTextStyle *minorTickWhiteTextStyle = [[[CPMutableTextStyle alloc] init] autorelease];
minorTickWhiteTextStyle.color = [CPColor whiteColor];
minorTickWhiteTextStyle.fontSize = 12.0;
x.labelingPolicy = CPAxisLabelingPolicyFixedInterval;
x.majorIntervalLength = CPDecimalFromDouble(0.5);
x.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0);
x.tickDirection = CPSignNone;
x.minorTicksPerInterval = 4;
x.majorTickLineStyle = majorLineStyle;
x.minorTickLineStyle = minorLineStyle;
x.axisLineStyle = majorLineStyle;
x.majorTickLength = 7.0;
x.minorTickLength = 5.0;
x.labelTextStyle = whiteTextStyle;
x.minorTickLabelTextStyle = minorTickWhiteTextStyle;
x.titleTextStyle = whiteTextStyle;
CPXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPAxisLabelingPolicyFixedInterval;
y.majorIntervalLength = CPDecimalFromDouble(0.5);
y.minorTicksPerInterval = 4;
y.orthogonalCoordinateDecimal = CPDecimalFromDouble(0.0);
y.tickDirection = CPSignNone;
y.majorTickLineStyle = majorLineStyle;
y.minorTickLineStyle = minorLineStyle;
y.axisLineStyle = majorLineStyle;
y.majorTickLength = 7.0;
y.minorTickLength = 5.0;
y.labelTextStyle = whiteTextStyle;
y.minorTickLabelTextStyle = minorTickWhiteTextStyle;
y.titleTextStyle = whiteTextStyle;
}
@end
| 08iteng-ipad | framework/Source/CPStocksTheme.m | Objective-C | bsd | 3,787 |
/*! @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 | framework/Source/mainpage.h | C | bsd | 2,042 |
dataTypes = ["CPUndefinedDataType", "CPIntegerDataType", "CPUnsignedIntegerDataType", "CPFloatingPointDataType", "CPComplexFloatingPointDataType", "CPDecimalDataType"]
types = { "CPUndefinedDataType" : [],
"CPIntegerDataType" : ["int8_t", "int16_t", "int32_t", "int64_t"],
"CPUnsignedIntegerDataType" : ["uint8_t", "uint16_t", "uint32_t", "uint64_t"],
"CPFloatingPointDataType" : ["float", "double"],
"CPComplexFloatingPointDataType" : ["float complex", "double complex"],
"CPDecimalDataType" : ["NSDecimal"] }
nsnumber_factory = { "int8_t" : "Char",
"int16_t" : "Short",
"int32_t" : "Long",
"int64_t" : "LongLong",
"uint8_t" : "UnsignedChar",
"uint16_t" : "UnsignedShort",
"uint32_t" : "UnsignedLong",
"uint64_t" : "UnsignedLongLong",
"float" : "Float",
"double" : "Double",
"float complex" : "Float",
"double complex" : "Double",
"NSDecimal" : "Decimal"
}
nsnumber_methods = { "int8_t" : "char",
"int16_t" : "short",
"int32_t" : "long",
"int64_t" : "longLong",
"uint8_t" : "unsignedChar",
"uint16_t" : "unsignedShort",
"uint32_t" : "unsignedLong",
"uint64_t" : "unsignedLongLong",
"float" : "float",
"double" : "double",
"float complex" : "float",
"double complex" : "double",
"NSDecimal" : "decimal"
}
null_values = { "int8_t" : "0",
"int16_t" : "0",
"int32_t" : "0",
"int64_t" : "0",
"uint8_t" : "0",
"uint16_t" : "0",
"uint32_t" : "0",
"uint64_t" : "0",
"float" : "NAN",
"double" : "NAN",
"float complex" : "NAN",
"double complex" : "NAN",
"NSDecimal" : "CPDecimalNaN()"
}
print "[CPNumericData sampleValue:]"
print ""
print "switch ( self.dataTypeFormat ) {"
for dt in dataTypes:
print "\tcase %s:" % dt
if ( len(types[dt]) == 0 ):
print '\t\t[NSException raise:NSInvalidArgumentException format:@"Unsupported data type (%s)"];' % (dt)
else:
print "\t\tswitch ( self.sampleBytes ) {"
for t in types[dt]:
print "\t\t\tcase sizeof(%s):" % t
if ( t == "NSDecimal" ):
number_class = "NSDecimalNumber"
number_method = "decimalNumber"
else:
number_class = "NSNumber"
number_method = "number"
print "\t\t\t\tresult = [%s %sWith%s:*(%s *)[self samplePointer:sample]];" % (number_class, number_method, nsnumber_factory[t], t)
print "\t\t\t\tbreak;"
print "\t\t}"
print "\t\tbreak;"
print "}"
print "\n\n"
print "---------------"
print "\n\n"
print "[CPNumericData dataFromArray:dataType:]"
print ""
print "switch ( newDataType.dataTypeFormat ) {"
for dt in dataTypes:
print "\tcase %s:" % dt
if ( len(types[dt]) == 0 ):
print "\t\t// Unsupported"
else:
print "\t\tswitch ( newDataType.sampleBytes ) {"
for t in types[dt]:
print "\t\t\tcase sizeof(%s): {" % t
print "\t\t\t\t%s *toBytes = (%s *)sampleData.mutableBytes;" % (t, t)
print "\t\t\t\tfor ( id sample in newData ) {"
print "\t\t\t\t\tif ( [sample respondsToSelector:@selector(%sValue)] ) {" % nsnumber_methods[t]
print "\t\t\t\t\t\t*toBytes++ = (%s)[(NSNumber *)sample %sValue];" % (t, nsnumber_methods[t])
print "\t\t\t\t\t}"
print "\t\t\t\t\telse {"
print "\t\t\t\t\t\t*toBytes++ = %s;" % null_values[t]
print "\t\t\t\t\t}"
print "\t\t\t\t}"
print "\t\t\t}"
print "\t\t\t\tbreak;"
print "\t\t}"
print "\t\tbreak;"
print "}"
print "\n\n"
print "---------------"
print "\n\n"
print "[CPNumericData convertData:dataType:toData:dataType:]"
print ""
print "switch ( sourceDataType->dataTypeFormat ) {"
for dt in dataTypes:
print "\tcase %s:" % dt
if ( len(types[dt]) > 0 ):
print "\t\tswitch ( sourceDataType->sampleBytes ) {"
for t in types[dt]:
print "\t\t\tcase sizeof(%s):" % t
print "\t\t\t\tswitch ( destDataType->dataTypeFormat ) {"
for ndt in dataTypes:
print "\t\t\t\t\tcase %s:" % ndt
if ( len(types[ndt]) > 0 ):
print "\t\t\t\t\t\tswitch ( destDataType->sampleBytes ) {"
for nt in types[ndt]:
print "\t\t\t\t\t\t\tcase sizeof(%s): { // %s -> %s" % (nt, t, nt)
if ( t == nt ):
print "\t\t\t\t\t\t\t\t\tmemcpy(destData.mutableBytes, sourceData.bytes, sampleCount * sizeof(%s));" % t
else:
print "\t\t\t\t\t\t\t\t\tconst %s *fromBytes = (%s *)sourceData.bytes;" % (t, t)
print "\t\t\t\t\t\t\t\t\tconst %s *lastSample = fromBytes + sampleCount;" % t
print "\t\t\t\t\t\t\t\t\t%s *toBytes = (%s *)destData.mutableBytes;" % (nt, nt)
if ( t == "NSDecimal" ):
print "\t\t\t\t\t\t\t\t\twhile ( fromBytes < lastSample ) *toBytes++ = CPDecimal%sValue(*fromBytes++);" % nsnumber_factory[nt]
elif ( nt == "NSDecimal" ):
print "\t\t\t\t\t\t\t\t\twhile ( fromBytes < lastSample ) *toBytes++ = CPDecimalFrom%s(*fromBytes++);" % nsnumber_factory[t]
else:
print "\t\t\t\t\t\t\t\t\twhile ( fromBytes < lastSample ) *toBytes++ = (%s)*fromBytes++;" % nt
print "\t\t\t\t\t\t\t\t}"
print "\t\t\t\t\t\t\t\tbreak;"
print "\t\t\t\t\t\t}"
print "\t\t\t\t\t\tbreak;"
print "\t\t\t\t}"
print "\t\t\t\tbreak;"
print "\t\t}"
print "\t\tbreak;"
print "}"
| 08iteng-ipad | framework/Source/CPNumericData+TypeConversions_Generation.py | Python | bsd | 5,910 |
#import "CPAxis.h"
#import "CPAxisSet.h"
#import "CPGraph.h"
#import "CPLineStyle.h"
#import "CPPlotSpace.h"
#import "CPPlotArea.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 borderLineStyle
* @brief The line style for the layer border.
* If nil, the border is not drawn.
**/
@synthesize borderLineStyle;
#pragma mark -
#pragma mark Init/Dealloc
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
axes = [[NSArray array] retain];
borderLineStyle = nil;
self.needsDisplayOnBoundsChange = YES;
}
return self;
}
-(id)initWithLayer:(id)layer
{
if ( self = [super initWithLayer:layer] ) {
CPAxisSet *theLayer = (CPAxisSet *)layer;
axes = [theLayer->axes retain];
borderLineStyle = [theLayer->borderLineStyle retain];
}
return self;
}
-(void)dealloc
{
[axes release];
[borderLineStyle release];
[super dealloc];
}
#pragma mark -
#pragma mark Labeling
/** @brief Updates the axis labels for each axis in the axis set.
**/
-(void)relabelAxes
{
NSArray *theAxes = self.axes;
[theAxes makeObjectsPerformSelector:@selector(setNeedsLayout)];
[theAxes makeObjectsPerformSelector:@selector(setNeedsRelabel)];
}
#pragma mark -
#pragma mark Layout
+(CGFloat)defaultZPosition
{
return CPDefaultZPositionAxisSet;
}
-(void)layoutSublayers
{
[super layoutSublayers];
NSArray *theAxes = self.axes;
[theAxes makeObjectsPerformSelector:@selector(setNeedsLayout)];
[theAxes makeObjectsPerformSelector:@selector(setNeedsDisplay)];
}
#pragma mark -
#pragma mark Accessors
-(void)setAxes:(NSArray *)newAxes
{
if ( newAxes != axes ) {
for ( CPAxis *axis in axes ) {
[axis removeFromSuperlayer];
axis.plotArea = nil;
}
[newAxes retain];
[axes release];
axes = newAxes;
CPPlotArea *plotArea = (CPPlotArea *)self.superlayer;
for ( CPAxis *axis in axes ) {
[self addSublayer:axis];
axis.plotArea = plotArea;
}
[self setNeedsLayout];
[self setNeedsDisplay];
}
}
-(void)setBorderLineStyle:(CPLineStyle *)newLineStyle
{
if ( newLineStyle != borderLineStyle ) {
[borderLineStyle release];
borderLineStyle = [newLineStyle copy];
[self setNeedsDisplay];
}
}
@end
| 08iteng-ipad | framework/Source/CPAxisSet.m | Objective-C | bsd | 2,378 |
#import "CPTestCase.h"
@interface CPDarkGradientThemeTests : CPTestCase {
}
@end
| 08iteng-ipad | framework/Source/CPDarkGradientThemeTests.h | Objective-C | bsd | 83 |
#import <stdlib.h>
#import "CPMutableNumericData.h"
#import "CPNumericData.h"
#import "CPTradingRangePlot.h"
#import "CPLineStyle.h"
#import "CPPlotArea.h"
#import "CPPlotSpace.h"
#import "CPPlotSpaceAnnotation.h"
#import "CPExceptions.h"
#import "CPUtilities.h"
#import "CPXYPlotSpace.h"
#import "CPPlotSymbol.h"
#import "CPFill.h"
#import "CPColor.h"
NSString * const CPTradingRangePlotBindingXValues = @"xValues"; ///< X values.
NSString * const CPTradingRangePlotBindingOpenValues = @"openValues"; ///< Open price values.
NSString * const CPTradingRangePlotBindingHighValues = @"highValues"; ///< High price values.
NSString * const CPTradingRangePlotBindingLowValues = @"lowValues"; ///< Low price values.
NSString * const CPTradingRangePlotBindingCloseValues = @"closeValues"; ///< Close price values.
/** @cond */
@interface CPTradingRangePlot ()
@property (nonatomic, readwrite, copy) CPMutableNumericData *xValues;
@property (nonatomic, readwrite, copy) CPMutableNumericData *openValues;
@property (nonatomic, readwrite, copy) CPMutableNumericData *highValues;
@property (nonatomic, readwrite, copy) CPMutableNumericData *lowValues;
@property (nonatomic, readwrite, copy) CPMutableNumericData *closeValues;
-(void)drawCandleStickInContext:(CGContextRef)context x:(CGFloat)x open:(CGFloat)open close:(CGFloat)close high:(CGFloat)high low:(CGFloat)low;
-(void)drawOHLCInContext:(CGContextRef)context x:(CGFloat)x open:(CGFloat)open close:(CGFloat)close high:(CGFloat)high low:(CGFloat)low;
@end
/** @endcond */
#pragma mark -
/** @brief A trading range financial plot.
**/
@implementation CPTradingRangePlot
@dynamic xValues;
@dynamic openValues;
@dynamic highValues;
@dynamic lowValues;
@dynamic closeValues;
/** @property lineStyle
* @brief The line style used to draw candlestick or OHLC symbol
**/
@synthesize lineStyle;
/** @property increaseFill
* @brief The fill used with a candlestick plot when close >= open.
**/
@synthesize increaseFill;
/** @property decreaseFill
* @brief The fill used with a candlestick plot when close < open.
**/
@synthesize decreaseFill;
/** @property plotStyle
* @brief The style of trading range plot drawn.
**/
@synthesize plotStyle;
/** @property barWidth
* @brief The width of bars in candlestick plots (view coordinates).
**/
@synthesize barWidth;
/** @property stickLength
* @brief The length of close and open sticks on OHLC plots (view coordinates).
**/
@synthesize stickLength;
/** @property barCornerRadius
* @brief The corner radius used for candlestick plots.
* Defaults to 0.0.
**/
@synthesize barCornerRadius;
#pragma mark -
#pragma mark init/dealloc
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
+(void)initialize
{
if ( self == [CPTradingRangePlot class] ) {
[self exposeBinding:CPTradingRangePlotBindingXValues];
[self exposeBinding:CPTradingRangePlotBindingOpenValues];
[self exposeBinding:CPTradingRangePlotBindingHighValues];
[self exposeBinding:CPTradingRangePlotBindingLowValues];
[self exposeBinding:CPTradingRangePlotBindingCloseValues];
}
}
#endif
-(id)initWithFrame:(CGRect)newFrame
{
if ( self = [super initWithFrame:newFrame] ) {
plotStyle = CPTradingRangePlotStyleOHLC;
lineStyle = [[CPLineStyle alloc] init];
increaseFill = [(CPFill *)[CPFill alloc] initWithColor:[CPColor whiteColor]];
decreaseFill = [(CPFill *)[CPFill alloc] initWithColor:[CPColor blackColor]];
barWidth = 5.0;
stickLength = 3.0;
barCornerRadius = 0.0;
self.labelField = CPTradingRangePlotFieldClose;
}
return self;
}
-(id)initWithLayer:(id)layer
{
if ( self = [super initWithLayer:layer] ) {
CPTradingRangePlot *theLayer = (CPTradingRangePlot *)layer;
plotStyle = theLayer->plotStyle;
lineStyle = [theLayer->lineStyle retain];
increaseFill = [theLayer->increaseFill retain];
decreaseFill = [theLayer->decreaseFill retain];
barWidth = theLayer->barWidth;
stickLength = theLayer->stickLength;
barCornerRadius = theLayer->barCornerRadius;
}
return self;
}
-(void)dealloc
{
[lineStyle release];
[increaseFill release];
[decreaseFill release];
[super dealloc];
}
#pragma mark -
#pragma mark Data Loading
-(void)reloadDataInIndexRange:(NSRange)indexRange
{
[super reloadDataInIndexRange:indexRange];
if ( self.dataSource ) {
id newXValues = [self numbersFromDataSourceForField:CPTradingRangePlotFieldX recordIndexRange:indexRange];
[self cacheNumbers:newXValues forField:CPTradingRangePlotFieldX atRecordIndex:indexRange.location];
id newOpenValues = [self numbersFromDataSourceForField:CPTradingRangePlotFieldOpen recordIndexRange:indexRange];
[self cacheNumbers:newOpenValues forField:CPTradingRangePlotFieldOpen atRecordIndex:indexRange.location];
id newHighValues = [self numbersFromDataSourceForField:CPTradingRangePlotFieldHigh recordIndexRange:indexRange];
[self cacheNumbers:newHighValues forField:CPTradingRangePlotFieldHigh atRecordIndex:indexRange.location];
id newLowValues = [self numbersFromDataSourceForField:CPTradingRangePlotFieldLow recordIndexRange:indexRange];
[self cacheNumbers:newLowValues forField:CPTradingRangePlotFieldLow atRecordIndex:indexRange.location];
id newCloseValues = [self numbersFromDataSourceForField:CPTradingRangePlotFieldClose recordIndexRange:indexRange];
[self cacheNumbers:newCloseValues forField:CPTradingRangePlotFieldClose atRecordIndex:indexRange.location];
}
else {
self.xValues = nil;
self.openValues = nil;
self.highValues = nil;
self.lowValues = nil;
self.closeValues = nil;
}
}
#pragma mark -
#pragma mark Drawing
-(void)renderAsVectorInContext:(CGContextRef)theContext
{
CPMutableNumericData *locations = [self cachedNumbersForField:CPTradingRangePlotFieldX];
CPMutableNumericData *opens = [self cachedNumbersForField:CPTradingRangePlotFieldOpen];
CPMutableNumericData *highs = [self cachedNumbersForField:CPTradingRangePlotFieldHigh];
CPMutableNumericData *lows = [self cachedNumbersForField:CPTradingRangePlotFieldLow];
CPMutableNumericData *closes = [self cachedNumbersForField:CPTradingRangePlotFieldClose];
NSUInteger sampleCount = locations.numberOfSamples;
if ( sampleCount == 0 ) return;
if ( opens == nil || highs == nil|| lows == nil|| closes == nil ) return;
if ( (opens.numberOfSamples != sampleCount) || (highs.numberOfSamples != sampleCount) || (lows.numberOfSamples != sampleCount) || (closes.numberOfSamples != sampleCount) ) {
[NSException raise:CPException format:@"Mismatching number of data values in trading range plot"];
}
[super renderAsVectorInContext:theContext];
[self.lineStyle setLineStyleInContext:theContext];
CGPoint openPoint, highPoint, lowPoint, closePoint;
const CPCoordinate independentCoord = CPCoordinateX;
const CPCoordinate dependentCoord = CPCoordinateY;
CPPlotArea *thePlotArea = self.plotArea;
CPPlotSpace *thePlotSpace = self.plotSpace;
CPTradingRangePlotStyle thePlotStyle = self.plotStyle;
if ( self.doublePrecisionCache ) {
const double *locationBytes = (const double *)locations.data.bytes;
const double *openBytes = (const double *)opens.data.bytes;
const double *highBytes = (const double *)highs.data.bytes;
const double *lowBytes = (const double *)lows.data.bytes;
const double *closeBytes = (const double *)closes.data.bytes;
for ( NSUInteger i = 0; i < sampleCount; i++ ) {
double plotPoint[2];
plotPoint[independentCoord] = *locationBytes++;
if ( isnan(plotPoint[independentCoord]) ) {
openBytes++;
highBytes++;
lowBytes++;
closeBytes++;
continue;
}
// open point
plotPoint[dependentCoord] = *openBytes++;
if ( isnan(plotPoint[dependentCoord]) ) {
openPoint = CGPointMake(NAN, NAN);
}
else {
openPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea];
}
// high point
plotPoint[dependentCoord] = *highBytes++;
if ( isnan(plotPoint[dependentCoord]) ) {
highPoint = CGPointMake(NAN, NAN);
}
else {
highPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea];
}
// low point
plotPoint[dependentCoord] = *lowBytes++;
if ( isnan(plotPoint[dependentCoord]) ) {
lowPoint = CGPointMake(NAN, NAN);
}
else {
lowPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea];
}
// close point
plotPoint[dependentCoord] = *closeBytes++;
if ( isnan(plotPoint[dependentCoord]) ) {
closePoint = CGPointMake(NAN, NAN);
}
else {
closePoint = [self convertPoint:[thePlotSpace plotAreaViewPointForDoublePrecisionPlotPoint:plotPoint] fromLayer:thePlotArea];
}
CGFloat xCoord = openPoint.x;
if ( isnan(xCoord) ) {
xCoord = highPoint.x;
}
else if ( isnan(xCoord) ) {
xCoord = lowPoint.x;
}
else if ( isnan(xCoord) ) {
xCoord = closePoint.x;
}
if ( !isnan(xCoord) ) {
// Draw
switch ( thePlotStyle ) {
case CPTradingRangePlotStyleOHLC:
[self drawOHLCInContext:theContext x:xCoord open:openPoint.y close:closePoint.y high:highPoint.y low:lowPoint.y];
break;
case CPTradingRangePlotStyleCandleStick:
[self drawCandleStickInContext:theContext x:xCoord open:openPoint.y close:closePoint.y high:highPoint.y low:lowPoint.y];
break;
default:
[NSException raise:CPException format:@"Invalid plot style in renderAsVectorInContext"];
break;
}
}
}
}
else {
const NSDecimal *locationBytes = (const NSDecimal *)locations.data.bytes;
const NSDecimal *openBytes = (const NSDecimal *)opens.data.bytes;
const NSDecimal *highBytes = (const NSDecimal *)highs.data.bytes;
const NSDecimal *lowBytes = (const NSDecimal *)lows.data.bytes;
const NSDecimal *closeBytes = (const NSDecimal *)closes.data.bytes;
for ( NSUInteger i = 0; i < sampleCount; i++ ) {
NSDecimal plotPoint[2];
plotPoint[independentCoord] = *locationBytes++;
if ( NSDecimalIsNotANumber(&plotPoint[independentCoord]) ) {
openBytes++;
highBytes++;
lowBytes++;
closeBytes++;
continue;
}
// open point
plotPoint[dependentCoord] = *openBytes++;
if ( NSDecimalIsNotANumber(&plotPoint[dependentCoord]) ) {
openPoint = CGPointMake(NAN, NAN);
}
else {
openPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea];
}
// high point
plotPoint[dependentCoord] = *highBytes++;
if ( NSDecimalIsNotANumber(&plotPoint[dependentCoord]) ) {
highPoint = CGPointMake(NAN, NAN);
}
else {
highPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea];
}
// low point
plotPoint[dependentCoord] = *lowBytes++;
if ( NSDecimalIsNotANumber(&plotPoint[dependentCoord]) ) {
lowPoint = CGPointMake(NAN, NAN);
}
else {
lowPoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea];
}
// close point
plotPoint[dependentCoord] = *closeBytes++;
if ( NSDecimalIsNotANumber(&plotPoint[dependentCoord]) ) {
closePoint = CGPointMake(NAN, NAN);
}
else {
closePoint = [self convertPoint:[thePlotSpace plotAreaViewPointForPlotPoint:plotPoint] fromLayer:thePlotArea];
}
CGFloat xCoord = openPoint.x;
if ( isnan(xCoord) ) {
xCoord = highPoint.x;
}
else if ( isnan(xCoord) ) {
xCoord = lowPoint.x;
}
else if ( isnan(xCoord) ) {
xCoord = closePoint.x;
}
if ( !isnan(xCoord) ) {
// Draw
switch ( thePlotStyle ) {
case CPTradingRangePlotStyleOHLC:
[self drawOHLCInContext:theContext x:xCoord open:openPoint.y close:closePoint.y high:highPoint.y low:lowPoint.y];
break;
case CPTradingRangePlotStyleCandleStick:
[self drawCandleStickInContext:theContext x:xCoord open:openPoint.y close:closePoint.y high:highPoint.y low:lowPoint.y];
break;
default:
[NSException raise:CPException format:@"Invalid plot style in renderAsVectorInContext"];
break;
}
}
}
}
}
-(void)drawCandleStickInContext:(CGContextRef)context x:(CGFloat)x open:(CGFloat)open close:(CGFloat)close high:(CGFloat)high low:(CGFloat)low
{
CGFloat halfBarWidth = 0.5 * self.barWidth;
// high - low
if ( !isnan(high) && !isnan(low) ) {
CGPoint alignedCenterPoint1 = CPAlignPointToUserSpace(context, CGPointMake(x, high));
CGPoint alignedCenterPoint2 = CPAlignPointToUserSpace(context, CGPointMake(x, low));
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, alignedCenterPoint1.x, alignedCenterPoint1.y);
CGPathAddLineToPoint(path, NULL, alignedCenterPoint2.x, alignedCenterPoint2.y);
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGPathRelease(path);
}
// open-close
if ( !isnan(open) && !isnan(close) ) {
CPFill *currentBarFill = ( open <= close ? self.increaseFill : self.decreaseFill );
if ( currentBarFill ) {
CGFloat radius = MIN(self.barCornerRadius, halfBarWidth);
radius = MIN(radius, ABS(close - open));
CGPoint alignedPoint1 = CPAlignPointToUserSpace(context, CGPointMake(x + halfBarWidth, open));
CGPoint alignedPoint2 = CPAlignPointToUserSpace(context, CGPointMake(x + halfBarWidth, close));
CGPoint alignedPoint3 = CPAlignPointToUserSpace(context, CGPointMake(x, close));
CGPoint alignedPoint4 = CPAlignPointToUserSpace(context, CGPointMake(x - halfBarWidth, close));
CGPoint alignedPoint5 = CPAlignPointToUserSpace(context, CGPointMake(x - halfBarWidth, open));
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, alignedPoint1.x, alignedPoint1.y);
CGPathAddArcToPoint(path, NULL, alignedPoint2.x, alignedPoint2.y, alignedPoint3.x, alignedPoint3.y, radius);
CGPathAddArcToPoint(path, NULL, alignedPoint4.x, alignedPoint4.y, alignedPoint5.x, alignedPoint5.y, radius);
CGPathAddLineToPoint(path, NULL, alignedPoint5.x, alignedPoint5.y);
CGPathCloseSubpath(path);
CGContextBeginPath(context);
CGContextAddPath(context, path);
[currentBarFill fillPathInContext:context];
CGPathRelease(path);
}
}
}
-(void)drawOHLCInContext:(CGContextRef)context x:(CGFloat)x open:(CGFloat)open close:(CGFloat)close high:(CGFloat)high low:(CGFloat)low
{
CGFloat theStickLength = self.stickLength;
CGMutablePathRef path = CGPathCreateMutable();
// high-low
if ( !isnan(high) && !isnan(low) ) {
CGPoint alignedHighPoint = CPAlignPointToUserSpace(context, CGPointMake(x, high));
CGPoint alignedLowPoint = CPAlignPointToUserSpace(context, CGPointMake(x, low));
CGPathMoveToPoint(path, NULL, alignedHighPoint.x, alignedHighPoint.y);
CGPathAddLineToPoint(path, NULL, alignedLowPoint.x, alignedLowPoint.y);
}
// open
if ( !isnan(open) ) {
CGPoint alignedOpenStartPoint = CPAlignPointToUserSpace(context, CGPointMake(x, open));
CGPoint alignedOpenEndPoint = CPAlignPointToUserSpace(context, CGPointMake(x - theStickLength, open)); // left side
CGPathMoveToPoint(path, NULL, alignedOpenStartPoint.x, alignedOpenStartPoint.y);
CGPathAddLineToPoint(path, NULL, alignedOpenEndPoint.x, alignedOpenEndPoint.y);
}
// close
if ( !isnan(close) ) {
CGPoint alignedCloseStartPoint = CPAlignPointToUserSpace(context, CGPointMake(x, close));
CGPoint alignedCloseEndPoint = CPAlignPointToUserSpace(context, CGPointMake(x + theStickLength, close)); // right side
CGPathMoveToPoint(path, NULL, alignedCloseStartPoint.x, alignedCloseStartPoint.y);
CGPathAddLineToPoint(path, NULL, alignedCloseEndPoint.x, alignedCloseEndPoint.y);
}
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGPathRelease(path);
}
#pragma mark -
#pragma mark Fields
-(NSUInteger)numberOfFields
{
return 5;
}
-(NSArray *)fieldIdentifiers
{
return [NSArray arrayWithObjects:
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldX],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldOpen],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldClose],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldHigh],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldLow],
nil];
}
-(NSArray *)fieldIdentifiersForCoordinate:(CPCoordinate)coord
{
NSArray *result = nil;
switch (coord) {
case CPCoordinateX:
result = [NSArray arrayWithObject:[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldX]];
break;
case CPCoordinateY:
result = [NSArray arrayWithObjects:
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldOpen],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldLow],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldHigh],
[NSNumber numberWithUnsignedInt:CPTradingRangePlotFieldClose],
nil];
break;
default:
[NSException raise:CPException format:@"Invalid coordinate passed to fieldIdentifiersForCoordinate:"];
break;
}
return result;
}
#pragma mark -
#pragma mark Data Labels
-(void)positionLabelAnnotation:(CPPlotSpaceAnnotation *)label forIndex:(NSUInteger)index
{
BOOL positiveDirection = YES;
CPPlotRange *yRange = [self.plotSpace plotRangeForCoordinate:CPCoordinateY];
if ( CPDecimalLessThan(yRange.length, CPDecimalFromInteger(0)) ) {
positiveDirection = !positiveDirection;
}
NSNumber *xValue = [self cachedNumberForField:CPTradingRangePlotFieldX recordIndex:index];
NSNumber *yValue;
NSArray *yValues = [NSArray arrayWithObjects:[self cachedNumberForField:CPTradingRangePlotFieldOpen recordIndex:index],
[self cachedNumberForField:CPTradingRangePlotFieldClose recordIndex:index],
[self cachedNumberForField:CPTradingRangePlotFieldHigh recordIndex:index],
[self cachedNumberForField:CPTradingRangePlotFieldLow recordIndex:index], nil];
NSArray *yValuesSorted = [yValues sortedArrayUsingSelector:@selector(compare:)];
if ( positiveDirection ) {
yValue = [yValuesSorted lastObject];
}
else {
yValue = [yValuesSorted objectAtIndex:0];
}
label.anchorPlotPoint = [NSArray arrayWithObjects:xValue, yValue, nil];
if ( positiveDirection ) {
label.displacement = CGPointMake(0.0, self.labelOffset);
}
else {
label.displacement = CGPointMake(0.0, -self.labelOffset);
}
label.contentLayer.hidden = isnan([xValue doubleValue]) || isnan([yValue doubleValue]);
}
#pragma mark -
#pragma mark Accessors
-(void)setLineStyle:(CPLineStyle *)newLineStyle
{
if ( lineStyle != newLineStyle ) {
[lineStyle release];
lineStyle = [newLineStyle copy];
[self setNeedsDisplay];
}
}
-(void)setIncreaseFill:(CPFill *)newFill
{
if ( increaseFill != newFill ) {
[increaseFill release];
increaseFill = [newFill copy];
[self setNeedsDisplay];
}
}
-(void)setDecreaseFill:(CPFill *)newFill
{
if ( decreaseFill != newFill ) {
[decreaseFill release];
decreaseFill = [newFill copy];
[self setNeedsDisplay];
}
}
-(void)setBarWidth:(CGFloat)newWidth
{
if ( barWidth != newWidth ) {
barWidth = newWidth;
[self setNeedsDisplay];
}
}
-(void)setStickLength:(CGFloat)newLength
{
if ( stickLength != newLength ) {
stickLength = newLength;
[self setNeedsDisplay];
}
}
-(void)setXValues:(CPMutableNumericData *)newValues
{
[self cacheNumbers:newValues forField:CPTradingRangePlotFieldX];
}
-(CPMutableNumericData *)xValues
{
return [self cachedNumbersForField:CPTradingRangePlotFieldX];
}
-(CPMutableNumericData *)openValues
{
return [self cachedNumbersForField:CPTradingRangePlotFieldOpen];
}
-(void)setOpenValues:(CPMutableNumericData *)newValues
{
[self cacheNumbers:newValues forField:CPTradingRangePlotFieldOpen];
}
-(CPMutableNumericData *)highValues
{
return [self cachedNumbersForField:CPTradingRangePlotFieldHigh];
}
-(void)setHighValues:(CPMutableNumericData *)newValues
{
[self cacheNumbers:newValues forField:CPTradingRangePlotFieldHigh];
}
-(CPMutableNumericData *)lowValues
{
return [self cachedNumbersForField:CPTradingRangePlotFieldLow];
}
-(void)setLowValues:(CPMutableNumericData *)newValues
{
[self cacheNumbers:newValues forField:CPTradingRangePlotFieldLow];
}
-(CPMutableNumericData *)closeValues
{
return [self cachedNumbersForField:CPTradingRangePlotFieldClose];
}
-(void)setCloseValues:(CPMutableNumericData *)newValues
{
[self cacheNumbers:newValues forField:CPTradingRangePlotFieldClose];
}
@end
| 08iteng-ipad | framework/Source/CPTradingRangePlot.m | Objective-C | bsd | 20,732 |
#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 | framework/Source/CPColorSpace.h | Objective-C | bsd | 321 |
#import "CPMutableNumericData+TypeConversion.h"
#import "CPNumericData+TypeConversion.h"
@implementation CPMutableNumericData(TypeConversion)
/** @property dataType
* @brief The type of data stored in the data buffer.
**/
@dynamic dataType;
/** @property dataTypeFormat
* @brief The format of the data stored in the data buffer.
**/
@dynamic dataTypeFormat;
/** @property sampleBytes
* @brief The number of bytes in a single sample of data.
**/
@dynamic sampleBytes;
/** @property byteOrder
* @brief The byte order used to store each sample in the data buffer.
**/
@dynamic byteOrder;
/** @brief Converts the current numeric data to a new data type.
* @param newDataType The new data type format.
* @param newSampleBytes The number of bytes used to store each sample.
* @param newByteOrder The new byte order.
* @return A copy of the current numeric data converted to the new data type.
**/
-(void)convertToType:(CPDataTypeFormat)newDataType
sampleBytes:(size_t)newSampleBytes
byteOrder:(CFByteOrder)newByteOrder
{
self.dataType = CPDataType(newDataType, newSampleBytes, newByteOrder);
}
#pragma mark -
#pragma mark Accessors
-(void)setDataTypeFormat:(CPDataTypeFormat)newDataTypeFormat
{
CPNumericDataType myDataType = self.dataType;
if ( newDataTypeFormat != myDataType.dataTypeFormat ) {
self.dataType = CPDataType(newDataTypeFormat, myDataType.sampleBytes, myDataType.byteOrder);
}
}
-(void)setSampleBytes:(size_t)newSampleBytes
{
CPNumericDataType myDataType = self.dataType;
if ( newSampleBytes != myDataType.sampleBytes ) {
self.dataType = CPDataType(myDataType.dataTypeFormat, newSampleBytes, myDataType.byteOrder);
}
}
-(void)setByteOrder:(CFByteOrder)newByteOrder
{
CPNumericDataType myDataType = self.dataType;
if ( newByteOrder != myDataType.byteOrder ) {
self.dataType = CPDataType(myDataType.dataTypeFormat, myDataType.sampleBytes, newByteOrder);
}
}
-(void)setDataType:(CPNumericDataType)newDataType
{
CPNumericDataType myDataType = self.dataType;
if ( (myDataType.dataTypeFormat == newDataType.dataTypeFormat)
&& (myDataType.sampleBytes == newDataType.sampleBytes)
&& (myDataType.byteOrder == newDataType.byteOrder) ) {
return;
}
NSParameterAssert(myDataType.dataTypeFormat != CPUndefinedDataType);
NSParameterAssert(myDataType.byteOrder != CFByteOrderUnknown);
NSParameterAssert(CPDataTypeIsSupported(newDataType));
NSParameterAssert(newDataType.dataTypeFormat != CPUndefinedDataType);
NSParameterAssert(newDataType.byteOrder != CFByteOrderUnknown);
dataType = newDataType;
if ( (myDataType.sampleBytes == sizeof(int8_t)) && (newDataType.sampleBytes == sizeof(int8_t)) ) {
return;
}
NSMutableData *myData = (NSMutableData *)self.data;
CFByteOrder hostByteOrder = CFByteOrderGetCurrent();
NSUInteger sampleCount = myData.length / myDataType.sampleBytes;
if ( myDataType.byteOrder != hostByteOrder ) {
[self swapByteOrderForData:myData sampleSize:myDataType.sampleBytes];
}
if ( newDataType.sampleBytes > myDataType.sampleBytes ) {
NSMutableData *newData = [[NSMutableData alloc] initWithLength:(sampleCount * newDataType.sampleBytes)];
[self convertData:myData dataType:&myDataType toData:newData dataType:&newDataType];
[data release];
data = newData;
myData = newData;
}
else {
[self convertData:myData dataType:&myDataType toData:myData dataType:&newDataType];
myData.length = sampleCount * newDataType.sampleBytes;
}
if ( newDataType.byteOrder != hostByteOrder ) {
[self swapByteOrderForData:myData sampleSize:newDataType.sampleBytes];
}
}
@end
| 08iteng-ipad | framework/Source/CPMutableNumericData+TypeConversion.m | Objective-C | bsd | 3,587 |
#import "CPDarkGradientThemeTests.h"
#import "CPDarkGradientTheme.h"
#import "CPGraph.h"
#import "CPXYGraph.h"
#import "CPDerivedXYGraph.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];
}
@end
| 08iteng-ipad | framework/Source/CPDarkGradientThemeTests.m | Objective-C | bsd | 867 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@class CPColor;
@interface CPTextStyle : NSObject <NSCoding, NSCopying, NSMutableCopying> {
@protected
NSString *fontName;
CGFloat fontSize;
CPColor *color;
}
@property(readonly, copy, nonatomic) NSString *fontName;
@property(readonly, assign, nonatomic) CGFloat fontSize;
@property(readonly, copy, nonatomic) CPColor *color;
/// @name Factory Methods
/// @{
+(id)textStyle;
/// @}
@end
/** @category NSString(CPTextStyleExtensions)
* @brief NSString extensions for drawing styled text.
**/
@interface NSString(CPTextStyleExtensions)
/// @name Measurement
/// @{
-(CGSize)sizeWithTextStyle:(CPTextStyle *)style;
/// @}
/// @name Drawing
/// @{
-(void)drawAtPoint:(CGPoint)point withTextStyle:(CPTextStyle *)style inContext:(CGContextRef)context;
/// @}
@end
| 08iteng-ipad | framework/Source/CPTextStyle.h | Objective-C | bsd | 850 |
#import "CPAxisLabelGroup.h"
/** @brief A container layer for the axis labels.
**/
@implementation CPAxisLabelGroup
#pragma mark -
#pragma mark Drawing
-(void)renderAsVectorInContext:(CGContextRef)context
{
// nothing to draw
}
#pragma mark -
#pragma mark Layout
-(void)layoutSublayers
{
// do nothing--axis is responsible for positioning its labels
}
@end
| 08iteng-ipad | framework/Source/CPAxisLabelGroup.m | Objective-C | bsd | 366 |
#import "CPTestCase.h"
@class CPPlotRange;
@interface CPPlotRangeTests : CPTestCase {
CPPlotRange *plotRange;
}
@property (retain, readwrite) CPPlotRange *plotRange;
@end
| 08iteng-ipad | framework/Source/CPPlotRangeTests.h | Objective-C | bsd | 179 |
#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
#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
#pragma mark -
@implementation CPFill(AbstractMethods)
#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 | framework/Source/CPFill.m | Objective-C | bsd | 3,422 |
#import "CPTestCase.h"
@interface CPUtilitiesTests : CPTestCase {
}
@end
| 08iteng-ipad | framework/Source/CPUtilitiesTests.h | Objective-C | bsd | 78 |
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
#import "CPLineStyle.h"
#import "CPResponder.h"
#import "CPPlatformSpecificDefines.h"
@protocol CPLayoutManager;
@class CPGraph;
@interface CPLayer : CALayer <CPResponder> {
@private
CGFloat paddingLeft;
CGFloat paddingTop;
CGFloat paddingRight;
CGFloat paddingBottom;
BOOL masksToBorder;
id <CPLayoutManager> layoutManager;
BOOL renderingRecursively;
BOOL useFastRendering;
__weak CPGraph *graph;
CGPathRef outerBorderPath;
CGPathRef innerBorderPath;
}
/// @name Graph
/// @{
@property (nonatomic, readwrite, assign) __weak CPGraph *graph;
/// @}
/// @name Padding
/// @{
@property (nonatomic, readwrite) CGFloat paddingLeft;
@property (nonatomic, readwrite) CGFloat paddingTop;
@property (nonatomic, readwrite) CGFloat paddingRight;
@property (nonatomic, readwrite) CGFloat paddingBottom;
/// @}
/// @name Drawing
/// @{
@property (nonatomic, readonly, assign) BOOL useFastRendering;
/// @}
/// @name Masking
/// @{
@property (nonatomic, readwrite, assign) BOOL masksToBorder;
@property (nonatomic, readwrite, assign) CGPathRef outerBorderPath;
@property (nonatomic, readwrite, assign) CGPathRef innerBorderPath;
@property (nonatomic, readonly, assign) CGPathRef maskingPath;
@property (nonatomic, readonly, assign) CGPathRef sublayerMaskingPath;
/// @}
/// @name Layout
/// @{
@property (readwrite, retain) id <CPLayoutManager> layoutManager;
@property (readonly) NSSet *sublayersExcludedFromAutomaticLayout;
/// @}
/// @name Initialization
/// @{
-(id)initWithFrame:(CGRect)newFrame;
/// @}
/// @name Drawing
/// @{
-(void)renderAsVectorInContext:(CGContextRef)context;
-(void)recursivelyRenderInContext:(CGContextRef)context;
-(void)layoutAndRenderInContext:(CGContextRef)context;
-(NSData *)dataForPDFRepresentationOfLayer;
/// @}
/// @name Masking
/// @{
-(void)applySublayerMaskToContext:(CGContextRef)context forSublayer:(CPLayer *)sublayer withOffset:(CGPoint)offset;
-(void)applyMaskToContext:(CGContextRef)context;
/// @}
/// @name Layout
/// @{
+(CGFloat)defaultZPosition;
-(void)pixelAlign;
/// @}
@end
| 08iteng-ipad | framework/Source/CPLayer.h | Objective-C | bsd | 2,112 |
#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 | framework/Source/_CPFillImage.h | Objective-C | bsd | 399 |