Merge branch 'master' of git://github.com/280north/cappuccino

This commit is contained in:
Randall Luecke committed 2010-12-26 16:14:34 -06:00
commit 645741aa23
28 files changed
+2659 -2018

No files matched your search

+1 -1
View File
@@ -908,7 +908,7 @@ CPRunContinuesResponse = -1002;
return;
}
if ([args class] != CPArray)
if (![args isKindOfClass:CPArray])
args = [CPArray arrayWithObject:args];
_args = args;
+1 -1
View File
@@ -231,7 +231,7 @@ var CPBindingOperationAnd = 0,
aValue = [valueTransformer transformedValue:aValue];
if (aValue === undefined || aValue === nil)
if (aValue === undefined || aValue === nil || aValue === [CPNull null])
aValue = [options objectForKey:CPNullPlaceholderBindingOption] || nil;
return aValue;
+5 -15
View File
@@ -182,7 +182,7 @@
- (CPArray)selectedObjects
{
return [[_CPObservableArray alloc] initWithObjects:[_contentObject] count:1];
return [[_CPObservableArray alloc] initWithArray:[_contentObject]];
}
- (id)selection
@@ -341,7 +341,7 @@ var CPObjectControllerContentKey = @"CPObjectControllerCo
@end
@implementation _CPObservableArray : CPMutableArray
@implementation _CPObservableArray : _CPJavaScriptArray
{
CPArray _observationProxies;
}
@@ -367,20 +367,10 @@ var CPObjectControllerContentKey = @"CPObjectControllerCo
- (id)initWithArray:(CPArray)anArray
{
if (self = [super initWithArray:anArray])
{
_observationProxies = [];
}
self = [super initWithArray:anArray];
return self;
}
- (id)initWithObjects:(CPArray)objects count:(unsigned)count
{
if (self = [super initWithObjects:objects count:count])
{
_observationProxies = [];
}
self.isa = [_CPObservableArray class];
self._observationProxies = [];
return self;
}
+6 -2
View File
@@ -1714,7 +1714,11 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_)
{
return idx = [_cachedRowHeights indexOfObject:aPoint sortedByFunction:function(aPoint, rowCache) {
return idx = [_cachedRowHeights indexOfObject:aPoint
inSortedRange:nil
options:0
usingComparator:function(aPoint, rowCache)
{
var upperBound = rowCache.heightAboveRow;
if (aPoint.y < upperBound)
@@ -1724,7 +1728,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
return CPOrderedDescending;
return CPOrderedSame;
}];
}];
}
var y = aPoint.y,
-1406
View File
File diff suppressed because it is too large. Load diff
+856
View File
@@ -0,0 +1,856 @@
/*
* CPArray.j
* Foundation
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import "CPEnumerator.j"
@import "CPException.j"
@import "CPObject.j"
@import "CPRange.j"
@import "CPSortDescriptor.j"
CPEnumerationNormal = 0;
CPEnumerationConcurrent = 1 << 0;
CPEnumerationReverse = 1 << 1;
CPBinarySearchingFirstEqual = 1 << 8;
CPBinarySearchingLastEqual = 1 << 9;
CPBinarySearchingInsertionIndex = 1 << 10;
#define FORWARD_TO_CONCRETE_CLASS()\
if (self === _CPSharedPlaceholderArray)\
{\
arguments[0] = [_CPJavaScriptArray alloc];\
return objj_msgSend.apply(this, arguments);\
}\
return [super init];
/*!
@class CPArray
@brief A mutable array backed by a JavaScript Array.
@ingroup foundation
A mutable array class backed by a JavaScript Array.
There is also a CPMutableArray class,
but it is just a child class of this class with an
empty implementation. All mutable functionality is
implemented directly in CPArray.
*/
@implementation CPArray : CPObject
/*!
Returns a new uninitialized CPArray.
*/
+ (id)alloc
{
if (self === CPArray || self === CPMutableArray)
return [_CPPlaceholderArray alloc];
return [super alloc];
}
/*!
Returns a new initialized CPArray.
*/
+ (id)array
{
return [[self alloc] init];
}
/*!
Creates a new array containing the objects in \c anArray.
@param anArray Objects in this array will be added to the new array
@return a new CPArray of the provided objects
*/
+ (id)arrayWithArray:(CPArray)anArray
{
return [[self alloc] initWithArray:anArray];
}
/*!
Creates a new array with \c anObject in it.
@param anObject the object to be added to the array
@return a new CPArray containing a single object
*/
+ (id)arrayWithObject:(id)anObject
{
return [[self alloc] initWithObjects:anObject];
}
/*!
Creates a new CPArray containing all the objects passed as arguments to the method.
@param anObject the objects that will be added to the new array
@return a new CPArray containing the argument objects
*/
+ (id)arrayWithObjects:(id)anObject, ...
{
arguments[0] = [self alloc];
arguments[1] = @selector(initWithObjects:);
return objj_msgSend.apply(this, arguments);
}
/*!
Creates a CPArray from a JavaScript array of objects.
@param objects the JavaScript Array
@param aCount the number of objects in the JS Array
@return a new CPArray containing the specified objects
*/
+ (id)arrayWithObjects:(id)objects count:(unsigned)aCount
{
return [[self alloc] initWithObjects:objects count:aCount];
}
/*!
Initializes the CPArray.
@return the initialized array
*/
- (id)init
{
FORWARD_TO_CONCRETE_CLASS();
}
// Creating an Array
/*!
Creates a new CPArray from \c anArray.
@param anArray objects in this array will be added to the new array
@return a new CPArray containing the objects of \c anArray
*/
- (id)initWithArray:(CPArray)anArray
{
FORWARD_TO_CONCRETE_CLASS();
}
/*!
Initializes a the array with the contents of \c anArray
and optionally performs a deep copy of the objects based on \c copyItems.
@param anArray the array to copy the data from
@param shouldCopyItems if \c YES, each object will be copied by having a \c -copy message
sent to it, and the returned object will be added to the receiver. Otherwise, no copying will be performed.
@return the initialized array of objects
*/
- (id)initWithArray:(CPArray)anArray copyItems:(BOOL)shouldCopyItems
{
FORWARD_TO_CONCRETE_CLASS();
}
/*!
initializes an array with the contents of anArray
*/
- (id)initWithObjects:(id)anObject, ...
{
FORWARD_TO_CONCRETE_CLASS();
}
/*!
Initializes the array with a JavaScript array of objects.
@param objects the array of objects to add to the receiver
@param aCount the number of objects in \c objects
@return the initialized CPArray
*/
- (id)initWithObjects:(id)objects count:(unsigned)aCount
{
FORWARD_TO_CONCRETE_CLASS();
}
// Querying an array
/*!
Returns \c YES if the array contains \c anObject. Otherwise, it returns \c NO.
@param anObject the method checks if this object is already in the array
*/
- (BOOL)containsObject:(id)anObject
{
return [self indexOfObject:anObject] !== CPNotFound;
}
/*!
Returns the number of elements in the array
*/
- (int)count
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Returns the last object in the array. If the array is empty, returns \c nil/
*/
- (id)lastObject
{
var count = [self count];
if (count <= 0)
return nil;
return [self objectAtIndex:count - 1];
}
/*!
Returns the object at index \c anIndex.
@throws CPRangeException if \c anIndex is out of bounds
*/
- (id)objectAtIndex:(int)anIndex
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Returns the objects at \c indexes in a new CPArray.
@param indexes the set of indices
@throws CPRangeException if any of the indices is greater than or equal to the length of the array
*/
- (CPArray)objectsAtIndexes:(CPIndexSet)indexes
{
var index = CPNotFound,
objects = [];
while ((index = [indexes indexGreaterThanIndex:index]) !== CPNotFound)
objects.push([self objectAtIndex:index]);
return objects;
}
/*!
Returns an enumerator describing the array sequentially
from the first to the last element. You should not modify
the array during enumeration.
*/
- (CPEnumerator)objectEnumerator
{
return [[_CPArrayEnumerator alloc] initWithArray:self];
}
/*!
Returns an enumerator describing the array sequentially
from the last to the first element. You should not modify
the array during enumeration.
*/
- (CPEnumerator)reverseObjectEnumerator
{
return [[_CPReverseArrayEnumerator alloc] initWithArray:self];
}
/*!
Returns the index of \c anObject in this array.
If the object is not in the array,
returns \c CPNotFound. It first attempts to find
a match using \c -isEqual:, then \c ===.
@param anObject the object to search for
*/
- (CPUInteger)indexOfObject:(id)anObject
{
return [self indexOfObject:anObject inRange:nil];
}
/*!
Returns the index of \c anObject in the array
within \c aRange. It first attempts to find
a match using \c -isEqual:, then \c ===.
@param anObject the object to search for
@param aRange the range to search within
@return the index of the object, or \c CPNotFound if it was not found.
*/
- (CPUInteger)indexOfObject:(id)anObject inRange:(CPRange)aRange
{
// Only use isEqual: if our object is a CPObject.
if (anObject && anObject.isa)
{
var index = aRange ? aRange.location : 0,
count = aRange ? CPMaxRange(aRange) : [self count];
for (; index < count; ++index)
if ([[self objectAtIndex:index] isEqual:anObject])
return index;
return CPNotFound;
}
return [self indexOfObjectIdenticalTo:anObject inRange:aRange];
}
/*!
Returns the index of \c anObject in the array. The test for equality is done using only \c ===.
@param anObject the object to search for
@return the index of the object in the array. \c CPNotFound if the object is not in the array.
*/
- (CPUInteger)indexOfObjectIdenticalTo:(id)anObject
{
return [self indexOfObjectIdenticalTo:anObject inRange:nil];
}
/*!
Returns the index of \c anObject in the array
within \c aRange. The test for equality is
done using only \c ==.
@param anObject the object to search for
@param aRange the range to search within
@return the index of the object, or \c CPNotFound if it was not found.
*/
- (CPUInteger)indexOfObjectIdenticalTo:(id)anObject inRange:(CPRange)aRange
{
var index = aRange ? aRange.location : 0,
count = aRange ? CPMaxRange(aRange) : [self count];
for (; index < count; ++index)
if ([self objectAtIndex:index] === anObject)
return index;
return CPNotFound;
}
/*!
Returns the index of the first object in the receiver that passes a test in a given Javascript function.
@param predicate The function to apply to elements of the array. The function receives two arguments:
object The element in the array.
index The index of the element in the array.
The predicate function should either return a Boolean value that indicates whether the object passed the test,
or nil to stop the search, which will return CPNotFound to the sender.
@return The index of the first matching object, or \c CPNotFound if there is no matching object.
*/
- (unsigned)indexOfObjectPassingTest:(Function)aPredicate
{
return [self indexOfObjectWithOptions:CPEnumerationNormal passingTest:aPredicate context:undefined];
}
/*!
Returns the index of the first object in the receiver that passes a test in a given Javascript function.
@param predicate The function to apply to elements of the array. The function receives two arguments:
object The element in the array.
index The index of the element in the array.
context The object passed to the receiver in the aContext parameter.
The predicate function should either return a Boolean value that indicates whether the object passed the test,
or nil to stop the search, which will return CPNotFound to the sender.
@param context An object that contains context information you want passed to the predicate function.
@return The index of the first matching object, or \c CPNotFound if there is no matching object.
*/
- (unsigned)indexOfObjectPassingTest:(Function)aPredicate context:(id)aContext
{
return [self indexOfObjectWithOptions:CPEnumerationNormal passingTest:aPredicate context:aContext];
}
/*!
Returns the index of the first object in the receiver that passes a test in a given Javascript function.
@param options Specifies the direction in which the array is searched. Pass CPEnumerationNormal to search forwards
or CPEnumerationReverse to search in reverse.
@param predicate The function to apply to elements of the array. The function receives two arguments:
object The element in the array.
index The index of the element in the array.
The predicate function should either return a Boolean value that indicates whether the object passed the test,
or nil to stop the search, which will return CPNotFound to the sender.
@return The index of the first matching object, or \c CPNotFound if there is no matching object.
*/
- (unsigned)indexOfObjectWithOptions:(CPEnumerationOptions)options passingTest:(Function)aPredicate
{
return [self indexOfObjectWithOptions:options passingTest:aPredicate context:undefined];
}
/*!
Returns the index of the first object in the receiver that passes a test in a given Javascript function.
@param options Specifies the direction in which the array is searched. Pass CPEnumerationNormal to search forwards
or CPEnumerationReverse to search in reverse.
@param predicate The function to apply to elements of the array. The function receives two arguments:
object The element in the array.
index The index of the element in the array.
context The object passed to the receiver in the aContext parameter.
The predicate function should either return a Boolean value that indicates whether the object passed the test,
or nil to stop the search, which will return CPNotFound to the sender.
@param context An object that contains context information you want passed to the predicate function.
@return The index of the first matching object, or \c CPNotFound if there is no matching object.
*/
- (unsigned)indexOfObjectWithOptions:(CPEnumerationOptions)options passingTest:(Function)aPredicate context:(id)aContext
{
// We don't use an enumerator because they return nil to indicate end of enumeration,
// but nil may actually be the value we are looking for, so we have to loop over the array.
if (options & CPEnumerationReverse)
{
var index = [self count] - 1,
stop = -1,
increment = -1;
}
else
{
var index = 0,
stop = [self count],
increment = 1;
}
for (; index !== stop; index += increment)
if (aPredicate([self objectAtIndex:index], index, aContext))
return index;
return CPNotFound;
}
- (CPUInteger)indexOfObject:(id)anObject
inSortedRange:(CPRange)aRange
options:(CPBinarySearchingOptions)options
usingComparator:(Function)aComparator
{
// FIXME: comparator is not a function
if (!aComparator)
_CPRaiseInvalidArgumentException(self, _cmd, "comparator is nil");
if ((options & CPBinarySearchingFirstEqual) && (options & CPBinarySearchingLastEqual))
_CPRaiseInvalidArgumentException(self, _cmd,
"both CPBinarySearchingFirstEqual and CPBinarySearchingLastEqual options cannot be specified");
var count = [self count];
if (count <= 0)
return (options & CPBinarySearchingInsertionIndex) ? 0 : CPNotFound;
var first = aRange ? aRange.location : 0,
last = aRange ? CPMaxRange(aRange) : [self count] - 1;
if (first < 0)
_CPRaiseRangeException(self, _cmd, first, count);
if (last >= count)
_CPRaiseRangeException(self, _cmd, last, count);
while (first <= last)
{
var middle = FLOOR((first + last) / 2),
result = aComparator(anObject, [self objectAtIndex:middle]);
if (result > 0)
first = middle + 1;
else if (result < 0)
last = middle - 1;
else
{
if (options & CPBinarySearchingFirstEqual)
while (middle++ < count - 1 &&
aComparator(anObject, [self objectAtIndex:middle]) === CPOrderedSame);
else if (options & CPBinarySearchingLastEqual)
{
while (middle-- > 0 &&
aComparator(anObject, [self objectAtIndex:middle]) === CPOrderedSame);
if (options & CPBinarySearchingInsertionIndex)
++middle;
}
return middle;
}
}
if (options & CPBinarySearchingInsertionIndex)
return MAX(first, 0);
return CPNotFound;
}
// Sending messages to elements
/*!
Sends each element in the array a message.
@param aSelector the selector of the message to send
@throws CPInvalidArgumentException if \c aSelector is \c nil
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector
{
[self makeObjectsPerformSelector:aSelector withObjects:nil];
}
/*!
Sends each element in the array a message with an argument.
@param aSelector the selector of the message to send
@param anObject the first argument of the message
@throws CPInvalidArgumentException if \c aSelector is \c nil
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject
{
return [self makeObjectsPerformSelector:aSelector withObjects:[anObject]];
}
- (void)makeObjectsPerformSelector:(SEL)aSelector withObjects:(CPArray)objects
{
if (!aSelector)
[CPException raise:CPInvalidArgumentException
reason:"makeObjectsPerformSelector:withObjects: 'aSelector' can't be nil"];
var index = 0,
count = [self count];
if ([objects count])
{
argumentsArray = [[nil, aSelector] arrayByAddingObjectsFromArray:objects];
for (; index < count; ++index)
{
argumentsArray[0] = [self objectAtIndex:index];
objj_msgSend.apply(this, argumentsArray);
}
}
else
for (; index < count; ++index)
objj_msgSend([self objectAtIndex:index], aSelector);
}
// Comparing arrays
/*!
Returns the first object found in the receiver (starting at index 0) which is present in the
\c otherArray as determined by using the \c -containsObject: method.
@return the first object found, or \c nil if no common object was found.
*/
- (id)firstObjectCommonWithArray:(CPArray)anArray
{
var count = [self count];
if (![anArray count] || !count)
return nil;
var index = 0;
for (; index < count; ++index)
{
var object = [self objectAtIndex:index];
if ([anArray containsObject:object])
return object;
}
return nil;
}
/*!
Returns true if anArray contains exactly the same objects as the reciever.
*/
- (BOOL)isEqualToArray:(id)anArray
{
if (self === anArray)
return YES;
if (![anArray isKindOfClass:CPArray])
return NO;
var count = [self count],
otherCount = [anArray count];
if (anArray === nil || count !== otherCount)
return NO;
var index = 0;
for (; index < count; ++index)
{
var lhs = [self objectAtIndex:index],
rhs = [anArray objectAtIndex:index];
// If they're not equal, and either doesn't have an isa, or they're !isEqual (not isEqual)
if (lhs !== rhs && (lhs && !lhs.isa || rhs && !rhs.isa || ![lhs isEqual:rhs]))
return NO;
}
return YES;
}
- (BOOL)isEqual:(id)anObject
{
return (self === anObject) || [self isEqualToArray:anObject];
}
// Deriving new arrays
/*!
Returns a copy of this array plus \c anObject inside the copy.
@param anObject the object to be added to the array copy
@throws CPInvalidArgumentException if \c anObject is \c nil
@return a new array that should be n+1 in size compared to the receiver.
*/
- (CPArray)arrayByAddingObject:(id)anObject
{
return self.concat(anObject);
}
/*!
Returns a new array which is the concatenation of \c self and otherArray (in this precise order).
@param anArray the array that will be concatenated to the receiver's copy
*/
- (CPArray)arrayByAddingObjectsFromArray:(CPArray)anArray
{
return self.concat(anArray);
}
/*
- (CPArray)filteredArrayUsingPredicate:(CPPredicate)aPredicate
{
var i= 0,
count = [self count],
array = [CPArray array];
for (; i<count; ++i)
if (aPredicate.evaluateWithObject(self[i]))
array.push(self[i]);
return array;
}
*/
/*!
Returns a subarray of the receiver containing the objects found in the specified range \c aRange.
@param aRange the range of objects to be copied into the subarray
@throws CPRangeException if the specified range exceeds the bounds of the array
*/
- (CPArray)subarrayWithRange:(CPRange)aRange
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
// Sorting arrays
/*
Not yet described.
*/
- (CPArray)sortedArrayUsingDescriptors:(CPArray)descriptors
{
var sorted = [self copy];
[sorted sortUsingDescriptors:descriptors];
return sorted;
}
/*!
Return a copy of the receiver sorted using the function passed into the first parameter.
*/
- (CPArray)sortedArrayUsingFunction:(Function)aFunction
{
return [self sortedArrayUsingFunction:aFunction context:nil];
}
/*!
Returns an array in which the objects are ordered according
to a sort with \c aFunction. This invokes
\c -sortUsingFunction:context.
@param aFunction a JavaScript 'Function' type that compares objects
@param aContext context information
@return a new sorted array
*/
- (CPArray)sortedArrayUsingFunction:(Function)aFunction context:(id)aContext
{
var sorted = [self copy];
[sorted sortUsingFunction:aFunction context:aContext];
return sorted;
}
/*!
Returns a new array in which the objects are ordered according to a sort with \c aSelector.
@param aSelector the selector that will perform object comparisons
*/
- (CPArray)sortedArrayUsingSelector:(SEL)aSelector
{
var sorted = [self copy];
[sorted sortUsingSelector:aSelector];
return sorted;
}
// Working with string elements
/*!
Returns a string formed by concatenating the objects in the
receiver, with the specified separator string inserted between each part.
If the element is a Objective-J object, then the \c -description
of that object will be used, otherwise the default JavaScript representation will be used.
@param aString the separator that will separate each object string
@return the string representation of the array
*/
- (CPString)componentsJoinedByString:(CPString)aString
{
var index = 0,
count = [self count],
components = [];
for (; index < count; ++index)
{
components.push([self objectAtIndex:index]);
if (index < count - 1)
components.push(aString);
}
return components.join("");
}
// Creating a description of the array
/*!
Returns a human readable description of this array and it's elements.
*/
- (CPString)description
{
var index = 0,
count = [self count],
description = '(';
for (; index < count; ++index)
{
if (index === 0)
description += '\n';
var object = [self objectAtIndex:index],
objectDescription = object && object.isa ? [object description] : String(object);
description += "\t" + objectDescription.split('\n').join("\n\t");
if (index !== count - 1)
description += ", ";
description += '\n';
}
return description + ')';
}
// Collecting paths
/*!
Returns a new array subset formed by selecting the elements that have
filename extensions from \c filterTypes. Only elements
that are of type CPString are candidates for inclusion in the returned array.
@param filterTypes an array of CPString objects that contain file extensions (without the '.')
@return a new array with matching paths
*/
- (CPArray)pathsMatchingExtensions:(CPArray)filterTypes
{
var index = 0,
count = [self count],
array = [];
for (; index < count; ++index)
if (self[index].isa && [self[index] isKindOfClass:[CPString class]] && [filterTypes containsObject:[self[index] pathExtension]])
array.push(self[index]);
return array;
}
// Copying arrays
/*!
Makes a copy of the receiver.
@return a new CPArray copy
*/
- (id)copy
{
return slice(0);
}
@end
@implementation CPArray (CPCoding)
- (id)initWithCoder:(CPCoder)aCoder
{
return [aCoder decodeObjectForKey:@"CP.objects"];
}
- (void)encodeWithCoder:(CPCoder)aCoder
{
[aCoder _encodeArrayOfObjects:self forKey:@"CP.objects"];
}
@end
/* @ignore */
@implementation _CPArrayEnumerator : CPEnumerator
{
CPArray _array;
int _index;
}
- (id)initWithArray:(CPArray)anArray
{
self = [super init];
if (self)
{
_array = anArray;
_index = -1;
}
return self;
}
- (id)nextObject
{
if (++_index >= [_array count])
return nil;
return [_array objectAtIndex:_index];
}
@end
/* @ignore */
@implementation _CPReverseArrayEnumerator : CPEnumerator
{
CPArray _array;
int _index;
}
- (id)initWithArray:(CPArray)anArray
{
self = [super init];
if (self)
{
_array = anArray;
_index = [_array count];
}
return self;
}
- (id)nextObject
{
if (--_index < 0)
return nil;
return [_array objectAtIndex:_index];
}
@end
var _CPSharedPlaceholderArray = nil;
@implementation _CPPlaceholderArray : CPArray
{
}
+ (id)alloc
{
if (!_CPSharedPlaceholderArray)
_CPSharedPlaceholderArray = [super alloc];
return _CPSharedPlaceholderArray;
}
@end
@import "CPArray.j"
@import "CPMutableArray.j"
@import "_CPJavaScriptArray.j"
+398
View File
@@ -0,0 +1,398 @@
@import "CPArray.j"
/*!
@class CPMutableArray
@ingroup compatability
This class is just an empty subclass of CPArray.
CPArray already implements mutable methods and
this class only exists for source compatability.
*/
@implementation CPMutableArray : CPArray
{
}
// Creating arrays
/*!
Creates an array able to store at least \c aCapacity
items. Because CPArray is backed by JavaScript arrays,
this method ends up simply returning a regular array.
*/
+ (CPArray)arrayWithCapacity:(unsigned)aCapacity
{
return [[self alloc] initWithCapacity:aCapacity];
}
/*!
Initializes an array able to store at least \c aCapacity items. Because CPArray
is backed by JavaScript arrays, this method ends up simply returning a regular array.
*/
- (id)initWithCapacity:(unsigned)aCapacity
{
return self;
}
// Adding and replacing objects
/*!
Adds \c anObject to the end of the array.
@param anObject the object to add to the array
*/
- (void)addObject:(id)anObject
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Adds the objects in \c anArray to the receiver array.
@param anArray the array of objects to add to the end of the receiver
*/
- (void)addObjectsFromArray:(CPArray)anArray
{
splice.apply(self, [length, 0].concat(anArray));
}
/*!
Inserts an object into the receiver at the specified location.
@param anObject the object to insert into the array
@param anIndex the location to insert \c anObject at
*/
- (void)insertObject:(id)anObject atIndex:(int)anIndex
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Inserts the objects in the provided array into the receiver at the indexes specified.
@param objects the objects to add to this array
@param anIndexSet the indices for the objects
*/
- (void)insertObjects:(CPArray)objects atIndexes:(CPIndexSet)indexes
{
var indexesCount = [indexes count],
objectsCount = [objects count];
if (indexesCount !== objectsCount)
[CPException raise:CPRangeException reason:"the counts of the passed-in array (" + objectsCount + ") and index set (" + indexesCount + ") must be identical."];
var lastIndex = [indexes lastIndex];
if (lastIndex >= [self count] + indexesCount)
[CPException raise:CPRangeException reason:"the last index (" + lastIndex + ") must be less than the sum of the original count (" + [self count] + ") and the insertion count (" + indexesCount + ")."];
var index = 0,
currentIndex = [indexes firstIndex];
for (; index < objectsCount; ++index, currentIndex = [indexes indexGreaterThanIndex:currentIndex])
[self insertObject:objects[index] atIndex:currentIndex];
}
- (unsigned)insertObject:(id)anObject inArraySortedByDescriptors:(CPArray)descriptors
{
var index,
count = [descriptors count];
if (count)
index = [self indexOfObject:anObject
inSortedRange:nil
options:CPBinarySearchingInsertionIndex
usingComparator:function(lhs, rhs)
{
var index = 0,
result = CPOrderedSame;
while (index < count && ((result = [[descriptors objectAtIndex:index] compareObject:lhs withObject:rhs]) === CPOrderedSame))
++index;
return result;
}];
else
index = [self count];
[self insertObject:anObject atIndex:index];
return index;
}
/*!
Replaces the element at \c anIndex with \c anObject.
The current element at position \c anIndex will be removed from the array.
@param anIndex the position in the array to place \c anObject
*/
- (void)replaceObjectAtIndex:(int)anIndex withObject:(id)anObject
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Replace the elements at the indices specified by \c anIndexSet with
the objects in \c objects.
@param anIndexSet the set of indices to array positions that will be replaced
@param objects the array of objects to place in the specified indices
*/
- (void)replaceObjectsAtIndexes:(CPIndexSet)anIndexSet withObjects:(CPArray)objects
{
var i = 0,
index = [anIndexSet firstIndex];
while (index != CPNotFound)
{
[self replaceObjectAtIndex:index withObject:objects[i++]];
index = [anIndexSet indexGreaterThanIndex:index];
}
}
/*!
Replaces some of the receiver's objects with objects from \c anArray. Specifically, the elements of the
receiver in the range specified by \c aRange,
with the elements of \c anArray in the range specified by \c otherRange.
@param aRange the range of elements to be replaced in the receiver
@param anArray the array to retrieve objects for placement into the receiver
@param otherRange the range of objects in \c anArray to pull from for placement into the receiver
*/
- (void)replaceObjectsInRange:(CPRange)aRange withObjectsFromArray:(CPArray)anArray range:(CPRange)otherRange
{
if (!otherRange.location && otherRange.length == [anArray count])
[self replaceObjectsInRange:aRange withObjectsFromArray:anArray];
else
splice.apply(self, [aRange.location, aRange.length].concat([anArray subarrayWithRange:otherRange]));
}
/*!
Replaces some of the receiver's objects with the objects from
\c anArray. Specifically, the elements of the
receiver in the range specified by \c aRange.
@param aRange the range of elements to be replaced in the receiver
@param anArray the array to retrieve objects for placement into the receiver
*/
- (void)replaceObjectsInRange:(CPRange)aRange withObjectsFromArray:(CPArray)anArray
{
splice.apply(self, [aRange.location, aRange.length].concat(anArray));
}
/*!
Sets the contents of the receiver to be identical to the contents of \c anArray.
@param anArray the array of objects used to replace the receiver's objects
*/
- (void)setArray:(CPArray)anArray
{
if (self == anArray)
return;
splice.apply(self, [0, length].concat(anArray));
}
// Removing Objects
/*!
Removes all objects from this array.
*/
- (void)removeAllObjects
{
splice(0, length);
}
/*!
Removes the last object from the array.
*/
- (void)removeLastObject
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Removes all entries of \c anObject from the array.
@param anObject the object whose entries are to be removed
*/
- (void)removeObject:(id)anObject
{
[self removeObject:anObject inRange:CPMakeRange(0, length)];
}
/*!
Removes all entries of \c anObject from the array, in the range specified by \c aRange.
@param anObject the object to remove
@param aRange the range to search in the receiver for the object
*/
- (void)removeObject:(id)anObject inRange:(CPRange)aRange
{
var index;
while ((index = [self indexOfObject:anObject inRange:aRange]) != CPNotFound)
{
[self removeObjectAtIndex:index];
aRange = CPIntersectionRange(CPMakeRange(index, length - index), aRange);
}
}
/*!
Removes the object at \c anIndex.
@param anIndex the location of the element to be removed
*/
- (void)removeObjectAtIndex:(int)anIndex
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
Removes the objects at the indices specified by \c CPIndexSet.
@param anIndexSet the indices of the elements to be removed from the array
*/
- (void)removeObjectsAtIndexes:(CPIndexSet)anIndexSet
{
var index = [anIndexSet lastIndex];
while (index != CPNotFound)
{
[self removeObjectAtIndex:index];
index = [anIndexSet indexLessThanIndex:index];
}
}
/*!
Remove the first instance of \c anObject from the array.
The search for the object is done using \c ==.
@param anObject the object to remove
*/
- (void)removeObjectIdenticalTo:(id)anObject
{
[self removeObjectIdenticalTo:anObject inRange:CPMakeRange(0, [self count])];
}
/*!
Remove the first instance of \c anObject from the array,
within the range specified by \c aRange.
The search for the object is done using \c ==.
@param anObject the object to remove
@param aRange the range in the array to search for the object
*/
- (void)removeObjectIdenticalTo:(id)anObject inRange:(CPRange)aRange
{
var index,
count = [self count];
while ((index = [self indexOfObjectIdenticalTo:anObject inRange:aRange]) !== CPNotFound)
{
[self removeObjectAtIndex:index];
aRange = CPIntersectionRange(CPMakeRange(index, (--count) - index), aRange);
}
}
/*!
Remove the objects in \c anArray from the receiver array.
@param anArray the array of objects to remove from the receiver
*/
- (void)removeObjectsInArray:(CPArray)anArray
{
var index = 0,
count = [anArray count];
for (; index < count; ++index)
[self removeObject:anArray[index]];
}
/*!
Removes all the objects in the specified range from the receiver.
@param aRange the range of objects to remove
*/
- (void)removeObjectsInRange:(CPRange)aRange
{
splice(aRange.location, aRange.length);
}
// Rearranging objects
/*!
Swaps the elements at the two specified indices.
@param anIndex the first index to swap from
@param otherIndex the second index to swap from
*/
- (void)exchangeObjectAtIndex:(unsigned)anIndex withObjectAtIndex:(unsigned)otherIndex
{
var temporary = self[anIndex];
self[anIndex] = self[otherIndex];
self[otherIndex] = temporary;
}
- (CPArray)sortUsingDescriptors:(CPArray)descriptors
{
[self sortUsingFunction:compareObjectsUsingDescriptors context:descriptors];
}
/*!
Sorts the receiver array using a JavaScript function as a comparator, and a specified context.
@param aFunction a JavaScript function that will be called to compare objects
@param aContext an object that will be passed to \c aFunction with comparison
*/
- (void)sortUsingFunction:(Function)aFunction context:(id)aContext
{
var h,
i,
j,
k,
l,
m,
n = [self count],
o;
var A,
B = [];
for (h = 1; h < n; h += h)
{
for (m = n - 1 - h; m >= 0; m -= h + h)
{
l = m - h + 1;
if (l < 0)
l = 0;
for (i = 0, j = l; j <= m; i++, j++)
B[i] = self[j];
for (i = 0, k = l; k < j && j <= m + h; k++)
{
A = self[j];
o = aFunction(A, B[i], aContext);
if (o >= 0)
self[k] = B[i++];
else
{
self[k] = A;
j++;
}
}
while (k < j)
self[k++] = B[i++];
}
}
}
/*!
Sorts the receiver array using an Objective-J method as a comparator.
@param aSelector the selector for the method to call for comparison
*/
- (void)sortUsingSelector:(SEL)aSelector
{
[self sortUsingFunction:selectorCompare context:aSelector];
}
@end
var selectorCompare = function selectorCompare(object1, object2, selector)
{
return [object1 performSelector:selector withObject:object2];
}
// sort using sort descriptors
var compareObjectsUsingDescriptors= function compareObjectsUsingDescriptors(lhs, rhs, descriptors)
{
var result = CPOrderedSame,
i = 0,
n = [descriptors count];
while (i < n && result === CPOrderedSame)
result = [descriptors[i++] compareObject:lhs withObject:rhs];
return result;
}
+222
View File
@@ -0,0 +1,222 @@
@import "CPMutableArray.j"
@implementation _CPJavaScriptArray : CPMutableArray
{
}
+ (id)alloc
{
return [];
}
+ (CPArray)array
{
return [];
}
+ (id)arrayWithArray:(CPArray)anArray
{
return [[self alloc] initWithArray:anArray];
}
+ (id)arrayWithObject:(id)anObject
{
return [anObject];
}
- (id)initWithArray:(CPArray)anArray
{
return anArray.slice(0);
}
- (id)initWithArray:(CPArray)anArray copyItems:(BOOL)shouldCopyItems
{
if (!shouldCopyItems)
return anArray.slice(0);
self = [super init];
var index = 0;
if (anArray.isa === _CPJavaScriptArray)
{
var count = anArray.length;
for (; index < count; ++index)
{
var object = anArray[index];
self[index] = object.isa ? [object copy] : object;
}
return self;
}
var count = [anArray count];
for (; index < count; ++index)
{
var object = [anArray objectatIndex:index];
self[index] = object.isa ? [object copy] : object;
}
return self;
}
- (id)initWithObjects:(id)anObject, ...
{
// The arguments array contains self and _cmd, so the first object is at position 2.
var index = 2,
count = arguments.length;
for (; index < count; ++index)
if (arguments[index] === nil)
break;
return Array.prototype.slice.call(arguments, 2, index);
}
- (id)initWithObjects:(CPArray)objects count:(CPUInteger)aCount
{
if (objects.isa === _CPJavaScriptArray)
return objects.slice(0);
var array = [],
index = 0;
for (; index < aCount; ++index)
array.push([objects objectAtIndex:index]);
return array;
}
- (BOOL)count
{
return self.length;
}
- (id)objectAtIndex:(CPUInteger)anIndex
{
if (anIndex >= self.length || anIndex < 0)
_CPRaiseRangeException(self, _cmd, anIndex, self.length);
return self[anIndex];
}
- (CPUInteger)indexOfObject:(id)anObject
{
return [self indexOfObject:anObject inRange:nil];
}
- (CPUInteger)indexOfObject:(id)anObject inRange:(CPRange)aRange
{
// Only use isEqual: if our object is a CPObject.
if (anObject && anObject.isa)
{
var index = aRange ? aRange.location : 0,
count = aRange ? CPMaxRange(aRange) : self.length;
for (; index < count; ++index)
if ([self[index] isEqual:anObject])
return index;
return CPNotFound;
}
return [self indexOfObjectIdenticalTo:anObject inRange:aRange];
}
- (CPUInteger)indexOfObjectIdenticalTo:(id)anObject
{
return [self indexOfObjectIdenticalTo:anObject inRange:nil];
}
- (CPUInteger)indexOfObjectIdenticalTo:(id)anObject inRange:(CPRange)aRange
{
if (self.indexOf)
return self.indexOf(anObject);
var index = aRange ? aRange.location : 0,
count = aRange ? CPMaxRange(aRange) : self.length;
for (; index < count; ++index)
if (self[index] === anObject)
return index;
return CPNotFound;
}
- (void)makeObjectsPerformSelector:(SEL)aSelector withObjects:(CPArray)objects
{
if (!aSelector)
[CPException raise:CPInvalidArgumentException
reason:"makeObjectsPerformSelector:withObjects: 'aSelector' can't be nil"];
var index = 0,
count = self.length;
if ([objects count])
{
argumentsArray = [[nil, aSelector] arrayByAddingObjectsFromArray:objects];
for (; index < count; ++index)
{
argumentsArray[0] = self[index];
objj_msgSend.apply(this, argumentsArray);
}
}
else
for (; index < count; ++index)
objj_msgSend(self[index], aSelector);
}
- (CPArray)subarrayWithRange:(CPRange)aRange
{
if (aRange.location < 0 || CPMaxRange(aRange) > self.length)
[CPException raise:CPRangeException reason:"subarrayWithRange: aRange out of bounds"];
return self.slice(aRange.location, CPMaxRange(aRange));
}
- (CPString)componentsJoinedByString:(CPString)aString
{
return self.join(aString);
}
- (void)insertObject:(id)anObject atIndex:(CPUInteger)anIndex
{
self.splice(anIndex, 0, anObject);
}
- (void)removeObjectAtIndex:(CPUInteger)anIndex
{
self.splice(anIndex, 1);
}
- (void)addObject:(id)anObject
{
self.push(anObject);
}
- (void)removeLastObject
{
self.pop();
}
- (void)replaceObjectAtIndex:(int)anIndex withObject:(id)anObject
{
self[anIndex] = anObject;
}
- (Class)classForCoder
{
return CPArray;
}
@end
Array.prototype.isa = _CPJavaScriptArray;
+1 -1
View File
@@ -146,7 +146,7 @@
return CPOrderedAscending;
}
return [_rangeEntries indexOfObject:anIndex sortedByFunction:sortFunction];
return [_rangeEntries indexOfObject:anIndex inSortedRange:nil options:0 usingComparator:sortFunction];
}
//Retrieving Attribute Information
+2 -2
View File
@@ -54,7 +54,7 @@
*/
- (void)encodeValueOfObjCType:(CPString)aType at:(id)anObject
{
CPInvalidAbstractInvocation();
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
@@ -63,7 +63,7 @@
*/
- (void)encodeDataObject:(CPData)aData
{
CPInvalidAbstractInvocation();
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*!
+1 -1
View File
@@ -29,7 +29,7 @@
@brief An mutable collection which may contain a specific object
numerous times.
*/
@implementation CPCountedSet : CPMutableSet
@implementation CPCountedSet : _CPConcreteMutableSet
{
Object _counts;
}
+15
View File
@@ -205,11 +205,26 @@ Error.prototype._userInfo = null;
[CPException initialize];
#define METHOD_CALL_STRING()\
((class_isMetaClass(anObject.isa) ? "+" : "-") + "[" + [anObject className] + " " + aSelector + "]: ")
function _CPRaiseInvalidAbstractInvocation(anObject, aSelector)
{
[CPException raise:CPInvalidArgumentException reason:@"*** -" + sel_getName(aSelector) + @" cannot be sent to an abstract object of class " + [anObject className] + @": Create a concrete instance!"];
}
function _CPRaiseInvalidArgumentException(anObject, aSelector, aMessage)
{
[CPException raise:CPInvalidArgumentException
reason:METHOD_CALL_STRING() + aMessage];
}
function _CPRaiseRangeException(anObject, aSelector, anIndex, aCount)
{
[CPException raise:CPRangeException
reason:METHOD_CALL_STRING() + "index (" + anIndex + ") beyond bounds (" + aCount + ")"];
}
function _CPReportLenientDeprecation(/*Class*/ aClass, /*SEL*/ oldSelector, /*SEL*/ newSelector)
{
CPLog.warn("[" + CPStringFromClass(aClass) + " " + CPStringFromSelector(oldSelector) + "] is deprecated, using " + CPStringFromSelector(newSelector) + " instead.");
+7 -5
View File
@@ -33,7 +33,9 @@
make sure that you cannot configure the public subclasses CPDateFormatter and CPNumberFormatter to satisfy your requirements.
*/
@import <Foundation/CPObject.j>
@import "CPException.j"
@import "CPObject.j"
@implementation CPFormatter : CPObject
@@ -51,7 +53,7 @@
*/
- (CPString)stringForObjectValue:(id)anObject
{
_CPRaiseInvalidAbstractInvocation(self, @selector(stringForObjectValue:));
_CPRaiseInvalidAbstractInvocation(self, _cmd);
return nil;
}
@@ -96,7 +98,7 @@
*/
- (BOOL)getObjectValue:(id)anObject forString:(CPString)aString errorDescription:(CPString)anError
{
_CPRaiseInvalidAbstractInvocation(self, @selector(getObjectValue:forString:errorDescription:));
_CPRaiseInvalidAbstractInvocation(self, _cmd);
return NO;
}
@@ -125,7 +127,7 @@
*/
- (BOOL)isPartialStringValid:(CPString)aPartialString newEditingString:(CPString)aNewString errorDescription:(CPString)anError
{
_CPRaiseInvalidAbstractInvocation(self, @selector(isPartialStringValid:newEditingString:errorDescription:));
_CPRaiseInvalidAbstractInvocation(self, _cmd);
return NO;
}
@@ -150,7 +152,7 @@
*/
- (BOOL)isPartialStringValue:(CPString)aPartialString proposedSelectedRange:(CPRange)aProposedSelectedRange originalString:(CPString)originalString originalSelectedRange:(CPRange)originalSelectedRange errorDescription:(CPString)anError
{
_CPRaiseInvalidAbstractInvocation(self, @selector(isPartialStringValue:proposedSelectedRange:originalString:originalSelectedRange:errorDescription:));
_CPRaiseInvalidAbstractInvocation(self, _cmd);
return NO;
}
+235 -136
View File
@@ -24,117 +24,15 @@
@import "CPDictionary.j"
@import "CPNull.j"
@import "CPObject.j"
@import "CPSet.j"
var CPObjectAccessorsForClass = nil,
CPObjectModifiersForClass = nil;
CPUndefinedKeyException = @"CPUndefinedKeyException";
CPTargetObjectUserInfoKey = @"CPTargetObjectUserInfoKey";
CPUnknownUserInfoKey = @"CPUnknownUserInfoKey";
var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
CPObjectModifiersForClassKey = @"$CPObjectModifiersForClassKey";
var Null = [CPNull null];
var _accessorForKey = function(theClass, aKey)
{
var selector = nil,
accessors = theClass[CPObjectAccessorsForClassKey];
if (accessors)
{
selector = accessors[aKey];
if (selector)
return selector === Null ? nil : selector;
}
else
accessors = theClass[CPObjectAccessorsForClassKey] = {};
var capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1);
if ([theClass instancesRespondToSelector:selector = CPSelectorFromString("get" + capitalizedKey)] ||
[theClass instancesRespondToSelector:selector = CPSelectorFromString(aKey)] ||
[theClass instancesRespondToSelector:selector = CPSelectorFromString("is" + capitalizedKey)] ||
[theClass instancesRespondToSelector:selector = CPSelectorFromString("_get" + capitalizedKey)] || //FIXME: is deprecated in Cocoa 10.3
[theClass instancesRespondToSelector:selector = CPSelectorFromString("_" + aKey)] || //FIXME: is deprecated in Cocoa 10.3
[theClass instancesRespondToSelector:selector = CPSelectorFromString("_is" + capitalizedKey)]) //FIXME: was NEVER supported by Cocoa
{
accessors[aKey] = selector;
return selector;
}
accessors[aKey] = Null;
return nil;
}
var _modifierForKey = function(theClass, aKey)
{
if (!CPObjectModifiersForClass)
CPObjectModifiersForClass = [CPDictionary dictionary];
var UID = [theClass UID],
selector = nil,
modifiers = [CPObjectModifiersForClass objectForKey:UID];
if (modifiers)
{
selector = [modifiers objectForKey:aKey];
if (selector)
return selector === Null ? nil : selector;
}
else
{
modifiers = [CPDictionary dictionary];
[CPObjectModifiersForClass setObject:modifiers forKey:UID];
}
var capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1) + ':';
if ([theClass instancesRespondToSelector:selector = CPSelectorFromString("set" + capitalizedKey)] ||
[theClass instancesRespondToSelector:selector = CPSelectorFromString("_set" + capitalizedKey)]) //FIXME: deprecated in Cocoa 10.3
{
[modifiers setObject:selector forKey:aKey];
return selector;
}
[modifiers setObject:Null forKey:aKey];
return nil;
}
var _ivarForKey = function(theObject, aKey)
{
var ivar = '_' + aKey;
if (typeof theObject[ivar] != "undefined")
return ivar;
var isKey = "is" + aKey.charAt(0).toUpperCase() + aKey.substr(1);
ivar = '_' + isKey;
if (typeof theObject[ivar] != "undefined")
return ivar;
ivar = aKey;
if (typeof theObject[ivar] != "undefined")
return ivar;
ivar = isKey;
if (typeof theObject[ivar] != "undefined")
return ivar;
return nil;
}
var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
CPObjectModifiersForClassKey = @"$CPObjectModifiersForClassKey";
@implementation CPObject (CPKeyValueCoding)
@@ -146,21 +44,74 @@ var _ivarForKey = function(theObject, aKey)
- (id)valueForKey:(CPString)aKey
{
var theClass = [self class],
selector = _accessorForKey(theClass, aKey);
accessor = nil,
accessors = theClass[CPObjectAccessorsForClassKey];
if (selector)
return objj_msgSend(self, selector);
if (!accessors)
accessors = theClass[CPObjectAccessorsForClassKey] = { };
//FIXME: at this point search for array access methods: "countOf<Key>", "objectIn<Key>AtIndex:", "<key>AtIndexes:"
// or set access methods: "countOf<Key>", "enumeratorOf<Key>", "memberOf<Key>:"
//and return (immutable) array/set proxy! (see NSKeyValueCoding.h)
if (accessors.hasOwnProperty(aKey))
accessor = accessors[aKey];
if ([theClass accessInstanceVariablesDirectly])
else
{
var ivar = _ivarForKey(self, aKey);
var string = nil,
capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1),
underscoreKey = nil,
isKey = nil;
if (ivar)
return self[ivar];
// First search for accessor methods of the form -get<Key>, -<key>, -is<Key>
// (the underscore versions are deprecated)
if ([theClass instancesRespondToSelector:string = sel_getUid("get" + capitalizedKey)] ||
[theClass instancesRespondToSelector:string = sel_getUid(aKey)] ||
[theClass instancesRespondToSelector:string = sel_getUid((isKey = "is" + capitalizedKey))] ||
//FIXME: is deprecated in Cocoa 10.3
[theClass instancesRespondToSelector:string = sel_getUid("_get" + capitalizedKey)] ||
//FIXME: is deprecated in Cocoa 10.3
[theClass instancesRespondToSelector:string = sel_getUid((underscoreKey = "_" + aKey))] ||
//FIXME: was NEVER supported by Cocoa
[theClass instancesRespondToSelector:string = sel_getUid("_" + isKey)])
accessor = accessors[aKey] = [0, string];
else if ([theClass instancesRespondToSelector:sel_getUid("countOf" + capitalizedKey)])
{
// Otherwise, search for ordered to-many relationships:
// -countOf<Key> and either of -objectIn<Key>atIndex: or -<key>AtIndexes:.
if ([theClass instancesRespondToSelector:sel_getUid("objectIn" + capitalizedKey + "AtIndex:")] ||
[theClass instancesRespondToSelector:sel_getUid(aKey + "AtIndexes:")])
accessor = accessors[aKey] = [1];
// Otherwise, search for unordered to-many relationships
// -countOf<Key>, -enumeratorOf<Key>, and -memberOf<Key>:.
else if ([theClass instancesRespondToSelector:sel_getUid("enumeratorOf" + capitalizedKey)] &&
[theClass instancesRespondToSelector:sel_getUid("memberOf" + capitalizedKey + ":")])
accessor = accessors[aKey] = [2];
}
if (!accessor)
{
// Otherwise search for instance variable: _<key>, _is<Key>, key, is<Key>
if (class_getInstanceVariable(theClass, string = underscoreKey) ||
class_getInstanceVariable(theClass, string = "_" + isKey) ||
class_getInstanceVariable(theClass, string = aKey) ||
class_getInstanceVariable(theClass, string = isKey))
accessor = accessors[aKey] = [3, string];
// Otherwise return valueForUndefinedKey:
else
accessor = accessors[aKey] = [];
}
}
switch (accessor[0])
{
case 0: return objj_msgSend(self, accessor[1]);
// FIXME: We shouldn't be creating a new one every time.
case 1: return [[_CPKeyValueCodingArray alloc] initWithTarget:self key:aKey];
// FIXME: We shouldn't be creating a new one every time.
case 2: return [[_CPKeyValueCodingSet alloc] initWithTarget:self key:aKey];
case 3: if ([theClass accessInstanceVariablesDirectly])
return self[accessor[1]];
}
return [self valueForUndefinedKey:aKey];
@@ -170,7 +121,7 @@ var _ivarForKey = function(theObject, aKey)
{
var firstDotIndex = aKeyPath.indexOf(".");
if (firstDotIndex === -1)
if (firstDotIndex === CPNotFound)
return [self valueForKey:aKeyPath];
var firstKeyComponent = aKeyPath.substring(0, firstDotIndex),
@@ -193,6 +144,7 @@ var _ivarForKey = function(theObject, aKey)
if (value === nil)
[dictionary setObject:[CPNull null] forKey:key];
else
[dictionary setObject:value forKey:key];
}
@@ -209,11 +161,12 @@ var _ivarForKey = function(theObject, aKey)
- (void)setValue:(id)aValue forKeyPath:(CPString)aKeyPath
{
if (!aKeyPath) aKeyPath = @"self";
if (!aKeyPath)
aKeyPath = @"self";
var firstDotIndex = aKeyPath.indexOf(".");
if (firstDotIndex === -1)
if (firstDotIndex === CPNotFound)
return [self setValue:aValue forKey:aKeyPath];
var firstKeyComponent = aKeyPath.substring(0, firstDotIndex),
@@ -226,28 +179,52 @@ var _ivarForKey = function(theObject, aKey)
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
var theClass = [self class],
selector = _modifierForKey(theClass, aKey);
modifier = nil,
modifiers = theClass[CPObjectModifiersForClassKey];
if (selector)
return objj_msgSend(self, selector, aValue);
if (!modifiers)
modifiers = theClass[CPObjectModifiersForClassKey] = { };
if ([theClass accessInstanceVariablesDirectly])
if (modifiers.hasOwnProperty(aKey))
modifier = modifiers[aKey];
else
{
var ivar = _ivarForKey(self, aKey);
var string = nil,
capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1),
isKey = nil;
if (ivar)
{
[self willChangeValueForKey:aKey];
if ([theClass instancesRespondToSelector:string = sel_getUid("set" + capitalizedKey + ":")] ||
//FIXME: deprecated in Cocoa 10.3
[theClass instancesRespondToSelector:string = sel_getUid("_set" + capitalizedKey + ":")])
modifier = modifiers[aKey] = [0, string];
self[ivar] = aValue;
else if (class_getInstanceVariable(theClass, string = "_" + aKey) ||
class_getInstanceVariable(theClass, string = "_" + (isKey = "is" + capitalizedKey)) ||
class_getInstanceVariable(theClass, string = aKey) ||
class_getInstanceVariable(theClass, string = isKey))
modifier = modifiers[aKey] = [1, string];
[self didChangeValueForKey:aKey];
return;
}
else
modifier = modifiers[aKey] = [];
}
[self setValue:aValue forUndefinedKey:aKey];
switch (modifier[0])
{
case 0: return objj_msgSend(self, modifier[1], aValue);
case 1: if ([theClass accessInstanceVariablesDirectly])
{
[self willChangeValueForKey:aKey];
self[modifier[1]] = aValue;
return [self didChangeValueForKey:aKey];
}
}
return [self setValue:aValue forUndefinedKey:aKey];
}
- (void)setValuesForKeysWithDictionary:(CPDictionary)keyedValues
@@ -259,8 +236,10 @@ var _ivarForKey = function(theObject, aKey)
while (key = [keyEnumerator nextObject])
{
value = [keyedValues objectForKey: key];
if (value === [CPNull null])
[self setValue: nil forKey: key];
else
[self setValue: value forKey: key];
}
@@ -275,7 +254,7 @@ var _ivarForKey = function(theObject, aKey)
@end
@implementation CPDictionary (KeyValueCoding)
@implementation CPDictionary (CPKeyValueCoding)
- (id)valueForKey:(CPString)aKey
{
@@ -287,21 +266,141 @@ var _ivarForKey = function(theObject, aKey)
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
if (aValue)
if (aValue !== nil)
[self setObject:aValue forKey:aKey];
else
[self removeObjectForKey: aKey];
[self removeObjectForKey:aKey];
}
@end
@implementation CPNull (KeyValueCoding)
@implementation CPNull (CPKeyValueCoding)
- (id)valueForKey:(CPString)aKey
{
return self;
}
@end
@implementation _CPKeyValueCodingArray : CPArray
{
id _target;
SEL _countOfSelector;
SEL _objectInAtIndexSelector;
SEL _atIndexesSelector;
}
- (id)initWithTarget:(id)aTarget key:(CPString)aKey
{
self = [super init];
if (self)
{
var capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1);
_target = aTarget;
_countOfSelector = CPSelectorFromString("countOf" + capitalizedKey);
_objectInAtIndexSelector = CPSelectorFromString("objectIn" + capitalizedKey + "AtIndex:");
if (![_target respondsToSelector:_objectInAtIndexSelector])
_objectInAtIndexSelector = nil;
_atIndexesSelector = CPSelectorFromString(aKey + "AtIndexes:");
if (![_target respondsToSelector:_atIndexesSelector])
_atIndexesSelector = nil;
}
return self;
}
- (CPUInteger)count
{
return objj_msgSend(_target, _countOfSelector);
}
- (id)objectAtIndex:(CPUInteger)anIndex
{
if (_objectInAtIndexSelector)
return objj_msgSend(_target, _objectInAtIndexSelector, anIndex);
return objj_msgSend(_target, _atIndexesSelector, [CPIndexSet indexSetWithIndex:anIndex])[0];
}
- (CPArray)objectsAtIndexes:(CPIndexSet)indexes
{
if (_atIndexesSelector)
return objj_msgSend(_target, _atIndexesSelector, indexes);
return [super objectsAtIndexes:indexes];
}
- (Class)classForCoder
{
return [CPArray class];
}
@end
@implementation _CPKeyValueCodingSet : CPSet
{
id _target;
SEL _countOfSelector;
SEL _enumeratorOfSelector;
SEL _memberOfSelector;
}
// This allows things like setByAddingObject: to work (since they use [[self class] alloc] internally).
- (id)initWithObjects:(CPArray)objects count:(CPUInteger)aCount
{
return [[CPSet alloc] initWithObjects:objects count:aCount];
}
- (id)initWithTarget:(id)aTarget key:(CPString)aKey
{
self = [super initWithObjects:nil count:0];
if (self)
{
var capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1);
_target = aTarget;
_countOfSelector = CPSelectorFromString("countOf" + capitalizedKey);
_enumeratorOfSelector = CPSelectorFromString("enumeratorOf" + capitalizedKey);
_memberOfSelector = CPSelectorFromString("memberOf" + capitalizedKey + ":");
}
return self;
}
- (CPUInteger)count
{
return objj_msgSend(_target, _countOfSelector);
}
- (CPEnumerator)objectEnumerator
{
return objj_msgSend(_target, _enumeratorOfSelector);
}
- (id)member:(id)anObject
{
return objj_msgSend(_target, _memberOfSelector, anObject);
}
- (Class)classForCoder
{
return [CPSet class];
}
@end
@import "CPKeyValueObserving.j"
+24 -28
View File
@@ -37,19 +37,19 @@
{
}
- (void)willChange:(CPKeyValueChange)change valuesAtIndexes:(CPIndexSet)indexes forKey:(CPString)key
- (void)willChange:(CPKeyValueChange)aChange valuesAtIndexes:(CPIndexSet)indexes forKey:(CPString)aKey
{
}
- (void)didChange:(CPKeyValueChange)change valuesAtIndexes:(CPIndexSet)indexes forKey:(CPString)key
- (void)didChange:(CPKeyValueChange)aChange valuesAtIndexes:(CPIndexSet)indexes forKey:(CPString)aKey
{
}
- (void)willChangeValueForKey:(CPString)key withSetMutation:(CPKeyValueSetMutationKind)mutationKind usingObjects:(CPSet)objects
- (void)willChangeValueForKey:(CPString)aKey withSetMutation:(CPKeyValueSetMutationKind)aMutationKind usingObjects:(CPSet)objects
{
}
- (void)didChangeValueForKey:(CPString)key withSetMutation:(CPKeyValueSetMutationKind)mutationKind usingObjects:(CPSet)objects
- (void)didChangeValueForKey:(CPString)aKey withSetMutation:(CPKeyValueSetMutationKind)aMutationKind usingObjects:(CPSet)objects
{
}
@@ -89,36 +89,38 @@
{
var changeKind = [aChange objectForKey:CPKeyValueChangeKindKey],
oldValue = [aChange objectForKey:CPKeyValueChangeOldKey],
newValue = [aChange objectForKey:CPKeyValueChangeNewKey],
indexes = [aChange objectForKey:CPKeyValueChangeIndexesKey];
newValue = [aChange objectForKey:CPKeyValueChangeNewKey];
if (newValue === [CPNull null])
newValue = nil;
if (changeKind === CPKeyValueChangeSetting)
{
[self setValue:newValue forKeyPath:aKeyPath];
return;
}
return [self setValue:newValue forKeyPath:aKeyPath];
//decide if this is a unordered or ordered to-many relationship
if ([newValue isKindOfClass: [CPSet class]] || [oldValue isKindOfClass: [CPSet class]])
var indexes = [aChange objectForKey:CPKeyValueChangeIndexesKey];
// If we have an indexes entry, then we have an ordered to-many relationship
if (indexes)
{
if (changeKind === CPKeyValueChangeInsertion)
[[self mutableSetValueForKeyPath:aKeyPath] unionSet:newValue];
[[self mutableArrayValueForKeyPath:aKeyPath] insertObjects:newValue atIndexes:indexes];
else if (changeKind === CPKeyValueChangeRemoval)
[[self mutableSetValueForKeyPath:aKeyPath] minusSet:oldValue];
[[self mutableArrayValueForKeyPath:aKeyPath] removeObjectsAtIndexes:indexes];
else if (changeKind === CPKeyValueChangeReplacement)
[[self mutableSetValueForKeyPath:aKeyPath] setSet: newValue];
[[self mutableArrayValueForKeyPath:aKeyPath] replaceObjectAtIndexes:indexes withObjects:newValue];
}
else
{
if (changeKind === CPKeyValueChangeInsertion)
[[self mutableArrayValueForKeyPath:aKeyPath] insertObjects:newValue atIndexes:indexes];
[[self mutableSetValueForKeyPath:aKeyPath] unionSet:newValue];
else if (changeKind === CPKeyValueChangeRemoval)
[[self mutableArrayValueForKeyPath:aKeyPath] removeObjectsAtIndexes:indexes];
[[self mutableSetValueForKeyPath:aKeyPath] minusSet:oldValue];
else if (changeKind === CPKeyValueChangeReplacement)
[[self mutableArrayValueForKeyPath:aKeyPath] replaceObjectAtIndexes:indexes withObjects:newValue];
[[self mutableSetValueForKeyPath:aKeyPath] setSet:newValue];
}
}
@@ -282,18 +284,12 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
kvoClass._replacedKeys = _replacedKeys;
//copy in the methods from our model subclass
var methodList = _CPKVOModelSubclass.method_list;
var methods = class_copyMethodList(_CPKVOModelSubclass);
if ([_targetObject isKindOfClass:[CPDictionary class]])
methodList = methodList.concat(_CPKVOModelDictionarySubclass.method_list);
methods = methods.concat(class_copyMethodList(_CPKVOModelDictionarySubclass));
var count = methodList.length,
i = 0;
for (; i < count; i++)
{
var method = methodList[i];
class_addMethod(kvoClass, method_getName(method), method_getImplementation(method), "");
}
class_addMethods(kvoClass, methods);
_targetObject.isa = kvoClass;
}
+2 -2
View File
@@ -385,7 +385,7 @@ var _CPKeyedArchiverStringClass = Nil,
{
var i = 0,
count = objects.length,
references = [CPArray arrayWithCapacity:count];
references = [];
for (; i < count; ++i)
[references addObject:_CPKeyedArchiverEncodeObject(self, objects[i], NO)];
@@ -434,7 +434,7 @@ var _CPKeyedArchiverStringClass = Nil,
if (!CPArchiverReplacementClassNames)
return aClass.name;
var className = [CPArchiverReplacementClassNames objectForKey:CPStringFromClass(aClassName)];
var className = [CPArchiverReplacementClassNames objectForKey:CPStringFromClass(aClass)];
return className ? className : aClass.name;
}
+1 -1
View File
@@ -335,7 +335,7 @@ var CPArrayClass = Ni
else if (objectClass === CPNumberClass || objectClass === CPDataClass || objectClass === CPStringClass)
return object;
else if (objectClass === CPArrayClass || objectClass === CPMutableArrayClass)
else if (objectClass === _CPJavaScriptArray)
{
var index = 0,
count = object.length,
+2
View File
@@ -471,6 +471,8 @@ CPLog(@"Got some class: %@", inst);
*/
- (CPString)className
{
// FIXME: Why doesn't this work in KVO???
// return class_getName([self class]);
return isa.name;
}
+4 -3
View File
@@ -536,12 +536,13 @@ function(newValue)\
if ([self scanString:@"{" intoString:NULL])
{
var a = [CPMutableArray arrayWithCapacity:10];
if ([self scanString:@"}" intoString:NULL])
return [CPExpression expressionForConstantValue:a];
var a = [];
[a addObject:[self parseExpression]];
while ([self scanString:@"," intoString:NULL])
[a addObject:[self parseExpression]];
@@ -779,7 +780,7 @@ function(newValue)\
{
// function - this parser allows for (max)(a, b, c) to be properly
// recognized and even (%K)(a, b, c) if %K evaluates to "max"
var args = [CPMutableArray arrayWithCapacity:5];
var args = [];
if (![left keyPath])
CPRaiseParseError(self, @"expression");
-33
View File
@@ -372,32 +372,6 @@
@implementation CPSet (CPKeyValueCoding)
- (id)valueForKey:(CPString)aKey
{
if (aKey.indexOf("@") === 0)
{
if (aKey.indexOf(".") !== -1)
[CPException raise:CPInvalidArgumentException reason:"called valueForKey: on a set with a complex key ("+aKey+"). use valueForKeyPath:"];
if (aKey == "@count")
return [self count];
return nil;
}
else
{
var valuesForKeySet = [CPSet set];
var containedObject, containedObjectValue, containedObjectEnumerator = [self objectEnumerator];
while(containedObject = [containedObjectEnumerator nextObject])
{
containedObjectValue = [containedObject valueForKey:aKey];
if(containedObjectValue)
[valuesForKeySet addObject:containedObjectValue];
}
return valuesForKeySet;
}
}
- (id)valueForKeyPath:(CPString)aKeyPath
{
if (aKeyPath.indexOf("@") === 0)
@@ -440,13 +414,6 @@
[containedObject setValue:aValue forKey:aKey];
}
- (void)setValue:(id)aValue forKeyPath:(CPString)aKeyPath
{
var containedObject, containedObjectEnumerator = [self objectEnumerator];
while (containedObject = [containedObjectEnumerator nextObject])
[containedObject setValue:aValue forKeyPath:aKeyPath];
}
@end
var kvoOperators = [];
+475 -308
View File
@@ -5,6 +5,7 @@
* Created by Bailey Carlson
* Extended by Ross Boucher
* Extended by Nabil Elisa
* Rewritten by Francisco Tolmasky
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
@@ -21,7 +22,6 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* TODO: Needs to implement CPCoding, CPCopying.
*/
@import "CPArray.j"
@@ -29,15 +29,17 @@
@import "CPNumber.j"
@import "CPObject.j"
/*!
@class CPSet
@ingroup foundation
@brief An unordered collection of objects.
*/
@implementation CPSet : CPObject
{
Object _contents;
unsigned _count;
}
+ (id)alloc
{
if (self === [CPSet class] || self === [CPMutableSet class])
return [_CPPlaceholderSet alloc];
return [super alloc];
}
/*
@@ -52,9 +54,9 @@
Creates and returns a set containing a uniqued collection of those objects contained in a given array.
@param anArray array containing the objects to add to the new set. If the same object appears more than once objects, it is added only once to the returned set.
*/
+ (id)setWithArray:(CPArray)array
+ (id)setWithArray:(CPArray)anArray
{
return [[self alloc] initWithArray:array];
return [[self alloc] initWithArray:anArray];
}
/*
@@ -63,7 +65,7 @@
*/
+ (id)setWithObject:(id)anObject
{
return [[self alloc] initWithArray:[anObject]];
return [[self alloc] initWithObjects:anObject];
}
/*
@@ -71,7 +73,7 @@
@param objects A array of objects to add to the new set. If the same object appears more than once objects, it is added only once to the returned set.
@param count The number of objects from objects to add to the new set.
*/
+ (id)setWithObjects:(id)objects count:(unsigned)count
+ (id)setWithObjects:(id)objects count:(CPUInteger)count
{
return [[self alloc] initWithObjects:objects count:count];
}
@@ -83,14 +85,12 @@
*/
+ (id)setWithObjects:(id)anObject, ...
{
var set = [[self alloc] init],
argLength = arguments.length,
i = 2;
var argumentsArray = Array.prototype.slice.apply(arguments);
for (; i < argLength && ((argument = arguments[i]) !== nil); ++i)
[set addObject:argument];
argumentsArray[0] = [self alloc];
argumentsArray[1] = @selector(initWithObjects:);
return set;
return objj_msgSend.apply(this, argumentsArray);
}
/*
@@ -102,18 +102,27 @@
return [[self alloc] initWithSet:set];
}
- (id)setByAddingObject:(id)anObject
{
return [[self class] setWithArray:[[self allObjects] arrayByAddingObject:anObject]];
}
- (id)setByAddingObjectsFromSet:(CPSet)aSet
{
return [self setByAddingObjectsFromArray:[aSet allObjects]];
}
- (id)setByAddingObjectsFromArray:(CPArray)anArray
{
return [[self class] setWithArray:[[self allObjects] arrayByAddingObjectsFromArray:anArray]];
}
/*
Basic initializer, returns an empty set
*/
- (id)init
{
if (self = [super init])
{
_count = 0;
_contents = {};
}
return self;
return [self initWithObjects:nil count:0];
}
/*
@@ -122,25 +131,7 @@
*/
- (id)initWithArray:(CPArray)anArray
{
if (self = [self init])
{
var count = anArray.length;
while (count--)
[self addObject:anArray[count]];
}
return self;
}
/*
Initializes a newly allocated set with members taken from the specified list of objects.
@param objects A array of objects to add to the new set. If the same object appears more than once objects, it is added only once to the returned set.
@param count The number of objects from objects to add to the new set.
*/
- (id)initWithObjects:(id)objects count:(unsigned)count
{
return [self initWithArray:objects.splice(0, count)];
return [self initWithObjects:anArray count:[anArray count]];
}
/*
@@ -150,24 +141,30 @@
*/
- (id)initWithObjects:(id)anObject, ...
{
if (self = [self init])
{
var argLength = arguments.length,
i = 2;
var index = 2,
count = arguments.length;
for (; i < argLength && (argument = arguments[i]) != nil; ++i)
[self addObject:argument];
}
for (; index < count; ++index)
if (arguments[index] === nil)
break;
return self;
return [self initWithObjects:Array.prototype.slice.call(arguments, 2, index) count:index - 2];
}
- (id)initWithObjects:(CPArray)objects count:(CPUInteger)aCount
{
if (self === _CPSharedPlaceholderSet)
return [[_CPConcreteMutableSet alloc] initWithObjects:objects count:aCount];
return [super init];
}
/*
Initializes a newly allocated set and adds to it objects from another given set. Only included for compatability.
Initializes a newly allocated set and adds to it objects from another given set.
*/
- (id)initWithSet:(CPSet)aSet
{
return [self initWithSet:aSet copyItems:NO];
return [self initWithArray:[aSet allObjects]];
}
/*
@@ -175,26 +172,18 @@
*/
- (id)initWithSet:(CPSet)aSet copyItems:(BOOL)shouldCopyItems
{
self = [self init];
if (shouldCopyItems)
return [aSet valueForKey:@"copy"];
if (!aSet)
return self;
return [self initWithSet:aSet];
}
var contents = aSet._contents,
property;
for (property in contents)
{
if (contents.hasOwnProperty(property))
{
if (shouldCopyItems)
[self addObject:[contents[property] copy]];
else
[self addObject:contents[property]];
}
}
return self;
/*
Returns the number of members in the receiver.
*/
- (CPUInteger)count
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
/*
@@ -202,16 +191,14 @@
*/
- (CPArray)allObjects
{
var array = [],
property;
var objects = [],
object,
objectEnumerator = [self objectEnumerator];
for (property in _contents)
{
if (_contents.hasOwnProperty(property))
array.push(_contents[property]);
}
while ((object = [objectEnumerator nextObject]) !== nil)
objects.push(object);
return array;
return objects;
}
/*
@@ -219,15 +206,7 @@
*/
- (id)anyObject
{
var property;
for (property in _contents)
{
if (_contents.hasOwnProperty(property))
return _contents[property];
}
return nil;
return [[self objectEnumerator] nextObject];
}
/*
@@ -236,25 +215,112 @@
*/
- (BOOL)containsObject:(id)anObject
{
var obj = _contents[[anObject UID]];
return [self member:anObject] !== nil;
}
if (obj !== undefined && [obj isEqual:anObject])
return YES;
- (void)filteredSetUsingPredicate:(CPPredicate)aPredicate
{
var objects = [],
object,
objectEnumerator = [self objectEnumerator];
return NO;
while ((object = [objectEnumerator nextObject]) !== nil)
if ([aPredicate evaluateWithObject:object])
objects.push(object);
return [[[self class] alloc] initWithArray:objects];
}
/*
Returns the number of members in the receiver.
Sends to each object in the receiver a message specified by a given selector.
@param aSelector A selector that specifies the message to send to the members of the receiver. The method must not take any arguments. It should not have the side effect of modifying the receiver. This value must not be NULL.
*/
- (unsigned)count
- (void)makeObjectsPerformSelector:(SEL)aSelector
{
return _count;
[self makeObjectsPerformSelector:aSelector withObjects:nil];
}
//- (CPString)description;
//
//- (CPString)descriptionWithLocale:(CPDictionary)locale;
/*
Sends to each object in the receiver a message specified by a given selector.
@param aSelector A selector that specifies the message to send to the receiver's members. The method must take a single argument of type id. The method should not, as a side effect, modify the receiver. The value must not be NULL.
@param anObject The object to pass as an argument to the method specified by aSelector.
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject
{
[self makeObjectsPerformSelector:aSelector withObjects:[anObject]];
}
/*
Sends to each object in the receiver a message specified by a given selector.
@param aSelector A selector that specifies the message to send to the receiver's members. The method must take a single argument of type id. The method should not, as a side effect, modify the receiver. The value must not be NULL.
@param objects The objects to pass as an argument to the method specified by aSelector.
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector withObjects:(CPArray)objects
{
var object,
objectEnumerator = [self objectEnumerator],
argumentsArray = [nil, aSelector].concat(objects || []);
while ((object = [objectEnumerator nextObject]) !== nil)
{
argumentsArray[0] = object;
objj_msgSend.apply(this, argumentsArray);
}
}
/*
Determines whether the receiver contains an object equal to a given object, and returns that object if it is present.
@param anObject The object for which to test for membership of the receiver.
*/
- (id)member:(id)anObject
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
- (CPEnumerator)objectEnumerator
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
- (void)enumerateObjectsUsingBlock:(Function)aFunction
{
var object,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
if (aFunction(object))
break;
}
// FIXME: stop is broken.
- (CPSet)objectsPassingTest:(Function)aFunction
{
var objects = [],
object = nil,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
if (aFunction(object))
objects.push(object);
return [[[self class] alloc] initWithArray:objects];
}
/*
Returns a Boolean value that indicates whether every object in the receiver is also present in another given set.
@param set The set with which to compare the receiver.
*/
- (BOOL)isSubsetOfSet:(CPSet)aSet
{
var object = nil,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
if (![self containsObject:object])
return NO;
return YES;
}
/*
Returns a Boolean value that indicates whether at least one object in the receiver is also present in another given set.
@@ -263,14 +329,14 @@
- (BOOL)intersectsSet:(CPSet)aSet
{
if (self === aSet)
return YES;
// The empty set intersects nothing
return [self count] > 0;
var objects = [aSet allObjects],
count = [objects count];
var object = nil,
objectEnumerator = [self objectEnumerator];
// If the sets share at least one item, they intersect
while (count--)
if ([self containsObject:objects[count]])
while ((object = [objectEnumerator nextObject]) !== nil)
if ([aSet containsObject:object])
return YES;
return NO;
@@ -280,215 +346,35 @@
Compares the receiver to another set.
@param set The set with which to compare the receiver.
*/
- (BOOL)isEqualToSet:(CPSet)set
- (BOOL)isEqualToSet:(CPSet)aSet
{
return [self isEqual:aSet];
}
- (BOOL)isEqual:(CPSet)aSet
{
// If both are subsets of each other, they are equal
return self === set || ([self count] === [set count] && [set isSubsetOfSet:self]);
}
/*
Returns a Boolean value that indicates whether every object in the receiver is also present in another given set.
@param set The set with which to compare the receiver.
*/
- (BOOL)isSubsetOfSet:(CPSet)set
{
var items = [self allObjects],
i = 0,
count = items.length;
for (; i < count; i++)
{
// If at least one item is not in both sets, self isn't a subset
if (![set containsObject:items[i]])
return NO;
}
return YES;
}
/*
Sends to each object in the receiver a message specified by a given selector.
@param aSelector A selector that specifies the message to send to the members of the receiver. The method must not take any arguments. It should not have the side effect of modifying the receiver. This value must not be NULL.
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector
{
[self makeObjectsPerformSelector:aSelector withObject:nil];
}
/*
Sends to each object in the receiver a message specified by a given selector.
@param aSelector A selector that specifies the message to send to the receiver's members. The method must take a single argument of type id. The method should not, as a side effect, modify the receiver. The value must not be NULL.
@param anObject The object to pass as an argument to the method specified by aSelector.
*/
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument
{
var items = [self allObjects],
i = 0,
count = items.length;
for (; i < count; i++)
{
[items[i] performSelector:aSelector withObject:argument];
}
}
/*
Determines whether the receiver contains an object equal to a given object, and returns that object if it is present.
@param anObject The object for which to test for membership of the receiver.
*/
- (id)member:(id)object
{
if ([self containsObject:object])
return object;
return nil;
}
- (CPEnumerator)objectEnumerator
{
return [[self allObjects] objectEnumerator];
}
// Mutable Set Methods
/*
Returns an initialized set with a given initial capacity.
@param numItems, only present for compatability
*/
- (id)initWithCapacity:(unsigned)numItems
{
// Only here for compatability with Cocoa
self = [self init];
return self;
}
/*
Creates and returns a set with a given initial capacity.
@param numItems, only present for compatability
*/
+ (id)setWithCapacity:(unsigned)numItems
{
return [[self alloc] initWithCapacity:numItems];
}
/*
Empties the receiver, then adds to the receiver each object contained in another given set.
@param set The set whose members replace the receiver's content.
*/
- (void)setSet:(CPSet)set
{
[self removeAllObjects];
[self addObjectsFromArray:[set allObjects]];
}
/*
Adds a given object to the receiver.
@param anObject The object to add to the receiver.
*/
- (void)addObject:(id)anObject
{
if ([self containsObject:anObject])
return;
_contents[[anObject UID]] = anObject;
_count++;
}
/*
Adds to the receiver each object contained in a given array that is not already a member.
@param array An array of objects to add to the receiver.
*/
- (void)addObjectsFromArray:(CPArray)objects
{
var count = [objects count];
while (count--)
[self addObject:objects[count]];
}
/*
Removes a given object from the receiver.
@param anObject The object to remove from the receiver.
*/
- (void)removeObject:(id)anObject
{
if ([self containsObject:anObject])
{
delete _contents[[anObject UID]];
_count--;
}
}
- (void)removeObjectsInArray:(CPArray)objects
{
var count = [objects count];
while (count--)
[self removeObject:objects[count]];
}
/*
Empties the receiver of all of its members.
*/
- (void)removeAllObjects
{
_contents = {};
_count = 0;
}
/*
Removes from the receiver each object that isn’t a member of another given set.
@param set The set with which to perform the intersection.
*/
- (void)intersectSet:(CPSet)set
{
var items = [self allObjects],
i = 0,
count = items.length;
for (; i < count; i++)
{
if (![set containsObject:items[i]])
[self removeObject:items[i]];
}
}
/*
Removes from the receiver each object contained in another given set that is present in the receiver.
@param set The set of objects to remove from the receiver.
*/
- (void)minusSet:(CPSet)set
{
var items = [set allObjects],
i = 0,
count = items.length;
for (; i < count; i++)
{
if ([self containsObject:items[i]])
[self removeObject:items[i]];
}
}
/*
Adds to the receiver each object contained in another given set
@param set The set of objects to add to the receiver.
*/
- (void)unionSet:(CPSet)set
{
var items = [set allObjects],
i = 0,
count = items.length;
for (; i < count; i++)
{
[self addObject:items[i]];
}
return self === aSet ||
[aSet isKindOfClass:[CPSet class]] &&
([self count] === [aSet count] &&
[aSet isSubsetOfSet:self]);
}
- (CPString)description
{
return @"{(" + [self allObjects].join(", ") + ")}";
var string = "{(\n",
objects = [self allObjects],
index = 0,
count = [objects count];
for (; index < count; ++index)
{
var object = objects[index];
string += "\t" + String(object).split('\n').join("\n\t") + "\n";
}
return string + ")}";
}
@end
@@ -523,6 +409,56 @@ var CPSetObjectsKey = @"CPSetObjectsKey";
@end
@implementation CPSet (CPKeyValueCoding)
- (id)valueForKey:(CPString)aKey
{
if (aKey === "@count")
return [self count];
var valueSet = [CPSet set],
object,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
{
var value = [object valueForKey:aKey];
// addObject: should be smart enough not to add these, but just in case...
if (value !== nil && value !== undefined)
[valueSet addObject:value];
}
return valueSet;
}
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
var object,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
[object setValue:aValue forKey:aKey];
}
@end
var _CPSharedPlaceholderSet = nil;
@implementation _CPPlaceholderSet : CPSet
{
}
+ (id)alloc
{
if (!_CPSharedPlaceholderSet)
_CPSharedPlaceholderSet = [super alloc];
return _CPSharedPlaceholderSet;
}
@end
/*!
@class CPMutableSet
@ingroup compatability
@@ -534,4 +470,235 @@ var CPSetObjectsKey = @"CPSetObjectsKey";
@implementation CPMutableSet : CPSet
/*
Returns an initialized set with a given initial capacity.
@param aCapacity, only present for compatability
*/
- (id)initWithCapacity:(unsigned)aCapacity
{
return [self init];
}
/*
Creates and returns a set with a given initial capacity.
@param aCapacity, only present for compatability
*/
+ (id)setWithCapacity:(CPUInteger)aCapacity
{
return [[self alloc] initWithCapacity:aCapacity];
}
- (void)filterUsingPredicate:(CPPredicate)aPredicate
{
var object,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
if (![aPredicate evaluateWithObject:object])
[self removeObject:object];
}
- (void)removeObject:(id)anObject
{
_CPRaiseInvalidAbstractInvocation(self, _cmd);
}
- (void)removeAllObjects
{
var object,
objectEnumerator = [self objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
[self removeObject:object];
}
/*
Adds to the receiver each object contained in a given array that is not already a member.
@param array An array of objects to add to the receiver.
*/
- (void)addObjectsFromArray:(CPArray)objects
{
var count = [objects count];
while (count--)
[self addObject:objects[count]];
}
/*
Adds to the receiver each object contained in another given set
@param set The set of objects to add to the receiver.
*/
- (void)unionSet:(CPSet)aSet
{
var object,
objectEnumerator = [aSet objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
[self addObject:object];
}
/*
Removes from the receiver each object contained in another given set that is present in the receiver.
@param set The set of objects to remove from the receiver.
*/
- (void)minusSet:(CPSet)aSet
{
var object,
objectEnumerator = [aSet objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
[self removeObject:object];
}
/*
Removes from the receiver each object that isn’t a member of another given set.
@param set The set with which to perform the intersection.
*/
- (void)intersectSet:(CPSet)aSet
{
var object,
objectEnumerator = [self objectEnumerator],
objectsToRemove = [];
while ((object = [objectEnumerator nextObject]) !== nil)
if (![aSet containsObject:object])
objectsToRemove.push(object);
var count = [objectsToRemove count];
while (count--)
[self removeObject:objectsToRemove[count]];
}
/*
Empties the receiver, then adds to the receiver each object contained in another given set.
@param set The set whose members replace the receiver's content.
*/
- (void)setSet:(CPSet)aSet
{
[self removeAllObjects];
[self unionSet:aSet];
}
@end
var hasOwnProperty = Object.prototype.hasOwnProperty;
/*!
@class CPSet
@ingroup foundation
@brief An unordered collection of objects.
*/
@implementation _CPConcreteMutableSet : CPMutableSet
{
Object _contents;
unsigned _count;
}
/*
Initializes a newly allocated set with members taken from the specified list of objects.
@param objects A array of objects to add to the new set. If the same object appears more than once objects, it is added only once to the returned set.
@param count The number of objects from objects to add to the new set.
*/
- (id)initWithObjects:(CPArray)objects count:(CPUInteger)aCount
{
self = [super initWithObjects:objects count:aCount];
if (self)
{
_count = 0;
_contents = { };
var index = 0,
count = MIN([objects count], aCount);
for (; index < count; ++index)
[self addObject:objects[index]];
}
return self;
}
- (CPUInteger)count
{
return _count;
}
- (id)member:(id)anObject
{
var UID = [anObject UID];
if (!hasOwnProperty.call(_contents, UID))
return nil;
var object = _contents[UID];
if (object === anObject || [object isEqual:anObject])
return object;
return nil;
}
- (CPArray)allObjects
{
var array = [],
property;
for (property in _contents)
{
if (hasOwnProperty.call(_contents, property))
array.push(_contents[property]);
}
return array;
}
- (CPEnumerator)objectEnumerator
{
return [[self allObjects] objectEnumerator];
}
/*
Adds a given object to the receiver.
@param anObject The object to add to the receiver.
*/
- (void)addObject:(id)anObject
{
if (anObject === nil || anObject === undefined)
return;
if ([self containsObject:anObject])
return;
_contents[[anObject UID]] = anObject;
_count++;
}
/*
Removes a given object from the receiver.
@param anObject The object to remove from the receiver.
*/
- (void)removeObject:(id)anObject
{
if (![self containsObject:anObject])
return;
delete _contents[[anObject UID]];
_count--;
}
/*
Performance improvement.
*/
- (void)removeAllObjects
{
_contents = {};
_count = 0;
}
- (Class)classForCoder
{
return [CPSet class];
}
@end
+36 -19
View File
@@ -61,11 +61,12 @@ GLOBAL(objj_class) = function(displayName)
this.name = NULL;
this.info = 0;
this.ivars = [];
this.ivar_list = [];
this.ivar_store = function() { };
this.ivar_dtable = this.ivar_store.prototype;
this.method_list = [];
this.method_hash = {};
this.method_store = function() { };
this.method_dtable = this.method_store.prototype;
@@ -135,10 +136,15 @@ GLOBAL(class_addIvar) = function(/*Class*/ aClass, /*String*/ aName, /*String*/
{
var thePrototype = aClass.allocator.prototype;
// FIXME: Use getInstanceVariable
if (typeof thePrototype[aName] != "undefined")
return NO;
aClass.ivars.push(new objj_ivar(aName, aType));
var ivar = new objj_ivar(aName, aType);
aClass.ivar_list.push(ivar);
aClass.ivar_dtable[aName] = ivar;
thePrototype[aName] = NULL;
return YES;
@@ -157,9 +163,12 @@ GLOBAL(class_addIvars) = function(/*Class*/ aClass, /*Array*/ivars)
var ivar = ivars[index],
name = ivar.name;
// FIXME: Use getInstanceVariable
if (typeof thePrototype[name] === "undefined")
{
aClass.ivars.push(ivar);
aClass.ivar_list.push(ivar);
aClass.ivar_dtable[name] = ivar;
thePrototype[name] = NULL;
}
}
@@ -169,20 +178,18 @@ DISPLAY_NAME(class_addIvars);
GLOBAL(class_copyIvarList) = function(/*Class*/ aClass)
{
return aClass.ivars.slice(0);
return aClass.ivar_list.slice(0);
}
DISPLAY_NAME(class_copyIvarList);
//#define class_copyIvarList(aClass) (aClass.ivars.slice(0))
//#define class_copyIvarList(aClass) (aClass.ivar_list.slice(0))
#define METHOD_DISPLAY_NAME(aClass, aMethod) (ISMETA(aClass) ? '+' : '-') + " [" + class_getName(aClass) + ' ' + method_getName(aMethod) + ']'
GLOBAL(class_addMethod) = function(/*Class*/ aClass, /*SEL*/ aName, /*IMP*/ anImplementation, /*Array<String>*/ types)
{
if (aClass.method_hash[aName])
return NO;
// FIXME: return NO if it exists?
var method = new objj_method(aName, anImplementation, types);
aClass.method_list.push(method);
@@ -215,9 +222,7 @@ GLOBAL(class_addMethods) = function(/*Class*/ aClass, /*Array*/ methods)
{
var method = methods[index];
if (aClass.method_hash[method.name])
continue;
// FIXME: Don't do it if it exists?
method_list.push(method);
method_dtable[method.name] = method;
@@ -246,6 +251,19 @@ GLOBAL(class_getInstanceMethod) = function(/*Class*/ aClass, /*SEL*/ aSelector)
DISPLAY_NAME(class_getInstanceMethod);
GLOBAL(class_getInstanceVariable) = function(/*Class*/ aClass, /*String*/ aName)
{
if (!aClass || !aName)
return NULL;
// FIXME: this doesn't appropriately deal with Object's properties.
var variable = aClass.ivar_dtable[aName];
return variable;
}
DISPLAY_NAME(class_getInstanceVariable);
GLOBAL(class_getClassMethod) = function(/*Class*/ aClass, /*SEL*/ aSelector)
{
if (!aClass || !aSelector)
@@ -370,12 +388,11 @@ GLOBAL(objj_allocateClassPair) = function(/*Class*/ superclass, /*String*/ aName
// Give our current allocator all the instance variables of our super class' allocator.
classObject.allocator.prototype = new superclass.allocator;
// "Inheret" parent methods.
classObject.method_store.prototype = new superclass.method_store;
classObject.method_dtable = classObject.method_store.prototype;
// "Inheret" parent properties.
classObject.ivar_dtable = classObject.ivar_store.prototype = new superclass.ivar_store;
classObject.method_dtable = classObject.method_store.prototype = new superclass.method_store;
metaClassObject.method_store.prototype = new superclass.isa.method_store;
metaClassObject.method_dtable = metaClassObject.method_store.prototype;
metaClassObject.method_dtable = metaClassObject.method_store.prototype = new superclass.isa.method_store;
// Set up the actual class hierarchy.
classObject.super_class = superclass;
@@ -456,7 +473,7 @@ class_createInstance = function(/*Class*/ aClass)
while (theClass)
{
var ivars = theClass.ivars,
var ivars = theClass.ivar_list,
count = ivars.length;
while (count--)
+4
View File
@@ -112,6 +112,10 @@
[bindTesterA setStringValue:nil];
[self assert:nil equals:[bindTesterA stringValue] message:"A value reset (placeholder)"];
[self assert:@"placeholder" equals:[bindTesterB stringValue] message:"B value updated (placeholder)"];
[bindTesterA setStringValue:[CPNull null]];
[self assert:[CPNull null] equals:[bindTesterA stringValue] message:"A value reset (placeholder)"];
[self assert:@"placeholder" equals:[bindTesterB stringValue] message:"B value updated (placeholder)"];
}
- (void)testControl
+30 -43
View File
@@ -38,8 +38,8 @@
[self assert:array equals:[@"one", @"two", @"three", @"four", @"a", @"b"]];
var array = [CPMutableArray arrayWithObjects: @"one", @"two", @"three", @"four"],
newAdditions = [CPArray arrayWithObjects: @"a", @"b", @"c"],
var array = [CPMutableArray arrayWithObjects:@"one", @"two", @"three", @"four"],
newAdditions = [CPArray arrayWithObjects:@"a", @"b", @"c"],
indexes = [CPMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:2];
@@ -50,8 +50,8 @@
[self assert:array equals:[@"one", @"a", @"b", @"two", @"c", @"three", @"four"]];
var array = [CPMutableArray arrayWithObjects: @"one", @"two", @"three", @"four"],
newAdditions = [CPArray arrayWithObjects: @"a", @"b", @"c"],
var array = [CPMutableArray arrayWithObjects:@"one", @"two", @"three", @"four"],
newAdditions = [CPArray arrayWithObjects:@"a", @"b", @"c"],
indexes = [CPMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:2];
@@ -83,11 +83,11 @@
- (void)testRemoveObjectsAtIndexes
{
var array = [CPMutableArray arrayWithObjects:@"one", @"two", @"three", @"four", nil],
indexes = [CPMutableIndexSet indexSetWithIndex: 2];
indexes = [CPMutableIndexSet indexSetWithIndex:2];
[array removeObjectsAtIndexes:indexes];
[self assert:array equals:[@"one", @"two", @"four", nil]];
[self assert:array equals:[@"one", @"two", @"four"]];
}
- (void)testIndexOfObjectPassingTest
@@ -140,25 +140,12 @@
[self assert:[array indexOfObjectWithOptions:CPEnumerationReverse passingTest:agePredicate context:7] equals:3];
}
- (void)testIndexOfObjectSortedByFunction
- (void)testIndexOfObject_inSortedRange_options_usingComparator_
{
var array = [0, 1, 2, 3, 4, 7];
[self assert:[array indexOfObject:3 sortedByFunction:function(a, b){ return a - b; }] equals:3];
[self assert:[[array arrayByReversingArray] indexOfObject:3 sortedByFunction:function(a, b){ return b - a; }] equals:2];
}
- (void)testIndexOfObjectSortedByDescriptors
{
var array = [0, 1, 2, 3, 4, 7];
[self assert:[array indexOfObject:3
sortedByDescriptors:[[[CPSortDescriptor alloc] initWithKey:@"intValue" ascending:YES]]]
equals:3];
[self assert:[[array arrayByReversingArray] indexOfObject:3
sortedByDescriptors:[[[CPSortDescriptor alloc] initWithKey:@"intValue" ascending:NO]]]
equals:2];
[self assert:[array indexOfObject:3 inSortedRange:nil options:0 usingComparator:function(a, b){ return a - b; }] equals:3];
[self assert:[[array arrayByReversingArray] indexOfObject:3 inSortedRange:nil options:0 usingComparator:function(a, b){ return a - b; }] equals:2];
}
- (void)testIndexOutOfBounds
@@ -171,7 +158,7 @@
catch (anException)
{
[self assert:[anException name] equals:CPRangeException];
[self assert:[anException reason] equals:@"index (0) beyond bounds (0)"];
[self assertTrue:[[anException reason] rangeOfString:(@"index (0) beyond bounds (0)")].location !== CPNotFound];
}
[[0, 1, 2] objectAtIndex:0];
@@ -186,7 +173,7 @@
catch (anException)
{
[self assert:[anException name] equals:CPRangeException];
[self assert:[anException reason] equals:@"index (3) beyond bounds (3)"];
[self assertTrue:[[anException reason] rangeOfString:(@"index (3) beyond bounds (3)")].location !== CPNotFound];
}
try
@@ -197,7 +184,7 @@
catch (anException)
{
[self assert:[anException name] equals:CPRangeException];
[self assert:[anException reason] equals:@"index (4) beyond bounds (3)"];
[self assertTrue:[[anException reason] rangeOfString:(@"index (4) beyond bounds (3)")].location !== CPNotFound];
}
}
@@ -206,79 +193,79 @@
var descriptors = [[[CPSortDescriptor alloc] initWithKey:@"intValue" ascending:YES]];
var array = [1, 3, 5];
[array insertObject: 0 inArraySortedByDescriptors:descriptors];
[array insertObject:0 inArraySortedByDescriptors:descriptors];
[self assert:[0, 1, 3, 5] equals:array];
array = [1, 3, 5];
[array insertObject: 2 inArraySortedByDescriptors:descriptors];
[array insertObject:2 inArraySortedByDescriptors:descriptors];
[self assert:[1, 2, 3, 5] equals:array];
array = [1, 3, 5];
[array insertObject: 1 inArraySortedByDescriptors:descriptors];
[array insertObject:1 inArraySortedByDescriptors:descriptors];
[self assert:[1, 1, 3, 5] equals:array];
array = [1, 3, 5];
[array insertObject: 6 inArraySortedByDescriptors:descriptors];
[array insertObject:6 inArraySortedByDescriptors:descriptors];
[self assert:[1, 3, 5, 6] equals:array];
array = [1, 3, 5];
[array insertObject: 3 inArraySortedByDescriptors:descriptors];
[array insertObject:3 inArraySortedByDescriptors:descriptors];
[self assert:[1, 3, 3, 5] equals:array];
array = [];
[array insertObject: 3 inArraySortedByDescriptors:descriptors];
[array insertObject:3 inArraySortedByDescriptors:descriptors];
[self assert:[3] equals:array];
descriptors = [[[CPSortDescriptor alloc] initWithKey:@"intValue" ascending:NO]];
array = [5, 3, 1];
[array insertObject: 0 inArraySortedByDescriptors:descriptors];
[array insertObject:0 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 1, 0] equals:array];
array = [5, 3, 1];
[array insertObject: 2 inArraySortedByDescriptors:descriptors];
[array insertObject:2 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 2, 1] equals:array];
array = [5, 3, 1];
[array insertObject: 1 inArraySortedByDescriptors:descriptors];
[array insertObject:1 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 1, 1] equals:array];
array = [5, 3, 1];
[array insertObject: 6 inArraySortedByDescriptors:descriptors];
[array insertObject:6 inArraySortedByDescriptors:descriptors];
[self assert:[6, 5, 3, 1] equals:array];
array = [5, 3, 1];
[array insertObject: 3 inArraySortedByDescriptors:descriptors];
[array insertObject:3 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 3, 1] equals:array];
array = [];
[array insertObject: 3 inArraySortedByDescriptors:descriptors];
[array insertObject:3 inArraySortedByDescriptors:descriptors];
[self assert:[3] equals:array];
descriptors = [[[CPSortDescriptor alloc] initWithKey:@"intValue" ascending:NO]];
array = [5, 3, 1];
[array insertObject: 0 inArraySortedByDescriptors:descriptors];
[array insertObject:0 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 1, 0] equals:array];
array = [5, 3, 1];
[array insertObject: 2 inArraySortedByDescriptors:descriptors];
[array insertObject:2 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 2, 1] equals:array];
array = [5, 3, 1];
[array insertObject: 1 inArraySortedByDescriptors:descriptors];
[array insertObject:1 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 1, 1] equals:array];
array = [5, 3, 1];
[array insertObject: 6 inArraySortedByDescriptors:descriptors];
[array insertObject:6 inArraySortedByDescriptors:descriptors];
[self assert:[6, 5, 3, 1] equals:array];
array = [5, 3, 1];
[array insertObject: 3 inArraySortedByDescriptors:descriptors];
[array insertObject:3 inArraySortedByDescriptors:descriptors];
[self assert:[5, 3, 3, 1] equals:array];
array = [];
[array insertObject: 3 inArraySortedByDescriptors:descriptors];
[array insertObject:3 inArraySortedByDescriptors:descriptors];
[self assert:[3] equals:array];
}
+160 -1
View File
@@ -469,7 +469,6 @@ var accessIVARS = YES;
[self assert:[CPNull null] equals:[nullObject valueForKey:@"a"] message:@"CPNull valueForKey:X returns nil"];
}
<<<<<<< HEAD
- (void)testValueForKeyPath
{
var department = [Department departmentWithName:@"Engineering"],
@@ -526,3 +525,163 @@ var accessIVARS = YES;
}
@end
@implementation ObjectInObjectsAtIndexClass : CPObject
{
}
- (id)objectInObjectsAtIndex:(CPUInteger)anIndex
{
switch (anIndex)
{
case 0: return @"one";
case 1: return @"two";
case 2: return @"three";
case 3: return @"four";
case 4: return @"five";
}
[CPException raise:CPRangeException reason:@"index (" + anIndex + @") beyond bounds (" + [self count] + @")"];
}
- (CPUInteger)countOfObjects
{
return 5;
}
@end
@implementation ObjectsAtIndexesClass : CPObject
{
}
- (id)objectsAtIndexes:(CPIndexSet)indexes
{
return [[@"one", @"two", @"three", @"four", @"five"] objectsAtIndexes:indexes];
}
- (CPUInteger)countOfObjects
{
return 5;
}
@end
@implementation CPKeyValueCodingTest (IndexedAccessorPattern)
- (void)testObjectInObjectsAtIndex_
{
var object = [ObjectInObjectsAtIndexClass new],
array = [object valueForKey:@"objects"];
[self assert:5 equals:[array count]];
[self assert:@"one" equals:[array objectAtIndex:0]];
[self assert:@"two" equals:[array objectAtIndex:1]];
[self assert:@"three" equals:[array objectAtIndex:2]];
[self assert:@"four" equals:[array objectAtIndex:3]];
[self assert:@"five" equals:[array objectAtIndex:4]];
var indexes = [CPIndexSet indexSet];
[indexes addIndex:1];
[indexes addIndex:3];
[self assert:[@"two", @"four"] equals:[array objectsAtIndexes:indexes]];
}
- (void)testObjectsAtIndexes_
{
var object = [ObjectsAtIndexesClass new],
array = [object valueForKey:@"objects"];
[self assert:5 equals:[array count]];
[self assert:@"one" equals:[array objectAtIndex:0]];
[self assert:@"two" equals:[array objectAtIndex:1]];
[self assert:@"three" equals:[array objectAtIndex:2]];
[self assert:@"four" equals:[array objectAtIndex:3]];
[self assert:@"five" equals:[array objectAtIndex:4]];
var indexes = [CPIndexSet indexSet];
[indexes addIndex:1];
[indexes addIndex:3];
[self assert:[@"two", @"four"] equals:[array objectsAtIndexes:indexes]];
}
@end
@implementation UnorderedAccessorClass : CPObject
{
}
- (id)memberOfObjects:(id)anObject
{
if ([[0, 1, 3, 5, 7] indexOfObjectIdenticalTo:anObject] !== CPNotFound)
return anObject;
return nil;
}
- (CPEnumerator)enumeratorOfObjects
{
return [[0, 1, 3, 5, 7] objectEnumerator];
}
- (CPUInteger)countOfObjects
{
return 5;
}
@end
@implementation CPKeyValueCodingTest (UnorderedAccessorPattern)
- (void)testUnorderedAccessorPattern
{
var object = [UnorderedAccessorClass new],
set = [object valueForKey:@"objects"];
[self assert:set equals:[CPSet setWithObjects:0, 1, 3, 5, 7]];
[self assertTrue:[set containsObject:0]];
[self assertTrue:[set containsObject:1]];
[self assertTrue:[set containsObject:3]];
[self assertTrue:[set containsObject:5]];
[self assertTrue:[set containsObject:7]];
[self assertFalse:[set containsObject:2]];
[self assertFalse:[set containsObject:4]];
[self assertFalse:[set containsObject:6]];
[self assertFalse:[set containsObject:8]];
[self assertFalse:[set containsObject:10]];
[self assert:[set setByAddingObjectsFromArray:[2, 3, 4, 5, 6]]
equals:[CPSet setWithObjects:0, 1, 2, 3, 4, 5, 6, 7]];
}
- (void)testObjectsAtIndexes_
{
var object = [ObjectsAtIndexesClass new],
array = [object valueForKey:@"objects"];
[self assert:5 equals:[array count]];
[self assert:@"one" equals:[array objectAtIndex:0]];
[self assert:@"two" equals:[array objectAtIndex:1]];
[self assert:@"three" equals:[array objectAtIndex:2]];
[self assert:@"four" equals:[array objectAtIndex:3]];
[self assert:@"five" equals:[array objectAtIndex:4]];
var indexes = [CPIndexSet indexSet];
[indexes addIndex:1];
[indexes addIndex:3];
[self assert:[@"two", @"four"] equals:[array objectsAtIndexes:indexes]];
}
@end
+146 -8
View File
@@ -1,18 +1,148 @@
@import <Foundation/CPSet.j>
@implementation CPSetTest : OJTestCase
{
CPSet set;
}
- (void)setUp
- (void)assertSet:(CPSet)aSet onlyHasObjects:(CPArray)objects
{
set = [CPSet new];
[self assert:[objects count] equals:[aSet count]];
var allObjects = [aSet allObjects],
index = 0,
count = [objects count];
[self assert:[objects count] equals:[allObjects count]];
for (; index < count; ++index)
{
var object = objects[index];
if ([allObjects indexOfObjectIdenticalTo:object] === CPNotFound)
return [self fail:@"Set does not contain " + object];
}
}
- (void)testEmptySet
{
var set = [CPSet set];
[self assert:@"{(\n)}" equals:[set description]];
[self assert:0 equals:[set count]];
[self assert:[] equals:[set allObjects]];
[self assert:nil equals:[set anyObject]];
[self assert:NO equals:[set containsObject:RAND()]];
[self assert:nil equals:[set member:RAND()]];
var object,
objectEnumerator = [set objectEnumerator];
while ((object = [objectEnumerator nextObject]) !== nil)
[self fail:@"Empty set had non-empty enumerator"];
[self assertTrue:[set isSubsetOfSet:set]];
[self assertTrue:[set isSubsetOfSet:[CPSet set]]];
// Empty set intersects nothing!
[self assertFalse:[set intersectsSet:set]];
[self assertFalse:[set intersectsSet:[CPSet set]]];
[self assertTrue:[set isEqualToSet:set]];
[self assertTrue:[set isEqualToSet:[CPSet set]]];
var copy = [set copy];
[self assert:@"{(\n)}" equals:[copy description]];
[self assertTrue:[set isEqualToSet:copy]];
}
- (void)testSetWithArray_
{
[self assertSet:[CPSet setWithArray:[]] onlyHasObjects:[]];
[self assertSet:[CPSet setWithArray:[@"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithArray:[@"a", @"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithArray:[@"a", @"a", @"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithArray:[@"a", @"b"]] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithArray:[@"a", @"b", @"a"]] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithArray:[@"a", @"b", @"a", 0]] onlyHasObjects:[@"a", @"b", 0]];
}
- (void)testSetWithObject
{
[self assertSet:[CPSet setWithObject:nil] onlyHasObjects:[]];
[self assertSet:[CPSet setWithObject:undefined] onlyHasObjects:[]];
[self assertSet:[CPSet setWithObject:0] onlyHasObjects:[0]];
[self assertSet:[CPSet setWithObject:@"a"] onlyHasObjects:[@"a"]];
}
- (void)testSetWithObjects_count_
{
[self assertSet:[CPSet setWithObjects:[] count:0] onlyHasObjects:[]];
[self assertSet:[CPSet setWithObjects:[@"a"] count:1] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"a"] count:2] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"a", @"a"] count:3] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"b"] count:2] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"b", @"a"] count:3] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"b", @"a", 0] count:4] onlyHasObjects:[@"a", @"b", 0]];
[self assertSet:[CPSet setWithObjects:[@"a", nil, undefined, 0] count:4] onlyHasObjects:[@"a", 0]];
[self assertSet:[CPSet setWithObjects:[] count:4] onlyHasObjects:[]];
[self assertSet:[CPSet setWithObjects:[@"a"] count:2] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"a"] count:0] onlyHasObjects:[]];
[self assertSet:[CPSet setWithObjects:[@"a", @"a", @"a"] count:1] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"b"] count:1] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"b", @"a"] count:2] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:[@"a", @"b", @"a", 0] count:10] onlyHasObjects:[@"a", @"b", 0]];
[self assertSet:[CPSet setWithObjects:[@"a", nil, undefined, 0] count:3] onlyHasObjects:[@"a"]];
}
- (void)testSetWithObjects_count_
{
[self assertSet:[CPSet setWithObjects:nil] onlyHasObjects:[]];
[self assertSet:[CPSet setWithObjects:@"a"] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", nil] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", @"a"] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", nil, @"a"] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", @"a", @"a"] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", @"a", @"a"] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", @"b"] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:@"a", @"b", nil] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:@"a", nil, @"b"] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", @"b", @"a"] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:@"a", @"b", @"a", 0] onlyHasObjects:[@"a", @"b", 0]];
[self assertSet:[CPSet setWithObjects:@"a", @"b", @"a", 0, nil] onlyHasObjects:[@"a", @"b", 0]];
[self assertSet:[CPSet setWithObjects:@"a", @"b", @"a", nil, 0] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithObjects:@"a", nil, undefined, 0] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithObjects:@"a", undefined, 0, nil] onlyHasObjects:[@"a", 0]];
}
- (void)testSetWithSet_
{
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:nil]] onlyHasObjects:[]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", nil]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", nil, @"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"a", @"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"a", @"a"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"b"]] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"b", nil]] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", nil, @"b"]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"b", @"a"]] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"b", @"a", 0]] onlyHasObjects:[@"a", @"b", 0]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"b", @"a", 0, nil]] onlyHasObjects:[@"a", @"b", 0]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", @"b", @"a", nil, 0]] onlyHasObjects:[@"a", @"b"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", nil, undefined, 0]] onlyHasObjects:[@"a"]];
[self assertSet:[CPSet setWithSet:[CPSet setWithObjects:@"a", undefined, 0, nil]] onlyHasObjects:[@"a", 0]];
}
- (void)testAddObject
{
var set = [CPSet new];
[self assertFalse:[set containsObject:"foo"]];
[set addObject:"foo"];
[self assertTrue:[set containsObject:"foo"]];
@@ -20,6 +150,8 @@
- (void)testAddZeroObject
{
var set = [CPSet new];
[self assertFalse:[set containsObject:0]];
[set addObject:0];
[self assertTrue:[set containsObject:0]];
@@ -27,6 +159,8 @@
- (void)testRemoveObject
{
var set = [CPSet new];
[set addObject:"foo"];
[self assertTrue:[set containsObject:"foo"]];
[set removeObject:"foo"];
@@ -35,6 +169,8 @@
- (void)testRemoveZeroObject
{
var set = [CPSet new];
[set addObject:0];
[self assertTrue:[set containsObject:0]];
[set removeObject:0];
@@ -43,6 +179,8 @@
- (void)testAddNilObject
{
var set = [CPSet new];
[self assertFalse:[set containsObject:nil]];
[set addObject:nil];
[self assertFalse:[set containsObject:nil]];
@@ -50,6 +188,8 @@
- (void)testRemoveNilObject
{
var set = [CPSet new];
[set addObject:nil];
[self assertFalse:[set containsObject:nil]];
[set removeObject:nil];
@@ -58,15 +198,13 @@
- (void)testDescription
{
[self assert:@"{()}" equals:[set description]];
var set = [CPSet new];
[self assert:@"{(\n)}" equals:[set description]];
[set addObject:"horizon"];
[set addObject:"surfer"];
[set addObject:"7"];
var desc = [set description];
// Ordering may not be guaranteed.
[self assertTrue:desc.match(new RegExp("{\(.*horizon.*\)}"))];
[self assertTrue:desc.match(new RegExp("{\(.*surfer.*\)}"))];
[self assertTrue:desc.match(new RegExp("{\(.*7.*\)}"))];
[self assertSet:set onlyHasObjects:["horizon", "surfer", "7"]];
}
@end
+2 -2
View File
@@ -18,7 +18,7 @@
@import <Foundation/Foundation.j>
@import <AppKit/AppKit.j>
@import "../../Foundation/CPUserDefaults.j"
CPUserDefaultsTestKey1 = @"KEY1";
CPUserDefaultsTestKey2 = @"KEY2";
@@ -136,7 +136,7 @@ CPUserDefaultsTestKey2 = @"KEY2";
- (void)testArray
{
[target setObject:[@"a", @"b", 3] forKey:CPUserDefaultsTestKey1];
[self assert:[[target arrayForKey:CPUserDefaultsTestKey1] class] equals:CPArray];
[self assertTrue:[[target arrayForKey:CPUserDefaultsTestKey1] isKindOfClass:CPArray]];
[self assert:[[target arrayForKey:CPUserDefaultsTestKey1] objectAtIndex:1] equals:@"b"];
[self assert:[[target arrayForKey:CPUserDefaultsTestKey1] objectAtIndex:2] equals:3];
[self assert:[target stringArrayForKey:CPUserDefaultsTestKey1] equals:nil];
+23
View File
@@ -102,6 +102,29 @@
@end
@implementation MyArray : CPArray
{
CPArray _storage;
}
- (id)initWithObjects:(id)anObject, ...
{
self = [super init];
if (self)
_storage = [[CPArray alloc] initWithObjects:Array.prototype.slice.call(arguments, 2)];
return self
}
- (id)objectAtIndex:(CPUInteger)anIndex
{
return [_storage objectAtIndex:anIndex];
}
- (CPUInteger)count
{
return [_storage count];
}
- (id)newMessage
{