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

This commit is contained in:
Alexander Ljungberg committed 2010-12-13 13:39:41 +01:00
commit 0e05f1a8b7
229 files changed
+13405 -2286

No files matched your search

+90 -14
View File
@@ -312,7 +312,7 @@ ACTUAL_FRAME_RATE = 0;
[_timingFunction getControlPointAtIndex:1 values:c1];
[_timingFunction getControlPointAtIndex:2 values:c2];
return CubicBezierAtTime(t,c1[0],c1[1],c2[0],c2[1],_duration);
return CubicBezierAtTime(t, c1[0], c1[1], c2[0], c2[1], _duration);
}
@end
@@ -320,28 +320,104 @@ ACTUAL_FRAME_RATE = 0;
// currently used function to determine time
// 1:1 conversion to js from webkit source files
// UnitBezier.h, WebCore_animation_AnimationBase.cpp
var CubicBezierAtTime = function CubicBezierAtTime(t,p1x,p1y,p2x,p2y,duration)
var CubicBezierAtTime = function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration)
{
var ax=0,bx=0,cx=0,ay=0,by=0,cy=0;
var ax = 0,
bx = 0,
cx = 0,
ay = 0,
by = 0,
cy = 0;
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
function sampleCurveX(t) {return ((ax*t+bx)*t+cx)*t;};
function sampleCurveY(t) {return ((ay*t+by)*t+cy)*t;};
function sampleCurveDerivativeX(t) {return (3.0*ax*t+2.0*bx)*t+cx;};
function sampleCurveX(t)
{
return ((ax * t + bx) * t + cx) * t;
}
function sampleCurveY(t)
{
return ((ay * t + by) * t + cy) * t;
}
function sampleCurveDerivativeX(t)
{
return (3.0 * ax * t + 2.0 * bx) * t + cx;
}
// The epsilon value to pass given that the animation is going to run over |duration| seconds. The longer the animation, the more precision is needed in the timing function result to avoid ugly discontinuities.
function solveEpsilon(duration) {return 1.0/(200.0*duration);};
function solve(x,epsilon) {return sampleCurveY(solveCurveX(x,epsilon));};
function solveEpsilon(duration)
{
return 1.0 / (200.0 * duration);
}
function solve(x, epsilon)
{
return sampleCurveY(solveCurveX(x, epsilon));
}
// Given an x value, find a parametric value it came from.
function solveCurveX(x,epsilon) {var t0,t1,t2,x2,d2,i;
function fabs(n) {if(n>=0) {return n;}else {return 0-n;}};
function solveCurveX(x, epsilon)
{
var t0,
t1,
t2 = x,
x2,
d2,
i = 0;
// First try a few iterations of Newton's method -- normally very fast.
for(t2=x, i=0; i<8; i++) {x2=sampleCurveX(t2)-x; if(fabs(x2)<epsilon) {return t2;} d2=sampleCurveDerivativeX(t2); if(fabs(d2)<1e-6) {break;} t2=t2-x2/d2;}
for (; i < 8; i++)
{
x2 = sampleCurveX(t2) - x;
if (ABS(x2) < epsilon)
return t2;
d2 = sampleCurveDerivativeX(t2);
if (ABS(d2) < 1e-6)
break;
t2 = t2 - x2 / d2;
}
// Fall back to the bisection method for reliability.
t0=0.0; t1=1.0; t2=x; if(t2<t0) {return t0;} if(t2>t1) {return t1;}
while(t0<t1) {x2=sampleCurveX(t2); if(fabs(x2-x)<epsilon) {return t2;} if(x>x2) {t0=t2;}else {t1=t2;} t2=(t1-t0)*.5+t0;}
t0 = 0.0;
t1 = 1.0;
t2 = x;
if (t2 < t0)
return t0;
if (t2 > t1)
return t1;
while (t0 < t1)
{
x2 = sampleCurveX(t2);
if (ABS(x2 - x) < epsilon)
return t2;
if (x > x2)
t0 = t2;
else
t1 = t2;
t2 = (t1 - t0) * 0.5 + t0;
}
return t2; // Failure.
};
// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
cx=3.0*p1x; bx=3.0*(p2x-p1x)-cx; ax=1.0-cx-bx; cy=3.0*p1y; by=3.0*(p2y-p1y)-cy; ay=1.0-cy-by;
cx = 3.0 * p1x;
bx = 3.0 * (p2x - p1x) - cx;
ax = 1.0 - cx - bx;
cy = 3.0 * p1y;
by = 3.0 * (p2y - p1y) - cy;
ay = 1.0 - cy - by;
// Convert from input time to parametric value in curve, then from that to output time.
return solve(t, solveEpsilon(duration));
};
+1 -1
View File
@@ -184,7 +184,6 @@ var DefaultLineWidth = 1.0;
CGContextBeginPath(ctx);
CGContextAddPath(ctx, _path);
CGContextSetLineWidth(ctx, [self lineWidth]);
CGContextClosePath(ctx);
CGContextStrokePath(ctx);
}
@@ -281,6 +280,7 @@ var DefaultLineWidth = 1.0;
{
CGPathAddPath(_path, nil, other._path);
}
/*!
Remove all path elements; clears path.
*/
+27 -7
View File
@@ -70,7 +70,13 @@ CPPushInCellMask = CPPushInButtonMask;
CPChangeGrayCellMask = CPGrayButtonMask;
CPChangeBackgroundCellMask = CPBackgroundButtonMask;
CPButtonStateMixed = CPThemeState("mixed");
CPButtonStateMixed = CPThemeState("mixed");
CPButtonStateBezelStyleRounded = CPThemeState("rounded");
// add all future correspondance between bezel styles and theme state here.
var CPButtonBezelStyleStateMap = [CPDictionary dictionaryWithObjects:[CPButtonStateBezelStyleRounded, nil]
forKeys:[CPRoundedBezelStyle, CPRoundRectBezelStyle]];
CPButtonDefaultHeight = 24.0;
CPButtonImageOffset = 3.0;
@@ -151,7 +157,7 @@ CPButtonImageOffset = 3.0;
_keyEquivalent = @"";
_keyEquivalentModifierMask = 0;
// [self setBezelStyle:CPRoundRectBezelStyle];
[self setBezelStyle:CPRoundRectBezelStyle];
[self setBordered:YES];
}
@@ -225,9 +231,9 @@ CPButtonImageOffset = 3.0;
/*!
Returns the button's next state.
@return The button's state. A button can have two or three states.
If it has two, this value is either \c CPOffState (the normal or unpressed state)
or \c CPOnState (the alternate or pressed state).
@return The button's state. A button can have two or three states.
If it has two, this value is either \c CPOffState (the normal or unpressed state)
or \c CPOnState (the alternate or pressed state).
If it has three, this value can be \c CPOnState (the feature is in effect everywhere), \c CPOffState (the feature is in effect nowhere), or \c CPMixedState (the feature is in effect somewhere).
*/
- (CPInteger)nextState
@@ -272,7 +278,7 @@ CPButtonImageOffset = 3.0;
/*!
Sets the title displayed by the button when in its normal state.
@param aTitle The string to set as the button's title. This title is always shown on buttons
@param aTitle The string to set as the button's title. This title is always shown on buttons
that don’t use their alternate contents when highlighting or displaying their alternate state.
*/
- (void)setTitle:(CPString)aTitle
@@ -288,7 +294,7 @@ CPButtonImageOffset = 3.0;
/*!
Returns the title displayed on the button when it’s in its normal state.
@return The title displayed on the receiver when it’s in its normal state
@return The title displayed on the receiver when it’s in its normal state
or the empty string if the button doesn’t display a title.
*/
- (CPString)title
@@ -678,10 +684,24 @@ CPButtonImageOffset = 3.0;
- (void)setBezelStyle:(unsigned)aBezelStyle
{
if (aBezelStyle === _bezelStyle)
return;
var currentState = [CPButtonBezelStyleStateMap objectForKey:_bezelStyle],
newState = [CPButtonBezelStyleStateMap objectForKey:aBezelStyle];
if (currentState)
[self unsetThemeState:currentState];
if (newState)
[self setThemeState:newState];
_bezelStyle = aBezelStyle;
}
- (unsigned)bezelStyle
{
return _bezelStyle;
}
@end
+1 -1
View File
@@ -534,7 +534,7 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
{
var point = [self convertPoint:[anEvent locationInWindow] fromView:nil];
if(point.x > [self bounds].size.width - 1 || point.x < 1)
if (point.x > [self bounds].size.width - 1 || point.x < 1)
return NO;
[[CPPasteboard pasteboardWithName:CPDragPboard] declareTypes:[CPArray arrayWithObject:CPColorDragType] owner:self];
+3 -3
View File
@@ -220,14 +220,14 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
[_draggingUpdateTimer invalidate];
_draggingUpdateTimer = nil;
var dragOperation = CPDragOperationCopy;
var dragOperation = CPDragOperationCopy,
// We have to convert base to bridge since the drag event comes from the source window, not the drag window.
var draggingDestination = [aPlatformWindow _dragHitTest:aLocation pasteboard:[CPDragServerDraggingInfo draggingPasteboard]];
draggingDestination = [aPlatformWindow _dragHitTest:aLocation pasteboard:[CPDragServerDraggingInfo draggingPasteboard]];
if (draggingDestination)
_draggingLocation = [DRAGGING_WINDOW(draggingDestination) convertPlatformWindowToBase:aLocation];
if(draggingDestination !== _draggingDestination)
if (draggingDestination !== _draggingDestination)
{
if ([_draggingDestination respondsToSelector:@selector(draggingExited:)])
[_draggingDestination draggingExited:CPDragServerDraggingInfo];
+7 -4
View File
@@ -158,6 +158,7 @@ CPFindFunctionKey = "\uF745";
CPHelpFunctionKey = "\uF746";
CPModeSwitchFunctionKey = "\uF747";
CPEscapeFunctionKey = "\u001B";
CPSpaceFunctionKey = "\u0020";
CPDOMEventDoubleClick = "dblclick",
@@ -527,7 +528,8 @@ var _CPEventPeriodicEventPeriod = 0,
if (_CPEventUpperCaseRegex.test(aKeyEquivalent))
aKeyEquivalentModifierMask |= CPShiftKeyMask;
if (CPBrowserIsOperatingSystem(CPWindowsOperatingSystem) && (aKeyEquivalentModifierMask & CPCommandKeyMask))
// Windows and Linux don't have command keys, so just switch it to ctrl.
if (!CPBrowserIsOperatingSystem(CPMacOperatingSystem) && (aKeyEquivalentModifierMask & CPCommandKeyMask))
{
aKeyEquivalentModifierMask |= CPControlKeyMask;
aKeyEquivalentModifierMask &= ~CPCommandKeyMask;
@@ -556,9 +558,9 @@ var _CPEventPeriodicEventPeriod = 0,
if (_modifierFlags & (CPCommandKeyMask | CPControlKeyMask))
return YES;
for(var i=0; i<characterCount; i++)
for (var i = 0; i < characterCount; i++)
{
switch(_characters.charAt(i))
switch (_characters.charAt(i))
{
case CPBackspaceCharacter:
case CPDeleteCharacter:
@@ -566,6 +568,7 @@ var _CPEventPeriodicEventPeriod = 0,
case CPTabCharacter:
case CPCarriageReturnCharacter:
case CPNewlineCharacter:
case CPSpaceFunctionKey:
case CPEscapeFunctionKey:
case CPPageUpFunctionKey:
case CPPageDownFunctionKey:
@@ -576,7 +579,7 @@ var _CPEventPeriodicEventPeriod = 0,
return YES;
}
}
// FIXME: More cases? Space?
// FIXME: More cases?
return NO;
}
+3 -3
View File
@@ -23,7 +23,7 @@
@import <Foundation/CPObject.j>
/*!
/*!
@ingroup appkit
@class CPFlashMovie
@@ -52,10 +52,10 @@
- (id)initWithFile:(CPString)aFilename
{
self = [super init];
if (self)
_filename = aFilename;
return self;
}
+21 -21
View File
@@ -32,10 +32,10 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
@implementation CPFlashView : CPView
{
CPFlashMovie _flashMovie;
CPDictionary _params;
CPDictionary _paramElements;
#if PLATFORM(DOM)
#if PLATFORM(DOM)
DOMElement _DOMParamElement;
DOMElement _DOMObjectElement;
DOMElement _DOMInnerObjectElement;
@@ -45,7 +45,7 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
- (id)initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self)
{
#if PLATFORM(DOM)
@@ -58,24 +58,24 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
_DOMObjectElement.style.left = @"0px";
_DOMObjectElement.type = @"application/x-shockwave-flash";
_DOMObjectElement.setAttribute(@"classid", IEFlashCLSID);
_DOMParamElement = document.createElement(@"param");
_DOMParamElement.name = @"movie";
_DOMInnerObjectElement = document.createElement(@"object");
_DOMInnerObjectElement.width = @"100%";
_DOMInnerObjectElement.height = @"100%";
_DOMObjectElement.appendChild(_DOMParamElement);
_DOMObjectElement.appendChild(_DOMInnerObjectElement);
_DOMElement.appendChild(_DOMObjectElement);
}
else
[self _rebuildIEObjects];
#endif
}
return self;
}
@@ -83,7 +83,7 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
{
if (_flashMovie == aFlashMovie)
return;
_flashMovie = aFlashMovie;
#if PLATFORM(DOM)
if (!CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
@@ -105,14 +105,14 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
{
var varString = @"",
enumerator = [aDictionary keyEnumerator];
var key;
while (key = [enumerator nextObject])
varString = [varString stringByAppendingFormat:@"&%@=%@", key, [aDictionary objectForKey:key]];
if (!_params)
_params = [CPDictionary dictionary];
[_params setObject:varString forKey:@"flashvars"];
[self setParameters:_params];
}
@@ -129,7 +129,7 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
{
var elements = [_paramElements allValues],
count = [elements count];
for (var i = 0; i < count; i++)
_DOMObjectElement.removeChild([elements objectAtIndex:i]);
}
@@ -139,18 +139,18 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
if (!CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
{
_paramElements = [CPDictionary dictionary];
var enumerator = [_params keyEnumerator],
key;
while (key = [enumerator nextObject] && _DOMObjectElement)
{
var param = document.createElement(@"param");
param.name = key;
param.value = [_params objectForKey:key];
_DOMObjectElement.appendChild(param);
[_paramElements setObject:param forKey:key];
}
}
@@ -170,17 +170,17 @@ var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
_DOMElement.innerHTML = @"";
if (![_flashMovie filename])
return;
var paramString = [CPString stringWithFormat:@"<param name='movie' value='%@' />", [_flashMovie filename]],
paramEnumerator = [_params keyEnumerator],
key;
while (key = [paramEnumerator nextObject])
paramString = [paramString stringByAppendingFormat:@"<param name='%@' value='%@' />", key, [_params objectForKey:key]];
_DOMObjectElement = document.createElement(@"object");
_DOMElement.appendChild(_DOMObjectElement);
_DOMObjectElement.outerHTML = [CPString stringWithFormat:@"<object classid=%@ width=%@ height=%@>%@</object>", IEFlashCLSID, CGRectGetWidth([self bounds]), CGRectGetHeight([self bounds]), paramString];
}
#endif
+38 -32
View File
@@ -45,7 +45,7 @@ var CPSharedFontManager = nil,
{
if (!CPSharedFontManager)
CPSharedFontManager = [[CPFontManagerFactory alloc] init];
return CPSharedFontManager;
}
@@ -65,7 +65,7 @@ var CPSharedFontManager = nil,
- (CPArray)availableFonts
{
if (!_availableFonts)
{
{
_CPFontDetectSpan = document.createElement("span");
_CPFontDetectSpan.fontSize = "24px";
_CPFontDetectSpan.appendChild(document.createTextNode("mmmmmmmmmml"));
@@ -74,13 +74,14 @@ var CPSharedFontManager = nil,
div.style.top = "-1000px";
div.appendChild(_CPFontDetectSpan);
document.getElementsByTagName("body")[0].appendChild(div);
_CPFontDetectReferenceFonts = _CPFontDetectPickTwoDifferentFonts(["monospace", "serif", "sans-serif", "cursive"]);
_CPFontDetectReferenceFonts = _CPFontDetectPickTwoDifferentFonts(["monospace", "serif", "sans-serif", "cursive"]);
_availableFonts = [];
for (var i = 0; i < _CPFontDetectAllFonts.length; i++) {
for (var i = 0; i < _CPFontDetectAllFonts.length; i++)
{
var available = _CPFontDetectFontAvailable(_CPFontDetectAllFonts[i]);
if (available)
if (available)
_availableFonts.push(_CPFontDetectAllFonts[i]);
}
}
@@ -101,8 +102,8 @@ var CPSharedFontManager = nil,
var _CPFontDetectSpan,
_CPFontDetectReferenceFonts,
_CPFontDetectAllFonts = [
/* "04b_21","A Charming Font","Abadi MT Condensed","Abadi MT Condensed Extra Bold","Abadi MT Condensed Light","Academy Engraved LET","Agency FB","Alba","Alba Matter","Alba Super","Algerian",*/
"American Typewriter",
/* "04b_21","A Charming Font","Abadi MT Condensed","Abadi MT Condensed Extra Bold","Abadi MT Condensed Light","Academy Engraved LET","Agency FB","Alba","Alba Matter","Alba Super","Algerian",*/
"American Typewriter",
/* "Andale Mono","Andale Mono IPA","Andy", */
"Apple Chancery","Arial","Arial Black","Arial Narrow","Arial Rounded MT Bold","Arial Unicode MS",
/* "Avant Garde","Avantgarde","Baby Kruffy","Base 02","Baskerville","Baskerville Old Face","Bauhaus 93","Beesknees ITC","Bell MT","Berlin Sans FB","Berlin Sans FB Demi","Bernard MT Condensed","Bickley Script",*/
@@ -122,8 +123,8 @@ var _CPFontDetectSpan,
/* "GlooGun","Gloucester MT Extra Condensed","Goudy Old Style","Goudy Stout","Haettenschweiler","Harlow Solid Italic","Harrington",*/
"Helvetica","Helvetica Narrow","Helvetica Neue","Herculanum","High Tower Text","Highlight LET","Hoefler Text","Impact","Imprint MT Shadow",
/* "Informal Roman","Jenkins v2.0","John Handy LET","Jokerman","Jokerman LET","Jokewood","Juice ITC","Kabel Ult BT","Kartika","Kino MT","Kristen ITC","Kunstler Script","La Bamba LET", */
"Lucida","Lucida Bright","Lucida Calligraphy","Lucida Console","Lucida Fax","Lucida Grande","Lucida Handwriting","Lucida Sans","Lucida Sans Typewriter","Lucida Sans Unicode",
/* "Luxi Mono","Luxi Sans","Luxi Serif","MARKETPRO","MS Reference Sans Serif","MS Reference Serif","Magneto","Maiandra GD", */
"Lucida","Lucida Bright","Lucida Calligraphy","Lucida Console","Lucida Fax","Lucida Grande","Lucida Handwriting","Lucida Sans","Lucida Sans Typewriter","Lucida Sans Unicode",
/* "Luxi Mono","Luxi Sans","Luxi Serif","MARKETPRO","MS Reference Sans Serif","MS Reference Serif","Magneto","Maiandra GD", */
"Marker Felt",
/* "Matisse ITC","Matura MT Script Capitals","Mead Bold","Mekanik LET","Mercurius Script MT Bold", */
"Microsoft Sans Serif","Milano LET","Minion Web","MisterEarl BT","Mistral","Monaco","Monotype Corsiva","Monotype.com","New Century Schoolbook","New York","News Gothic MT",
@@ -136,39 +137,44 @@ var _CPFontDetectSpan,
"Zapfino"];
// Compare against the reference fonts. Return true if it produces a different size than at least one of them.
var _CPFontDetectFontAvailable = function(font) {
for (var i = 0; i < _CPFontDetectReferenceFonts.length; i++)
if (_CPFontDetectCompareFonts(_CPFontDetectReferenceFonts[i], font))
return true;
return false;
var _CPFontDetectFontAvailable = function(font)
{
for (var i = 0; i < _CPFontDetectReferenceFonts.length; i++)
if (_CPFontDetectCompareFonts(_CPFontDetectReferenceFonts[i], font))
return true;
return false;
}
var _CPFontDetectCache = {};
// Compares two given fonts. Returns true if they produce different sizes (i.e. fontA didn't fallback to fontB)
var _CPFontDetectCompareFonts = function(fontA, fontB) {
var _CPFontDetectCompareFonts = function(fontA, fontB)
{
var a;
if (_CPFontDetectCache[fontA]) {
if (_CPFontDetectCache[fontA])
a = _CPFontDetectCache[fontA];
} else {
_CPFontDetectSpan.style.fontFamily = '"' + fontA + '"';
else
{
_CPFontDetectSpan.style.fontFamily = '"' + fontA + '"';
_CPFontDetectCache[fontA] = a = { w: _CPFontDetectSpan.offsetWidth, h: _CPFontDetectSpan.offsetHeight };
}
_CPFontDetectSpan.style.fontFamily= '"' + fontB + '", "' + fontA + '"';
var bWidth = _CPFontDetectSpan.offsetWidth;
var bHeight = _CPFontDetectSpan.offsetHeight;
return (a.w != bWidth || a.h != bHeight);
_CPFontDetectSpan.style.fontFamily = '"' + fontB + '", "' + fontA + '"';
var bWidth = _CPFontDetectSpan.offsetWidth,
bHeight = _CPFontDetectSpan.offsetHeight;
return (a.w != bWidth || a.h != bHeight);
}
// Test the candidate fonts pairwise until we find two that are different. Otherwise return the first.
var _CPFontDetectPickTwoDifferentFonts = function(candidates) {
for (var i = 0; i < candidates.length; i++)
for (var j = 0; j < i; j++)
if (_CPFontDetectCompareFonts(candidates[i], candidates[j]))
return [candidates[i], candidates[j]];
return [candidates[0]];
var _CPFontDetectPickTwoDifferentFonts = function(candidates)
{
for (var i = 0; i < candidates.length; i++)
for (var j = 0; j < i; j++)
if (_CPFontDetectCompareFonts(candidates[i], candidates[j]))
return [candidates[i], candidates[j]];
return [candidates[0]];
}
[CPFontManager setFontManagerFactory:[CPFontManager class]];
+1 -1
View File
@@ -71,7 +71,7 @@ function CPPointMake(x, y)
function CPRectInset(aRect, dX, dY)
{
return CPRectMake( aRect.origin.x + dX, aRect.origin.y + dY,
aRect.size.width - 2 * dX, aRect.size.height - 2*dY);
aRect.size.width - 2 * dX, aRect.size.height - 2 * dY);
}
/*!
+2 -2
View File
@@ -71,10 +71,10 @@ var CPGraphicsContextCurrent = nil;
- (id)initWithGraphicsPort:(CPContext)aGraphicsPort
{
self = [super init];
if (self)
_graphicsPort = aGraphicsPort;
return self;
}
+2 -2
View File
@@ -65,7 +65,7 @@ function CPAppKitImage(aFilename, aSize)
return CPImageInBundle(aFilename, aSize, [CPBundle bundleForClass:[CPView class]]);
}
/*!
/*!
@ingroup appkit
@class CPImage
@@ -73,7 +73,7 @@ function CPAppKitImage(aFilename, aSize)
all image types supported by the browser.
@par Delegate Methods
@delegate -(void)imageDidLoad:(CPImage)image;
Called when the specified image has finished loading.
@param image the image that loaded
+45 -44
View File
@@ -43,7 +43,7 @@ CPImageAlignRight = 8;
var CPImageViewShadowBackgroundColor = nil,
CPImageViewEmptyPlaceholderImage = nil;
var LEFT_SHADOW_INSET = 3.0,
RIGHT_SHADOW_INSET = 3.0,
TOP_SHADOW_INSET = 3.0,
@@ -51,7 +51,7 @@ var LEFT_SHADOW_INSET = 3.0,
VERTICAL_SHADOW_INSET = TOP_SHADOW_INSET + BOTTOM_SHADOW_INSET,
HORIZONTAL_SHADOW_INSET = LEFT_SHADOW_INSET + RIGHT_SHADOW_INSET;
/*!
/*!
@ingroup appkit
@class CPImageView
@@ -60,7 +60,7 @@ var LEFT_SHADOW_INSET = 3.0,
@implementation CPImageView : CPControl
{
DOMElement _DOMImageElement;
BOOL _hasShadow;
CPView _shadowView;
@@ -73,14 +73,14 @@ var LEFT_SHADOW_INSET = 3.0,
+ (void)initialize
{
var bundle = [CPBundle bundleForClass:[CPView class]];
CPImageViewEmptyPlaceholderImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"empty.png"]];
}
- (id)initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self)
{
#if PLATFORM(DOM)
@@ -96,11 +96,11 @@ var LEFT_SHADOW_INSET = 3.0,
}
CPDOMDisplayServerAppendChild(_DOMElement, _DOMImageElement);
_DOMImageElement.style.visibility = "hidden";
#endif
}
return self;
}
@@ -121,29 +121,29 @@ var LEFT_SHADOW_INSET = 3.0,
- (void)setObjectValue:(CPImage)anImage
{
var oldImage = [self objectValue];
if (oldImage === anImage)
return;
[super setObjectValue:anImage];
var defaultCenter = [CPNotificationCenter defaultCenter];
if (oldImage)
[defaultCenter removeObserver:self name:CPImageDidLoadNotification object:oldImage];
var newImage = [self objectValue];
#if PLATFORM(DOM)
_DOMImageElement.src = newImage ? [newImage filename] : [CPImageViewEmptyPlaceholderImage filename];
#endif
var size = [newImage size];
if (size && size.width === -1 && size.height === -1)
{
[defaultCenter addObserver:self selector:@selector(imageDidLoad:) name:CPImageDidLoadNotification object:newImage];
#if PLATFORM(DOM)
_DOMImageElement.width = 0;
_DOMImageElement.height = 0;
@@ -162,7 +162,7 @@ var LEFT_SHADOW_INSET = 3.0,
- (void)imageDidLoad:(CPNotification)aNotification
{
[self hideOrDisplayContents];
[self setNeedsLayout];
[self setNeedsDisplay:YES];
}
@@ -184,25 +184,25 @@ var LEFT_SHADOW_INSET = 3.0,
{
if (_hasShadow == shouldHaveShadow)
return;
_hasShadow = shouldHaveShadow;
if (_hasShadow)
{
_shadowView = [[CPShadowView alloc] initWithFrame:[self bounds]];
[self addSubview:_shadowView];
[self setNeedsLayout];
[self setNeedsDisplay:YES];
}
else
{
[_shadowView removeFromSuperview];
_shadowView = nil;
}
[self hideOrDisplayContents];
}
@@ -215,12 +215,12 @@ var LEFT_SHADOW_INSET = 3.0,
{
if (_imageAlignment == anImageAlignment)
return;
_imageAlignment = anImageAlignment;
if (![self image])
return;
[self setNeedsLayout];
[self setNeedsDisplay:YES];
}
@@ -238,14 +238,14 @@ var LEFT_SHADOW_INSET = 3.0,
- (void)setImageScaling:(CPImageScaling)anImageScaling
{
[super setImageScaling:anImageScaling];
#if PLATFORM(DOM)
if ([self currentValueForThemeAttribute:@"image-scaling"] === CPScaleToFit)
{
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, 0.0, 0.0);
}
#endif
[self setNeedsLayout];
[self setNeedsDisplay:YES];
}
@@ -314,7 +314,7 @@ var LEFT_SHADOW_INSET = 3.0,
else
{
var size = [image size];
if (size.width == -1 && size.height == -1)
return;
@@ -331,7 +331,7 @@ var LEFT_SHADOW_INSET = 3.0,
{
var imageRatio = size.width / size.height,
viewRatio = width / height;
if (viewRatio > imageRatio)
width = height * imageRatio;
else
@@ -348,7 +348,7 @@ var LEFT_SHADOW_INSET = 3.0,
width = size.width;
height = size.height;
}
if (imageScaling == CPScaleNone)
{
#if PLATFORM(DOM)
@@ -357,8 +357,9 @@ var LEFT_SHADOW_INSET = 3.0,
#endif
}
var x, y;
var x,
y;
switch (_imageAlignment)
{
case CPImageAlignLeft:
@@ -366,7 +367,7 @@ var LEFT_SHADOW_INSET = 3.0,
case CPImageAlignBottomLeft:
x = 0.0;
break;
case CPImageAlignRight:
case CPImageAlignTopRight:
case CPImageAlignBottomRight:
@@ -377,7 +378,7 @@ var LEFT_SHADOW_INSET = 3.0,
x = (boundsWidth - width) / 2.0;
break;
}
switch (_imageAlignment)
{
case CPImageAlignTop:
@@ -385,7 +386,7 @@ var LEFT_SHADOW_INSET = 3.0,
case CPImageAlignTopRight:
y = 0.0;
break;
case CPImageAlignBottom:
case CPImageAlignBottomLeft:
case CPImageAlignBottomRight:
@@ -395,7 +396,7 @@ var LEFT_SHADOW_INSET = 3.0,
default:
y = (boundsHeight - height) / 2.0;
break;
}
}
#if PLATFORM(DOM)
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, x, y);
@@ -403,7 +404,7 @@ var LEFT_SHADOW_INSET = 3.0,
}
_imageRect = _CGRectMake(x, y, width, height);
if (_hasShadow)
[_shadowView setFrame:_CGRectMake(x - LEFT_SHADOW_INSET, y - TOP_SHADOW_INSET, width + insetWidth, height + insetHeight)];
}
@@ -450,7 +451,7 @@ var LEFT_SHADOW_INSET = 3.0,
[self setImage:images[0]];
[self sendAction:[self action] to:[self target]];
}
return YES;
}
@@ -485,7 +486,7 @@ var CPImageViewImageKey = @"CPImageViewImageKey",
#endif
self = [super initWithCoder:aCoder];
if (self)
{
#if PLATFORM(DOM)
@@ -494,14 +495,14 @@ var CPImageViewImageKey = @"CPImageViewImageKey",
[self setHasShadow:[aCoder decodeBoolForKey:CPImageViewHasShadowKey]];
[self setImageAlignment:[aCoder decodeIntForKey:CPImageViewImageAlignmentKey]];
if ([aCoder decodeBoolForKey:CPImageViewIsEditableKey] || NO)
[self setEditable:YES];
[self setNeedsLayout];
[self setNeedsDisplay:YES];
}
return self;
}
@@ -512,21 +513,21 @@ var CPImageViewImageKey = @"CPImageViewImageKey",
*/
- (void)encodeWithCoder:(CPCoder)aCoder
{
// We do this in order to avoid encoding the _shadowView, which
// We do this in order to avoid encoding the _shadowView, which
// should just automatically be created programmatically as needed.
if (_shadowView)
{
var actualSubviews = _subviews;
_subviews = [_subviews copy];
[_subviews removeObjectIdenticalTo:_shadowView];
}
[super encodeWithCoder:aCoder];
if (_shadowView)
_subviews = actualSubviews;
[aCoder encodeBool:_hasShadow forKey:CPImageViewHasShadowKey];
[aCoder encodeInt:_imageAlignment forKey:CPImageViewImageAlignmentKey];
+36 -36
View File
@@ -43,12 +43,12 @@ var CPBindingOperationAnd = 0,
+ (void)exposeBinding:(CPString)aBinding forClass:(Class)aClass
{
var bindings = [exposedBindingsMap objectForKey:[aClass hash]];
var bindings = [exposedBindingsMap objectForKey:[aClass UID]];
if (!bindings)
{
bindings = [];
[exposedBindingsMap setObject:bindings forKey:[aClass hash]];
[exposedBindingsMap setObject:bindings forKey:[aClass UID]];
}
bindings.push(aBinding);
@@ -56,12 +56,12 @@ var CPBindingOperationAnd = 0,
+ (CPArray)exposedBindingsForClass:(Class)aClass
{
return [[exposedBindingsMap objectForKey:[aClass hash]] copy];
return [[exposedBindingsMap objectForKey:[aClass UID]] copy];
}
+ (CPKeyValueBinding)getBinding:(CPString)aBinding forObject:(id)anObject
{
return [[bindingsMap objectForKey:[anObject hash]] objectForKey:aBinding];
return [[bindingsMap objectForKey:[anObject UID]] objectForKey:aBinding];
}
+ (CPDictionary)infoForBinding:(CPString)aBinding forObject:(id)anObject
@@ -76,12 +76,12 @@ var CPBindingOperationAnd = 0,
+ (CPDictionary)allBindingsForObject:(id)anObject
{
return [bindingsMap objectForKey:[anObject hash]];
return [bindingsMap objectForKey:[anObject UID]];
}
+ (void)unbind:(CPString)aBinding forObject:(id)anObject
{
var bindings = [bindingsMap objectForKey:[anObject hash]];
var bindings = [bindingsMap objectForKey:[anObject UID]];
if (!bindings)
return;
@@ -101,7 +101,7 @@ var CPBindingOperationAnd = 0,
+ (void)unbindAllForObject:(id)anObject
{
var bindings = [bindingsMap objectForKey:[anObject hash]];
var bindings = [bindingsMap objectForKey:[anObject UID]];
if (!bindings)
return;
@@ -111,7 +111,7 @@ var CPBindingOperationAnd = 0,
while (count--)
[anObject unbind:[bindings objectForKey:allKeys[count]]];
[bindingsMap removeObjectForKey:[anObject hash]];
[bindingsMap removeObjectForKey:[anObject UID]];
}
- (id)initWithBinding:(CPString)aBinding name:(CPString)aName to:(id)aDestination keyPath:(CPString)aKeyPath options:(CPDictionary)options from:(id)aSource
@@ -128,11 +128,11 @@ var CPBindingOperationAnd = 0,
[aDestination addObserver:self forKeyPath:aKeyPath options:CPKeyValueObservingOptionNew context:aBinding];
var bindings = [bindingsMap objectForKey:[_source hash]];
var bindings = [bindingsMap objectForKey:[_source UID]];
if (!bindings)
{
bindings = [CPDictionary new];
[bindingsMap setObject:bindings forKey:[_source hash]];
[bindingsMap setObject:bindings forKey:[_source UID]];
}
[bindings setObject:self forKey:aName];
@@ -320,7 +320,7 @@ var CPBindingOperationAnd = 0,
- (void)setValueFor:(CPString)aBinding
{
var bindings = [bindingsMap valueForKey:[_source hash]];
var bindings = [bindingsMap valueForKey:[_source UID]];
if (!bindings)
return;
@@ -341,7 +341,7 @@ var CPBindingOperationAnd = 0,
- (void)setValueFor:(CPString)aBinding
{
var bindings = [bindingsMap objectForKey:[_source hash]];
var bindings = [bindingsMap objectForKey:[_source UID]];
if (!bindings)
return;
@@ -441,30 +441,30 @@ CPToolTipBinding = @"CPToolTipBinding";
CPValueBinding = @"value";
//Binding options constants
CPAllowsEditingMultipleValuesSelectionBindingOption = @"CPAllowsEditingMultipleValuesSelectionBindingOption";
CPAllowsNullArgumentBindingOption = @"CPAllowsNullArgumentBindingOption";
CPConditionallySetsEditableBindingOption = @"CPConditionallySetsEditableBindingOption";
CPConditionallySetsEnabledBindingOption = @"CPConditionallySetsEnabledBindingOption";
CPConditionallySetsHiddenBindingOption = @"CPConditionallySetsHiddenBindingOption";
CPContinuouslyUpdatesValueBindingOption = @"CPContinuouslyUpdatesValueBindingOption";
CPCreatesSortDescriptorBindingOption = @"CPCreatesSortDescriptorBindingOption";
CPDeletesObjectsOnRemoveBindingsOption = @"CPDeletesObjectsOnRemoveBindingsOption";
CPDisplayNameBindingOption = @"CPDisplayNameBindingOption";
CPDisplayPatternBindingOption = @"CPDisplayPatternBindingOption";
CPHandlesContentAsCompoundValueBindingOption = @"CPHandlesContentAsCompoundValueBindingOption";
CPInsertsNullPlaceholderBindingOption = @"CPInsertsNullPlaceholderBindingOption";
CPInvokesSeparatelyWithArrayObjectsBindingOption = @"CPInvokesSeparatelyWithArrayObjectsBindingOption";
CPMultipleValuesPlaceholderBindingOption = @"CPMultipleValuesPlaceholderBindingOption";
CPNoSelectionPlaceholderBindingOption = @"CPNoSelectionPlaceholderBindingOption";
CPNotApplicablePlaceholderBindingOption = @"CPNotApplicablePlaceholderBindingOption";
CPNullPlaceholderBindingOption = @"CPNullPlaceholderBindingOption";
CPPredicateFormatBindingOption = @"CPPredicateFormatBindingOption";
CPRaisesForNotApplicableKeysBindingOption = @"CPRaisesForNotApplicableKeysBindingOption";
CPSelectorNameBindingOption = @"CPSelectorNameBindingOption";
CPSelectsAllWhenSettingContentBindingOption = @"CPSelectsAllWhenSettingContentBindingOption";
CPValidatesImmediatelyBindingOption = @"CPValidatesImmediatelyBindingOption";
CPValueTransformerNameBindingOption = @"CPValueTransformerNameBindingOption";
CPValueTransformerBindingOption = @"CPValueTransformerBindingOption";
CPAllowsEditingMultipleValuesSelectionBindingOption = @"CPAllowsEditingMultipleValuesSelection";
CPAllowsNullArgumentBindingOption = @"CPAllowsNullArgument";
CPConditionallySetsEditableBindingOption = @"CPConditionallySetsEditable";
CPConditionallySetsEnabledBindingOption = @"CPConditionallySetsEnabled";
CPConditionallySetsHiddenBindingOption = @"CPConditionallySetsHidden";
CPContinuouslyUpdatesValueBindingOption = @"CPContinuouslyUpdatesValue";
CPCreatesSortDescriptorBindingOption = @"CPCreatesSortDescriptor";
CPDeletesObjectsOnRemoveBindingsOption = @"CPDeletesObjectsOnRemove";
CPDisplayNameBindingOption = @"CPDisplayName";
CPDisplayPatternBindingOption = @"CPDisplayPattern";
CPHandlesContentAsCompoundValueBindingOption = @"CPHandlesContentAsCompoundValue";
CPInsertsNullPlaceholderBindingOption = @"CPInsertsNullPlaceholder";
CPInvokesSeparatelyWithArrayObjectsBindingOption = @"CPInvokesSeparatelyWithArrayObjects";
CPMultipleValuesPlaceholderBindingOption = @"CPMultipleValuesPlaceholder";
CPNoSelectionPlaceholderBindingOption = @"CPNoSelectionPlaceholder";
CPNotApplicablePlaceholderBindingOption = @"CPNotApplicablePlaceholder";
CPNullPlaceholderBindingOption = @"CPNullPlaceholder";
CPPredicateFormatBindingOption = @"CPPredicateFormat";
CPRaisesForNotApplicableKeysBindingOption = @"CPRaisesForNotApplicableKeys";
CPSelectorNameBindingOption = @"CPSelectorName";
CPSelectsAllWhenSettingContentBindingOption = @"CPSelectsAllWhenSettingContent";
CPValidatesImmediatelyBindingOption = @"CPValidatesImmediately";
CPValueTransformerNameBindingOption = @"CPValueTransformerName";
CPValueTransformerBindingOption = @"CPValueTransformer";
CPIsControllerMarker = function(/*id*/anObject)
{
+1 -1
View File
@@ -692,7 +692,7 @@ var _CPMenuBarVisible = NO,
var delegate = [self delegate];
if ([delegate respondsToSelector:@selector(menuWillOpen:)])
[delegate menuWillOpen:aMenu];
[delegate menuWillOpen:self];
// Convert location to global coordinates if not already in them.
if (aView)
+6 -6
View File
@@ -459,7 +459,7 @@ CPOffState
if (supermenu)
[CPException raise:CPInvalidArgumentException
reason: @"Can't add submenu \"" + [aMenu title] + "\" to item \"" + [self title] + "\", because it is already submenu of \"" + [[aMenu supermenu] title] + "\""];
reason: @"Can't add submenu \"" + [aMenu title] + "\" to item \"" + [self title] + "\", because it is already submenu of \"" + [[aMenu supermenu] title] + "\""];
_submenu = aMenu;
@@ -592,7 +592,7 @@ CPControlKeyMask
return @"";
var string = _keyEquivalent.toUpperCase(),
needsShift = _keyEquivalentModifierMask & CPShiftKeyMask ||
needsShift = _keyEquivalentModifierMask & CPShiftKeyMask ||
(string === _keyEquivalent && _keyEquivalent.toLowerCase() !== _keyEquivalent.toUpperCase());
if (CPBrowserIsOperatingSystem(CPMacOperatingSystem))
@@ -791,12 +791,12 @@ CPControlKeyMask
- (id)copy
{
var item = [[CPMenuItem alloc] init];
// No point in going through accessors and doing lots of unnecessary state checking/updating
item._isSeparator = _isSeparator;
[item setTitle:_title];
[item setFont:_font];
[item setFont:_font];
[item setTarget:_target];
[item setAction:_action];
[item setEnabled:_isEnabled];
@@ -815,7 +815,7 @@ CPControlKeyMask
[item setIndentationLevel:_indentationLevel];
[item setToolTip:_toolTip];
[item setRepresentedObject:_representedObject];
return item;
}
+17 -13
View File
@@ -513,10 +513,10 @@ CPOutlineViewDropOnItemIndex = -1;
],
delegateCount = [delegateMethods count];
for (var i=0; i < delegateCount; i += 2)
for (var i = 0; i < delegateCount; i += 2)
{
var bitMask = delegateMethods[i],
selector = delegateMethods[i+1];
selector = delegateMethods[i + 1];
if ([_outlineViewDelegate respondsToSelector:selector])
_implementedOutlineViewDelegateMethods |= bitMask;
@@ -670,8 +670,8 @@ CPOutlineViewDropOnItemIndex = -1;
if (_shouldRetargetItem)
return _retargetedItem;
var lowerLevel = [self levelForRow:theLowerRowIndex]
upperItem = [self itemAtRow:theUpperRowIndex];
var lowerLevel = [self levelForRow:theLowerRowIndex],
upperItem = [self itemAtRow:theUpperRowIndex],
upperLevel = [self levelForItem:upperItem];
// If the row above us has a higher level the item can be added to multiple parent items
@@ -875,7 +875,7 @@ var _reloadItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anItem)
if (!anItem)
return;
with(anOutlineView)
with (anOutlineView)
{
// Get the existing info if it exists.
var itemInfosForItems = _itemInfosForItems,
@@ -911,7 +911,7 @@ var _reloadItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anItem)
// FIX ME: We're using with() here because Safari fails if we use anOutlineView._itemInfosForItems or whatever...
var _loadItemInfoForItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anItem, /*BOOL*/ isIntermediate)
{
with(anOutlineView)
with (anOutlineView)
{
var itemInfosForItems = _itemInfosForItems,
dataSource = _outlineViewDataSource;
@@ -1119,8 +1119,8 @@ var _loadItemInfoForItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anIt
if (!(_outlineView._implementedOutlineViewDataSourceMethods & CPOutlineViewDataSource_outlineView_acceptDrop_item_childIndex_))
return NO;
var location = [_outlineView convertPoint:[theInfo draggingLocation] fromView:nil],
parentItem = [self _parentItemForDropOperation:theOperation row:theRow offset:location];
var location = [_outlineView convertPoint:[theInfo draggingLocation] fromView:nil],
parentItem = [self _parentItemForDropOperation:theOperation row:theRow offset:location],
childIndex = [self _childIndexForDropOperation:theOperation row:theRow offset:location];
_outlineView._retargetedItem = nil;
@@ -1180,13 +1180,13 @@ var _loadItemInfoForItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anIt
return NO;
}
- (float)tableView:(CPTableView)theTableView heightOfRow:(int)theRow
/*- (float)tableView:(CPTableView)theTableView heightOfRow:(int)theRow
{
if ((_outlineView._implementedOutlineViewDelegateMethods & CPOutlineViewDelegate_outlineView_heightOfRowByItem_))
return [_outlineView._outlineViewDelegate outlineView:_outlineView heightOfRowByItem:[_outlineView itemAtRow:theRow]];
return [theTableView rowHeight];
}
}*/
- (void)tableView:(CPTableView)aTableView willDisplayView:(id)aView forTableColumn:(CPTableColumn)aTableColumn row:(int)aRowIndex
{
@@ -1261,12 +1261,16 @@ var _loadItemInfoForItem = function(/*CPOutlineView*/ anOutlineView, /*id*/ anIt
CGContextBeginPath(context);
CGContextMoveToPoint(context, 0.0, 0.0);
if(_angle === 0.0) {
if (_angle === 0.0)
{
CGContextAddLineToPoint(context, 4.5, 8.0);
CGContextAddLineToPoint(context, 9.0, 0.0);
} else {
CGContextAddLineToPoint(context, 4.5, 8.0);
}
else
CGContextAddLineToPoint(context, 4.5, 8.0);
CGContextSetStrokeColor(context, [CPColor colorWithCalibratedWhite:1.0 alpha: 0.8]);
CGContextStrokePath(context);
}
+1 -1
View File
@@ -51,7 +51,7 @@ CPCancelButton = 0;
@global
@class CPWindow
*/
CPDocModalWindowMask = 1 << 6;
CPDocModalWindowMask = 1 << 6;
@implementation CPPanel : CPWindow
{
+24 -24
View File
@@ -50,18 +50,18 @@ CPImagePboardType = @"CPImagePboardType";
var CPPasteboards = nil,
supportsNativePasteboard = NO;
/*!
/*!
@ingroup appkit
@class CPPasteboard
CPPasteBoard is the object responsible for cut/copy/paste and drag&drop operations.
CPPasteBoard is the object responsible for cut/copy/paste and drag&drop operations.
*/
@implementation CPPasteboard : CPObject
{
CPArray _types;
CPDictionary _owners;
CPDictionary _provided;
unsigned _changeCount;
CPString _stateUID;
@@ -77,7 +77,7 @@ var CPPasteboards = nil,
return;
[self setVersion:1.0];
CPPasteboards = [CPDictionary dictionary];
if (typeof window.cpPasteboardWithName !== "undefined")
@@ -103,10 +103,10 @@ var CPPasteboards = nil,
if (pasteboard)
return pasteboard;
pasteboard = [[CPPasteboard alloc] _initWithName:aName];
[CPPasteboards setObject:pasteboard forKey:aName];
return pasteboard;
}
@@ -114,15 +114,15 @@ var CPPasteboards = nil,
- (id)_initWithName:(CPString)aName
{
self = [super init];
if (self)
{
_name = aName;
_types = [];
_owners = [CPDictionary dictionary];
_provided = [CPDictionary dictionary];
_changeCount = 0;
if (supportsNativePasteboard)
@@ -131,7 +131,7 @@ var CPPasteboards = nil,
[self _synchronizePasteboard];
}
}
return self;
}
@@ -145,17 +145,17 @@ var CPPasteboards = nil,
{
var i = 0,
count = types.length;
for (; i < count; ++i)
{
var type = types[i];
if(![_owners objectForKey:type])
if (![_owners objectForKey:type])
{
[_types addObject:type];
[_provided removeObjectForKey:type];
}
[_owners setObject:anOwner forKey:type];
}
@@ -191,7 +191,7 @@ var CPPasteboards = nil,
_provided = [CPDictionary dictionary];
var count = _types.length;
while (count--)
[_owners setObject:anOwner forKey:_types[count]];
@@ -283,18 +283,18 @@ var CPPasteboards = nil,
- (CPData)dataForType:(CPString)aType
{
var data = [_provided objectForKey:aType];
if (data)
return data;
var owner = [_owners objectForKey:aType];
if (owner)
{
[owner pasteboard:self provideDataForType:aType];
[owner pasteboard:self provideDataForType:aType];
return [_provided objectForKey:aType];
}
if (aType === CPStringPboardType)
return [self dataForType:UTF8PboardType];
@@ -339,10 +339,10 @@ var CPPasteboards = nil,
- (id)propertyListForType:(CPString)aType
{
var data = [self dataForType:aType];
if (data)
return [CPPropertyListSerialization propertyListFromData:data format:CPPropertyList280NorthFormat_v1_0];
return nil;
}
@@ -360,9 +360,9 @@ var CPPasteboards = nil,
- (CPString)_generateStateUID
{
var bits = 32;
_stateUID = @"";
while (bits--)
_stateUID += FLOOR(RAND() * 16.0).toString(16).toUpperCase();
+25
View File
@@ -49,6 +49,11 @@ CPPopUpButtonStatePullsDown = CPThemeState("pulls-down");
return "popup-button";
}
+ (CPSet)keyPathsForValuesAffectingSelectedTag
{
return [CPSet setWithObject:@"selectedIndex"];
}
/*!
Initializes the pop-up button to the specified size.
@param aFrame the size for the button
@@ -233,6 +238,22 @@ CPPopUpButtonStatePullsDown = CPThemeState("pulls-down");
return _selectedIndex;
}
/*!
@ignore
*/
- (int)_selectedTag
{
return [[self selectedItem] tag];
}
/*!
@ignore
*/
- (void)_setSelectedTag:(int)aTag
{
[self selectItemWithTag:aTag];
}
// Setting the Current Selection
/*!
Selects the specified menu item.
@@ -252,6 +273,8 @@ CPPopUpButtonStatePullsDown = CPThemeState("pulls-down");
if (_selectedIndex == anIndex)
return;
[self willChangeValueForKey:@"selectedIndex"];
if (_selectedIndex >= 0 && ![self pullsDown])
[[self selectedItem] setState:CPOffState];
@@ -261,6 +284,8 @@ CPPopUpButtonStatePullsDown = CPThemeState("pulls-down");
[[self selectedItem] setState:CPOnState];
[self synchronizeTitleAndSelectedItem];
[self didChangeValueForKey:@"selectedIndex"];
}
/*!
+40 -41
View File
@@ -47,7 +47,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
CPProgressIndicatorStyleIdentifiers = nil,
CPProgressIndicatorStyleSizes = nil;
/*!
/*!
@ingroup appkit
@class CPProgressIndicator
@@ -59,19 +59,19 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
double _minValue;
double _maxValue;
double _doubleValue;
CPControlSize _controlSize;
BOOL _isIndeterminate;
CPProgressIndicatorStyle _style;
BOOL _isAnimating;
BOOL _isDisplayedWhenStoppedSet;
BOOL _isDisplayedWhenStopped;
CPView _barView;
}
@@ -82,11 +82,11 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (self != [CPProgressIndicator class])
return;
var bundle = [CPBundle bundleForClass:self];
CPProgressIndicatorSpinningStyleColors = [];
CPProgressIndicatorSpinningStyleColors[CPMiniControlSize] = [CPColor colorWithPatternImage:[[CPImage alloc] initWithContentsOfFile:
[bundle pathForResource:@"CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif"] size:CGSizeMake(64.0, 64.0)]];
CPProgressIndicatorSpinningStyleColors[CPSmallControlSize] = [CPColor colorWithPatternImage:[[CPImage alloc] initWithContentsOfFile:
@@ -95,10 +95,10 @@ var CPProgressIndicatorSpinningStyleColors = nil,
[bundle pathForResource:@"CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif"] size:CGSizeMake(64.0, 64.0)]];
CPProgressIndicatorBezelBorderViewPool = [];
var start = CPProgressIndicatorBarStyle,
end = CPProgressIndicatorHUDBarStyle;
for (; start <= end; ++start)
{
CPProgressIndicatorBezelBorderViewPool[start] = [];
@@ -106,14 +106,14 @@ var CPProgressIndicatorSpinningStyleColors = nil,
CPProgressIndicatorBezelBorderViewPool[start][CPSmallControlSize] = [];
CPProgressIndicatorBezelBorderViewPool[start][CPRegularControlSize] = [];
}
CPProgressIndicatorClassName = [self className];
CPProgressIndicatorStyleIdentifiers = [];
CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle] = @"Bar";
CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorSpinningStyle] = @"Spinny";
CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorHUDBarStyle] = @"HUDBar";
var regularIdentifier = _CPControlIdentifierForControlSize(CPRegularControlSize),
smallIdentifier = _CPControlIdentifierForControlSize(CPSmallControlSize),
miniIdentifier = _CPControlIdentifierForControlSize(CPMiniControlSize);
@@ -128,7 +128,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
CPProgressIndicatorClassName + @"Bar" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorHUDBarStyle]
];
for (var i = 0, count = prefixes.length; i<count; i++)
for (var i = 0, count = prefixes.length; i < count; i++)
{
var prefix = prefixes[i];
CPProgressIndicatorStyleSizes[prefix + regularIdentifier] = [_CGSizeMake(3.0, 16.0), _CGSizeMake(1.0, 16.0), _CGSizeMake(3.0, 16.0)];
@@ -140,23 +140,23 @@ var CPProgressIndicatorSpinningStyleColors = nil,
- (id)initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self)
{
_minValue = 0.0;
_maxValue = 100.0;
_doubleValue = 0.0;
_style = CPProgressIndicatorBarStyle;
_isDisplayedWhenStoppedSet = NO;
_controlSize = CPRegularControlSize;
[self updateBackgroundColor];
[self drawBar];
}
return self;
}
@@ -174,7 +174,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
- (void)startAnimation:(id)aSender
{
_isAnimating = YES;
[self _hideOrDisplay];
}
@@ -213,7 +213,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
- (void)setDoubleValue:(double)aValue
{
_doubleValue = MIN(MAX(aValue, _minValue), _maxValue);
[self drawBar];
}
@@ -268,7 +268,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (_controlSize == aControlSize)
return;
_controlSize = aControlSize;
[self updateBackgroundColor];
@@ -320,7 +320,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (_isIndeterminate == isIndeterminate)
return;
_isIndeterminate = isIndeterminate;
[self updateBackgroundColor];
@@ -342,9 +342,9 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (_style == aStyle)
return;
_style = aStyle;
[self updateBackgroundColor];
}
@@ -357,8 +357,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
[self setFrameSize:[[CPProgressIndicatorSpinningStyleColors[_controlSize] patternImage] size]];
else
[self setFrameSize:CGSizeMake(CGRectGetWidth([self frame]), CPProgressIndicatorStyleSizes[
CPProgressIndicatorClassName + @"BezelBorder" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle] +
_CPControlIdentifierForControlSize(_controlSize)][0].height)];
CPProgressIndicatorClassName + @"BezelBorder" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle] + _CPControlIdentifierForControlSize(_controlSize)][0].height)];
}
/*!
@@ -370,11 +369,11 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (_isDisplayedWhenStoppedSet && _isDisplayedWhenStopped == isDisplayedWhenStopped)
return;
_isDisplayedWhenStoppedSet = YES;
_isDisplayedWhenStopped = isDisplayedWhenStopped;
[self _hideOrDisplay];
}
@@ -385,10 +384,10 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (_isDisplayedWhenStoppedSet)
return _isDisplayedWhenStopped;
if (_style == CPProgressIndicatorBarStyle || _style == CPProgressIndicatorHUDBarStyle)
return YES;
return NO;
}
@@ -401,7 +400,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
- (void)setFrameSize:(CGSize)aSize
{
[super setFrameSize:aSize];
[self drawBar];
}
@@ -410,13 +409,13 @@ var CPProgressIndicatorSpinningStyleColors = nil,
{
if (_style == CPProgressIndicatorSpinningStyle)
return;
if (!_barView)
{
_barView = [[CPView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 16.0)];
_barView = [[CPView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 16.0)];
[self addSubview:_barView];
}
[_barView setBackgroundColor:_CPControlThreePartImagePattern(
NO,
CPProgressIndicatorStyleSizes,
@@ -442,9 +441,9 @@ var CPProgressIndicatorSpinningStyleColors = nil,
if (_style == CPProgressIndicatorSpinningStyle)
{
[_barView removeFromSuperview];
_barView = nil;
[self setBackgroundColor:CPProgressIndicatorSpinningStyleColors[_controlSize]];
}
else
@@ -456,7 +455,7 @@ var CPProgressIndicatorSpinningStyleColors = nil,
@"BezelBorder",
CPProgressIndicatorStyleIdentifiers[_style],
_CPControlIdentifierForControlSize(_controlSize))];
[self drawBar];
}
}
+111 -136
View File
@@ -23,12 +23,10 @@
@import "CPButton.j"
@import "CPTextField.j"
CPSearchFieldRecentsTitleMenuItemTag = 1000;
CPSearchFieldRecentsMenuItemTag = 1001;
CPSearchFieldClearRecentsMenuItemTag = 1002;
CPSearchFieldNoRecentsMenuItemTag = 1003;
CPSearchFieldSeparatorMenuItemTag = 1004;
var CPSearchFieldSearchImage = nil,
CPSearchFieldFindImage = nil,
@@ -39,15 +37,16 @@ var SEARCH_BUTTON_DEFAULT_WIDTH = 25.0,
CANCEL_BUTTON_DEFAULT_WIDTH = 22.0,
BUTTON_DEFAULT_HEIGHT = 22.0;
var CPAutosavedRecentsChangedNotification = @"CPAutosavedRecentsChangedNotification";
var RECENT_SEARCH_PREFIX = @" ";
/*!
/*!
@ingroup appkit
@class CPSearchField
The CPSearchField class defines the programmatic interface for text fields that are optimized for text-based searches. A CPSearchField object directly inherits from the CPTextField class. The search field implemented by these classes presents a standard user interface for searches, including a search button, a cancel button, and a pop-up icon menu for listing recent search strings and custom search categories.
When the user types and then pauses, the text field's action message is sent to its target. You can query the text field's string value for the current text to search for. Do not rely on the sender of the action to be an CPMenu object because the menu may change. If you need to change the menu, modify the search menu template and call the setSearchMenuTemplate: method to update.
When the user types and then pauses, the text field's action message is sent to its target. You can query the text field's string value for the current text to search for. Do not rely on the sender of the action to be an CPMenu object because the menu may change. If you need to change the menu, modify the search menu template and call the setSearchMenuTemplate: method to update.
*/
@implementation CPSearchField : CPTextField
{
@@ -58,7 +57,7 @@ var RECENT_SEARCH_PREFIX = @" ";
CPString _recentsAutosaveName;
CPArray _recentSearches;
int _maximumRecents;
BOOL _sendsWholeSearchString;
BOOL _sendsSearchStringImmediately;
@@ -96,9 +95,9 @@ var RECENT_SEARCH_PREFIX = @" ";
#if PLATFORM(DOM)
_cancelButton._DOMElement.style.cursor = "default";
_searchButton._DOMElement.style.cursor = "default";
#endif
#endif
}
return self;
}
@@ -112,17 +111,17 @@ var RECENT_SEARCH_PREFIX = @" ";
[self setEditable:YES];
[self setDelegate:self];
[self setContinuous:YES];
var bounds = [self bounds],
cancelButton = [[CPButton alloc] initWithFrame:[self cancelButtonRectForBounds:bounds]],
searchButton = [[CPButton alloc] initWithFrame:[self searchButtonRectForBounds:bounds]];
[self setCancelButton:cancelButton];
[self resetCancelButton];
[self setSearchButton:searchButton];
[self resetSearchButton];
_canResignFirstResponder = YES;
}
@@ -132,12 +131,12 @@ var RECENT_SEARCH_PREFIX = @" ";
@param button The search button.
*/
- (void)setSearchButton:(CPButton)button
{
{
if (button != _searchButton)
{
[_searchButton removeFromSuperview];
_searchButton = button;
[_searchButton setFrame:[self searchButtonRectForBounds:[self bounds]]];
[_searchButton setAutoresizingMask:CPViewMaxXMargin];
[self addSubview:_searchButton];
@@ -161,7 +160,7 @@ var RECENT_SEARCH_PREFIX = @" ";
{
var button = [self searchButton],
searchButtonImage = (_searchMenuTemplate === nil) ? CPSearchFieldSearchImage : CPSearchFieldFindImage;
[button setBordered:NO];
[button setImageScaling:CPScaleToFit];
[button setImage:searchButtonImage];
@@ -178,11 +177,11 @@ var RECENT_SEARCH_PREFIX = @" ";
{
[_cancelButton removeFromSuperview];
_cancelButton = button;
[_cancelButton setFrame:[self cancelButtonRectForBounds:[self bounds]]];
[_cancelButton setAutoresizingMask:CPViewMinXMargin];
[_cancelButton setTarget:self];
[_cancelButton setAction:@selector(_searchFieldCancel:)];
[_cancelButton setAction:@selector(_searchFieldCancel:)];
[self _updateCancelButtonVisibility];
[self addSubview:_cancelButton];
}
@@ -222,22 +221,22 @@ var RECENT_SEARCH_PREFIX = @" ";
*/
- (CGRect)searchTextRectForBounds:(CGRect)rect
{
var leftOffset = 0,
var leftOffset = 0,
width = _CGRectGetWidth(rect),
bounds = [self bounds];
if (_searchButton)
{
var searchBounds = [self searchButtonRectForBounds:bounds];
leftOffset = _CGRectGetMaxX(searchBounds) + 2;
}
if (_cancelButton)
{
var cancelRect = [self cancelButtonRectForBounds:bounds];
width = _CGRectGetMinX(cancelRect) - leftOffset;
}
return _CGRectMake(leftOffset, _CGRectGetMinY(rect), width, _CGRectGetHeight(rect));
}
@@ -257,7 +256,7 @@ var RECENT_SEARCH_PREFIX = @" ";
Subclasses can override this method to return a new bounding rectangle for the cancel button. You might use this method to provide a custom layout for the search field control.
*/
- (CGRect)cancelButtonRectForBounds:(CGRect)rect
{
{
return _CGRectMake(_CGRectGetWidth(rect) - CANCEL_BUTTON_DEFAULT_WIDTH - 5, (_CGRectGetHeight(rect) - CANCEL_BUTTON_DEFAULT_WIDTH) / 2, BUTTON_DEFAULT_HEIGHT, BUTTON_DEFAULT_HEIGHT);
}
@@ -279,7 +278,7 @@ var RECENT_SEARCH_PREFIX = @" ";
- (void)setSearchMenuTemplate:(CPMenu)aMenu
{
_searchMenuTemplate = aMenu;
[self resetSearchButton];
[self _loadRecentSearchList];
[self _updateSearchMenu];
@@ -291,8 +290,8 @@ var RECENT_SEARCH_PREFIX = @" ";
@return \c YES if the action message is sent all at once when the user clicks the search button or presses return; otherwise, NO if the search string is sent after each keystroke. The default value is NO.
*/
- (BOOL)sendsWholeSearchString
{
return _sendsWholeSearchString;
{
return _sendsWholeSearchString;
}
/*!
@@ -309,8 +308,8 @@ var RECENT_SEARCH_PREFIX = @" ";
@return \c YES if the text field sends its action immediately upon notification of any changes to the search field; otherwise, NO.
*/
- (BOOL)sendsSearchStringImmediately
{
return _sendsSearchStringImmediately;
{
return _sendsSearchStringImmediately;
}
/*!
@@ -328,7 +327,7 @@ var RECENT_SEARCH_PREFIX = @" ";
@return The maximum number of search strings that can appear in the menu. This value is between 0 and 254.
*/
- (int)maximumRecents
{
{
return _maximumRecents;
}
@@ -342,13 +341,13 @@ var RECENT_SEARCH_PREFIX = @" ";
max = 254;
else if (max < 0)
max = 10;
_maximumRecents = max;
}
/*!
Returns the list of recent search strings for the control.
@return An array of \c CPString objects, each of which contains a search string either displayed in the search menu or from a recent autosave archive. If there have been no recent searches and no prior searches saved under an autosave name, this array may be empty.
@return An array of \c CPString objects, each of which contains a search string either displayed in the search menu or from a recent autosave archive. If there have been no recent searches and no prior searches saved under an autosave name, this array may be empty.
*/
- (CPArray)recentSearches
{
@@ -364,8 +363,8 @@ var RECENT_SEARCH_PREFIX = @" ";
{
var max = MIN([self maximumRecents], [searches count]),
searches = [searches subarrayWithRange:CPMakeRange(0, max)];
_recentSearches = searches;
_recentSearches = searches;
[self _autosaveRecentSearchList];
}
@@ -375,7 +374,7 @@ var RECENT_SEARCH_PREFIX = @" ";
*/
- (CPString)recentsAutosaveName
{
return _recentsAutosaveName;
return _recentsAutosaveName;
}
/*!
@@ -386,9 +385,9 @@ var RECENT_SEARCH_PREFIX = @" ";
{
if (_recentsAutosaveName != nil)
[self _deregisterForAutosaveNotification];
_recentsAutosaveName = name;
if (_recentsAutosaveName != nil)
[self _registerForAutosaveNotification];
}
@@ -397,13 +396,13 @@ var RECENT_SEARCH_PREFIX = @" ";
- (CGRect)contentRectForBounds:(CGRect)bounds
{
var superbounds = [super contentRectForBounds:bounds];
var superbounds = [super contentRectForBounds:bounds];
return [self searchTextRectForBounds:superbounds];
}
+ (double)_keyboardDelayForPartialSearchString:(CPString)string
{
return (6 - MIN([string length],4))/10;
return (6 - MIN([string length], 4)) / 10;
}
- (CPMenu)menu
@@ -431,15 +430,15 @@ var RECENT_SEARCH_PREFIX = @" ";
{
[_partialStringTimer invalidate];
var timeInterval = [CPSearchField _keyboardDelayForPartialSearchString:[self stringValue]];
_partialStringTimer = [CPTimer scheduledTimerWithTimeInterval:timeInterval
target:self
selector:@selector(_sendPartialString)
userInfo:nil
repeats:NO];
_partialStringTimer = [CPTimer scheduledTimerWithTimeInterval:timeInterval
target:self
selector:@selector(_sendPartialString)
userInfo:nil
repeats:NO];
}
}
[self _updateCancelButtonVisibility];
}
@@ -462,7 +461,7 @@ var RECENT_SEARCH_PREFIX = @" ";
{
if (string === nil || string === @"" || [_recentSearches containsObject:string])
return;
var searches = [CPMutableArray arrayWithArray:_recentSearches];
[searches addObject:string];
[self setRecentSearches:searches];
@@ -471,7 +470,7 @@ var RECENT_SEARCH_PREFIX = @" ";
- (CPView)hitTest:(CGPoint)aPoint
{
// Make sure a hit anywhere within the search field returns the search field itself
// Make sure a hit anywhere within the search field returns the search field itself
if (_CGRectContainsPoint([self frame], aPoint))
return self;
else
@@ -493,8 +492,8 @@ var RECENT_SEARCH_PREFIX = @" ";
if (_searchMenuTemplate == nil)
[self _sendAction:self];
else
[self _showMenu];
}
[self _showMenu];
}
else if (_CGRectContainsPoint([self cancelButtonRectForBounds:[self bounds]], point))
[_cancelButton mouseDown:anEvent];
else
@@ -504,69 +503,69 @@ var RECENT_SEARCH_PREFIX = @" ";
/*!
Provides the common case items for a recent searches menu. If there are not recent searches,
displays a single disabled item:
No Recent Searches
If there are 1 more recent searches, it displays:
Recent Searches
recent search 1
recent search 2
etc.
---------------------
Clear Recent Searches
If you wish to add items before or after the template, you can. If you put items
before, a separator will automatically be placed before the default template item.
If you add items after the default template, it is your responsibility to add a separator.
To add a custom item:
item = [[CPMenuItem alloc] initWithTitle:@"google"
action:@selector(google:)
item = [[CPMenuItem alloc] initWithTitle:@"google"
action:@selector(google:)
keyEquivalent:@""];
[item setTag:700];
[item setTarget:self];
[template addItem:item];
Be sure that your custom items do not use tags in the range 1000-1004 inclusive.
Be sure that your custom items do not use tags in the range 1000-1003 inclusive.
If you wish to maintain state in custom menu items that you add, you will need to maintain
the item state yourself, then in the action method of the custom items, modify the items
in the search menu template and send [searchField setSearchMenuTemplate:template] to update the menu.
*/
- (CPMenu)defaultSearchMenuTemplate
{
var template = [[CPMenu alloc] init],
var template = [[CPMenu alloc] init],
item;
item = [[CPMenuItem alloc] initWithTitle:@"Recent Searches"
action:nil
item = [[CPMenuItem alloc] initWithTitle:@"Recent Searches"
action:nil
keyEquivalent:@""];
[item setTag:CPSearchFieldRecentsTitleMenuItemTag];
[item setEnabled:NO];
[template addItem:item];
item = [[CPMenuItem alloc] initWithTitle:@"Recent search item"
action:@selector(_searchFieldSearch:)
item = [[CPMenuItem alloc] initWithTitle:@"Recent search item"
action:@selector(_searchFieldSearch:)
keyEquivalent:@""];
[item setTag:CPSearchFieldRecentsMenuItemTag];
[item setTarget:self];
[template addItem:item];
item = [[CPMenuItem alloc] initWithTitle:@"Clear Recent Searches"
action:@selector(_searchFieldClearRecents:)
item = [[CPMenuItem alloc] initWithTitle:@"Clear Recent Searches"
action:@selector(_searchFieldClearRecents:)
keyEquivalent:@""];
[item setTag:CPSearchFieldClearRecentsMenuItemTag];
[item setTarget:self];
[template addItem:item];
item = [[CPMenuItem alloc] initWithTitle:@"No Recent Searches"
action:nil
item = [[CPMenuItem alloc] initWithTitle:@"No Recent Searches"
action:nil
keyEquivalent:@""];
[item setTag:CPSearchFieldNoRecentsMenuItemTag];
[item setEnabled:NO];
[template addItem:item];
return template;
}
@@ -574,72 +573,66 @@ var RECENT_SEARCH_PREFIX = @" ";
{
if (_searchMenuTemplate === nil)
return;
var menu = [[CPMenu alloc] init],
countOfRecents = [_recentSearches count],
numberOfItems = [_searchMenuTemplate numberOfItems];
for (var i = 0; i < numberOfItems; i++)
{
var item = [[_searchMenuTemplate itemAtIndex:i] copy];
switch ([item tag])
{
case CPSearchFieldRecentsTitleMenuItemTag:
if (countOfRecents === 0)
continue;
if ([menu numberOfItems] > 0)
[self _addSeparatorToMenu:menu];
break;
case CPSearchFieldRecentsMenuItemTag:
{
var itemAction = @selector(_searchFieldSearch:);
for (var recentIndex = 0; recentIndex < countOfRecents; ++recentIndex)
{
// RECENT_SEARCH_PREFIX is a hack until CPMenuItem -setIndentationLevel works
var recentItem = [[CPMenuItem alloc] initWithTitle:RECENT_SEARCH_PREFIX + [_recentSearches objectAtIndex:recentIndex]
action:itemAction
var recentItem = [[CPMenuItem alloc] initWithTitle:RECENT_SEARCH_PREFIX + [_recentSearches objectAtIndex:recentIndex]
action:itemAction
keyEquivalent:[item keyEquivalent]];
[item setTarget:self];
[menu addItem:recentItem];
}
continue;
}
case CPSearchFieldClearRecentsMenuItemTag:
if (countOfRecents === 0)
continue;
if ([menu numberOfItems] > 0)
[self _addSeparatorToMenu:menu];
[item setAction:@selector(_searchFieldClearRecents:)];
[item setTarget:self];
break;
case CPSearchFieldNoRecentsMenuItemTag:
if (countOfRecents !== 0)
continue;
if ([menu numberOfItems] > 0)
[self _addSeparatorToMenu:menu];
break;
case CPSearchFieldSeparatorMenuItemTag:
item = [CPMenuItem separatorItem];
[item setEnabled:NO];
[menu addItem:item];
continue;
}
}
[item setEnabled:([item isEnabled] && [item action] != nil && [item target] != nil)];
[menu addItem:item];
}
[menu setDelegate:self];
_searchMenu = menu;
@@ -660,7 +653,7 @@ var RECENT_SEARCH_PREFIX = @" ";
- (void)menuDidClose:(CPMenu)menu
{
_canResignFirstResponder = YES;
[self becomeFirstResponder];
}
@@ -668,12 +661,12 @@ var RECENT_SEARCH_PREFIX = @" ";
{
if (_searchMenu === nil || [_searchMenu numberOfItems] === 0 || ![self isEnabled])
return;
var aFrame = [[self superview] convertRect:[self frame] toView:nil],
location = CPMakePoint(aFrame.origin.x + 10, aFrame.origin.y + aFrame.size.height - 4);
var anEvent = [CPEvent mouseEventWithType:CPRightMouseDown location:location modifierFlags:0 timestamp:[[CPApp currentEvent] timestamp] windowNumber:[[self window] windowNumber] context:nil eventNumber:1 clickCount:1 pressure:0];
[self selectAll:nil];
[CPMenu popUpContextMenu:_searchMenu withEvent:anEvent forView:self];
}
@@ -685,7 +678,7 @@ var RECENT_SEARCH_PREFIX = @" ";
}
- (void)_searchFieldCancel:(id)sender
{
{
[self setObjectValue:@""];
[self _sendPartialString];
[self _updateCancelButtonVisibility];
@@ -694,14 +687,14 @@ var RECENT_SEARCH_PREFIX = @" ";
- (void)_searchFieldSearch:(id)sender
{
var searchString = [[sender title] substringFromIndex:[RECENT_SEARCH_PREFIX length]];
if ([sender tag] != CPSearchFieldRecentsMenuItemTag)
[self _addStringToRecentSearches:searchString];
[self setObjectValue:searchString];
[self _sendPartialString];
[self selectAll:nil];
[self _updateCancelButtonVisibility];
}
@@ -715,54 +708,36 @@ var RECENT_SEARCH_PREFIX = @" ";
- (void)_registerForAutosaveNotification
{
[[CPNotificationCenter defaultCenter] addObserver:self selector:@selector(_updateAutosavedRecents:) name:@"CPAutosavedRecentsChangedNotification" object:nil];
[[CPNotificationCenter defaultCenter] addObserver:self selector:@selector(_updateAutosavedRecents:) name:CPAutosavedRecentsChangedNotification object:_recentsAutosaveName];
}
- (void)_deregisterForAutosaveNotification
{
[[CPNotificationCenter defaultCenter] removeObserver:self name:@"CPAutosavedRecentsChangedNotification" object:nil];
[[CPNotificationCenter defaultCenter] removeObserver:self name:CPAutosavedRecentsChangedNotification object:_recentsAutosaveName];
}
- (void)_autosaveRecentSearchList
{
if (_recentsAutosaveName != nil)
[[CPNotificationCenter defaultCenter] postNotificationName:@"CPAutosavedRecentsChangedNotification" object:_recentsAutosaveName];
{
if (_recentsAutosaveName != nil)
[[CPNotificationCenter defaultCenter] postNotificationName:CPAutosavedRecentsChangedNotification object:_recentsAutosaveName];
}
- (void)_updateAutosavedRecents:(id)notification
{
var list = [self recentSearches],
name = [notification object],
bundle_name = [[[CPBundle mainBundle] infoDictionary] objectForKey:"CPBundleName"],
cookie_name = [bundle_name lowercaseString] + "." + [notification object],
cookie = [[CPCookie alloc] initWithName:cookie_name],
cookie_value = [list componentsJoinedByString:@","];
[cookie setValue:cookie_value
expires:[[CPDate alloc] initWithTimeIntervalSinceNow:3600*24*365]
domain:(window.location.href.hostname)];
var name = [notification object];
[[CPUserDefaults standardUserDefaults] setObject:_recentSearches forKey:name];
}
- (void)_loadRecentSearchList
{
var list,
name = [self recentsAutosaveName];
var name = [self recentsAutosaveName];
if (name === nil)
return;
var bundle_name = [[[CPBundle mainBundle] infoDictionary] objectForKey:"CPBundleName"],
cookie_name = [bundle_name lowercaseString] + "." + name,
var list = [[CPUserDefaults standardUserDefaults] objectForKey:name];
cookie = [[CPCookie alloc] initWithName:cookie_name];
if (cookie != nil)
{
var cookie_value = [cookie value];
list = (cookie_value != @"") ? [cookie_value componentsSeparatedByString:@","] : [CPArray array];
if (list !== nil)
_recentSearches = list;
}
}
@end
@@ -780,7 +755,7 @@ var CPRecentsAutosaveNameKey = @"CPRecentsAutosaveNameKey",
[_searchButton removeFromSuperview];
[_cancelButton removeFromSuperview];
[super encodeWithCoder:coder];
[super encodeWithCoder:coder];
if (_searchButton)
[self addSubview:_searchButton];
@@ -793,7 +768,7 @@ var CPRecentsAutosaveNameKey = @"CPRecentsAutosaveNameKey",
if (_recentsAutosaveName)
[coder encodeObject:_recentsAutosaveName forKey:CPRecentsAutosaveNameKey];
if (_searchMenuTemplate)
[coder encodeObject:_searchMenuTemplate forKey:CPSearchMenuTemplateKey];
}
@@ -802,16 +777,16 @@ var CPRecentsAutosaveNameKey = @"CPRecentsAutosaveNameKey",
{
if (self = [super initWithCoder:coder])
{
_recentsAutosaveName = [coder decodeObjectForKey:CPRecentsAutosaveNameKey];
[self setRecentsAutosaveName:[coder decodeObjectForKey:CPRecentsAutosaveNameKey]];
_sendsWholeSearchString = [coder decodeBoolForKey:CPSendsWholeSearchStringKey];
_sendsSearchStringImmediately = [coder decodeBoolForKey:CPSendsSearchStringImmediatelyKey];
_maximumRecents = [coder decodeIntForKey:CPMaximumRecentsKey];
var template = [coder decodeObjectForKey:CPSearchMenuTemplateKey];
if (template)
[self setSearchMenuTemplate:template];
[self _init];
}
+6 -6
View File
@@ -23,8 +23,8 @@
@import <Foundation/CPObject.j>
/*!
@deprecated
/*!
@deprecated
@class CPShadow
Instances of this class contain the attributes of a drop shadow used in Cappuccino.
@@ -34,7 +34,7 @@
CPSize _offset;
float _blurRadius;
CPColor _color;
CPString _cssString;
}
@@ -54,16 +54,16 @@
- (id)_initWithOffset:(CPSize)anOffset blurRadius:(float)aBlurRadius color:(CPColor)aColor
{
self = [super init];
if (self)
{
_offset = anOffset;
_blurRadius = aBlurRadius;
_color = aColor;
_cssString = [_color cssString] + " " + Math.round(anOffset.width) + @"px " + Math.round(anOffset.height) + @"px " + Math.round(_blurRadius) + @"px";
}
return self;
}
+52 -45
View File
@@ -28,16 +28,16 @@
@ignore
*/
@implementation CPSliderColorPicker : CPColorPicker
{
{
CPView _contentView;
CPSlider _redSlider;
CPSlider _greenSlider;
CPSlider _blueSlider;
CPSlider _hueSlider;
CPSlider _saturationSlider;
CPSlider _brightnessSlider;
CPTextField _rgbLabel;
CPTextField _hsbLabel;
CPTextField _redLabel;
@@ -58,27 +58,27 @@
CPTextField _brightnessValue;
}
- (id)initWithPickerMask:(int)mask colorPanel:(CPColorPanel)owningColorPanel
- (id)initWithPickerMask:(int)mask colorPanel:(CPColorPanel)owningColorPanel
{
return [super initWithPickerMask:mask colorPanel: owningColorPanel];
}
-(id)initView
- (id)initView
{
aFrame = CPRectMake(0, 0, CPColorPickerViewWidth, CPColorPickerViewHeight);
aFrame = CGRectMake(0, 0, CPColorPickerViewWidth, CPColorPickerViewHeight);
_contentView = [[CPView alloc] initWithFrame:aFrame];
[_contentView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
_rgbLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 10, 100, 20)];
[_contentView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
_rgbLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 10, 100, 20)];
[_rgbLabel setStringValue: "Red, Green, Blue"];
[_rgbLabel setTextColor:[CPColor blackColor]];
_redLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 35, 15, 20)];
_redLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 35, 15, 20)];
[_redLabel setStringValue: "R"];
[_redLabel setTextColor:[CPColor blackColor]];
_redSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 35, aFrame.size.width - 70, 20)];
_redSlider = [[CPSlider alloc] initWithFrame: CGRectMake(15, 35, aFrame.size.width - 70, 20)];
[_redSlider setMaxValue: 1.0];
[_redSlider setMinValue: 0.0];
[_redSlider setTarget: self];
@@ -93,11 +93,11 @@
[_redValue setDelegate: self];
[_contentView addSubview: _redValue];
_greenLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 58, 15, 20)];
_greenLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 58, 15, 20)];
[_greenLabel setStringValue: "G"];
[_greenLabel setTextColor:[CPColor blackColor]];
_greenSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 58, aFrame.size.width - 70, 20)];
_greenSlider = [[CPSlider alloc] initWithFrame: CGRectMake(15, 58, aFrame.size.width - 70, 20)];
[_greenSlider setMaxValue: 1.0];
[_greenSlider setMinValue: 0.0];
[_greenSlider setTarget: self];
@@ -112,11 +112,11 @@
[_greenValue setDelegate: self];
[_contentView addSubview: _greenValue];
_blueLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 81, 15, 20)];
_blueLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 81, 15, 20)];
[_blueLabel setStringValue: "B"];
[_blueLabel setTextColor:[CPColor blackColor]];
_blueSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 81, aFrame.size.width - 70, 20)];
_blueSlider = [[CPSlider alloc] initWithFrame: CGRectMake(15, 81, aFrame.size.width - 70, 20)];
[_blueSlider setMaxValue: 1.0];
[_blueSlider setMinValue: 0.0];
[_blueSlider setTarget: self];
@@ -131,15 +131,15 @@
[_blueValue setDelegate: self];
[_contentView addSubview: _blueValue];
_hsbLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 120, 190, 20)];
_hsbLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 120, 190, 20)];
[_hsbLabel setStringValue: "Hue, Saturation, Brightness"];
[_hsbLabel setTextColor:[CPColor blackColor]];
_hueLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 145, 15, 20)];
_hueLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 145, 15, 20)];
[_hueLabel setStringValue: "H"];
[_hueLabel setTextColor:[CPColor blackColor]];
_hueSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 145, aFrame.size.width - 70, 20)];
_hueSlider = [[CPSlider alloc] initWithFrame: CGRectMake(15, 145, aFrame.size.width - 70, 20)];
[_hueSlider setMaxValue: 359.0];
[_hueSlider setMinValue: 0.0];
[_hueSlider setTarget: self];
@@ -154,11 +154,11 @@
[_hueValue setDelegate: self];
[_contentView addSubview: _hueValue];
_saturationLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 168, 15, 20)];
_saturationLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 168, 15, 20)];
[_saturationLabel setStringValue: "S"];
[_saturationLabel setTextColor:[CPColor blackColor]];
_saturationSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 168, aFrame.size.width - 70, 20)];
_saturationSlider = [[CPSlider alloc] initWithFrame: CGRectMake(15, 168, aFrame.size.width - 70, 20)];
[_saturationSlider setMaxValue: 100.0];
[_saturationSlider setMinValue: 0.0];
[_saturationSlider setTarget: self];
@@ -173,11 +173,11 @@
[_saturationValue setDelegate: self];
[_contentView addSubview: _saturationValue];
_brightnessLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 191, 15, 20)];
_brightnessLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 191, 15, 20)];
[_brightnessLabel setStringValue: "B"];
[_brightnessLabel setTextColor:[CPColor blackColor]];
_brightnessSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 191, aFrame.size.width - 70, 20)];
_brightnessSlider = [[CPSlider alloc] initWithFrame: CGRectMake(15, 191, aFrame.size.width - 70, 20)];
[_brightnessSlider setMaxValue: 100.0];
[_brightnessSlider setMinValue: 0.0];
[_brightnessSlider setTarget: self];
@@ -192,7 +192,7 @@
[_brightnessValue setDelegate: self];
[_contentView addSubview: _brightnessValue];
_hexLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 230, 30, 20)];
_hexLabel = [[CPTextField alloc] initWithFrame: CGRectMake(0, 230, 30, 20)];
[_hexLabel setStringValue: "Hex"];
[_hexLabel setTextColor:[CPColor blackColor]];
@@ -210,7 +210,7 @@
[_contentView addSubview: _redSlider];
[_contentView addSubview: _greenSlider];
[_contentView addSubview: _blueSlider];
[_contentView addSubview: _hsbLabel];
[_contentView addSubview: _hueLabel];
[_contentView addSubview: _saturationLabel];
@@ -218,24 +218,24 @@
[_contentView addSubview: _hueSlider];
[_contentView addSubview: _saturationSlider];
[_contentView addSubview: _brightnessSlider];
[_contentView addSubview: _hexLabel];
}
- (CPView)provideNewView:(BOOL)initialRequest
- (CPView)provideNewView:(BOOL)initialRequest
{
if (initialRequest)
if (initialRequest)
[self initView];
return _contentView;
}
- (int)currentMode
- (int)currentMode
{
return CPSliderColorPickerMode;
}
- (BOOL)supportsMode:(int)mode
- (BOOL)supportsMode:(int)mode
{
return (mode == CPSliderColorPickerMode) ? YES : NO;
}
@@ -246,7 +246,7 @@
colorPanel = [self colorPanel],
alpha = [colorPanel opacity];
switch(sender)
switch (sender)
{
case _hueSlider:
case _saturationSlider:
@@ -254,21 +254,21 @@
saturation: [_saturationSlider floatValue]
brightness: [_brightnessSlider floatValue]
alpha: alpha];
[self updateRGBSliders: newColor];
break;
case _redSlider:
case _greenSlider:
case _blueSlider: newColor = [CPColor colorWithCalibratedRed: [_redSlider floatValue]
green: [_greenSlider floatValue]
blue: [_blueSlider floatValue]
alpha: alpha];
[self updateHSBSliders: newColor];
break;
}
[self updateLabels];
[self updateHex: newColor];
[colorPanel setColor: newColor];
@@ -285,7 +285,7 @@
-(void)updateHSBSliders:(CPColor)aColor
{
var hsb = [aColor hsbComponents];
[_hueSlider setFloatValue:hsb[0]];
[_saturationSlider setFloatValue:hsb[1]];
[_brightnessSlider setFloatValue:hsb[2]];
@@ -310,7 +310,7 @@
[_hueValue setStringValue: ROUND([_hueSlider floatValue])];
[_saturationValue setStringValue: ROUND([_saturationSlider floatValue])];
[_brightnessValue setStringValue: ROUND([_brightnessSlider floatValue])];
[_redValue setStringValue: ROUND([_redSlider floatValue] * 255)];
[_greenValue setStringValue: ROUND([_greenSlider floatValue] * 255)];
[_blueValue setStringValue: ROUND([_blueSlider floatValue] * 255)];
@@ -330,14 +330,21 @@
{
var field = [aNotification object],
value = [[field stringValue] stringByTrimmingWhitespace];
if (field === _hexValue) {
if (field === _hexValue)
{
var newColor = [CPColor colorWithHexString: value];
if (newColor) {
if (newColor)
{
[self setColor: newColor];
[[self colorPanel] setColor: newColor];
}
} else {
switch(field) {
}
else
{
switch (field)
{
case _redValue: [_redSlider setFloatValue:MAX(MIN(ROUND(value), 255) / 255.0, 0)];
[self sliderChanged: _redSlider];
break;
+14 -11
View File
@@ -621,17 +621,20 @@ var CPSplitViewHorizontalImage = nil,
viewFrame = CGRectMakeCopy(bounds),
isSizable = isVertical ? [view autoresizingMask] & CPViewWidthSizable : [view autoresizingMask] & CPViewHeightSizable;
if (index + 1 == count)
viewFrame.size[_sizeComponent] = bounds.size[_sizeComponent] - viewFrame.origin[_originComponent];
else if (totalSizableSpace && isSizable && lastSizableIndex === index)
viewFrame.size[_sizeComponent] = MAX(0, ROUND([view frame].size[_sizeComponent] + remainingFlexibleSpace))
else if (isSizable || !totalSizableSpace)
{
viewFrame.size[_sizeComponent] = MAX(0, ROUND(ratio * [view frame].size[_sizeComponent]));
remainingFlexibleSpace -= (viewFrame.size[_sizeComponent] - [view frame].size[_sizeComponent]);
}
else if (totalSizableSpace && !isSizable)
viewFrame.size[_sizeComponent] = [view frame].size[_sizeComponent];
if (index + 1 === count)
viewFrame.size[_sizeComponent] = bounds.size[_sizeComponent] - viewFrame.origin[_originComponent];
else if (totalSizableSpace && isSizable && lastSizableIndex === index)
viewFrame.size[_sizeComponent] = MAX(0, ROUND([view frame].size[_sizeComponent] + remainingFlexibleSpace))
else if (isSizable || !totalSizableSpace)
{
viewFrame.size[_sizeComponent] = MAX(0, ROUND(ratio * [view frame].size[_sizeComponent]));
remainingFlexibleSpace -= (viewFrame.size[_sizeComponent] - [view frame].size[_sizeComponent]);
}
else if (totalSizableSpace && !isSizable)
viewFrame.size[_sizeComponent] = [view frame].size[_sizeComponent];
bounds.origin[_originComponent] += viewFrame.size[_sizeComponent] + dividerThickness;
+18 -16
View File
@@ -37,7 +37,7 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
int _increment @accessors(property=increment);
int _maxValue @accessors(property=maxValue);
int _minValue @accessors(property=minValue);
_CPContinuousButton _buttonDown;
_CPContinuousButton _buttonUp;
}
@@ -57,11 +57,11 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
[stepper setDoubleValue:aValue];
[stepper setMinValue:aMinValue];
[stepper setMaxValue:aMaxValue];
return stepper;
}
/*! Initializes a CPStepper with default values:
/*! Initializes a CPStepper with default values:
- minValue = 0.0
- maxValue = 59.0
- value = 0.0
@@ -84,23 +84,23 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
_minValue = 0.0;
_increment = 1.0;
_valueWraps = YES;
[self setDoubleValue:0.0];
_buttonUp = [[_CPContinuousButton alloc] initWithFrame:CPRectMake(aFrame.size.width - CPStepperButtonsSize.width, 0, CPStepperButtonsSize.width, CPStepperButtonsSize.height)];
[_buttonUp setContinuous:YES];
[_buttonUp setTarget:self];
[_buttonUp setAction:@selector(_buttonDidClick:)];
[_buttonUp setAutoresizingMask:CPViewNotSizable];
[self addSubview:_buttonUp];
_buttonDown = [[_CPContinuousButton alloc] initWithFrame:CPRectMake(aFrame.size.width - CPStepperButtonsSize.width, CPStepperButtonsSize.height, CPStepperButtonsSize.width, CPStepperButtonsSize.height - 1)];
[_buttonDown setContinuous:YES];
[_buttonDown setTarget:self];
[_buttonDown setAction:@selector(_buttonDidClick:)];
[_buttonDown setAutoresizingMask:CPViewNotSizable];
[self addSubview:_buttonDown];
[self setNeedsLayout];
}
@@ -139,7 +139,7 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
[_buttonUp setValue:[self valueForThemeAttribute:@"bezel-color-up-button" inState:CPThemeStateBordered | CPThemeStateHighlighted] forThemeAttribute:@"bezel-color" inState:CPThemeStateBordered | CPThemeStateHighlighted];
[_buttonDown setValue:[self valueForThemeAttribute:@"bezel-color-down-button" inState:CPThemeStateBordered] forThemeAttribute:@"bezel-color" inState:CPThemeStateBordered];
[_buttonDown setValue:[self valueForThemeAttribute:@"bezel-color-down-button" inState:CPThemeStateBordered | CPThemeStateDisabled] forThemeAttribute:@"bezel-color" inState:CPThemeStateBordered | CPThemeStateDisabled];
[_buttonDown setValue:[self valueForThemeAttribute:@"bezel-color-down-button" inState:CPThemeStateBordered | CPThemeStateHighlighted] forThemeAttribute:@"bezel-color" inState:CPThemeStateBordered | CPThemeStateHighlighted];
[_buttonDown setValue:[self valueForThemeAttribute:@"bezel-color-down-button" inState:CPThemeStateBordered | CPThemeStateHighlighted] forThemeAttribute:@"bezel-color" inState:CPThemeStateBordered | CPThemeStateHighlighted];
}
/*! set if CPStepper should autorepeat
@@ -235,7 +235,7 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
- (void)encodeWithCoder:(CPCoder)aCoder
{
[super encodeWithCoder:aCoder];
[aCoder encodeObject:_maxValue forKey:@"_maxValue"];
[aCoder encodeObject:_minValue forKey:@"_minValue"];
[aCoder encodeObject:_increment forKey:@"_increment"];
@@ -264,7 +264,7 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
_periodicInterval = 0.05;
_periodicDelay = 0.5;
}
return self;
}
@@ -278,13 +278,15 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
{
if ([self isContinuous])
{
_continuousDelayTimer = [CPTimer scheduledTimerWithTimeInterval:_periodicDelay callback: function(){
_continuousDelayTimer = [CPTimer scheduledTimerWithTimeInterval:_periodicDelay callback: function()
{
if (!_continuousTimer)
_continuousTimer = [CPTimer scheduledTimerWithTimeInterval:_periodicInterval target:self selector:@selector(onContinousEvent:) userInfo:anEvent repeats:YES];
}
}
repeats:NO];
}
[super mouseDown:anEvent];
}
@@ -304,10 +306,10 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
{
if (_continuousTimer)
{
[_continuousTimer invalidate];
[_continuousTimer invalidate];
_continuousTimer = nil;
}
if (_continuousDelayTimer)
{
[_continuousDelayTimer invalidate];
@@ -334,7 +336,7 @@ var CPStepperButtonsSize = CPSizeMake(19, 13);
- (void)encodeWithCoder:(CPCoder)aCoder
{
[super encodeWithCoder:aCoder];
[self invalidateTimers];
[aCoder encodeObject:_periodicDelay forKey:@"_periodicDelay"];
[aCoder encodeObject:_periodicInterval forKey:@"_periodicInterval"];
+9 -9
View File
@@ -44,7 +44,7 @@ CPBackgroundTab = 1;
*/
CPPressedTab = 2;
/*!
/*!
@ingroup appkit
@class CPTabViewItem
@@ -55,10 +55,10 @@ CPPressedTab = 2;
{
id _identifier;
CPString _label;
CPView _view;
CPView _auxiliaryView;
CPTabView _tabView;
}
@@ -74,10 +74,10 @@ CPPressedTab = 2;
- (id)initWithIdentifier:(id)anIdentifier
{
self = [super init];
if (self)
_identifier = anIdentifier;
return self;
}
@@ -191,16 +191,16 @@ var CPTabViewItemIdentifierKey = "CPTabViewItemIdentifierKey",
- (id)initWithCoder:(CPCoder)aCoder
{
self = [super init];
if (self)
{
_identifier = [aCoder decodeObjectForKey:CPTabViewItemIdentifierKey];
_label = [aCoder decodeObjectForKey:CPTabViewItemLabelKey];
_view = [aCoder decodeObjectForKey:CPTabViewItemViewKey];
_auxiliaryView = [aCoder decodeObjectForKey:CPTabViewItemAuxViewKey];
}
return self;
}
@@ -208,7 +208,7 @@ var CPTabViewItemIdentifierKey = "CPTabViewItemIdentifierKey",
{
[aCoder encodeObject:_identifier forKey:CPTabViewItemIdentifierKey];
[aCoder encodeObject:_label forKey:CPTabViewItemLabelKey];
[aCoder encodeObject:_view forKey:CPTabViewItemViewKey];
[aCoder encodeObject:_auxiliaryView forKey:CPTabViewItemAuxViewKey];
}
+11 -11
View File
@@ -56,7 +56,7 @@
{
_textField = [[_CPImageAndTextView alloc] initWithFrame:_CGRectMakeZero()];
[_textField setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
[_textField setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
[_textField setLineBreakMode:CPLineBreakByTruncatingTail];
[_textField setAlignment:CPLeftTextAlignment];
@@ -107,15 +107,15 @@
- (void)_setIndicatorImage:(CPImage)anImage
{
if (anImage)
{
[_textField setImage:anImage];
[_textField setImagePosition:CPImageRight];
}
else
{
[_textField setImagePosition:CPNoImage];
}
if (anImage)
{
[_textField setImage:anImage];
[_textField setImagePosition:CPImageRight];
}
else
{
[_textField setImagePosition:CPNoImage];
}
}
@end
@@ -634,7 +634,7 @@ var _CPTableColumnHeaderViewStringValueKey = @"_CPTableColumnHeaderViewStringVal
columnMaxX;
CGContextBeginPath(context);
for(; columnArrayIndex < columnArrayCount; columnArrayIndex++)
for (; columnArrayIndex < columnArrayCount; columnArrayIndex++)
{
// grab each column rect and add vertical lines
var columnIndex = columnsArray[columnArrayIndex],
+241 -132
View File
@@ -100,6 +100,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
#define NUMBER_OF_COLUMNS() (_tableColumns.length)
#define UPDATE_COLUMN_RANGES_IF_NECESSARY() if (_dirtyTableColumnRangeIndex !== CPNotFound) [self _recalculateTableColumnRanges];
@implementation _CPTableDrawView : CPView
{
CPTableView _tableView;
@@ -151,6 +152,8 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
BOOL _reloadAllRows;
Object _objectValues;
CGRect _exposedRect;
CPIndexSet _exposedRows;
CPIndexSet _exposedColumns;
@@ -180,6 +183,8 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
unsigned _numberOfRows;
CPIndexSet _groupRows;
CPArray _cachedRowHeights;
// Persistence
CPString _autosaveName;
BOOL _autosaveTableColumns;
@@ -274,7 +279,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
_currentHighlightedTableColumn = nil;
_sortDescriptors = [CPArray array];
_sortDescriptors = [];
_draggedRowIndexes = [CPIndexSet indexSet];
_verticalMotionCanDrag = YES;
@@ -314,13 +319,14 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
_dirtyTableColumnRangeIndex = 0;
_numberOfHiddenColumns = 0;
_objectValues = { };
_dataViewsForTableColumns = { };
_dataViews= [];
_numberOfRows = 0;
_exposedRows = [CPIndexSet indexSet];
_exposedColumns = [CPIndexSet indexSet];
_cachedDataViews = { };
_objectValues = { };
_dataViewsForTableColumns = { };
_dataViews = [];
_numberOfRows = 0;
_exposedRows = [CPIndexSet indexSet];
_exposedColumns = [CPIndexSet indexSet];
_cachedDataViews = { };
_cachedRowHeights = [];
_groupRows = [CPIndexSet indexSet];
@@ -430,6 +436,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
_reloadAllRows = YES;
_objectValues = { };
_cachedRowHeights = [];
// This updates the size too.
[self noteNumberOfRowsChanged];
@@ -1130,7 +1137,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
*/
- (int)numberOfRows
{
if (_numberOfRows)
if (_numberOfRows !== nil)
return _numberOfRows;
var contentBindingInfo = [self infoForBinding:@"content"];
@@ -1140,13 +1147,14 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
var destination = [contentBindingInfo objectForKey:CPObservedObjectKey],
keyPath = [contentBindingInfo objectForKey:CPObservedKeyPathKey];
return [[destination valueForKeyPath:keyPath] count];
_numberOfRows = [[destination valueForKeyPath:keyPath] count];
}
else if (_dataSource)
return [_dataSource numberOfRowsInTableView:self];
_numberOfRows = [_dataSource numberOfRowsInTableView:self];
else
_numberOfRows = 0;
return 0;
return _numberOfRows;
}
//Displaying Cell
@@ -1284,6 +1292,10 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
// Complexity:
// O(1)
/*!
Returns a CGRect with the location and size of the column
@param aColumnIndex the index of the column you want the rect of
*/
- (CGRect)rectOfColumn:(CPInteger)aColumnIndex
{
aColumnIndex = +aColumnIndex;
@@ -1297,14 +1309,32 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
var range = _tableColumnRanges[aColumnIndex];
return _CGRectMake(range.location, 0.0, range.length, CGRectGetHeight([self bounds]));
return _CGRectMake(range.location, 0.0, range.length, _CGRectGetHeight([self bounds]));
}
// Complexity:
// O(1)
/*!
Returns a CGRect with the location and size of the row
@param aRowIndex the index of the row you want the rect of
*/
- (CGRect)rectOfRow:(CPInteger)aRowIndex
{
var height = _rowHeight + _intercellSpacing.height;
if (aRowIndex > [self numberOfRows] - 1 || aRowIndex < 0)
return _CGRectMakeZero();
return _CGRectMake(0.0, aRowIndex * height, _CGRectGetWidth([self bounds]), height);
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_)
{
var y = _cachedRowHeights[aRowIndex].heightAboveRow,
height = _cachedRowHeights[aRowIndex].height + _intercellSpacing.height;
}
else
{
var y = aRowIndex * (_rowHeight + _intercellSpacing.height),
height = _rowHeight + _intercellSpacing.height;
}
return _CGRectMake(0.0, y, _CGRectGetWidth([self bounds]), height);
}
// Complexity:
@@ -1313,7 +1343,6 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
Returns a range of indices for the rows that lie wholly or partially within the vertical boundaries of a given rectangle.
@param aRect A rectangle in the coordinate system of the receiver.
*/
- (CPRange)rowsInRect:(CGRect)aRect
{
// If we have no rows, then we won't intersect anything.
@@ -1419,30 +1448,57 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
return CPNotFound;
}
//Complexity
// O(1) for static row height
// 0(lg Rows) for variable row heights
- (CPInteger)rowAtPoint:(CGPoint)aPoint
{
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_)
{
return idx = [_cachedRowHeights indexOfObject:aPoint sortedByFunction:function(aPoint, rowCache) {
var upperBound = rowCache.heightAboveRow;
if (aPoint.y < upperBound)
return CPOrderedAscending;
if (aPoint.y > upperBound + rowCache.height)
return CPOrderedDescending;
return CPOrderedSame;
}];
}
var y = aPoint.y,
row = FLOOR(y / (_rowHeight + _intercellSpacing.height));
if (row >= _numberOfRows)
return -1;
return CPNotFound;
return row;
}
/*!
returns a rect for the dataview / cell at the column and row given
if the column or row index is greater than the number of columns or rows a CGZeroRect is returned
@param aColumn index of the column
@param aRow index of the row
*/
- (CGRect)frameOfDataViewAtColumn:(CPInteger)aColumn row:(CPInteger)aRow
{
UPDATE_COLUMN_RANGES_IF_NECESSARY();
if (aColumn > [self numberOfColumns] || aRow > [self numberOfRows])
return _CGRectMakeZero();
var tableColumnRange = _tableColumnRanges[aColumn],
rectOfRow = [self rectOfRow:aRow],
leftInset = FLOOR(_intercellSpacing.width / 2.0),
topInset = FLOOR(_intercellSpacing.height / 2.0);
return _CGRectMake(tableColumnRange.location + leftInset,
_CGRectGetMinY(rectOfRow) + topInset,
tableColumnRange.length - _intercellSpacing.width,
_CGRectGetHeight(rectOfRow) - _intercellSpacing.height);
return _CGRectMake(tableColumnRange.location + leftInset, _CGRectGetMinY(rectOfRow) + topInset, tableColumnRange.length - _intercellSpacing.width, _CGRectGetHeight(rectOfRow) - _intercellSpacing.height);
}
- (void)resizeWithOldSuperviewSize:(CGSize)aSize
@@ -1634,7 +1690,12 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
var oldNumberOfRows = _numberOfRows;
_numberOfRows = nil;
_numberOfRows = [self numberOfRows];
_cachedRowHeights = [];
// this line serves two purposes
// 1. it updates the _numberOfRows cache with the -numberOfRows call
// 2. it updates the row height cache if needed
[self noteHeightOfRowsWithIndexesChanged:[CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, [self numberOfRows])]];
// remove row indexes from the selection if they no longer exist
var hangingSelections = oldNumberOfRows - _numberOfRows;
@@ -1652,15 +1713,65 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
[self tile];
}
/*!
Informs the receiver that the rows specified in indexSet have changed height.
@param anIndexSet an index set containing the indexes of the rows which changed height
*/
- (void)noteHeightOfRowsWithIndexesChanged:(CPIndexSet)anIndexSet
{
if (!(_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_))
return;
// this method will update the height of those rows, but since the cached array also contains
// the height above the row it needs to recalculate for the rows below it too
var i = [anIndexSet firstIndex],
count = _numberOfRows - i,
heightAbove = (i > 0) ? _cachedRowHeights[i - 1].height + _cachedRowHeights[i - 1].heightAboveRow + _intercellSpacing.height : 0;
for (; i < count; i++)
{
// update the cache if the user told us to
if ([anIndexSet containsIndex:i])
var height = [_delegate tableView:self heightOfRow:i];
if (_cachedRowHeights.length > i)
{
// since it exists, update it
_cachedRowHeights[i].height = height;
_cachedRowHeights[i].heightAboveRow = heightAbove;
}
else
_cachedRowHeights[i] = {"height":height, "heightAboveRow":heightAbove};
heightAbove += height + _intercellSpacing.height;
}
}
/*!
lays out the dataviews and resizes the tableview so that everything fits
*/
- (void)tile
{
UPDATE_COLUMN_RANGES_IF_NECESSARY();
// FIXME: variable row heights.
var width = _tableColumnRanges.length > 0 ? CPMaxRange([_tableColumnRanges lastObject]) : 0.0,
height = (_rowHeight + _intercellSpacing.height) * _numberOfRows,
superview = [self superview];
if (!(_implementedDelegateMethods & CPTableViewDelegate_tableView_heightOfRow_))
var height = (_rowHeight + _intercellSpacing.height) * _numberOfRows;
else
{
// if this is the fist run we need to populate the cache
if ([self numberOfRows] !== _cachedRowHeights.length)
[self noteHeightOfRowsWithIndexesChanged:[CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, [self numberOfRows])]];
var heightObject = _cachedRowHeights[_cachedRowHeights.length - 1],
height = heightObject.heightAboveRow + heightObject.height + _intercellSpacing.height;
}
if ([superview isKindOfClass:[CPClipView class]])
{
var superviewSize = [superview bounds].size;
@@ -1675,17 +1786,6 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
[self setNeedsDisplay:YES];
}
/*
* - tile
* - sizeToFit
* - noteHeightOfRowsWithIndexesChanged:
*/
//Scrolling
/*
* - scrollRowToVisible:
* - scrollColumnToVisible:
*/
/*!
Scrolls the receiver vertically in an enclosing NSClipView so the row specified by rowIndex is visible.
@param aRowIndex the index of the row to scroll to.
@@ -1943,7 +2043,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
*/
- (BOOL)_sendDelegateDeleteKeyPressed
{
if([_delegate respondsToSelector: @selector(tableViewDeleteKeyPressed:)])
if ([_delegate respondsToSelector: @selector(tableViewDeleteKeyPressed:)])
{
[_delegate tableViewDeleteKeyPressed:self];
return YES;
@@ -2128,8 +2228,8 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
}
var dragPoint = [self convertPoint:[theDragEvent locationInWindow] fromView:nil];
dragViewOffset.x = CGRectGetWidth(bounds) / 2 - dragPoint.x;
dragViewOffset.y = CGRectGetHeight(bounds) / 2 - dragPoint.y;
dragViewOffset.x = _CGRectGetWidth(bounds) / 2 - dragPoint.x;
dragViewOffset.y = _CGRectGetHeight(bounds) / 2 - dragPoint.y;
return view;
}
@@ -2144,7 +2244,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
{
var dragView = [[_CPColumnDragView alloc] initWithLineColor:[self gridColor]],
tableColumn = [[self tableColumns] objectAtIndex:theColumnIndex],
bounds = CPRectMake(0.0, 0.0, [tableColumn width], _CGRectGetHeight([self visibleRect]) + 23.0),
bounds = _CGRectMake(0.0, 0.0, [tableColumn width], _CGRectGetHeight([self exposedRect]) + 23.0),
columnRect = [self rectOfColumn:theColumnIndex],
headerView = [tableColumn headerView],
row = [_exposedRows firstIndex];
@@ -2158,7 +2258,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
dataViewFrame.origin.x = 0.0;
// Offset by table header height - scroll position
dataViewFrame.origin.y = ( _CGRectGetMinY(dataViewFrame) - _CGRectGetMinY([self visibleRect]) ) + 23.0;
dataViewFrame.origin.y = ( _CGRectGetMinY(dataViewFrame) - _CGRectGetMinY([self exposedRect]) ) + 23.0;
[dataView setFrame:dataViewFrame];
[dataView setObjectValue:[self _objectValueForTableColumn:tableColumn row:row]];
@@ -2298,6 +2398,24 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
return objectValue;
}
- (CGRect)exposedRect
{
if (!_exposedRect)
{
var superview = [self superview];
// FIXME: Should we be rect intersecting in case
// there are multiple views in the clip view?
if ([superview isKindOfClass:[CPClipView class]])
_exposedRect = [superview bounds];
else
_exposedRect = [self bounds];
}
return _exposedRect;
}
- (void)load
{
if (_reloadAllRows)
@@ -2310,7 +2428,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
_reloadAllRows = NO;
}
var exposedRect = [self visibleRect],
var exposedRect = [self exposedRect],
exposedRows = [CPIndexSet indexSetWithIndexesInRange:[self rowsInRect:exposedRect]],
exposedColumns = [self columnIndexesInRect:exposedRect],
obscuredRows = [_exposedRows copy],
@@ -2469,7 +2587,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_isGroupRow_)
{
if([_delegate tableView:self isGroupRow:row])
if ([_delegate tableView:self isGroupRow:row])
{
[_groupRows addIndex:row];
[dataView setThemeState:CPThemeStateGroupRow];
@@ -2589,6 +2707,29 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
if (_headerView)
[_headerView setFrameSize:_CGSizeMake(_CGRectGetWidth([self frame]), _CGRectGetHeight([_headerView frame]))];
_exposedRect = nil;
}
- (void)setFrameOrigin:(CGPoint)aPoint
{
[super setFrameOrigin:aPoint];
_exposedRect = nil;
}
- (void)setBoundsOrigin:(CGPoint)aPoint
{
[super setBoundsOrigin:aPoint];
_exposedRect = nil;
}
- (void)setBoundsSize:(CGSize)aSize
{
[super setBoundsSize:aSize];
_exposedRect = nil;
}
- (void)setNeedsDisplay:(BOOL)aFlag
@@ -2602,7 +2743,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
// FIX ME: All three of these methods will likely need to be rewritten for 1.0
// We've got grid drawing in highlightSelection and crap everywhere.
var exposedRect = [self visibleRect];
var exposedRect = [self exposedRect];
[self drawBackgroundInClipRect:exposedRect];
[self drawGridInClipRect:exposedRect];
@@ -2632,65 +2773,31 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
return;
}
// CGContextFillRect(context, CGRectIntersection(aRect, fillRect));
// console.profile("row-paint");
var exposedRows = [self rowsInRect:aRect],
firstRow = exposedRows.location,
lastRow = CPMaxRange(exposedRows) - 1,
colorIndex = MIN(exposedRows.length, colorCount),
heightFilled = 0.0,
groupRowRects = [ ];
lastRow = CPMaxRange(exposedRows),
colorIndex = 0,
groupRowRects = [],
row = exposedRows.location;
while (colorIndex--)
//loop through each color so we only draw once for each color
while (colorIndex < colorCount)
{
var row = firstRow - firstRow % colorCount + colorIndex,
fillRect = _CGRectMakeZero();
CGContextBeginPath(context);
for (; row <= lastRow; row += colorCount)
if (row >= firstRow)
{
if (![_groupRows containsIndex:row] && _selectionHighlightStyle !== CPTableViewSelectionHighlightStyleSourceList)
CGContextAddRect(context, CGRectIntersection(aRect, fillRect = [self rectOfRow:row]));
else
groupRowRects.push(CGRectIntersection(aRect, [self rectOfRow:row]));
}
if (row - colorCount === lastRow)
heightFilled = _CGRectGetMaxY(fillRect);
for (var row = colorIndex; row < lastRow; row += colorCount)
{
// if it's not a group row draw it otherwise we draw it later
if (![_groupRows containsIndex:row])
CGContextAddRect(context, CGRectIntersection(aRect, [self rectOfRow:row]));
else
groupRowRects.push(CGRectIntersection(aRect, [self rectOfRow:row]));
}
CGContextClosePath(context);
CGContextSetFillColor(context, rowColors[colorIndex]);
CGContextFillPath(context);
}
// console.profileEnd("row-paint");
// FIX ME: this is really terrible, it seems like such a hack...
var totalHeight = _CGRectGetMaxY(aRect);
if (heightFilled >= totalHeight || _rowHeight <= 0.0)
{
[self _drawGroupRowsForRects:groupRowRects];
return;
}
var rowHeight = _rowHeight + _intercellSpacing.height,
fillRect = _CGRectMake(_CGRectGetMinX(aRect), _CGRectGetMinY(aRect) + heightFilled, _CGRectGetWidth(aRect), rowHeight);
for (row = lastRow + 1; heightFilled < totalHeight; ++row)
{
if(![_groupRows containsIndex:row] && _selectionHighlightStyle !== CPTableViewSelectionHighlightStyleSourceList)
{
CGContextSetFillColor(context, rowColors[row % colorCount]);
CGContextFillRect(context, fillRect);
}
heightFilled += rowHeight;
fillRect.origin.y += rowHeight;
colorIndex++;
}
[self _drawGroupRowsForRects:groupRowRects];
@@ -3016,7 +3123,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
object:superview];
}
if (aView)
if ([aView isKindOfClass:[CPClipView class]])
{
[aView setPostsFrameChangedNotifications:YES];
[aView setPostsBoundsChangedNotifications:YES];
@@ -3037,12 +3144,16 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
- (void)superviewBoundsChanged:(CPNotification)aNotification
{
_exposedRect = nil;
[self setNeedsDisplay:YES];
[self setNeedsLayout];
}
- (void)superviewFrameChanged:(CPNotification)aNotification
{
_exposedRect = nil;
[self tile];
}
@@ -3338,21 +3449,20 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
*/
- (CPInteger)_proposedRowAtPoint:(CGPoint)dragPoint
{
// We don't use rowAtPoint here because the drag indicator can appear below the last row
// and rowAtPoint doesn't return rows that are larger than numberOfRows
// FIX ME: this is going to break when we implement variable row heights...
var row = FLOOR(dragPoint.y / ( _rowHeight + _intercellSpacing.height )),
var row = [self rowAtPoint:dragPoint],
// Determine if the mouse is currently closer to this row or the row below it
lowerRow = row + 1,
rect = [self rectOfRow:row],
bottomPoint = CGRectGetMaxY(rect),
bottomThirty = bottomPoint - ((bottomPoint - CGRectGetMinY(rect)) * 0.3);
bottomPoint = _CGRectGetMaxY(rect),
bottomThirty = bottomPoint - ((bottomPoint - _CGRectGetMinY(rect)) * 0.3),
numberOfRows = [self numberOfRows];
if (dragPoint.y > MAX(bottomThirty, bottomPoint - 6))
if (row < 0)
row = (_CGRectGetMaxY(rect) < dragPoint.y) ? numberOfRows : row;
else if (dragPoint.y > MAX(bottomThirty, bottomPoint - 6))
row = lowerRow;
if (row >= [self numberOfRows])
row = [self numberOfRows];
row = MIN(numberOfRows, row);
return row;
}
@@ -3387,20 +3497,19 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
dropOperation = [self _proposedDropOperationAtPoint:location],
numberOfRows = [self numberOfRows],
row = [self _proposedRowAtPoint:location],
dragOperation = [self _validateDrop:sender proposedRow:row proposedDropOperation:dropOperation],
exposedClipRect = [self visibleRect];
dragOperation = [self _validateDrop:sender proposedRow:row proposedDropOperation:dropOperation];
if (_retargetedDropRow !== nil)
row = _retargetedDropRow;
if (dropOperation === CPTableViewDropOn && row >= [self numberOfRows])
row = [self numberOfRows] - 1;
if (dropOperation === CPTableViewDropOn && row >= numberOfRows)
row = numberOfRows - 1;
var rect = _CGRectMakeZero();
if (row === -1)
rect = exposedClipRect;
rect = [self exposedRect];
else if (dropOperation === CPTableViewDropAbove)
rect = [self _rectForDropHighlightViewBetweenUpperRow:row - 1 andLowerRow:row offset:location];
@@ -3457,7 +3566,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
*/
- (void)draggedImage:(CPImage)anImage endedAt:(CGPoint)aLocation operation:(CPDragOperation)anOperation
{
if([_dataSource respondsToSelector:@selector(tableView:didEndDraggedImage:atPosition:operation:)])
if ([_dataSource respondsToSelector:@selector(tableView:didEndDraggedImage:atPosition:operation:)])
[_dataSource tableView:self didEndDraggedImage:anImage atPosition:aLocation operation:anOperation];
}
@@ -3474,7 +3583,7 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
- (void)_updateSelectionWithMouseAtRow:(CPInteger)aRow
{
//check to make sure the row exists
if(aRow < 0)
if (aRow < 0)
return;
var newSelection,
@@ -3619,43 +3728,43 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
![_delegate selectionShouldChangeInTableView:self])
return;
if([[self selectedRowIndexes] count] > 0)
if ([[self selectedRowIndexes] count] > 0)
{
var extend = NO;
if(([theEvent modifierFlags] & CPShiftKeyMask) && _allowsMultipleSelection)
if (([theEvent modifierFlags] & CPShiftKeyMask) && _allowsMultipleSelection)
extend = YES;
var i = [[self selectedRowIndexes] lastIndex];
if(i<[self numberOfRows] - 1)
if (i < [self numberOfRows] - 1)
i++; //set index to the next row after the last row selected
}
else
{
var extend = NO;
//no rows are currently selected
if([self numberOfRows] > 0)
if ([self numberOfRows] > 0)
var i = 0; //select the first row
}
if(_implementedDelegateMethods & CPTableViewDelegate_tableView_shouldSelectRow_)
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_shouldSelectRow_)
{
while((![_delegate tableView:self shouldSelectRow:i]) && i<[self numberOfRows])
while ((![_delegate tableView:self shouldSelectRow:i]) && i < [self numberOfRows])
{
//check to see if the row can be selected if it can't be then see if the next row can be selected
i++;
}
//if the index still can be selected after the loop then just return
if(![_delegate tableView:self shouldSelectRow:i])
if (![_delegate tableView:self shouldSelectRow:i])
return;
}
[self selectRowIndexes:[CPIndexSet indexSetWithIndex:i] byExtendingSelection:extend];
if(i >= 0)
if (i >= 0)
[self scrollRowToVisible:i];
}
@@ -3665,43 +3774,43 @@ CPTableViewFirstColumnOnlyAutoresizingStyle = 5;
![_delegate selectionShouldChangeInTableView:self])
return;
if([[self selectedRowIndexes] count] > 0)
if ([[self selectedRowIndexes] count] > 0)
{
var extend = NO;
if(([theEvent modifierFlags] & CPShiftKeyMask) && _allowsMultipleSelection)
if (([theEvent modifierFlags] & CPShiftKeyMask) && _allowsMultipleSelection)
extend = YES;
var i = [[self selectedRowIndexes] firstIndex];
if(i > 0)
if (i > 0)
i--; //set index to the prev row before the first row selected
}
else
{
var extend = NO;
//no rows are currently selected
if([self numberOfRows] > 0)
if ([self numberOfRows] > 0)
var i = [self numberOfRows] - 1; //select the first row
}
if(_implementedDelegateMethods & CPTableViewDelegate_tableView_shouldSelectRow_)
if (_implementedDelegateMethods & CPTableViewDelegate_tableView_shouldSelectRow_)
{
while((![_delegate tableView:self shouldSelectRow:i]) && i > 0)
while ((![_delegate tableView:self shouldSelectRow:i]) && i > 0)
{
//check to see if the row can be selected if it can't be then see if the prev row can be selected
i--;
}
//if the index still can be selected after the loop then just return
if(![_delegate tableView:self shouldSelectRow:i])
if (![_delegate tableView:self shouldSelectRow:i])
return;
}
[self selectRowIndexes:[CPIndexSet indexSetWithIndex:i] byExtendingSelection:extend];
if(i >= 0)
if (i >= 0)
[self scrollRowToVisible:i];
}
@@ -3855,7 +3964,7 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
var firstindex = [self firstIndex];
var index = MIN(firstindex, [otherSet firstIndex]);
var switchFlag = (index == firstindex);
while(index != CPNotFound)
while (index != CPNotFound)
{
var indexSet = (switchFlag) ? otherSet : self;
otherIndex = [indexSet indexGreaterThanOrEqualToIndex:index];
@@ -3881,7 +3990,7 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
- (void)drawRect:(CGRect)aRect
{
if(tableView._destinationDragStyle === CPTableViewDraggingDestinationFeedbackStyleNone || isBlinking)
if (tableView._destinationDragStyle === CPTableViewDraggingDestinationFeedbackStyleNone || isBlinking)
return;
var context = [[CPGraphicsContext currentContext] graphicsPort];
@@ -3900,7 +4009,7 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
var selectedRows = [tableView selectedRowIndexes],
newRect = _CGRectMake(aRect.origin.x + 2, aRect.origin.y + 2, aRect.size.width - 4, aRect.size.height - 5);
if([selectedRows containsIndex:currentRow])
if ([selectedRows containsIndex:currentRow])
{
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColor(context, [CPColor whiteColor]);
@@ -3916,11 +4025,11 @@ var CPTableViewDataSourceKey = @"CPTableViewDataSourceKey",
else if (dropOperation === CPTableViewDropAbove)
{
//reposition the view up a tad
[self setFrameOrigin:CGPointMake(_frame.origin.x, _frame.origin.y - 8)];
[self setFrameOrigin:_CGPointMake(_frame.origin.x, _frame.origin.y - 8)];
var selectedRows = [tableView selectedRowIndexes];
if([selectedRows containsIndex:currentRow - 1] || [selectedRows containsIndex:currentRow])
if ([selectedRows containsIndex:currentRow - 1] || [selectedRows containsIndex:currentRow])
{
CGContextSetStrokeColor(context, [CPColor whiteColor]);
CGContextSetLineWidth(context, 4);
+16 -3
View File
@@ -667,7 +667,7 @@ var _CPToolbarItemInfoMake = function(anIndex, aView, aLabel, aMinWidth)
// Determine all the items that have flexible width.
// Also determine the height of the toolbar.
var count = _visibleItems.length
var count = _visibleItems.length,
flexibleItemIndexes = [CPIndexSet indexSet];
while (count--)
@@ -799,10 +799,11 @@ var _CPToolbarItemInfoMake = function(anIndex, aView, aLabel, aMinWidth)
hasNonSeparatorItem = YES;
var menuItem = [[CPMenuItem alloc] initWithTitle:[item label] action:[item action] keyEquivalent:nil];
var menuItem = [[CPMenuItem alloc] initWithTitle:[item label] action:@selector(didSelectMenuItem:) keyEquivalent:nil];
[menuItem setRepresentedObject:item];
[menuItem setImage:[item image]];
[menuItem setTarget:[item target]];
[menuItem setTarget:self];
[menuItem setEnabled:[item isEnabled]];
[_additionalItemsButton addItem:menuItem];
@@ -812,6 +813,18 @@ var _CPToolbarItemInfoMake = function(anIndex, aView, aLabel, aMinWidth)
[_additionalItemsButton removeFromSuperview];
}
/*
Used privately.
@ignore
*/
- (void)didSelectMenuItem:(id)aSender
{
var toolbarItem = [aSender representedObject];
[CPApp sendAction:[toolbarItem action] to:[toolbarItem target] from:toolbarItem];
}
- (void)reloadToolbarItems
{
// Get rid of all our current subviews.
+36 -36
View File
@@ -40,7 +40,7 @@ CPToolbarShowFontsItemIdentifier = @"CPToolbarShowFontsItem";
CPToolbarCustomizeToolbarItemIdentifier = @"CPToolbarCustomizeToolbarItem";
CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
/*!
/*!
@ingroup appkit
@class CPToolbarItem
@@ -49,9 +49,9 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
@implementation CPToolbarItem : CPObject
{
CPString _itemIdentifier;
CPToolbar _toolbar;
CPString _label;
CPString _paletteLabel;
CPString _toolTip;
@@ -61,12 +61,12 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
BOOL _isEnabled;
CPImage _image;
CPImage _alternateImage;
CPView _view;
CGSize _minSize;
CGSize _maxSize;
CGSize _maxSize;
int _visibilityPriority;
BOOL _autovalidates;
@@ -86,21 +86,21 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
- (id)initWithItemIdentifier:(CPString)anItemIdentifier
{
self = [super init];
if (self)
{
_itemIdentifier = anItemIdentifier;
_tag = 0;
_isEnabled = YES;
_minSize = CGSizeMakeZero();
_maxSize = CGSizeMakeZero();
_visibilityPriority = CPToolbarItemVisibilityPriorityStandard;
_autovalidates = YES;
}
return self;
}
@@ -170,7 +170,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(toolTip)])
return [_view toolTip];
return _toolTip;
}
@@ -182,7 +182,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(setToolTip:)])
[_view setToolTip:aToolTip];
_toolTip = aToolTip;
}
@@ -193,7 +193,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(tag)])
return [_view tag];
return _tag;
}
@@ -205,7 +205,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(setTag:)])
[_view setTag:aTag];
_tag = aTag;
}
@@ -216,12 +216,12 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if (_view)
return [_view respondsToSelector:@selector(target)] ? [_view target] : nil;
return _target;
}
/*!
Sets the target of the action that is triggered when the user clicks this item. \c nil will cause
Sets the target of the action that is triggered when the user clicks this item. \c nil will cause
the action to be passed on to the first responder.
@param aTarget the new target
*/
@@ -229,7 +229,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if (!_view)
_target = aTarget;
else if ([_view respondsToSelector:@selector(setTarget:)])
[_view setTarget:aTarget];
}
@@ -241,7 +241,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if (_view)
return [_view respondsToSelector:@selector(action)] ? [_view action] : nil;
return _action;
}
@@ -265,7 +265,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(isEnabled)])
return [_view isEnabled];
return _isEnabled;
}
@@ -277,7 +277,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(setEnabled:)])
[_view setEnabled:shouldBeEnabled];
_isEnabled = shouldBeEnabled;
}
@@ -288,7 +288,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(image)])
return [_view image];
return _image;
}
@@ -302,11 +302,11 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
[_view setImage:anImage];
_image = anImage;
if (!_image)
return;
if (_minSize.width === 0 && _minSize.height === 0 &&
if (_minSize.width === 0 && _minSize.height === 0 &&
_maxSize.width === 0 && _maxSize.height === 0)
{
var imageSize = [_image size];
@@ -327,7 +327,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(setAlternateImage:)])
[_view setAlternateImage:anImage];
_alternateImage = anImage;
}
@@ -338,7 +338,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if ([_view respondsToSelector:@selector(alternateIamge)])
return [_view alternateImage];
return _alternateImage;
}
@@ -358,7 +358,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
{
if (_view == aView)
return;
_view = aView;
if (_view)
@@ -366,7 +366,7 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
// Tags get forwarded.
if (_tag !== 0 && [_view respondsToSelector:@selector(setTag:)])
[_view setTag:_tag];
_target = nil;
_action = nil;
}
@@ -386,11 +386,11 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
*/
- (void)setMinSize:(CGSize)aMinSize
{
if(!aMinSize.height || !aMinSize.width)
if (!aMinSize.height || !aMinSize.width)
return;
_minSize = CGSizeMakeCopy(aMinSize);
// Try to provide some sanity: Make maxSize >= minSize
_maxSize = CGSizeMake(MAX(_minSize.width, _maxSize.width), MAX(_minSize.height, _maxSize.height));
}
@@ -409,11 +409,11 @@ CPToolbarPrintItemIdentifier = @"CPToolbarPrintItem";
*/
- (void)setMaxSize:(CGSize)aMaxSize
{
if(!aMaxSize.height || !aMaxSize.width)
if (!aMaxSize.height || !aMaxSize.width)
return;
_maxSize = CGSizeMakeCopy(aMaxSize);
// Try to provide some sanity: Make minSize <= maxSize
_minSize = CGSizeMake(MIN(_minSize.width, _maxSize.width), MIN(_minSize.height, _maxSize.height));
}
@@ -623,7 +623,7 @@ var CPToolbarItemItemIdentifierKey = @"CPToolbarItemItemIdentifierKey",
case CPToolbarCustomizeToolbarItemIdentifier: return nil;
case CPToolbarPrintItemIdentifier: return nil;
}
return nil;
}
+22 -9
View File
@@ -23,13 +23,13 @@
@import "CPAnimation.j"
CPViewAnimationTargetKey = @"CPViewAnimationTarget";
CPViewAnimationStartFrameKey = @"CPViewAnimationStartFrame";
CPViewAnimationEndFrameKey = @"CPViewAnimationEndFrame";
CPViewAnimationEffectKey = @"CPViewAnimationEffect";
CPViewAnimationTargetKey = @"CPViewAnimationTargetKey";
CPViewAnimationStartFrameKey = @"CPViewAnimationStartFrameKey";
CPViewAnimationEndFrameKey = @"CPViewAnimationEndFrameKey";
CPViewAnimationEffectKey = @"CPViewAnimationEffectKey";
CPViewAnimationFadeInEffect = @"CPViewAnimationFadeIn";
CPViewAnimationFadeOutEffect = @"CPViewAnimationFadeOut";
CPViewAnimationFadeInEffect = @"CPViewAnimationFadeInEffect";
CPViewAnimationFadeOutEffect = @"CPViewAnimationFadeOutEffect";
@implementation CPViewAnimation : CPAnimation
{
@@ -61,7 +61,7 @@ CPViewAnimationFadeOutEffect = @"CPViewAnimationFadeOut";
if (effect === CPViewAnimationFadeInEffect)
{
[view setAlphaValue:0.0];
[view setHidden:NO];
[self _targetView:view setHidden:NO];
}
else if (effect === CPViewAnimationFadeOutEffect)
[view setAlphaValue:1.0];
@@ -104,7 +104,7 @@ CPViewAnimationFadeOutEffect = @"CPViewAnimationFadeOut";
[view setAlphaValue:1.0 + ( 0.0 - 1.0 ) * progress];
if (progress === 1.0)
[view setHidden:_CGRectIsNull(endFrame) || [view alphaValue] === 0.0];
[self _targetView:view setHidden:_CGRectIsNull(endFrame) || [view alphaValue] === 0.0];
}
}
@@ -125,12 +125,25 @@ CPViewAnimationFadeOutEffect = @"CPViewAnimationFadeOut";
else if (effect === CPViewAnimationFadeOutEffect)
[view setAlphaValue:0.0];
[view setHidden:_CGRectIsNull(endFrame) || [view alphaValue] === 0.0];
[self _targetView:view setHidden:_CGRectIsNull(endFrame) || [view alphaValue] === 0.0];
}
[super stopAnimation];
}
- (void)_targetView:(id)theView setHidden:(BOOL)isHidden
{
if ([theView isKindOfClass:[CPWindow class]])
{
if (isHidden)
[theView orderOut:self];
else
[theView orderFront:self];
}
else
[theView setHidden:isHidden];
}
- (id)_targetView:(CPDictionary)dictionary
{
var targetView = [dictionary valueForKey:CPViewAnimationTargetKey];
+24 -25
View File
@@ -107,7 +107,7 @@ CPWebViewScrollNative = 2;
_ignoreLoadEnd = YES;
_iframe = document.createElement("iframe");
_iframe.name = "iframe_" + Math.floor(Math.random()*10000);
_iframe.name = "iframe_" + FLOOR(RAND() * 10000);
_iframe.style.width = "100%";
_iframe.style.height = "100%";
_iframe.style.borderWidth = "0px";
@@ -116,47 +116,46 @@ CPWebViewScrollNative = 2;
[self setDrawsBackground:YES];
_loadCallback = function() {
// HACK: this block handles the case where we don't know about loads initiated by the user clicking a link
if (!_ignoreLoadStart)
{
// post the start load notification
[self _startedLoading];
// HACK: this block handles the case where we don't know about loads initiated by the user clicking a link
if (!_ignoreLoadStart)
{
// post the start load notification
[self _startedLoading];
if (_mainFrameURL)
[_backwardStack addObject:_mainFrameURL];
if (_mainFrameURL)
[_backwardStack addObject:_mainFrameURL];
// FIXME: this doesn't actually get the right URL for different domains. Not possible due to browser security restrictions.
// FIXME: this doesn't actually get the right URL for different domains. Not possible due to browser security restrictions.
_mainFrameURL = _iframe.src;
_mainFrameURL = _iframe.src;
// clear the forward
[_forwardStack removeAllObjects];
}
else
[_forwardStack removeAllObjects];
}
else
_ignoreLoadStart = NO;
if (!_ignoreLoadEnd)
{
if (!_ignoreLoadEnd)
{
[self _finishedLoading];
}
else
_ignoreLoadEnd = NO;
}
else
_ignoreLoadEnd = NO;
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
}
if (_iframe.addEventListener)
_iframe.addEventListener("load", _loadCallback, false);
else if (_iframe.attachEvent)
_iframe.attachEvent("onload", _loadCallback);
}
if (_iframe.addEventListener)
_iframe.addEventListener("load", _loadCallback, false);
else if (_iframe.attachEvent)
_iframe.attachEvent("onload", _loadCallback);
_frameView = [[CPView alloc] initWithFrame:[self bounds]];
[_frameView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
[_frameView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
_scrollView = [[CPScrollView alloc] initWithFrame:[self bounds]];
[_scrollView setAutohidesScrollers:YES];
[_scrollView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
[_scrollView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
[_scrollView setDocumentView:_frameView];
_frameView._DOMElement.appendChild(_iframe);
+1 -1
View File
@@ -938,7 +938,7 @@ CPTexturedBackgroundWindowMask
/*!
Sets the window's minimum size. If the provided
size is the same as the current minimum size, the method simply returns.
@aSize the new minimum size for the window
@param aSize the new minimum size for the window
*/
- (void)setMinSize:(CGSize)aSize
{
+34 -32
View File
@@ -19,9 +19,11 @@
* 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 "CPTextField.j"
var _CPHUDWindowViewBackgroundColor = nil,
CPHUDCloseButtonImage = nil;
var HUD_TITLEBAR_HEIGHT = 26.0;
@@ -29,7 +31,7 @@ var HUD_TITLEBAR_HEIGHT = 26.0;
@implementation _CPHUDWindowView : _CPWindowView
{
CPView _toolbarView;
CPTextField _titleField;
CPButton _closeButton;
}
@@ -38,19 +40,19 @@ var HUD_TITLEBAR_HEIGHT = 26.0;
{
if (self != [_CPHUDWindowView class])
return;
var bundle = [CPBundle bundleForClass:self];
_CPHUDWindowViewBackgroundColor = [CPColor colorWithPatternImage:[[CPNinePartImage alloc] initWithImageSlices:
[
[
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground0.png"] size:CPSizeMake(7.0, 37.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground1.png"] size:CPSizeMake(1.0, 37.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground2.png"] size:CPSizeMake(7.0, 37.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground3.png"] size:CPSizeMake(7.0, 1.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground4.png"] size:CPSizeMake(2.0, 2.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground5.png"] size:CPSizeMake(7.0, 1.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground6.png"] size:CPSizeMake(7.0, 3.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground7.png"] size:CPSizeMake(1.0, 3.0)],
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/HUD/CPWindowHUDBackground8.png"] size:CPSizeMake(7.0, 3.0)]
@@ -64,7 +66,7 @@ var HUD_TITLEBAR_HEIGHT = 26.0;
{
var contentRect = CGRectMakeCopy(aFrameRect),
titleBarHeight = HUD_TITLEBAR_HEIGHT;
contentRect.origin.y += titleBarHeight;
contentRect.size.height -= titleBarHeight;
@@ -75,92 +77,92 @@ var HUD_TITLEBAR_HEIGHT = 26.0;
{
var frameRect = CGRectMakeCopy(aContentRect),
titleBarHeight = HUD_TITLEBAR_HEIGHT;
frameRect.origin.y -= titleBarHeight;
frameRect.size.height += titleBarHeight;
return frameRect;
}
- (CGRect)contentRectForFrameRect:(CGRect)aFrameRect
{
var contentRect = [[self class] contentRectForFrameRect:aFrameRect];
if ([[[self window] toolbar] isVisible])
{
toolbarHeight = CGRectGetHeight([[self toolbarView] frame]);
contentRect.origin.y += toolbarHeight;
contentRect.size.height -= toolbarHeight;
}
return contentRect;
}
- (CGRect)frameRectForContentRect:(CGRect)aContentRect
{
var frameRect = [[self class] frameRectForContentRect:aContentRect];
if ([[[self window] toolbar] isVisible])
{
toolbarHeight = CGRectGetHeight([[self toolbarView] frame]);
frameRect.origin.y -= toolbarHeight;
frameRect.size.height += toolbarHeight;
}
return frameRect;
}
- (id)initWithFrame:(CPRect)aFrame styleMask:(unsigned)aStyleMask
{
self = [super initWithFrame:aFrame styleMask:aStyleMask];
if (self)
{
var bounds = [self bounds];
[self setBackgroundColor:_CPHUDWindowViewBackgroundColor];
_titleField = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
[_titleField setHitTests:NO];
[_titleField setFont:[CPFont systemFontOfSize:11.0]];
[_titleField setTextColor:[CPColor whiteColor]];
[_titleField setTextShadowColor:[CPColor blackColor]];
[_titleField setTextShadowOffset:CGSizeMake(0.0, 1.0)];
[_titleField setAutoresizingMask:CPViewWidthSizable];
// FIXME: Make this to CPLineBreakByTruncatingMiddle once it's implemented.
[_titleField setLineBreakMode:CPLineBreakByTruncatingTail];
[_titleField setAlignment:CPCenterTextAlignment];
[_titleField setStringValue:@"Untitled"];
[_titleField sizeToFit];
[_titleField setAutoresizingMask:CPViewWidthSizable];
[_titleField setStringValue:@""];
[_titleField setFrame:CGRectMake(20.0, 3.0, CGRectGetWidth([self bounds]) - 40.0, CGRectGetHeight([_titleField frame]))];
[self addSubview:_titleField];
if (_styleMask & CPClosableWindowMask)
{
var closeSize = [_CPHUDWindowViewCloseImage size];
_closeButton = [[CPButton alloc] initWithFrame:CGRectMake(8.0, 5.0, closeSize.width, closeSize.height)];
[_closeButton setBordered:NO];
[_closeButton setImage:_CPHUDWindowViewCloseImage];
[_closeButton setAlternateImage:_CPHUDWindowViewCloseActiveImage];
[self addSubview:_closeButton];
}
[self setResizeIndicatorOffset:CGSizeMake(5.0, 5.0)];
}
return self;
}
+42 -41
View File
@@ -20,6 +20,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import "CPTextField.j"
@import "_CPWindowView.j"
@@ -40,7 +41,7 @@ var _CPTexturedWindowHeadGradientColor = nil,
if (!_CPTexturedWindowHeadGradientColor)
{
var bundle = [CPBundle bundleForClass:[_CPWindowView class]];
_CPTexturedWindowHeadGradientColor = [CPColor colorWithPatternImage:[[CPThreePartImage alloc] initWithImageSlices:
[
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPWindow/Standard/CPWindowStandardTop0.png"] size:CGSizeMake(6.0, 41.0)],
@@ -50,7 +51,7 @@ var _CPTexturedWindowHeadGradientColor = nil,
isVertical:NO
]];
}
return _CPTexturedWindowHeadGradientColor;
}
@@ -58,37 +59,37 @@ var _CPTexturedWindowHeadGradientColor = nil,
{
if (!_CPTexturedWindowHeadSolidColor)
_CPTexturedWindowHeadSolidColor = [CPColor colorWithCalibratedRed:195.0 / 255.0 green:195.0 / 255.0 blue:195.0 / 255.0 alpha:1.0];
return _CPTexturedWindowHeadSolidColor;
}
- (id)initWithFrame:(CGRect)aFrame
{
self = [super initWithFrame:aFrame];
if (self)
{
var theClass = [self class],
bounds = [self bounds];
_gradientView = [[CPView alloc] initWithFrame:CGRectMake(0.0, 0.0, CGRectGetWidth(bounds), GRADIENT_HEIGHT)];
[_gradientView setBackgroundColor:[theClass gradientColor]];
[self addSubview:_gradientView];
_solidView = [[CPView alloc] initWithFrame:CGRectMake(0.0, GRADIENT_HEIGHT, CGRectGetWidth(bounds), CGRectGetHeight(bounds) - GRADIENT_HEIGHT)];
[_solidView setBackgroundColor:[theClass solidColor]];
[self addSubview:_solidView];
}
return self;
}
- (void)resizeSubviewsWithOldSize:(CGSize)aSize
{
var bounds = [self bounds];
[_gradientView setFrameSize:CGSizeMake(CGRectGetWidth(bounds), GRADIENT_HEIGHT)];
[_solidView setFrameSize:CGSizeMake(CGRectGetWidth(bounds), CGRectGetHeight(bounds) - GRADIENT_HEIGHT)];
}
@@ -114,7 +115,7 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
CPView _dividerView;
CPView _bodyView;
CPView _toolbarView;
CPTextField _titleField;
CPButton _closeButton;
CPButton _minimizeButton;
@@ -126,15 +127,15 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
{
if (!_CPStandardWindowViewBodyBackgroundColor)
_CPStandardWindowViewBodyBackgroundColor = [CPColor colorWithWhite:0.96 alpha:1.0];
return _CPStandardWindowViewBodyBackgroundColor;
return _CPStandardWindowViewBodyBackgroundColor;
}
+ (CPColor)dividerBackgroundColor
{
if (!_CPStandardWindowViewDividerBackgroundColor)
_CPStandardWindowViewDividerBackgroundColor = [CPColor colorWithCalibratedRed:125.0 / 255.0 green:125.0 / 255.0 blue:125.0 / 255.0 alpha:1.0];
return _CPStandardWindowViewDividerBackgroundColor;
}
@@ -142,7 +143,7 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
{
if (!_CPStandardWindowViewTitleBackgroundColor)
_CPStandardWindowViewTitleBackgroundColor = [CPColor colorWithCalibratedRed:44.0 / 255.0 green:44.0 / 255.0 blue:44.0 / 255.0 alpha:1.0];
return _CPStandardWindowViewTitleBackgroundColor;
}
@@ -150,7 +151,7 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
{
var contentRect = CGRectMakeCopy(aFrameRect),
titleBarHeight = [self titleBarHeight] + 1.0;
contentRect.origin.y += titleBarHeight;
contentRect.size.height -= titleBarHeight;
@@ -161,10 +162,10 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
{
var frameRect = CGRectMakeCopy(aContentRect),
titleBarHeight = [self titleBarHeight] + 1.0;
frameRect.origin.y -= titleBarHeight;
frameRect.size.height += titleBarHeight;
return frameRect;
}
@@ -177,15 +178,15 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
{
var contentRect = [[self class] contentRectForFrameRect:aFrameRect],
theToolbar = [[self window] toolbar];
if ([theToolbar isVisible])
{
toolbarHeight = CGRectGetHeight([[theToolbar _toolbarView] frame]);
contentRect.origin.y += toolbarHeight;
contentRect.size.height -= toolbarHeight;
}
return contentRect;
}
@@ -193,72 +194,72 @@ var STANDARD_GRADIENT_HEIGHT = 41.0;
{
var frameRect = [[self class] frameRectForContentRect:aContentRect],
theToolbar = [[self window] toolbar];
if ([theToolbar isVisible])
{
toolbarHeight = CGRectGetHeight([[theToolbar _toolbarView] frame]);
frameRect.origin.y -= toolbarHeight;
frameRect.size.height += toolbarHeight;
}
return frameRect;
}
- (id)initWithFrame:(CPRect)aFrame styleMask:(unsigned)aStyleMask
{
self = [super initWithFrame:aFrame styleMask:aStyleMask];
if (self)
{
var theClass = [self class],
bounds = [self bounds];
_headView = [[_CPTexturedWindowHeadView alloc] initWithFrame:CGRectMake(0.0, 0.0, CGRectGetWidth(bounds), [[self class] titleBarHeight])];
[_headView setAutoresizingMask:CPViewWidthSizable];;
[_headView setHitTests:NO];
[self addSubview:_headView];
_dividerView = [[CPView alloc] initWithFrame:CGRectMake(0.0, CGRectGetMaxY([_headView frame]), CGRectGetWidth(bounds), 1.0)];
[_dividerView setAutoresizingMask:CPViewWidthSizable];
[_dividerView setBackgroundColor:[theClass dividerBackgroundColor]];
[_dividerView setHitTests:NO];
[self addSubview:_dividerView];
var y = CGRectGetMaxY([_dividerView frame]);
_bodyView = [[CPView alloc] initWithFrame:CGRectMake(0.0, y, CGRectGetWidth(bounds), CGRectGetHeight(bounds) - y)];
[_bodyView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
[_bodyView setBackgroundColor:[theClass bodyBackgroundColor]];
[_bodyView setHitTests:NO];
[self addSubview:_bodyView];
[self setResizeIndicatorOffset:CGSizeMake(2.0, 2.0)];
_titleField = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
[_titleField setFont:[CPFont boldSystemFontOfSize:12.0]];
[_titleField setAutoresizingMask:CPViewWidthSizable];
// FIXME: Make this to CPLineBreakByTruncatingMiddle once it's implemented.
[_titleField setLineBreakMode:CPLineBreakByTruncatingTail];
[_titleField setAlignment:CPCenterTextAlignment];
[_titleField setTextShadowColor:[CPColor whiteColor]];
[_titleField setTextShadowOffset:CGSizeMake(0.0, 1.0)];
[_titleField setStringValue:@"Untitled"];
[_titleField sizeToFit];
[_titleField setAutoresizingMask:CPViewWidthSizable];
[_titleField setStringValue:@""];
[self addSubview:_titleField];
if (_styleMask & CPClosableWindowMask)
{
if (!_CPStandardWindowViewCloseButtonImage)
+37 -38
View File
@@ -29,15 +29,14 @@ var _CPWindowViewResizeIndicatorImage = nil;
@implementation _CPWindowView : CPView
{
unsigned _styleMask;
CPImageView _resizeIndicator;
CGSize _resizeIndicatorOffset;
CPView _toolbarView;
CGSize _toolbarOffset;
// BOOL _isAnimatingToolbar;
CGRect _resizeFrame;
CGPoint _mouseDraggedPoint;
@@ -48,7 +47,7 @@ var _CPWindowViewResizeIndicatorImage = nil;
{
if (self != [_CPWindowView class])
return;
_CPWindowViewResizeIndicatorImage = [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[CPWindow class]] pathForResource:@"_CPWindowView/_CPWindowViewResizeIndicator.png"] size:CGSizeMake(12.0, 12.0)];
}
@@ -75,14 +74,14 @@ var _CPWindowViewResizeIndicatorImage = nil;
- (id)initWithFrame:(CPRect)aFrame styleMask:(unsigned)aStyleMask
{
self = [super initWithFrame:aFrame];
if (self)
{
_styleMask = aStyleMask;
_resizeIndicatorOffset = CGSizeMakeZero();
_toolbarOffset = CGSizeMakeZero();
}
return self;
}
@@ -107,14 +106,14 @@ var _CPWindowViewResizeIndicatorImage = nil;
{
// FIXME: This should be better
var frame = [_resizeIndicator frame];
if (CGRectContainsPoint(frame, [self convertPoint:[anEvent locationInWindow] fromView:nil]))
return [self trackResizeWithEvent:anEvent];
}
if ([theWindow isMovableByWindowBackground])
[self trackMoveWithEvent:anEvent];
else
[super mouseDown:anEvent];
}
@@ -123,29 +122,29 @@ var _CPWindowViewResizeIndicatorImage = nil;
{
var location = [anEvent locationInWindow],
type = [anEvent type];
if (type === CPLeftMouseUp)
return;
var theWindow = [self window];
if (type === CPLeftMouseDown)
{
var frame = [theWindow frame];
_resizeFrame = CGRectMake(location.x, location.y, CGRectGetWidth(frame), CGRectGetHeight(frame));
}
else if (type === CPLeftMouseDragged)
{
var newSize = CGSizeMake(CGRectGetWidth(_resizeFrame) + location.x - CGRectGetMinX(_resizeFrame), CGRectGetHeight(_resizeFrame) + location.y - CGRectGetMinY(_resizeFrame));
{
var newSize = CGSizeMake(CGRectGetWidth(_resizeFrame) + location.x - CGRectGetMinX(_resizeFrame), CGRectGetHeight(_resizeFrame) + location.y - CGRectGetMinY(_resizeFrame));
if (theWindow._isSheet && theWindow._parentView && (theWindow._frame.size.width !== newSize.width))
[theWindow._parentView _setAttachedSheetFrameOrigin];
[theWindow setFrameSize:newSize];
[theWindow._parentView _setAttachedSheetFrameOrigin];
[theWindow setFrameSize:newSize];
}
[CPApp setTarget:self selector:@selector(trackResizeWithEvent:) forNextEventMatchingMask:CPLeftMouseDraggedMask | CPLeftMouseUpMask untilDate:nil inMode:nil dequeue:YES];
}
@@ -161,10 +160,10 @@ var _CPWindowViewResizeIndicatorImage = nil;
visibleFrame = [[CPPlatformWindow primaryPlatformWindow] visibleFrame];
var minPointY = 0;
if([CPMenu menuBarVisible])
minPointY = [[CPApp mainMenu] menuBarHeight];
var restrictedPoint = CGPointMake(0, 0);
restrictedPoint.x = MIN(MAX(aPoint.x, -_frame.size.width + 4.0), CGRectGetMaxX(visibleFrame) - 4.0);
@@ -194,14 +193,14 @@ var _CPWindowViewResizeIndicatorImage = nil;
var theWindow = [self window],
frame = [theWindow frame],
location = [theWindow convertBaseToGlobal:[anEvent locationInWindow]],
origin = [self _pointWithinScreenFrame:CGPointMake(_CGRectGetMinX(frame) + (location.x - _mouseDraggedPoint.x),
origin = [self _pointWithinScreenFrame:CGPointMake(_CGRectGetMinX(frame) + (location.x - _mouseDraggedPoint.x),
_CGRectGetMinY(frame) + (location.y - _mouseDraggedPoint.y))];
[theWindow setFrameOrigin:origin];
_mouseDraggedPoint = [self _pointWithinScreenFrame:location];
}
[CPApp setTarget:self selector:@selector(trackMoveWithEvent:) forNextEventMatchingMask:CPLeftMouseDraggedMask | CPLeftMouseUpMask untilDate:nil inMode:nil dequeue:YES];
}
@@ -211,9 +210,9 @@ var _CPWindowViewResizeIndicatorImage = nil;
{
var size = [_CPWindowViewResizeIndicatorImage size],
boundsSize = [self frame].size;
_resizeIndicator = [[CPImageView alloc] initWithFrame:CGRectMake(boundsSize.width - size.width - _resizeIndicatorOffset.width, boundsSize.height - size.height - _resizeIndicatorOffset.height, size.width, size.height)];
[_resizeIndicator setImage:_CPWindowViewResizeIndicatorImage];
[_resizeIndicator setAutoresizingMask:CPViewMinXMargin | CPViewMinYMargin];
@@ -236,15 +235,15 @@ var _CPWindowViewResizeIndicatorImage = nil;
{
if (CGSizeEqualToSize(_resizeIndicatorOffset, anOffset))
return;
_resizeIndicatorOffset = anOffset;
if (!_resizeIndicator)
return;
var size = [_resizeIndicator frame].size,
boundsSize = [self frame].size;
[_resizeIndicator setFrameOrigin:CGPointMake(boundsSize.width - size.width - anOffset.width, boundsSize.height - size.height - anOffset.height)];
}
@@ -280,7 +279,7 @@ var _CPWindowViewResizeIndicatorImage = nil;
{
if (!_toolbarView || [_toolbarView isHidden])
return [self toolbarOffset].height;
return CGRectGetMaxY([_toolbarView frame]);
}
@@ -294,20 +293,20 @@ var _CPWindowViewResizeIndicatorImage = nil;
var theWindow = [self window],
bounds = [self bounds],
width = CGRectGetWidth(bounds);
if ([[theWindow toolbar] isVisible])
{
var toolbarView = [self toolbarView],
toolbarOffset = [self toolbarOffset];
[toolbarView setFrame:CGRectMake(toolbarOffset.width, toolbarOffset.height, width, CGRectGetHeight([toolbarView frame]))];
}
if ([self showsResizeIndicator])
{
var size = [_resizeIndicator frame].size,
boundsSize = [self bounds].size;
[_resizeIndicator setFrameOrigin:CGPointMake(boundsSize.width - size.width - _resizeIndicatorOffset.width, boundsSize.height - size.height - _resizeIndicatorOffset.height)];
}
}
@@ -317,11 +316,11 @@ var _CPWindowViewResizeIndicatorImage = nil;
var theWindow = [self window],
toolbar = [theWindow toolbar],
toolbarView = [toolbar _toolbarView];
if (_toolbarView !== toolbarView)
{
[_toolbarView removeFromSuperview];
if (toolbarView)
{
[toolbarView removeFromSuperview];
@@ -329,7 +328,7 @@ var _CPWindowViewResizeIndicatorImage = nil;
[self addSubview:toolbarView];
}
_toolbarView = toolbarView;
}
+5 -5
View File
@@ -28,7 +28,7 @@
@import "CPDocument.j"
/*!
/*!
@ingroup appkit
@class CPWindowController
@@ -171,8 +171,8 @@
if (_window === nil && [_cibOwner isKindOfClass:[CPDocument class]])
[self setWindow:[_cibOwner valueForKey:@"window"]];
if (!_window)
if (!_window)
{
var reason = [CPString stringWithFormat:@"Window for %@ could not be loaded from Cib or no window specified. \
Override loadWindow to load the window manually.", self];
@@ -232,7 +232,7 @@
{
if (![self supportsMultipleDocuments])
[self removeDocument:_document];
[defaultCenter removeObserver:self
name:CPDocumentWillSaveNotification
object:_document];
@@ -381,7 +381,7 @@
}
/*!
Sets whether the document has unsaved changes. The window can use this as a hint to
Sets whether the document has unsaved changes. The window can use this as a hint to
@param isEdited \c YES means the document has unsaved changes.
*/
- (void)setDocumentEdited:(BOOL)isEdited
+2 -2
View File
@@ -34,7 +34,7 @@ var _CPCibCustomObjectClassName = @"_CPCibCustomObjectClassName";
if (self)
_className = [aCoder decodeObjectForKey:_CPCibCustomObjectClassName];
return self;
}
@@ -65,7 +65,7 @@ var _CPCibCustomObjectClassName = @"_CPCibCustomObjectClassName";
if (theClass === [CPApplication class])
return [CPApplication sharedApplication];
return [[theClass alloc] init];
}
+21 -21
View File
@@ -35,30 +35,30 @@
{
CPArray _namesKeys;
CPArray _namesValues;
CPArray _accessibilityConnectors;
CPArray _accessibilityOidsKeys;
CPArray _accessibilityOidsValues;
CPArray _classesKeys;
CPArray _classesValues;
CPArray _connections;
id _fontManager;
CPString _framework;
int _nextOid;
CPArray _objectsKeys;
CPArray _objectsValues;
CPArray _oidKeys;
CPArray _oidValues;
_CPCibCustomObject _fileOwner;
CPSet _visibleWindows;
JSObject _replacementObjects;
@@ -114,28 +114,28 @@
var _CPCibObjectDataNamesKeysKey = @"_CPCibObjectDataNamesKeysKey",
_CPCibObjectDataNamesValuesKey = @"_CPCibObjectDataNamesValuesKey",
_CPCibObjectDataAccessibilityConnectorsKey = @"_CPCibObjectDataAccessibilityConnectors",
_CPCibObjectDataAccessibilityOidsKeysKey = @"_CPCibObjectDataAccessibilityOidsKeys",
_CPCibObjectDataAccessibilityOidsValuesKey = @"_CPCibObjectDataAccessibilityOidsValues",
_CPCibObjectDataClassesKeysKey = @"_CPCibObjectDataClassesKeysKey",
_CPCibObjectDataClassesValuesKey = @"_CPCibObjectDataClassesValuesKey",
_CPCibObjectDataConnectionsKey = @"_CPCibObjectDataConnectionsKey",
_CPCibObjectDataFontManagerKey = @"_CPCibObjectDataFontManagerKey",
_CPCibObjectDataFrameworkKey = @"_CPCibObjectDataFrameworkKey",
_CPCibObjectDataNextOidKey = @"_CPCibObjectDataNextOidKey",
_CPCibObjectDataObjectsKeysKey = @"_CPCibObjectDataObjectsKeysKey",
_CPCibObjectDataObjectsValuesKey = @"_CPCibObjectDataObjectsValuesKey",
_CPCibObjectDataOidKeysKey = @"_CPCibObjectDataOidKeysKey",
_CPCibObjectDataOidValuesKey = @"_CPCibObjectDataOidValuesKey",
_CPCibObjectDataFileOwnerKey = @"_CPCibObjectDataFileOwnerKey",
_CPCibObjectDataVisibleWindowsKey = @"_CPCibObjectDataVisibleWindowsKey";
@@ -195,17 +195,17 @@ var _CPCibObjectDataNamesKeysKey = @"_CPCibObjectDataNamesKeysKey
[aCoder encodeObject:_connections forKey:_CPCibObjectDataConnectionsKey];
//id _fontManager;
[aCoder encodeObject:_framework forKey:_CPCibObjectDataFrameworkKey];
[aCoder encodeInt:_nextOid forKey:_CPCibObjectDataNextOidKey];
[aCoder encodeObject:_objectsKeys forKey:_CPCibObjectDataObjectsKeysKey];
[aCoder encodeObject:_objectsValues forKey:_CPCibObjectDataObjectsValuesKey];
[aCoder encodeObject:_oidKeys forKey:_CPCibObjectDataOidKeysKey];
[aCoder encodeObject:_oidValues forKey:_CPCibObjectDataOidValuesKey];
[aCoder encodeObject:_fileOwner forKey:_CPCibObjectDataFileOwnerKey];
// CPCustomObject _fileOwner;
+23 -23
View File
@@ -31,7 +31,7 @@ function CFHashCode(aCFObject)
{
if (!aCFObject.hash)
aCFObject.hash = ++CFTypeGlobalCount;
return aCFObject;
}
@@ -47,7 +47,7 @@ function CGColorGetConstantColor(aColorName)
}
/*!
This function is for source compatability.
This function is for source compatability.
*/
function CGColorRetain(aColor)
{
@@ -55,7 +55,7 @@ function CGColorRetain(aColor)
}
/*!
This function is for source compatability.
This function is for source compatability.
*/
function CGColorRelease()
{
@@ -74,14 +74,14 @@ function CGColorCreate(aColorSpace, components)
return NULL;
var components = components.slice();
CGColorSpaceStandardizeComponents(aColorSpace, components);
var UID = CFHashCode(aColorSpace) + components.join("");
if (_CGColorMap[UID])
return _CGColorMap[UID];
return _CGColorMap[UID] = { colorspace:aColorSpace, pattern:NULL, components:components };
}
@@ -150,9 +150,9 @@ function CGColorCreateGenericCMYK(cyan, magenta, yellow, black, alpha)
function CGColorCreateCopyWithAlpha(aColor, anAlpha)
{
var components = aColor.components;
if (!aColor || anAlpha == components[components.length - 1])
return aColor;
return aColor;
if (aColor.pattern)
var copy = CGColorCreateWithPattern(aColor.colorspace, aColor.pattern, components);
@@ -160,7 +160,7 @@ function CGColorCreateCopyWithAlpha(aColor, anAlpha)
var copy = CGColorCreate(aColor.colorspace, components);
copy.components[components.length - 1] = anAlpha;
return copy;
}
@@ -191,7 +191,7 @@ function CGColorEqualToColor(lhs, rhs)
{
if (lhs == rhs)
return true;
if (!lhs || !rhs)
return false;
@@ -201,17 +201,17 @@ function CGColorEqualToColor(lhs, rhs)
if (lhsComponentCount != rhsComponents.length)
return false;
while (lhsComponentCount--)
while (lhsComponentCount--)
if (lhsComponents[lhsComponentCount] != rhsComponents[lhsComponentCount])
return false;
if (lhs.pattern != rhs.pattern)
return false;
if (CGColorSpaceEqualToColorSpace(lhs.colorspace, rhs.colorspace))
return false;
return true;
}
@@ -224,7 +224,7 @@ function CGColorEqualToColor(lhs, rhs)
function CGColorGetAlpha(aColor)
{
var components = aColor.components;
return components[components.length - 1];
}
@@ -273,13 +273,13 @@ function CGColorGetPattern(aColor)
}
/* var components = aColor.components;
case : _CGCSSForColor[CFGetHash(aColor)] = "rgba(" + ROUND(components[0] * 255.0) + ',' + ROUND(components[0] * 255.0) + ',' ROUND(components[0] * 255.0) + ',' + ROUND(components[0] * 255.0);
_cssString = (hasAlpha ? "rgba(" : "rgb(") +
parseInt(_components[0] * 255.0) + ", " +
parseInt(_components[1] * 255.0) + ", " +
parseInt(_components[2] * 255.0) +
(hasAlpha ? (", " + _components[3]) : "") + ")";
_cssString = (hasAlpha ? "rgba(" : "rgb(") +
parseInt(_components[0] * 255.0) + ", " +
parseInt(_components[1] * 255.0) + ", " +
parseInt(_components[2] * 255.0) +
(hasAlpha ? (", " + _components[3]) : "") + ")";
function CFStringFromColor()
{
+28 -26
View File
@@ -27,7 +27,7 @@
kCGLineCapButt = 0;
kCGLineCapRound = 1;
kCGLineCapRound = 1;
kCGLineCapSquare = 2;
kCGLineJoinMiter = 0;
@@ -114,8 +114,8 @@ if (!CPFeatureIsCompatible(CPHTMLCanvasFeature))
*/
function CGGStateCreate()
{
return { alpha:1.0, strokeStyle:"#000", fillStyle:"#ccc", lineWidth:1.0, lineJoin:kCGLineJoinMiter, lineCap:kCGLineCapButt, miterLimit:10.0, globalAlpha:1.0,
blendMode:kCGBlendModeNormal,
return { alpha:1.0, strokeStyle:"#000", fillStyle:"#ccc", lineWidth:1.0, lineJoin:kCGLineJoinMiter, lineCap:kCGLineCapButt, miterLimit:10.0, globalAlpha:1.0,
blendMode:kCGBlendModeNormal,
shadowOffset:_CGSizeMakeZero(), shadowBlur:0.0, shadowColor:NULL, CTM:_CGAffineTransformMakeIdentity() };
}
@@ -126,9 +126,9 @@ function CGGStateCreate()
*/
function CGGStateCreateCopy(aGState)
{
return { alpha:aGState.alpha, strokeStyle:aGState.strokeStyle, fillStyle:aGState.fillStyle, lineWidth:aGState.lineWidth,
lineJoin:aGState.lineJoin, lineCap:aGState.lineCap, miterLimit:aGState.miterLimit, globalAlpha:aGState.globalAlpha,
blendMode:aGState.blendMode,
return { alpha:aGState.alpha, strokeStyle:aGState.strokeStyle, fillStyle:aGState.fillStyle, lineWidth:aGState.lineWidth,
lineJoin:aGState.lineJoin, lineCap:aGState.lineCap, miterLimit:aGState.miterLimit, globalAlpha:aGState.globalAlpha,
blendMode:aGState.blendMode,
shadowOffset:aGState.shadowOffset, shadowBlur:aGState.shadowBlur, shadowColor:aGState.shadowColor, CTM:_CGAffineTransformMakeCopy(aGState.CTM) };
}
@@ -256,10 +256,10 @@ function CGContextAddPath(aContext, aPath)
{
if (!aContext || CGPathIsEmpty(aPath))
return;
if (!aContext.path)
aContext.path = CGPathCreateMutable();
CGPathAddPath(aContext.path, aContext.gState.CTM, aPath);
}
@@ -332,7 +332,7 @@ function CGContextMoveToPoint(aContext, x, y)
{
if (!aContext.path)
aContext.path = CGPathCreateMutable();
CGPathMoveToPoint(aContext.path, aContext.gState.CTM, x, y);
}
@@ -358,11 +358,11 @@ function CGContextFillRects(aContext, rects, count)
{
if (arguments[2] === undefined)
var count = rects.length;
CGContextBeginPath(aContext);
CGContextAddRects(aContext, rects, count);
CGContextClosePath(aContext);
CGContextDrawPath(aContext, kCGPathFill);
}
@@ -373,11 +373,11 @@ function CGContextFillRects(aContext, rects, count)
@return void
*/
function CGContextStrokeRect(aContext, aRect)
{
{
CGContextBeginPath(aContext);
CGContextAddRect(aContext, aRect);
CGContextClosePath(aContext);
CGContextDrawPath(aContext, kCGPathStroke);
}
@@ -391,10 +391,10 @@ function CGContextStrokeRect(aContext, aRect)
function CGContextStrokeRectWithWidth(aContext, aRect, aWidth)
{
CGContextSaveGState(aContext);
CGContextSetLineWidth(aContext, aWidth);
CGContextStrokeRect(aContext, aRect);
CGContextRestoreGState(aContext);
}
@@ -407,7 +407,7 @@ function CGContextStrokeRectWithWidth(aContext, aRect, aWidth)
function CGContextConcatCTM(aContext, aTransform)
{
var CTM = aContext.gState.CTM;
_CGAffineTransformConcatTo(CTM, aTransform, CTM);
}
@@ -431,7 +431,7 @@ function CGContextGetCTM(aContext)
function CGContextRotateCTM(aContext, anAngle)
{
var gState = aContext.gState;
gState.CTM = CGAffineTransformRotate(gState.CTM, anAngle);
}
@@ -445,7 +445,7 @@ function CGContextRotateCTM(aContext, anAngle)
function CGContextScaleCTM(aContext, sx, sy)
{
var gState = aContext.gState;
gState.CTM = _CGAffineTransformScale(gState.CTM, sx, sy);
}
@@ -459,7 +459,7 @@ function CGContextScaleCTM(aContext, sx, sy)
function CGContextTranslateCTM(aContext, tx, ty)
{
var gState = aContext.gState;
gState.CTM = _CGAffineTransformTranslate(gState.CTM, tx, ty);
}
@@ -474,7 +474,7 @@ function CGContextTranslateCTM(aContext, tx, ty)
function CGContextSetShadow(aContext, aSize, aBlur)
{
var gState = aContext.gState;
gState.shadowOffset = _CGSizeMakeCopy(aSize);
gState.shadowBlur = aBlur;
gState.shadowColor = [CPColor shadowColor];
@@ -491,7 +491,7 @@ function CGContextSetShadow(aContext, aSize, aBlur)
function CGContextSetShadowWithColor(aContext, aSize, aBlur, aColor)
{
var gState = aContext.gState;
gState.shadowOffset = _CGSizeMakeCopy(aSize);
gState.shadowBlur = aBlur;
gState.shadowColor = aColor;
@@ -535,6 +535,7 @@ function CGContextEOFillPath(aContext)
function CGContextFillPath(aContext)
{
CGContextDrawPath(aContext, kCGPathFill);
CGContextClosePath(aContext);
}
var KAPPA = 4.0 * ((SQRT2 - 1.0) / 3.0);
@@ -588,6 +589,7 @@ function CGContextStrokeEllipseInRect(aContext, aRect)
function CGContextStrokePath(aContext)
{
CGContextDrawPath(aContext, kCGPathStroke);
CGContextClosePath(aContext);
}
/*!
@@ -603,10 +605,10 @@ function CGContextStrokePath(aContext)
function CGContextStrokeLineSegments(aContext, points, count)
{
var i = 0;
if (arguments["count"] == NULL)
var count = points.length;
CGContextBeginPath(aContext);
for (; i < count; i += 2)
@@ -614,7 +616,7 @@ function CGContextStrokeLineSegments(aContext, points, count)
CGContextMoveToPoint(aContext, points[i].x, points[i].y);
CGContextAddLineToPoint(aContext, points[i + 1].x, points[i + 1].y);
}
CGContextStrokePath(aContext);
}
@@ -679,12 +681,12 @@ function CGContextFillRoundedRectangleInRect(aContext, aRect, aRadius, ne, se, s
function CGContextStrokeRoundedRectangleInRect(aContext, aRect, aRadius, ne, se, sw, nw)
{
CGContextBeginPath(aContext);
CGContextAddPath(aContext, CGPathWithRoundedRectangleInRect(aRect, aRadius, aRadius, ne, se, sw, nw));
CGContextAddPath(aContext, CGPathWithRoundedRectangleInRect(aRect, aRadius, aRadius, ne, se, sw, nw));
CGContextClosePath(aContext);
CGContextStrokePath(aContext);
}
/*!
/*!
@}
*/
-2
View File
@@ -255,8 +255,6 @@ function CGContextDrawPath(aContext, aMode)
vml.push("</cg_vml_:shape>");
aContext.path = NULL;
if (aContext.buffer != nil)
aContext.buffer += vml.join("");
else
+44 -43
View File
@@ -267,21 +267,21 @@ var KAPPA = 4.0 * ((SQRT2 - 1.0) / 3.0);
function CGPathWithEllipseInRect(aRect)
{
var path = CGPathCreateMutable();
if (_CGRectGetWidth(aRect) == _CGRectGetHeight(aRect))
if (_CGRectGetWidth(aRect) == _CGRectGetHeight(aRect))
CGPathAddArc(path, nil, _CGRectGetMidX(aRect), _CGRectGetMidY(aRect), _CGRectGetWidth(aRect) / 2.0, 0.0, 2 * PI, YES);
else
{
var axis = _CGSizeMake(_CGRectGetWidth(aRect) / 2.0, _CGRectGetHeight(aRect) / 2.0),
center = _CGPointMake(_CGRectGetMinX(aRect) + axis.width, _CGRectGetMinY(aRect) + axis.height);
else
{
var axis = _CGSizeMake(_CGRectGetWidth(aRect) / 2.0, _CGRectGetHeight(aRect) / 2.0),
center = _CGPointMake(_CGRectGetMinX(aRect) + axis.width, _CGRectGetMinY(aRect) + axis.height);
CGPathMoveToPoint(path, nil, center.x, center.y - axis.height);
CGPathAddCurveToPoint(path, nil, center.x + (KAPPA * axis.width), center.y - axis.height, center.x + axis.width, center.y - (KAPPA * axis.height), center.x + axis.width, center.y);
CGPathAddCurveToPoint(path, nil, center.x + axis.width, center.y + (KAPPA * axis.height), center.x + (KAPPA * axis.width), center.y + axis.height, center.x, center.y + axis.height);
CGPathAddCurveToPoint(path, nil, center.x - (KAPPA * axis.width), center.y + axis.height, center.x - axis.width, center.y + (KAPPA * axis.height), center.x - axis.width, center.y);
CGPathAddCurveToPoint(path, nil, center.x - axis.width, center.y - (KAPPA * axis.height), center.x - (KAPPA * axis.width), center.y - axis.height, center.x, center.y - axis.height);
}
CGPathAddCurveToPoint(path, nil, center.x + (KAPPA * axis.width), center.y - axis.height, center.x + axis.width, center.y - (KAPPA * axis.height), center.x + axis.width, center.y);
CGPathAddCurveToPoint(path, nil, center.x + axis.width, center.y + (KAPPA * axis.height), center.x + (KAPPA * axis.width), center.y + axis.height, center.x, center.y + axis.height);
CGPathAddCurveToPoint(path, nil, center.x - (KAPPA * axis.width), center.y + axis.height, center.x - axis.width, center.y + (KAPPA * axis.height), center.x - axis.width, center.y);
CGPathAddCurveToPoint(path, nil, center.x - axis.width, center.y - (KAPPA * axis.height), center.x - (KAPPA * axis.width), center.y - axis.height, center.x, center.y - axis.height);
}
CGPathCloseSubpath(path);
@@ -297,37 +297,38 @@ function CGPathWithRoundedRectangleInRect(aRect, xRadius, yRadius/*not currently
yMax = _CGRectGetMaxY(aRect);
CGPathMoveToPoint(path, nil, xMin + xRadius, yMin);
if (ne)
{
CGPathAddLineToPoint(path, nil, xMax - xRadius, yMin);
CGPathAddCurveToPoint(path, nil, xMax - xRadius, yMin, xMax, yMin, xMax, yMin + xRadius);
}
else
CGPathAddLineToPoint(path, nil, xMax, yMin);
if (se)
{
CGPathAddLineToPoint(path, nil, xMax, yMax - xRadius);
CGPathAddCurveToPoint(path, nil, xMax, yMax - xRadius, xMax, yMax, xMax - xRadius, yMax);
}
else
CGPathAddLineToPoint(path, nil, xMax, yMax);
if (sw)
{
CGPathAddLineToPoint(path, nil, xMin + xRadius, yMax);
CGPathAddCurveToPoint(path, nil, xMin + xRadius, yMax, xMin, yMax, xMin, yMax - xRadius);
}
else
CGPathAddLineToPoint(path, nil, xMin, yMax);
if (nw)
{
CGPathAddLineToPoint(path, nil, xMin, yMin + xRadius);
CGPathAddCurveToPoint(path, nil, xMin, yMin + xRadius, xMin, yMin, xMin + xRadius, yMin);
} else
CGPathAddLineToPoint(path, nil, xMin, yMin);
if (ne)
{
CGPathAddLineToPoint(path, nil, xMax - xRadius, yMin);
CGPathAddCurveToPoint(path, nil, xMax - xRadius, yMin, xMax, yMin, xMax, yMin + xRadius);
}
else
CGPathAddLineToPoint(path, nil, xMax, yMin);
if (se)
{
CGPathAddLineToPoint(path, nil, xMax, yMax - xRadius);
CGPathAddCurveToPoint(path, nil, xMax, yMax - xRadius, xMax, yMax, xMax - xRadius, yMax);
}
else
CGPathAddLineToPoint(path, nil, xMax, yMax);
if (sw)
{
CGPathAddLineToPoint(path, nil, xMin + xRadius, yMax);
CGPathAddCurveToPoint(path, nil, xMin + xRadius, yMax, xMin, yMax, xMin, yMax - xRadius);
}
else
CGPathAddLineToPoint(path, nil, xMin, yMax);
if (nw)
{
CGPathAddLineToPoint(path, nil, xMin, yMin + xRadius);
CGPathAddCurveToPoint(path, nil, xMin, yMin + xRadius, xMin, yMin, xMin + xRadius, yMin);
}
else
CGPathAddLineToPoint(path, nil, xMin, yMin);
CGPathCloseSubpath(path);
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1023 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+87 -16
View File
@@ -337,7 +337,8 @@ var themedButtonValues = nil,
+ (CPButton)button
{
var button = [self makeButton],
// RoundRect
bezelColor = PatternColor(
[
["button-bezel-left.png", 4.0, 24.0],
@@ -353,7 +354,15 @@ var themedButtonValues = nil,
["button-bezel-highlighted-right.png", 4.0, 24.0]
],
PatternIsHorizontal),
disabledBezelColor = PatternColor(
[
["button-bezel-disabled-left.png", 4.0, 24.0],
["button-bezel-disabled-center.png", 1.0, 24.0],
["button-bezel-disabled-right.png", 4.0, 24.0]
],
PatternIsHorizontal),
defaultBezelColor = PatternColor(
[
["default-button-bezel-left.png", 4.0, 24.0],
@@ -378,13 +387,56 @@ var themedButtonValues = nil,
],
PatternIsHorizontal),
disabledBezelColor = PatternColor(
// Rounded
roundedBezelColor = PatternColor(
[
["button-bezel-disabled-left.png", 4.0, 24.0],
["button-bezel-disabled-center.png", 1.0, 24.0],
["button-bezel-disabled-right.png", 4.0, 24.0]
["button-bezel-rounded-left.png", 12.0, 24.0],
["button-bezel-rounded-center.png", 1.0, 24.0],
["button-bezel-rounded-right.png", 12.0, 24.0]
],
PatternIsHorizontal),
roundedHighlightedBezelColor = PatternColor(
[
["button-bezel-rounded-highlighted-left.png", 12.0, 24.0],
["button-bezel-rounded-highlighted-center.png", 1.0, 24.0],
["button-bezel-rounded-highlighted-right.png", 12.0, 24.0]
],
PatternIsHorizontal),
roundedDisabledBezelColor = PatternColor(
[
["button-bezel-rounded-disabled-left.png", 12.0, 24.0],
["button-bezel-rounded-disabled-center.png", 1.0, 24.0],
["button-bezel-rounded-disabled-right.png", 12.0, 24.0]
],
PatternIsHorizontal),
defaultRoundedBezelColor = PatternColor(
[
["default-button-bezel-rounded-left.png", 12.0, 24.0],
["default-button-bezel-rounded-center.png", 1.0, 24.0],
["default-button-bezel-rounded-right.png", 12.0, 24.0]
],
PatternIsHorizontal),
defaultRoundedHighlightedBezelColor = PatternColor(
[
["default-button-bezel-rounded-highlighted-left.png", 12.0, 24.0],
["default-button-bezel-rounded-highlighted-center.png", 1.0, 24.0],
["default-button-bezel-rounded-highlighted-right.png", 12.0, 24.0]
],
PatternIsHorizontal),
defaultRoundedDisabledBezelColor = PatternColor(
[
["default-button-bezel-rounded-disabled-left.png", 12.0, 24.0],
["default-button-bezel-rounded-disabled-center.png", 1.0, 24.0],
["default-button-bezel-rounded-disabled-right.png", 12.0, 24.0]
],
PatternIsHorizontal),
defaultTextColor = [CPColor colorWithCalibratedRed:13.0 / 255.0 green:51.0 / 255.0 blue:70.0 / 255.0 alpha:1.0],
defaultDisabledTextColor = [CPColor colorWithCalibratedRed:13.0 / 255.0 green:51.0 / 255.0 blue:70.0 / 255.0 alpha:0.6];
@@ -398,18 +450,27 @@ var themedButtonValues = nil,
[@"text-shadow-offset", CGSizeMake(0.0, 1.0), CPThemeStateBordered],
[@"line-break-mode", CPLineBreakByTruncatingTail],
[@"content-inset", CGInsetMake(0.0, 7.0, 0.0, 7.0), CPThemeStateBordered],
[@"bezel-color", bezelColor, CPThemeStateBordered],
[@"bezel-color", highlightedBezelColor, CPThemeStateBordered | CPThemeStateHighlighted],
[@"text-color", [CPColor colorWithCalibratedWhite:0.6 alpha:1.0], CPThemeStateDisabled],
[@"bezel-color", disabledBezelColor, CPThemeStateBordered | CPThemeStateDisabled],
[@"bezel-color", defaultDisabledBezelColor, CPThemeStateBordered | CPThemeStateDefault | CPThemeStateDisabled],
[@"text-color", defaultTextColor, CPThemeStateDefault],
[@"text-color", defaultDisabledTextColor, CPThemeStateDefault | CPThemeStateDisabled],
[@"bezel-color", bezelColor, CPThemeStateBordered],
[@"bezel-color", highlightedBezelColor, CPThemeStateBordered | CPThemeStateHighlighted],
[@"bezel-color", disabledBezelColor, CPThemeStateBordered | CPThemeStateDisabled],
[@"bezel-color", defaultBezelColor, CPThemeStateBordered | CPThemeStateDefault],
[@"bezel-color", defaultHighlightedBezelColor, CPThemeStateBordered | CPThemeStateHighlighted | CPThemeStateDefault],
[@"bezel-color", defaultDisabledBezelColor, CPThemeStateBordered | CPThemeStateDefault | CPThemeStateDisabled],
[@"content-inset", CGInsetMake(0.0, 5.0, 0.0, 5.0), CPThemeStateBordered],
[@"bezel-color", roundedBezelColor, CPThemeStateBordered | CPButtonStateBezelStyleRounded],
[@"bezel-color", roundedHighlightedBezelColor, CPThemeStateBordered | CPThemeStateHighlighted | CPButtonStateBezelStyleRounded],
[@"bezel-color", roundedDisabledBezelColor, CPThemeStateBordered | CPThemeStateDisabled | CPButtonStateBezelStyleRounded],
[@"bezel-color", defaultRoundedBezelColor, CPThemeStateBordered | CPThemeStateDefault | CPButtonStateBezelStyleRounded],
[@"bezel-color", defaultRoundedHighlightedBezelColor, CPThemeStateBordered | CPThemeStateHighlighted | CPThemeStateDefault | CPButtonStateBezelStyleRounded],
[@"bezel-color", defaultRoundedDisabledBezelColor, CPThemeStateBordered | CPThemeStateDefault | CPThemeStateDisabled | CPButtonStateBezelStyleRounded],
[@"content-inset", CGInsetMake(0.0, 10.0, 0.0, 10.0), CPThemeStateBordered],
[@"text-color", [CPColor colorWithCalibratedWhite:0.6 alpha:1.0], CPThemeStateDisabled],
[@"text-color", defaultTextColor, CPThemeStateDefault],
[@"text-color", defaultDisabledTextColor, CPThemeStateDefault | CPThemeStateDisabled],
[@"min-size", CGSizeMake(0.0, CPButtonDefaultHeight)],
[@"max-size", CGSizeMake(-1.0, CPButtonDefaultHeight)],
@@ -441,6 +502,16 @@ var themedButtonValues = nil,
return button;
}
+ (CPButton)themedRoundedButton
{
var button = [self button];
[button setTitle:@"Save"];
[button setThemeState:CPButtonStateBezelStyleRounded];
return button;
}
+ (CPPopUpButton)themedPopUpButton
{
var button = [[CPPopUpButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 24.0) pullsDown:NO],
+13 -6
View File
@@ -41,12 +41,12 @@
var firstPart = aKeyPath.substring(0, dotIndex),
lastPart = aKeyPath.substring(dotIndex + 1);
return [[self valueForKeyPath:firstPart] valueForKeyPath:lastPart];
return [[self valueForKeyPath:firstPart] mutableArrayValueForKeyPath:lastPart];
}
@end
@implementation _CPKVCArray : CPArray
@implementation _CPKVCArray : CPMutableArray
{
id _proxyObject;
id _key;
@@ -72,6 +72,9 @@
SEL _objectAtIndexSEL;
Function _objectAtIndex;
SEL _objectsAtIndexesSEL;
Function _objectsAtIndexes;
SEL _countSEL;
Function _count;
@@ -114,19 +117,19 @@
if ([_proxyObject respondsToSelector:_removeSEL])
_remove = [_proxyObject methodForSelector:_removeSEL];
_replaceSEL = sel_getName(@"replaceObjectFrom"+capitalizedKey+"AtIndex:withObject:");
_replaceSEL = sel_getName(@"replaceObjectIn"+capitalizedKey+"AtIndex:withObject:");
if ([_proxyObject respondsToSelector:_replaceSEL])
_replace = [_proxyObject methodForSelector:_replaceSEL];
_insertManySEL = sel_getName(@"insertObjects:in"+capitalizedKey+"AtIndexes:");
_insertManySEL = sel_getName(@"insert"+capitalizedKey+":atIndexes:");
if ([_proxyObject respondsToSelector:_insertManySEL])
_insertMany = [_proxyObject methodForSelector:_insertManySEL];
_removeManySEL = sel_getName(@"removeObjectsFrom"+capitalizedKey+"AtIndexes:");
_removeManySEL = sel_getName(@"remove"+capitalizedKey+"AtIndexes:");
if ([_proxyObject respondsToSelector:_removeManySEL])
_remove = [_proxyObject methodForSelector:_removeManySEL];
_replaceManySEL = sel_getName(@"replaceObjectsFrom"+capitalizedKey+"AtIndexes:withObjects:");
_replaceManySEL = sel_getName(@"replace"+capitalizedKey+"AtIndexes:with"+capitalizedKey+":");
if ([_proxyObject respondsToSelector:_replaceManySEL])
_replace = [_proxyObject methodForSelector:_replaceManySEL];
@@ -134,6 +137,10 @@
if ([_proxyObject respondsToSelector:_objectAtIndexSEL])
_objectAtIndex = [_proxyObject methodForSelector:_objectAtIndexSEL];
_objectsAtIndexesSEL = sel_getName(_key+"AtIndexes:");
if ([_proxyObject respondsToSelector:_objectsAtIndexesSEL])
_objectsAtIndexes = [_proxyObject methodForSelector:_objectsAtIndexesSEL];
_countSEL = sel_getName(@"countOf"+capitalizedKey);
if ([_proxyObject respondsToSelector:_countSEL])
_count = [_proxyObject methodForSelector:_countSEL];
+3 -33
View File
@@ -108,7 +108,9 @@ CPEnumerationReverse = 1 << 1;
*/
+ (id)alloc
{
return [];
var result = [];
result.isa = [self class];
return result;
}
/*!
@@ -972,38 +974,6 @@ CPEnumerationReverse = 1 << 1;
return array;
}
// Key value coding
/*!
Sets the key-value for each element in the array.
@param aValue the value for the coding
@param aKey the key for the coding
*/
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
var i = 0,
count = [self count];
for (; i < count; ++i)
[self[i] setValue:aValue forKey:aKey];
}
/*!
Returns the value for \c aKey from each element in the array.
@param aKey the key to return the value for
@return an array of containing a value for each element in the array
*/
- (CPArray)valueForKey:(CPString)aKey
{
var i = 0,
count = [self count],
array = [];
for (; i < count; ++i)
array.push([self[i] valueForKey:aKey]);
return array;
}
// Copying arrays
/*!
+3 -1
View File
@@ -36,7 +36,9 @@
+ (id)alloc
{
return new CFMutableData();
var result = new CFMutableData();
result.isa = [self class];
return result;
}
+ (CPData)data
+3 -1
View File
@@ -39,7 +39,9 @@ var CPDateReferenceDate = new Date(Date.UTC(2001, 1, 1, 0, 0, 0, 0));
+ (id)alloc
{
return new Date;
var result = new Date;
result.isa = [self class];
return result;
}
+ (id)date
+2 -2
View File
@@ -152,14 +152,14 @@ function CPDecimalMakeWithString(string, locale)
{
if (i >= CPDecimalMaxDigits)
break; // truncate
[m addObject:parseInt(intpart[i])];
[m addObject:parseInt(intpart.charAt(i))];
}
var j = 0;
for (; j < (decpart?decpart.length:0); j++)
{
if ((i + j) >= CPDecimalMaxDigits)
break; // truncate
[m addObject:parseInt(decpart[j])];
[m addObject:parseInt(decpart.charAt(j))];
}
var dcm = {_exponent:exponent, _isNegative:isNegative, _isCompact:NO, _isNaN:NO, _mantissa:m};
+4 -4
View File
@@ -196,7 +196,7 @@ _cappdefaultDcmHandler = [CPDecimalNumberHandler decimalNumberHandlerWithRoundin
{
if (self = [self init])
{
if( flag )
if (flag)
mantissa *= -1;
_data = CPDecimalMakeWithParts(mantissa, exponent);
@@ -259,7 +259,7 @@ _cappdefaultDcmHandler = [CPDecimalNumberHandler decimalNumberHandlerWithRoundin
{
var s = @"",
i = 0;
for(;i < CPDecimalMaxDigits; i++)
for (;i < CPDecimalMaxDigits; i++)
s += "9";
s += "e" + CPDecimalMaxExponent;
return [[self alloc] initWithString:s];
@@ -269,7 +269,7 @@ _cappdefaultDcmHandler = [CPDecimalNumberHandler decimalNumberHandlerWithRoundin
{
var s = @"-",
i = 0;
for(;i < CPDecimalMaxDigits; i++)
for (;i < CPDecimalMaxDigits; i++)
s += "9";
s += "e" + CPDecimalMinExponent;
return [[self alloc] initWithString:s];
@@ -444,7 +444,7 @@ _cappdefaultDcmHandler = [CPDecimalNumberHandler decimalNumberHandlerWithRoundin
*/
- (CPString)hash
{
objj_exception_throw("hash: NOT YET IMPLEMENTED");
[CPException raise:CPUnsupportedMethodException reason:"hash: NOT YET IMPLEMENTED"];
}
/*!
+3 -1
View File
@@ -84,7 +84,9 @@
*/
+ (id)alloc
{
return new CFMutableDictionary();
var result = new CFMutableDictionary();
result.isa = [self class];
return result;
}
/*!
+17 -8
View File
@@ -54,7 +54,9 @@ if (input == nil)
*/
+ (id)alloc
{
return new Error();
var result = new Error();
result.isa = [self class];
return result;
}
/*!
@@ -88,9 +90,7 @@ if (input == nil)
*/
- (id)initWithName:(CPString)aName reason:(CPString)aReason userInfo:(CPDictionary)aUserInfo
{
self = [super init];
if (self)
if (self = [super init])
{
name = aName;
message = aReason;
@@ -140,6 +140,17 @@ if (input == nil)
throw self;
}
- (BOOL)isEqual:(id)anObject
{
if (!anObject || !anObject.isa)
return NO;
return [anObject isKindOfClass:CPException] &&
name === [anObject name] &&
message === [anObject message] &&
(_userInfo === [anObject userInfo] || ([_userInfo isEqual:[anObject userInfo]]));
}
@end
@implementation CPException (CPCopying)
@@ -164,9 +175,7 @@ var CPExceptionNameKey = "CPExceptionNameKey",
*/
- (id)initWithCoder:(CPCoder)aCoder
{
self = [super init];
if (self)
if (self = [super init])
{
name = [aCoder decodeObjectForKey:CPExceptionNameKey];
message = [aCoder decodeObjectForKey:CPExceptionReasonKey];
@@ -192,7 +201,7 @@ var CPExceptionNameKey = "CPExceptionNameKey",
// toll-free bridge Error to CPException
// [CPException alloc] uses an objj_exception, which is a subclass of Error
Error.prototype.isa = CPException;
Error.prototype._userInfo = NULL;
Error.prototype._userInfo = null;
[CPException initialize];
+1 -1
View File
@@ -85,7 +85,7 @@
if (anObject === self)
return YES;
if([anObject class] !== [CPIndexPath class])
if ([anObject class] !== [CPIndexPath class])
return NO;
return [_indexes isEqualToArray:[anObject indexes]];
+54 -75
View File
@@ -36,55 +36,47 @@ CPUnknownUserInfoKey = @"CPUnknownUserInfoKey";
var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
CPObjectModifiersForClassKey = @"$CPObjectModifiersForClassKey";
@implementation CPObject (CPKeyValueCoding)
+ (BOOL)accessInstanceVariablesDirectly
{
return YES;
}
/* @ignore */
+ (SEL)_accessorForKey:(CPString)aKey
var Null = [CPNull null];
var _accessorForKey = function(theClass, aKey)
{
var selector = nil,
accessors = isa[CPObjectAccessorsForClassKey];
accessors = theClass[CPObjectAccessorsForClassKey];
if (accessors)
{
selector = accessors[aKey];
if (selector)
return selector === [CPNull null] ? nil : selector;
return selector === Null ? nil : selector;
}
else
accessors = isa[CPObjectAccessorsForClassKey] = {};
accessors = theClass[CPObjectAccessorsForClassKey] = {};
var capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1);
if ([self instancesRespondToSelector:selector = CPSelectorFromString("get" + capitalizedKey)] ||
[self instancesRespondToSelector:selector = CPSelectorFromString(aKey)] ||
[self instancesRespondToSelector:selector = CPSelectorFromString("is" + capitalizedKey)] ||
[self instancesRespondToSelector:selector = CPSelectorFromString("_get" + capitalizedKey)] ||
[self instancesRespondToSelector:selector = CPSelectorFromString("_" + aKey)] ||
[self instancesRespondToSelector:selector = CPSelectorFromString("_is" + capitalizedKey)])
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] = [CPNull null];
accessors[aKey] = Null;
return nil;
}
/* @ignore */
+ (SEL)_modifierForKey:(CPString)aKey
var _modifierForKey = function(theClass, aKey)
{
if (!CPObjectModifiersForClass)
CPObjectModifiersForClass = [CPDictionary dictionary];
var UID = [isa UID],
var UID = [theClass UID],
selector = nil,
modifiers = [CPObjectModifiersForClass objectForKey:UID];
@@ -93,7 +85,7 @@ var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
selector = [modifiers objectForKey:aKey];
if (selector)
return selector === [CPNull null] ? nil : selector;
return selector === Null ? nil : selector;
}
else
{
@@ -102,52 +94,55 @@ var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
[CPObjectModifiersForClass setObject:modifiers forKey:UID];
}
if (selector)
return selector === [CPNull null] ? nil : selector;
var capitalizedKey = aKey.charAt(0).toUpperCase() + aKey.substr(1) + ':';
if ([self instancesRespondToSelector:selector = CPSelectorFromString("set" + capitalizedKey)] ||
[self instancesRespondToSelector:selector = CPSelectorFromString("_set" + capitalizedKey)])
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:[CPNull null] forKey:aKey];
[modifiers setObject:Null forKey:aKey];
return nil;
}
/* @ignore */
- (CPString)_ivarForKey:(CPString)aKey
var _ivarForKey = function(theObject, aKey)
{
var ivar = '_' + aKey;
if (typeof self[ivar] != "undefined")
if (typeof theObject[ivar] != "undefined")
return ivar;
var isKey = "is" + aKey.charAt(0).toUpperCase() + aKey.substr(1);
ivar = '_' + isKey;
if (typeof self[ivar] != "undefined")
if (typeof theObject[ivar] != "undefined")
return ivar;
ivar = aKey;
if (typeof self[ivar] != "undefined")
if (typeof theObject[ivar] != "undefined")
return ivar;
ivar = isKey;
if (typeof self[ivar] != "undefined")
if (typeof theObject[ivar] != "undefined")
return ivar;
return nil;
}
@implementation CPObject (CPKeyValueCoding)
+ (BOOL)accessInstanceVariablesDirectly
{
return YES;
}
- (id)valueForKey:(CPString)aKey
{
var theClass = [self class],
@@ -156,9 +151,13 @@ var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
if (selector)
return objj_msgSend(self, selector);
//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 ([theClass accessInstanceVariablesDirectly])
{
var ivar = [self _ivarForKey:aKey];
var ivar = _ivarForKey(self, aKey);
if (ivar)
return self[ivar];
@@ -227,14 +226,14 @@ var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
var theClass = [self class],
selector = [theClass _modifierForKey:aKey];
selector = _modifierForKey(theClass, aKey);
if (selector)
return objj_msgSend(self, selector, aValue);
if ([theClass accessInstanceVariablesDirectly])
{
var ivar = [self _ivarForKey:aKey];
var ivar = _ivarForKey(self, aKey);
if (ivar)
{
@@ -251,6 +250,19 @@ var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
[self setValue:aValue forUndefinedKey:aKey];
}
- (void)setValuesForKeysWithDictionary:(CPDictionary)keyedValues
{
var value, key, keyEnumerator = [keyedValues keyEnumerator];
while(key = [keyEnumerator nextObject])
{
value = [keyedValues objectForKey: key];
if(value === [CPNull null])
[self setValue: nil forKey: key];
else
[self setValue: value forKey: key];
}
}
- (void)setValue:(id)aValue forUndefinedKey:(CPString)aKey
{
[[CPException exceptionWithName:CPUndefinedKeyException
@@ -260,41 +272,6 @@ var CPObjectAccessorsForClassKey = @"$CPObjectAccessorsForClassKey",
@end
var Null = [CPNull null];
var _accessorForKey = function(theClass, aKey)
{
var selector = nil,
accessors = theClass.isa[CPObjectAccessorsForClassKey];
if (accessors)
{
selector = accessors[aKey];
if (selector)
return selector === Null ? nil : selector;
}
else
accessors = theClass.isa[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)] ||
[theClass instancesRespondToSelector:selector = CPSelectorFromString("_" + aKey)] ||
[theClass instancesRespondToSelector:selector = CPSelectorFromString("_is" + capitalizedKey)])
{
accessors[aKey] = selector;
return selector;
}
accessors[aKey] = Null;
return nil;
}
@implementation CPDictionary (KeyValueCoding)
- (id)valueForKey:(CPString)aKey
@@ -307,7 +284,10 @@ var _accessorForKey = function(theClass, aKey)
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
[self setObject:aValue forKey:aKey];
if(aValue)
[self setObject:aValue forKey:aKey];
else
[self removeObjectForKey: aKey];
}
@end
@@ -322,4 +302,3 @@ var _accessorForKey = function(theClass, aKey)
@end
@import "CPKeyValueObserving.j"
@import "CPArray+KVO.j"
+261 -72
View File
@@ -45,11 +45,19 @@
{
}
- (void)willChangeValueForKey:(CPString)key withSetMutation:(CPKeyValueSetMutationKind)mutationKind usingObjects:(CPSet)objects
{
}
- (void)didChangeValueForKey:(CPString)key withSetMutation:(CPKeyValueSetMutationKind)mutationKind usingObjects:(CPSet)objects
{
}
- (void)addObserver:(id)anObserver forKeyPath:(CPString)aPath options:(unsigned)options context:(id)aContext
{
if (!anObserver || !aPath)
return;
//CPLog.warn(anObserver+" is adding itself as an observer to object: "+self+" forKeyPath: "+aPath+" context: "+aContext);
[[_CPKVOProxy proxyForObject:self] _addObserver:anObserver forKeyPath:aPath options:options context:aContext];
}
@@ -79,28 +87,39 @@
- (void)applyChange:(CPDictionary)aChange toKeyPath:(CPString)aKeyPath
{
var changeKind = [aChange objectForKey:CPKeyValueChangeKindKey];
var changeKind = [aChange objectForKey:CPKeyValueChangeKindKey],
oldValue = [aChange objectForKey:CPKeyValueChangeOldKey],
newValue = [aChange objectForKey:CPKeyValueChangeNewKey],
indexes = [aChange objectForKey:CPKeyValueChangeIndexesKey];
if(newValue === [CPNull null])
newValue = nil;
if (changeKind === CPKeyValueChangeSetting)
{
var value = [aChange objectForKey:CPKeyValueChangeNewKey];
[self setValue:value === [CPNull null] ? nil : value forKeyPath:aKeyPath];
[self setValue:newValue forKeyPath:aKeyPath];
return;
}
else if (changeKind === CPKeyValueChangeInsertion)
[[self mutableArrayValueForKeyPath:aKeyPath]
insertObjects:[aChange objectForKey:CPKeyValueChangeNewKey]
atIndexes:[aChange objectForKey:CPKeyValueChangeIndexesKey]];
else if (changeKind === CPKeyValueChangeRemoval)
[[self mutableArrayValueForKeyPath:aKeyPath]
removeObjectsAtIndexes:[aChange objectForKey:CPKeyValueChangeIndexesKey]];
else if (changeKind === CPKeyValueChangeReplacement)
[[self mutableArrayValueForKeyPath:aKeyPath]
replaceObjectAtIndexes:[aChange objectForKey:CPKeyValueChangeIndexesKey]
withObjects:[aChange objectForKey:CPKeyValueChangeNewKey]];
//decide if this is a unordered or ordered to-many relationship
if([newValue isKindOfClass: [CPSet class]] || [oldValue isKindOfClass: [CPSet class]])
{
if (changeKind === CPKeyValueChangeInsertion)
[[self mutableSetValueForKeyPath:aKeyPath] unionSet:newValue];
else if (changeKind === CPKeyValueChangeRemoval)
[[self mutableSetValueForKeyPath:aKeyPath] minusSet:oldValue];
else if (changeKind === CPKeyValueChangeReplacement)
[[self mutableSetValueForKeyPath:aKeyPath] setSet: newValue];
}
else
{
if (changeKind === CPKeyValueChangeInsertion)
[[self mutableArrayValueForKeyPath:aKeyPath] insertObjects:newValue atIndexes:indexes];
else if (changeKind === CPKeyValueChangeRemoval)
[[self mutableArrayValueForKeyPath:aKeyPath] removeObjectsAtIndexes:indexes];
else if (changeKind === CPKeyValueChangeReplacement)
[[self mutableArrayValueForKeyPath:aKeyPath] replaceObjectAtIndexes:indexes withObjects:newValue];
}
}
@end
@@ -173,6 +192,32 @@ CPKeyValueChangeInsertion = 2;
CPKeyValueChangeRemoval = 3;
CPKeyValueChangeReplacement = 4;
// CPKeyValueSetMutationKind
CPKeyValueUnionSetMutation = 1;
CPKeyValueMinusSetMutation = 2;
CPKeyValueIntersectSetMutation = 3;
CPKeyValueSetSetMutation = 4;
//FIXME: "secret" dict ivar-keys are workaround to support unordered to-many relationships without too many modifications
_CPKeyValueChangeSetMutationObjectsKey = @"_CPKeyValueChangeSetMutationObjectsKey";
_CPKeyValueChangeSetMutationKindKey = @"_CPKeyValueChangeSetMutationKindKey";
_CPKeyValueChangeSetMutationNewValueKey = @"_CPKeyValueChangeSetMutationNewValueKey";
var _changeKindForSetMutationKind = function(mutationKind)
{
switch(mutationKind)
{
case CPKeyValueUnionSetMutation:
return CPKeyValueChangeInsertion;
case CPKeyValueMinusSetMutation:
return CPKeyValueChangeRemoval;
case CPKeyValueIntersectSetMutation:
return CPKeyValueChangeRemoval;
case CPKeyValueSetSetMutation:
return CPKeyValueChangeReplacement;
}
}
var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
DependentKeysKey = "$KVODEPENDENT",
KVOProxyKey = "$KVOPROXY";
@@ -197,25 +242,22 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
if (proxy)
return proxy;
proxy = [[self alloc] initWithTarget:anObject];
[proxy _replaceClass];
anObject[KVOProxyKey] = proxy;
return proxy;
return [[self alloc] initWithTarget:anObject];
}
- (id)initWithTarget:(id)aTarget
{
self = [super init];
_targetObject = aTarget;
_nativeClass = [aTarget class];
_observersForKey = {};
_changesForKey = {};
_observersForKeyLength = 0;
if(self = [super init])
{
_targetObject = aTarget;
_nativeClass = [aTarget class];
_observersForKey = {};
_changesForKey = {};
_observersForKeyLength = 0;
[self _replaceClass];
aTarget[KVOProxyKey] = self;
}
return self;
}
@@ -240,8 +282,11 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
kvoClass._replacedKeys = _replacedKeys;
//copy in the methods from our model subclass
var methodList = _CPKVOModelSubclass.method_list,
count = methodList.length,
var methodList = _CPKVOModelSubclass.method_list;
if ([_targetObject isKindOfClass:[CPDictionary class]])
methodList = methodList.concat(_CPKVOModelDictionarySubclass.method_list);
var count = methodList.length,
i = 0;
for (; i < count; i++)
@@ -250,23 +295,10 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
class_addMethod(kvoClass, method_getName(method), method_getImplementation(method), "");
}
if ([_targetObject isKindOfClass:[CPDictionary class]])
{
var methodList = _CPKVOModelDictionarySubclass.method_list,
count = methodList.length,
i = 0;
for (; i < count; i++)
{
var method = methodList[i];
class_addMethod(kvoClass, method_getName(method), method_getImplementation(method), "");
}
}
_targetObject.isa = kvoClass;
}
- (void)_replaceSetterForKey:(CPString)aKey
- (void)_replaceModifiersForKey:(CPString)aKey
{
if ([_replacedKeys containsObject:aKey] || ![_nativeClass automaticallyNotifiesObserversForKey:aKey])
return;
@@ -278,8 +310,16 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
"set" + capitalizedKey + ":", _kvoMethodForMethod,
"_set" + capitalizedKey + ":", _kvoMethodForMethod,
"insertObject:in" + capitalizedKey + "AtIndex:", _kvoInsertMethodForMethod,
"insert" + capitalizedKey + ":atIndexes:", _kvoInsertManyMethodForMethod,
"replaceObjectIn" + capitalizedKey + "AtIndex:withObject:", _kvoReplaceMethodForMethod,
"removeObjectFrom" + capitalizedKey + "AtIndex:", _kvoRemoveMethodForMethod
"replace" + capitalizedKey + "AtIndexes:with" + capitalizedKey + ":", _kvoReplaceManyMethodForMethod,
"removeObjectFrom" + capitalizedKey + "AtIndex:", _kvoRemoveMethodForMethod,
"remove" + capitalizedKey + "AtIndexes:", _kvoRemoveManyMethodForMethod,
"add" + capitalizedKey + "Object:", _kvoUnionMethodForMethod,
"add" + capitalizedKey + ":", _kvoUnionManyMethodForMethod,
"remove" + capitalizedKey + "Object:", _kvoMinusMethodForMethod,
"remove" + capitalizedKey + ":", _kvoMinusManyMethodForMethod,
"intersect" + capitalizedKey + ":", _kvoIntersectManyMethodForMethod
];
var i = 0,
@@ -326,11 +366,13 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
[affectedKeys addObject:aKey];
// Observe key paths of objects other then ourselves, so ware notified of the changes
//observe key paths of objects other then ourselves, so we are notified of the changes
//use CPKeyValueObservingOptionPrior to ensure proper wrapping around changes
//so CPKeyValueObservingOptionPrior and CPKeyValueObservingOptionOld can be fulfilled even for dependent keys
if (affectingKey.indexOf(@".") !== -1)
[_targetObject addObserver:self forKeyPath:affectingKey options:0 context:nil];
[_targetObject addObserver:self forKeyPath:affectingKey options:CPKeyValueObservingOptionPrior | kvoNewAndOld context:nil];
else
[self _replaceSetterForKey:affectingKey];
[self _replaceModifiersForKey:affectingKey];
}
}
@@ -340,10 +382,11 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
var dependentKeysForClass = _nativeClass[DependentKeysKey],
dependantKeys = [dependentKeysForClass[theKeyPath] allObjects];
var isBeforeFlag = !![theChanges objectForKey:CPKeyValueChangeNotificationIsPriorKey];
for (var i = 0; i < [dependantKeys count]; i++)
{
var dependantKey = [dependantKeys objectAtIndex:i];
[self _sendNotificationsForKey:dependantKey changeOptions:theChanges isBefore:NO];
[self _sendNotificationsForKey:dependantKey changeOptions:theChanges isBefore:isBeforeFlag];
}
}
@@ -357,7 +400,7 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
if (aPath.indexOf('.') != CPNotFound)
forwarder = [[_CPKVOForwardingObserver alloc] initWithKeyPath:aPath object:_targetObject observer:anObserver options:options context:aContext];
else
[self _replaceSetterForKey:aPath];
[self _replaceModifiersForKey:aPath];
var observers = _observersForKey[aPath];
@@ -411,7 +454,6 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
- (void)_sendNotificationsForKey:(CPString)aKey changeOptions:(CPDictionary)changeOptions isBefore:(BOOL)isBefore
{
// CPLog.warn("_sendNotificationsForKey: " + aKey + " ...isBefore: " + isBefore);
var changes = _changesForKey[aKey];
if (isBefore)
@@ -419,12 +461,36 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
changes = changeOptions;
var indexes = [changes objectForKey:CPKeyValueChangeIndexesKey];
var setMutationKind = changes[_CPKeyValueChangeSetMutationKindKey];
if (indexes)
if(setMutationKind)
{
var setMutationObjects = [changes[_CPKeyValueChangeSetMutationObjectsKey] copy];
var setExistingObjects = [[_targetObject valueForKey: aKey] copy];
if(setMutationKind == CPKeyValueMinusSetMutation)
{
[setExistingObjects intersectSet: setMutationObjects];
[changes setValue:setExistingObjects forKey:CPKeyValueChangeOldKey];
}
else if (setMutationKind === CPKeyValueIntersectSetMutation || setMutationKind === CPKeyValueSetSetMutation)
{
[setExistingObjects minusSet: setMutationObjects];
[changes setValue:setExistingObjects forKey:CPKeyValueChangeOldKey];
}
//for unordered to-many relationships (CPSet) even new values can only be calculated before!!!
if (setMutationKind === CPKeyValueUnionSetMutation || setMutationKind === CPKeyValueSetSetMutation)
{
[setMutationObjects minusSet: setExistingObjects];
//hide new value (for CPKeyValueObservingOptionPrior messages)
//as long as "didChangeValue..." is not yet called!
changes[_CPKeyValueChangeSetMutationNewValueKey] = setMutationObjects;
}
}
else if (indexes)
{
var type = [changes objectForKey:CPKeyValueChangeKindKey];
// for to-many relationships, oldvalue is only sensible for replace and remove
// for ordered to-many relationships, oldvalue is only sensible for replace and remove
if (type === CPKeyValueChangeReplacement || type === CPKeyValueChangeRemoval)
{
//FIXME: do we need to go through and replace "" with CPNull?
@@ -448,20 +514,30 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
}
else
{
// The isBefore path may not have been called as would happen if didChangeX
// was called alone.
if (!changes)
changes = [CPDictionary new];
[CPException raise:@"CPKeyValueObservingException" reason:@"'didChange...' message called without prior call of 'willChange...'"];
[changes removeObjectForKey:CPKeyValueChangeNotificationIsPriorKey];
var indexes = [changes objectForKey:CPKeyValueChangeIndexesKey];
var setMutationKind = changes[_CPKeyValueChangeSetMutationKindKey];
if (indexes)
if(setMutationKind)
{
//old and new values for unordered to-many relationships can only be calculated before
//set precalculated hidden new value as soon as "didChangeValue..." is called!
var newValue = changes[_CPKeyValueChangeSetMutationNewValueKey];
[changes setValue:newValue forKey:CPKeyValueChangeNewKey];
//delete hidden values
delete changes[_CPKeyValueChangeSetMutationNewValueKey];
delete changes[_CPKeyValueChangeSetMutationObjectsKey];
delete changes[_CPKeyValueChangeSetMutationKindKey];
}
else if (indexes)
{
var type = [changes objectForKey:CPKeyValueChangeKindKey];
// for to-many relationships, oldvalue is only sensible for replace and remove
// for ordered to-many relationships, newvalue is only sensible for replace and insert
if (type == CPKeyValueChangeReplacement || type == CPKeyValueChangeInsertion)
{
//FIXME: do we need to go through and replace "" with CPNull?
@@ -510,9 +586,6 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
{
var keyPath = dependentKeyPaths[index];
// CPLog.warn("firing dependepent key " + index + " for " + aKey + ": "+keyPath);
// objj_backtrace_print(CPLog.error);
[self _sendNotificationsForKey:keyPath
changeOptions:isBefore ? [changeOptions copy] : _changesForKey[keyPath]
isBefore:isBefore];
@@ -585,6 +658,39 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
[[_CPKVOProxy proxyForObject:self] _sendNotificationsForKey:aKey changeOptions:nil isBefore:NO];
}
- (void)willChangeValueForKey:(CPString)aKey withSetMutation:(CPKeyValueSetMutationKind)mutationKind usingObjects:(CPSet)objects
{
var superClass = [self class],
methodSelector = @selector(willChangeValueForKey:withSetMutation:usingObjects:),
methodImp = class_getMethodImplementation(superClass, methodSelector);
methodImp(self, methodSelector, aKey, mutationKind, objects);
if (!aKey)
return;
var changeKind = _changeKindForSetMutationKind(mutationKind);
var changeOptions = [CPDictionary dictionaryWithObject:changeKind forKey:CPKeyValueChangeKindKey];
//set hidden change-dict ivars to support unordered to-many relationships
changeOptions[_CPKeyValueChangeSetMutationObjectsKey] = objects;
changeOptions[_CPKeyValueChangeSetMutationKindKey] = mutationKind;
[[_CPKVOProxy proxyForObject:self] _sendNotificationsForKey:aKey changeOptions:changeOptions isBefore:YES];
}
- (void)didChangeValueForKey:(CPString)aKey withSetMutation:(CPKeyValueSetMutationKind)mutationKind usingObjects:(CPSet)objects
{
var superClass = [self class],
methodSelector = @selector(didChangeValueForKey:withSetMutation:usingObjects:),
methodImp = class_getMethodImplementation(superClass, methodSelector);
methodImp(self, methodSelector, aKey, mutationKind, objects);
if (!aKey)
return;
[[_CPKVOProxy proxyForObject:self] _sendNotificationsForKey:aKey changeOptions:nil isBefore:NO];
}
- (Class)class
{
return self[KVOProxyKey]._nativeClass;
@@ -668,6 +774,7 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
id _object;
id _observer;
id _context;
unsigned _options;
//a.b
CPString _firstPart; //a
CPString _secondPart; //b
@@ -682,8 +789,7 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
_context = aContext;
_observer = anObserver;
_object = anObject;
//current ignoring options (FIXME?)
_options = options;
var dotIndex = aKeyPath.indexOf('.');
@@ -694,13 +800,13 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
_secondPart = aKeyPath.substring(dotIndex + 1);
//become an observer of the first part of our key (a)
[_object addObserver:self forKeyPath:_firstPart options:kvoNewAndOld context:nil];
[_object addObserver:self forKeyPath:_firstPart options:_options context:nil];
//the current value of a (not the value of a.b)
_value = [_object valueForKey:_firstPart];
if (_value)
[_value addObserver:self forKeyPath:_secondPart options:kvoNewAndOld context:nil]; //we're observing b on current a
[_value addObserver:self forKeyPath:_secondPart options:_options context:nil]; //we're observing b on current a
return self;
}
@@ -718,7 +824,7 @@ var kvoNewAndOld = CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld,
_value = [_object valueForKey:_firstPart];
if (_value)
[_value addObserver:self forKeyPath:_secondPart options:kvoNewAndOld context:nil];
[_value addObserver:self forKeyPath:_secondPart options:_options context:nil];
}
else
{
@@ -756,6 +862,7 @@ var _kvoMethodForMethod = function _kvoMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, object)
{
//FIXME: do we have to call the specific willChange methods for to-many relationships?
[self willChangeValueForKey:theKey];
theMethod.method_imp(self, _cmd, object);
[self didChangeValueForKey:theKey];
@@ -772,6 +879,16 @@ var _kvoInsertMethodForMethod = function _kvoInsertMethodForMethod(theKey, theMe
}
}
var _kvoInsertManyMethodForMethod = function _kvoInsertManyMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, objects, indexes)
{
[self willChange:CPKeyValueChangeInsertion valuesAtIndexes:indexes forKey:theKey];
theMethod.method_imp(self, _cmd, objects, indexes);
[self didChange:CPKeyValueChangeInsertion valuesAtIndexes:indexes forKey:theKey];
}
}
var _kvoReplaceMethodForMethod = function _kvoReplaceMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, index, object)
@@ -782,6 +899,16 @@ var _kvoReplaceMethodForMethod = function _kvoReplaceMethodForMethod(theKey, the
}
}
var _kvoReplaceManyMethodForMethod = function _kvoReplaceManyMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, indexes, objects)
{
[self willChange:CPKeyValueChangeReplacement valuesAtIndexes:indexes forKey:theKey];
theMethod.method_imp(self, _cmd, indexes, objects);
[self didChange:CPKeyValueChangeReplacement valuesAtIndexes:indexes forKey:theKey];
}
}
var _kvoRemoveMethodForMethod = function _kvoRemoveMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, index)
@@ -792,4 +919,66 @@ var _kvoRemoveMethodForMethod = function _kvoRemoveMethodForMethod(theKey, theMe
}
}
var _kvoRemoveManyMethodForMethod = function _kvoRemoveManyMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, indexes)
{
[self willChange:CPKeyValueChangeRemoval valuesAtIndexes:indexes forKey:theKey];
theMethod.method_imp(self, _cmd, indexes);
[self didChange:CPKeyValueChangeRemoval valuesAtIndexes:indexes forKey:theKey];
}
}
var _kvoUnionMethodForMethod = function _kvoUnionMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, object)
{
[self willChangeValueForKey:theKey withSetMutation:CPKeyValueUnionSetMutation usingObjects: [CPSet setWithObject: object]];
theMethod.method_imp(self, _cmd, object);
[self didChangeValueForKey:theKey withSetMutation:CPKeyValueUnionSetMutation usingObjects: [CPSet setWithObject: object]];
}
}
var _kvoUnionManyMethodForMethod = function _kvoUnionManyMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, objects)
{
[self willChangeValueForKey:theKey withSetMutation:CPKeyValueUnionSetMutation usingObjects: objects];
theMethod.method_imp(self, _cmd, objects);
[self didChangeValueForKey:theKey withSetMutation:CPKeyValueUnionSetMutation usingObjects: objects];
}
}
var _kvoMinusMethodForMethod = function _kvoMinusMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, object)
{
[self willChangeValueForKey:theKey withSetMutation:CPKeyValueMinusSetMutation usingObjects: [CPSet setWithObject: object]];
theMethod.method_imp(self, _cmd, object);
[self didChangeValueForKey:theKey withSetMutation:CPKeyValueMinusSetMutation usingObjects: [CPSet setWithObject: object]];
}
}
var _kvoMinusManyMethodForMethod = function _kvoMinusManyMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, objects)
{
[self willChangeValueForKey:theKey withSetMutation:CPKeyValueMinusSetMutation usingObjects: objects];
theMethod.method_imp(self, _cmd, objects);
[self didChangeValueForKey:theKey withSetMutation:CPKeyValueMinusSetMutation usingObjects: objects];
}
}
var _kvoIntersectManyMethodForMethod = function _kvoIntersectManyMethodForMethod(theKey, theMethod)
{
return function(self, _cmd, objects)
{
[self willChangeValueForKey:theKey withSetMutation:CPKeyValueIntersectSetMutation usingObjects: objects];
theMethod.method_imp(self, _cmd, objects);
[self didChangeValueForKey:theKey withSetMutation:CPKeyValueIntersectSetMutation usingObjects: objects];
}
}
@import "CPArray+KVO.j"
@import "CPSet+KVO.j"
+4 -3
View File
@@ -24,8 +24,7 @@
@import "CPObjJRuntime.j"
var __placeholder = new Number(),
CPNumberUIDs = new CFMutableDictionary();
var CPNumberUIDs = new CFMutableDictionary();
/*!
@class CPNumber
@@ -43,7 +42,9 @@ var __placeholder = new Number(),
+ (id)alloc
{
return __placeholder;
var result = new Number();
result.isa = [self class];
return result;
}
+ (id)numberWithBool:(BOOL)aBoolean
+5 -5
View File
@@ -61,6 +61,8 @@ CPLog(@"Got some class: %@", inst);
@todo document KVC usage.
*/
@implementation CPObject
{
Class isa;
@@ -450,11 +452,9 @@ CPLog(@"Got some class: %@", inst);
Sets the class version number.
@param the new version number for the class
*/
+ (id)setVersion:(int)aVersion
+ (void)setVersion:(int)aVersion
{
version = aVersion;
return self;
class_setVersion(self, aVersion);
}
/*!
@@ -462,7 +462,7 @@ CPLog(@"Got some class: %@", inst);
*/
+ (int)version
{
return version;
return class_getVersion(self);
}
// Scripting (?)
+4 -2
View File
@@ -115,7 +115,8 @@ function CPLocationInRange(aLocation, aRange)
function CPUnionRange(lhsRange, rhsRange)
{
var location = MIN(lhsRange.location, rhsRange.location);
return CPMakeRange(location, MAX(CPMaxRange(lhsRange), CPMaxRange(rhsRange)) - location);
return CPMakeRange(location, MAX(CPMaxRange(lhsRange), CPMaxRange(rhsRange)) - location);
}
/*!
@@ -127,10 +128,11 @@ function CPUnionRange(lhsRange, rhsRange)
*/
function CPIntersectionRange(lhsRange, rhsRange)
{
if(CPMaxRange(lhsRange) < rhsRange.location || CPMaxRange(rhsRange) < lhsRange.location)
if (CPMaxRange(lhsRange) < rhsRange.location || CPMaxRange(rhsRange) < lhsRange.location)
return CPMakeRange(0, 0);
var location = MAX(lhsRange.location, rhsRange.location);
return CPMakeRange(location, MIN(CPMaxRange(lhsRange), CPMaxRange(rhsRange)) - location);
}
+24 -24
View File
@@ -72,12 +72,12 @@
- (id)copy
{
var copy = [[CPScanner alloc] initWithString:[self string]];
[copy setCharactersToBeSkipped:[self charactersToBeSkipped]];
[copy setCaseSensitive:[self caseSensitive]];
[copy setLocale:[self locale]];
[copy setScanLocation:[self scanLocation]];
return copy;
}
@@ -179,14 +179,14 @@
{
if ([self isAtEnd])
return nil;
var current = [self scanLocation];
var str = nil;
while (current < _string.length)
{
var c = (_string.charAt(current));
if ([scanSet characterIsMember:c] == stop)
break;
@@ -196,13 +196,13 @@
str = '';
str += c;
}
current++;
}
if (str)
[self setScanLocation:current];
return str;
}
@@ -215,15 +215,15 @@
var current = [self scanLocation];
var string = [self string];
var toSkip = [self charactersToBeSkipped];
while (current < string.length)
{
if (![toSkip characterIsMember:string.charAt(current)])
break;
current++;
}
[self setScanLocation:current];
}
@@ -265,22 +265,22 @@
var currentStr = str.substr(current, s.length);
if (currentStr == s || (!_caseSensitive && currentStr.toLowerCase() == s.toLowerCase()))
break;
if (!captured)
captured = '';
captured += str.charAt(current);
current++;
}
if (captured)
[self setScanLocation:current];
// evil private method use!
// this method is defined in the category on CPString
// in CPCharacterSet.j
if ([self charactersToBeSkipped])
captured = [captured _stringByTrimmingCharactersInSet:[self charactersToBeSkipped] options:_CPCharacterSetTrimAtBeginning];
return captured;
}
@@ -292,10 +292,10 @@
{
[self _movePastCharactersToBeSkipped];
var str = [self string], current = [self scanLocation];
if ([self isAtEnd])
return 0;
var s = str.substring(current, str.length);
var f = parseFloat(s); // wont work with non . decimal separator !!
if (f)
@@ -303,16 +303,16 @@
var pos, foundDash = NO;
/*
var decimalSeparatorString;
if(_locale != nil)
if (_locale != nil)
decimalSeparatorString = [_locale objectForKey:CPLocaleDecimalSeparator];
else
decimalSeparatorString = [[CPLocale systemLocale] objectForKey:CPLocaleDecimalSeparator];
var separatorCode = (decimalSeparatorString.length >0) decimalSeparatorString.charCodeAt(0) : 45;
*/
var separatorCode = 45;
for(pos = current; pos < current + str.length; pos++)
for (pos = current; pos < current + str.length; pos++)
{
var charCode = str.charCodeAt(pos);
if (charCode == separatorCode)
@@ -324,11 +324,11 @@
else if (charCode < 48 || charCode > 57 || (charCode == 45 && pos != current)) // not a digit or a "-" but not prefix
break;
}
[self setScanLocation:pos];
return f;
}
return nil;
}
@@ -357,11 +357,11 @@
else if (charCode < 48 || charCode > 57 || (charCode == 45 && pos != current))
break;
}
[self setScanLocation:pos];
return i;
}
return nil;
}
+546
View File
@@ -0,0 +1,546 @@
/*
* CPSet+KVO.j
* Foundation
*
* Created by Daniel Stolzenberg.
* Copyright 2010, University of Rostock
*
* 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 "CPSet.j"
@implementation CPObject (CPSetKVO)
- (id)mutableSetValueForKey:(id)aKey
{
return [[_CPKVCSet alloc] initWithKey:aKey forProxyObject:self];
}
- (id)mutableSetValueForKeyPath:(id)aKeyPath
{
var dotIndex = aKeyPath.indexOf(".");
if (dotIndex < 0)
return [self mutableSetValueForKey:aKeyPath];
var firstPart = aKeyPath.substring(0, dotIndex),
lastPart = aKeyPath.substring(dotIndex + 1);
return [[self valueForKeyPath:firstPart] mutableSetValueForKeyPath:lastPart];
}
@end
@implementation _CPKVCSet : CPMutableSet
{
id _proxyObject;
id _key;
SEL _accessSEL;
Function _access;
SEL _setSEL;
Function _set;
SEL _countSEL;
Function _count;
SEL _enumeratorSEL;
Function _enumerator;
SEL _memberSEL;
Function _member;
SEL _addSEL;
Function _add;
SEL _addManySEL;
Function _addMany;
SEL _removeSEL;
Function _remove;
SEL _removeManySEL;
Function _removeMany;
SEL _intersectSEL;
Function _intersect;
}
+ (id)alloc
{
var set = [CPMutableSet set];
set.isa = self;
var ivars = class_copyIvarList(self),
count = ivars.length;
while (count--)
set[ivar_getName(ivars[count])] = nil;
return set;
}
- (id)initWithKey:(id)aKey forProxyObject:(id)anObject
{
self = [super init];
_key = aKey;
_proxyObject = anObject;
var capitalizedKey = _key.charAt(0).toUpperCase() + _key.substring(1);
_accessSEL = sel_getName(_key);
if ([_proxyObject respondsToSelector:_accessSEL])
_access = [_proxyObject methodForSelector:_accessSEL];
_setSEL = sel_getName(@"set"+capitalizedKey+":");
if ([_proxyObject respondsToSelector:_setSEL])
_set = [_proxyObject methodForSelector:_setSEL];
_countSEL = sel_getName(@"countOf"+capitalizedKey);
if ([_proxyObject respondsToSelector:_countSEL])
_count = [_proxyObject methodForSelector:_countSEL];
_enumeratorSEL = sel_getName(@"enumeratorOf"+capitalizedKey);
if ([_proxyObject respondsToSelector:_enumeratorSEL])
_enumerator = [_proxyObject methodForSelector:_enumeratorSEL];
_memberSEL = sel_getName(@"memberOf"+capitalizedKey+":");
if ([_proxyObject respondsToSelector:_memberSEL])
_member = [_proxyObject methodForSelector:_memberSEL];
_addSEL = sel_getName(@"add"+capitalizedKey+"Object:");
if ([_proxyObject respondsToSelector:_addSEL])
_add = [_proxyObject methodForSelector:_addSEL];
_addManySEL = sel_getName(@"add"+capitalizedKey+":");
if ([_proxyObject respondsToSelector:_addManySEL])
_addMany = [_proxyObject methodForSelector:_addManySEL];
_removeSEL = sel_getName(@"remove"+capitalizedKey+"Object:");
if ([_proxyObject respondsToSelector:_removeSEL])
_remove = [_proxyObject methodForSelector:_removeSEL];
_removeManySEL = sel_getName(@"remove"+capitalizedKey+":");
if ([_proxyObject respondsToSelector:_removeManySEL])
_removeMany = [_proxyObject methodForSelector:_removeManySEL];
_intersectSEL = sel_getName(@"intersect"+capitalizedKey+":");
if ([_proxyObject respondsToSelector:_intersectSEL])
_intersect = [_proxyObject methodForSelector:_intersectSEL];
return self;
}
- (id)_representedObject
{
if (_access)
return _access(_proxyObject, _accessSEL);
return [_proxyObject valueForKey:_key];
}
- (void)_setRepresentedObject:(id)anObject
{
if (_set)
return _set(_proxyObject, _setSEL, anObject);
[_proxyObject setValue:anObject forKey:_key];
}
- (unsigned)count
{
if (_count)
return _count(_proxyObject, _countSEL);
return [[self _representedObject] count];
}
- (CPEnumerator)objectEnumerator
{
if (_enumerator)
return _enumerator(_proxyObject, _enumeratorSEL);
return [[self _representedObject] objectEnumerator];
}
- (id)member:(id)anObject
{
if (_member)
return _member(_proxyObject, _memberSEL, anObject);
return [[self _representedObject] member:anObject];
}
- (void)addObject:(id)anObject
{
if (_add)
_add(_proxyObject, _addSEL, anObject);
else if(_addMany)
{
var objectSet = [CPSet setWithObject: anObject];
_addMany(_proxyObject, _addManySEL, objectSet);
}
else
{
var target = [[self _representedObject] copy];
[target addObject:anObject];
[self _setRepresentedObject:target];
}
}
- (void)addObjectsFromArray:(CPArray)objects
{
if(_addMany)
{
var objectSet = [CPSet setWithArray: objects];
_addMany(_proxyObject, _addManySEL, objectSet);
}
else if(_add)
{
var object, objectEnumerator = [objects objectEnumerator];
while(object = [objectEnumerator nextObject])
_add(_proxyObject, _addSEL, object);
}
else
{
var target = [[self _representedObject] copy];
[target addObjectsFromArray:objects];
[self _setRepresentedObject:target];
}
}
- (void)unionSet:(CPSet)aSet
{
if (_addMany)
_addMany(_proxyObject, _addManySEL, aSet);
else if(_add)
{
var object, objectEnumerator = [aSet objectEnumerator];
while(object = [objectEnumerator nextObject])
_add(_proxyObject, _addSEL, object);
}
else
{
var target = [[self _representedObject] copy];
[target unionSet:aSet];
[self _setRepresentedObject:target];
}
}
- (void)removeObject:(id)anObject
{
if (_remove)
_remove(_proxyObject, _removeSEL, anObject);
else if(_removeMany)
{
var objectSet = [CPSet setWithObject: anObject];
_removeMany(_proxyObject, _removeManySEL, objectSet);
}
else
{
var target = [[self _representedObject] copy];
[target removeObject:anObject];
[self _setRepresentedObject:target];
}
}
- (void)minusSet:(CPSet)aSet
{
if(_removeMany)
_removeMany(_proxyObject, _removeManySEL, aSet);
else if(_remove)
{
var object, objectEnumerator = [aSet objectEnumerator];
while(object = [objectEnumerator nextObject])
_remove(_proxyObject, _removeSEL, object);
}
else
{
var target = [[self _representedObject] copy];
[target minusSet:aSet];
[self _setRepresentedObject:target];
}
}
- (void)removeObjectsInArray:(CPArray)objects
{
if(_removeMany)
{
var objectSet = [CPSet setWithArray:objects];
_removeMany(_proxyObject, _removeManySEL, objectSet);
}
else if(_remove)
{
var object, objectEnumerator = [objects objectEnumerator];
while(object = [objectEnumerator nextObject])
_remove(_proxyObject, _removeSEL, object);
}
else
{
var target = [[self _representedObject] copy];
[target removeObjectsInArray:objects];
[self _setRepresentedObject:target];
}
}
- (void)removeAllObjects
{
if(_removeMany)
{
var allObjectsSet = [[self _representedObject] copy];
_removeMany(_proxyObject, _removeManySEL, allObjectsSet);
}
else if(_remove)
{
var object, objectEnumerator = [[[self _representedObject] copy] objectEnumerator];
while(object = [objectEnumerator nextObject])
_remove(_proxyObject, _removeSEL, object);
}
else
{
var target = [[self _representedObject] copy];
[target removeAllObjects];
[self _setRepresentedObject:target];
}
}
- (void)intersectSet:(CPSet)aSet
{
if(_intersect)
_intersect(_proxyObject, _intersectSEL, aSet);
else
{
var target = [[self _representedObject] copy];
[target intersectSet:aSet];
[self _setRepresentedObject:target];
}
}
- (void)setSet:(CPSet)set
{
[self _setRepresentedObject: set];
}
- (CPArray)allObjects
{
return [[self _representedObject] allObjects];
}
- (id)anyObject
{
return [[self _representedObject] anyObject];
}
- (BOOL)containsObject:(id)anObject
{
return [[self _representedObject] containsObject: anObject];
}
- (BOOL)intersectsSet:(CPSet)aSet
{
return [[self _representedObject] intersectsSet: aSet];
}
- (BOOL)isEqualToSet:(CPSet)aSet
{
return [[self _representedObject] isEqualToSet: aSet];
}
- (id)copy
{
return [[self _representedObject] copy];
}
@end
@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)
{
var dotIndex = aKeyPath.indexOf("."),
operator,
parameter;
if (dotIndex !== -1)
{
operator = aKeyPath.substring(1, dotIndex);
parameter = aKeyPath.substring(dotIndex + 1);
}
else
operator = aKeyPath.substring(1);
if (kvoOperators[operator])
return kvoOperators[operator](self, _cmd, parameter);
return nil;
}
else
{
var valuesForKeySet = [CPSet set];
var containedObject, containedObjectValue, containedObjectEnumerator = [self objectEnumerator];
while(containedObject = [containedObjectEnumerator nextObject])
{
containedObjectValue = [containedObject valueForKeyPath:aKeyPath];
if(containedObjectValue)
[valuesForKeySet addObject:containedObjectValue];
}
return valuesForKeySet;
}
}
- (void)setValue:(id)aValue forKey:(CPString)aKey
{
var containedObject, containedObjectEnumerator = [self objectEnumerator];
while (containedObject = [containedObjectEnumerator nextObject])
[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 = [];
// FIXME: this is not DRY because the implementation in CPArray+KVO is merely the same!
// HACK: prevent these from becoming globals. workaround for obj-j "function foo(){}" behavior
var avgOperator, maxOperator, minOperator, countOperator, sumOperator;
kvoOperators["avg"] = function avgOperator(self, _cmd, param)
{
//CPSet returns a CPSet - to obtain an array call allObjects
var objects = [[self valueForKeyPath:param] allObjects],
length = [objects count],
index = length;
average = 0.0;
if (!length)
return 0;
while (index--)
average += [objects[index] doubleValue];
return average / length;
}
kvoOperators["max"] = function maxOperator(self, _cmd, param)
{
//CPSet returns a CPSet - to obtain an array call allObjects
var objects = [[self valueForKeyPath:param] allObjects],
index = [objects count] - 1,
max = [objects lastObject];
while (index--)
{
var item = objects[index];
if ([max compare:item] < 0)
max = item;
}
return max;
}
kvoOperators["min"] = function minOperator(self, _cmd, param)
{
//CPSet returns a CPSet - to obtain an array call allObjects
var objects = [[self valueForKeyPath:param] allObjects],
index = [objects count] - 1,
min = [objects lastObject];
while (index--)
{
var item = objects[index];
if ([min compare:item] > 0)
min = item;
}
return min;
}
kvoOperators["count"] = function countOperator(self, _cmd, param)
{
return [self count];
}
kvoOperators["sum"] = function sumOperator(self, _cmd, param)
{
//CPSet returns a CPSet - to obtain an array call allObjects
var objects = [[self valueForKeyPath:param] allObjects],
index = [objects count],
sum = 0.0;
while (index--)
sum += [objects[index] doubleValue];
return sum;
}
@implementation CPSet (CPKeyValueObserving)
- (void)addObserver:(id)observer forKeyPath:(CPString)aKeyPath options:(unsigned)options context:(id)context
{
if ([isa instanceMethodForSelector:_cmd] === [CPSet instanceMethodForSelector:_cmd])
[CPException raise:CPInvalidArgumentException reason:"Unsupported method on CPSet"];
else
[super addObserver:observer forKeyPath:aKeyPath options:options context:context];
}
-(void)removeObserver:(id)observer forKeyPath:(CPString)aKeyPath
{
if ([isa instanceMethodForSelector:_cmd] === [CPSet instanceMethodForSelector:_cmd])
[CPException raise:CPInvalidArgumentException reason:"Unsupported method on CPSet"];
else
[super removeObserver:observer forKeyPath:aKeyPath];
}
@end
+2 -2
View File
@@ -152,8 +152,8 @@
{
if (self = [self init])
{
var argLength = arguments.length,
i = 2;
var argLength = arguments.length,
i = 2;
for (; i < argLength && (argument = arguments[i]) != nil; ++i)
[self addObject:argument];
+21 -10
View File
@@ -91,6 +91,9 @@ var CPStringRegexSpecialCharacters = [
*/
+ (id)alloc
{
if ([self class] !== CPString)
return [super alloc];
return new String;
}
@@ -134,7 +137,14 @@ var CPStringRegexSpecialCharacters = [
*/
- (id)initWithString:(CPString)aString
{
return String(aString);
if ([self class] === CPString)
return String(aString);
var result = new String(aString);
result.isa = [self class];
return result;
}
/*!
@@ -425,7 +435,7 @@ var CPStringRegexSpecialCharacters = [
- (CPString)stringByReplacingCharactersInRange:(CPRange)range withString:(CPString)replacement
{
return '' + substring(0, range.location) + replacement + substring(range.location + range.length, self.length);
return '' + substring(0, range.location) + replacement + substring(range.location + range.length, self.length);
}
/*!
@@ -475,15 +485,16 @@ var CPStringRegexSpecialCharacters = [
rhs = rhs.toLowerCase();
}
if(aMask & CPDiacriticInsensitiveSearch)
if (aMask & CPDiacriticInsensitiveSearch)
{
lhs = lhs.stripDiacritics();
rhs = rhs.stripDiacritics();
lhs = lhs.stripDiacritics();
rhs = rhs.stripDiacritics();
}
if (lhs < rhs)
return CPOrderedAscending;
else if (lhs > rhs)
if (lhs > rhs)
return CPOrderedDescending;
return CPOrderedSame;
@@ -707,9 +718,9 @@ var CPStringRegexSpecialCharacters = [
}
/*!
Deletes the last path component of a string.
This method assumes that the string's content is a '/'
separated file system path.
Deletes the last path component of a string.
This method assumes that the string's content is a '/'
separated file system path.
*/
- (CPString)stringByDeletingLastPathComponent
{
@@ -808,7 +819,7 @@ String.prototype.stripDiacritics = function ()
{
var drange = diacritics[i];
if (code >= drange[0] && code <= drange[drange.length-1])
if (code >= drange[0] && code <= drange[drange.length - 1])
{
code = normalized[i];
break;
+6 -2
View File
@@ -54,7 +54,9 @@ CPURLCustomIconKey = @"CPURLCustomIconKey";
+ (id)alloc
{
return new CFURL();
var result = new CFURL();
result.isa = [self class];
return result;
}
- (id)init
@@ -81,7 +83,9 @@ CPURLCustomIconKey = @"CPURLCustomIconKey";
- (id)initWithString:(CPString)URLString relativeToURL:(CPURL)aBaseURL
{
return new CFURL(URLString, aBaseURL);
var result = new CFURL(URLString, aBaseURL);
result.isa = [self class];
return result;
}
+ (id)URLWithString:(CPString)URLString relativeToURL:(CPURL)aBaseURL
Loaded 100 of 229 files, more files were not shown because too many files have changed in this diff. Show more