mirror of
https://github.com/cappuccino/cappuccino.git
synced 2026-09-09 12:17:13 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6678bba94f |
-13
@@ -5,16 +5,3 @@ Demos
|
||||
./Aristo
|
||||
WebSite
|
||||
.push-package
|
||||
*.xcodeproj*
|
||||
*.xcodeproj/*.pbxuser
|
||||
*.xcodeproj/*.perspectivev3
|
||||
xcuserdata/
|
||||
!*.xcodeproj/project.pbxproj
|
||||
*.xCodeSupport/
|
||||
*.XcodeSupport/
|
||||
*XcodeSupport/
|
||||
Tests/Manual/**/*.xcodeproj
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
*.tm_properties
|
||||
*.idea
|
||||
@@ -1,6 +0,0 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.8
|
||||
install: ./bootstrap.sh --noprompt --directory ./narwhal
|
||||
script: jake test
|
||||
env: PATH="$TRAVIS_BUILD_DIR/narwhal/bin:$PATH" CAPP_BUILD="$TRAVIS_BUILD_DIR/Build" NARWHAL_ENGINE=rhino
|
||||
+7
-36
@@ -20,17 +20,10 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "_CPObject+Theme.j"
|
||||
@import "_CPToolTip.j"
|
||||
@import "CALayer.j"
|
||||
@import "CGGeometry.j"
|
||||
@import "CPAccordionView.j"
|
||||
@import "CPAlert.j"
|
||||
@import "CPAnimation.j"
|
||||
@import "CPAnimationContext.j"
|
||||
@import "CPAppearance.j"
|
||||
@import "CPApplication.j"
|
||||
@import "CPArrayController.j"
|
||||
@import "CPBezierPath.j"
|
||||
@import "CPBox.j"
|
||||
@import "CPBrowser.j"
|
||||
@@ -38,80 +31,58 @@
|
||||
@import "CPButtonBar.j"
|
||||
@import "CPCheckBox.j"
|
||||
@import "CPCib.j"
|
||||
@import "CPCibBindingConnector.j"
|
||||
@import "CPCibConnector.j"
|
||||
@import "CPCibControlConnector.j"
|
||||
@import "CPCibHelpConnector.j"
|
||||
@import "CPCibLoading.j"
|
||||
@import "CPCibOutletConnector.j"
|
||||
@import "CPCibRuntimeAttributesConnector.j"
|
||||
@import "CPClipView.j"
|
||||
@import "CPCollectionView.j"
|
||||
@import "CPCollectionViewItem.j"
|
||||
@import "CPCollectionView.j"
|
||||
@import "CPColor.j"
|
||||
@import "CPColorPanel.j"
|
||||
@import "CPColorSpace.j"
|
||||
@import "CPColorWell.j"
|
||||
@import "CPComboBox.j"
|
||||
@import "CPCompatibility.j"
|
||||
@import "CPControl.j"
|
||||
@import "CPController.j"
|
||||
@import "CPCookie.j"
|
||||
@import "CPCursor.j"
|
||||
@import "CPDatePicker.j"
|
||||
@import "CPDocument.j"
|
||||
@import "CPDocumentController.j"
|
||||
@import "CPEvent.j"
|
||||
@import "CPFlashMovie.j"
|
||||
@import "CPFlashView.j"
|
||||
@import "CPFont.j"
|
||||
@import "CPFontManager.j"
|
||||
@import "CPGradient.j"
|
||||
@import "CPGraphics.j"
|
||||
@import "CPGeometry.j"
|
||||
@import "CPImage.j"
|
||||
@import "CPImageView.j"
|
||||
@import "CPKeyBinding.j"
|
||||
@import "CPLevelIndicator.j"
|
||||
@import "CPMenu.j"
|
||||
@import "CPMenuItem.j"
|
||||
@import "CPOpenPanel.j"
|
||||
@import "CPOutlineView.j"
|
||||
@import "CPPanel.j"
|
||||
@import "CPPasteboard.j"
|
||||
@import "CPPopover.j"
|
||||
@import "CPPopUpButton.j"
|
||||
@import "CPPredicateEditor.j"
|
||||
@import "CPPredicateEditorRowTemplate.j"
|
||||
@import "CPProgressIndicator.j"
|
||||
@import "CPRadio.j"
|
||||
@import "CPResponder.j"
|
||||
@import "CPRuleEditor.j"
|
||||
@import "CPScroller.j"
|
||||
@import "CPScrollView.j"
|
||||
@import "CPSearchField.j"
|
||||
@import "CPScrollView.j"
|
||||
@import "CPScroller.j"
|
||||
@import "CPSecureTextField.j"
|
||||
@import "CPSegmentedControl.j"
|
||||
@import "CPShadow.j"
|
||||
@import "CPSlider.j"
|
||||
@import "CPSound.j"
|
||||
@import "CPSplitView.j"
|
||||
@import "CPStepper.j"
|
||||
@import "CPTabView.j"
|
||||
@import "CPTableColumn.j"
|
||||
@import "CPTableView.j"
|
||||
@import "CPTabView.j"
|
||||
@import "CPText.j"
|
||||
@import "CPTextField.j"
|
||||
@import "CPTextView.j"
|
||||
@import "CPTokenField.j"
|
||||
@import "CPToolbar.j"
|
||||
@import "CPToolbarItem.j"
|
||||
@import "CPTrackingArea.j"
|
||||
@import "CPTreeNode.j"
|
||||
@import "CPUserDefaultsController.j"
|
||||
@import "CPView.j"
|
||||
@import "CPViewAnimator.j"
|
||||
@import "CPViewAnimation.j"
|
||||
@import "CPViewController.j"
|
||||
@import "CPVisualEffectView.j"
|
||||
@import "CPWebView.j"
|
||||
@import "CPWindow.j"
|
||||
@import "CPWindowController.j"
|
||||
@import "CPWorkspace.j"
|
||||
|
||||
+29
-64
@@ -26,16 +26,11 @@
|
||||
@import <Foundation/CPIndexSet.j>
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
@import "CPView.j"
|
||||
@import "CPButton.j"
|
||||
@import <AppKit/CPView.j>
|
||||
|
||||
#import "CoreGraphics/CGGeometry.h"
|
||||
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPAccordionViewItem
|
||||
|
||||
<p>A CPAccordionViewItem represents a single section of a CPAccordionView.</p>
|
||||
*/
|
||||
@implementation CPAccordionViewItem : CPObject
|
||||
{
|
||||
CPString _identifier @accessors(property=identifier);
|
||||
@@ -48,10 +43,6 @@
|
||||
return [self initWithIdentifier:@""];
|
||||
}
|
||||
|
||||
/*!
|
||||
Initializes a new CPAccordionViewItem with the specified identifier. This identifier may
|
||||
then be used in subsequent methods to provide abstract introspection of the CPAccordionView.
|
||||
*/
|
||||
- (id)initWithIdentifier:(CPString)anIdentifier
|
||||
{
|
||||
self = [super init];
|
||||
@@ -64,25 +55,6 @@
|
||||
|
||||
@end
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPAccordionView
|
||||
|
||||
<p>CPAccordionView provides a container for CPAccordionViewItem objects and manages layout state
|
||||
for all sub-layout items.</p>
|
||||
|
||||
<strong>Example</strong><br />
|
||||
<pre>
|
||||
var myAccordionView = [[CPAccordionView alloc] initWithFrame:CGRectMakeZero()];
|
||||
var firstItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"firstSection"]];
|
||||
[firstItem setView:[[CPView alloc] initWithFrame:CGRectMakeZero()]];
|
||||
var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection"]];
|
||||
[secondItem setView:[[CPView alloc] initWithFrame:CGRectMakeZero()]];
|
||||
[myAccordionView addItem:firstItem];
|
||||
[myAccordionView addItem:secondItem];
|
||||
[myAccordionView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable];
|
||||
</pre>
|
||||
*/
|
||||
@implementation CPAccordionView : CPView
|
||||
{
|
||||
CPInteger _dirtyItemIndex;
|
||||
@@ -92,10 +64,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
CPMutableArray _itemViews;
|
||||
CPIndexSet _expandedItemIndexes;
|
||||
}
|
||||
/*!
|
||||
Initializes the receiver for usage with the specified bounding rectangle
|
||||
@return the initialized view
|
||||
*/
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
@@ -106,7 +75,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
_itemViews = [];
|
||||
_expandedItemIndexes = [CPIndexSet indexSet];
|
||||
|
||||
[self setItemHeaderPrototype:[[CPButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 24.0)]];
|
||||
[self setItemHeaderPrototype:[[CPButton alloc] initWithFrame:_CGRectMake(0.0, 0.0, 100.0, 24.0)]];
|
||||
}
|
||||
|
||||
return self;
|
||||
@@ -126,17 +95,13 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
{
|
||||
return _items;
|
||||
}
|
||||
/*!
|
||||
Append a CPAccordionViewItem to the receiver. Note that the CPAccordionViewItem must contain
|
||||
a valid CPView derived component or a TypeError will be generated when the contents of the
|
||||
ViewItem are disclosed.
|
||||
*/
|
||||
- (void)addItem:(CPAccordionViewItem)anItem
|
||||
|
||||
- (void)addItem:(CPAccordionItem)anItem
|
||||
{
|
||||
[self insertItem:anItem atIndex:_items.length];
|
||||
}
|
||||
|
||||
- (void)insertItem:(CPAccordionViewItem)anItem atIndex:(CPInteger)anIndex
|
||||
- (void)insertItem:(CPAccordionItem)anItem atIndex:(CPInteger)anIndex
|
||||
{
|
||||
// FIXME: SHIFT ITEMS RIGHT
|
||||
[_expandedItemIndexes addIndex:anIndex];
|
||||
@@ -157,7 +122,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)removeItem:(CPAccordionViewItem)anItem
|
||||
- (void)removeItem:(CPAccordionItem)anItem
|
||||
{
|
||||
[self removeItemAtIndex:[_items indexOfObjectIdenticalTo:anItem]];
|
||||
}
|
||||
@@ -213,7 +178,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
|
||||
if ([itemView isCollapsed])
|
||||
[self expandItemAtIndex:anIndex];
|
||||
|
||||
|
||||
else
|
||||
[self collapseItemAtIndex:anIndex];
|
||||
}
|
||||
@@ -227,7 +192,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
{
|
||||
var indexSet = [CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, _items.length)];
|
||||
|
||||
[indexSet removeIndexes:_expandedItemIndexes];
|
||||
[indexSet removeIndexes:_expandedIndexes];
|
||||
|
||||
return indexSet;
|
||||
}
|
||||
@@ -237,12 +202,12 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
var itemView = _itemViews[anIndex];
|
||||
if (!itemView)
|
||||
return;
|
||||
|
||||
|
||||
if (!isEnabled)
|
||||
[self collapseItemAtIndex:anIndex];
|
||||
else
|
||||
[self expandItemAtIndex:anIndex];
|
||||
|
||||
|
||||
[itemView setEnabled:isEnabled];
|
||||
}
|
||||
|
||||
@@ -258,19 +223,19 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
|
||||
- (void)setFrameSize:(CGSize)aSize
|
||||
{
|
||||
var width = CGRectGetWidth([self frame]);
|
||||
var width = _CGRectGetWidth([self frame]);
|
||||
|
||||
[super setFrameSize:aSize];
|
||||
|
||||
if (width !== CGRectGetWidth([self frame]))
|
||||
if (width !== _CGRectGetWidth([self frame]))
|
||||
[self _invalidateItemsStartingAtIndex:0];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
if (_items.length <= 0)
|
||||
return [self setFrameSize:CGSizeMake(CGRectGetWidth([self frame]), 0.0)];
|
||||
|
||||
return [self setFrameSize:_CGSizeMake(_CGRectGetWidth([self frame]), 0.0)];
|
||||
|
||||
if (_dirtyItemIndex === CPNotFound)
|
||||
return;
|
||||
|
||||
@@ -278,7 +243,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
|
||||
var index = _dirtyItemIndex,
|
||||
count = _itemViews.length,
|
||||
width = CGRectGetWidth([self bounds]),
|
||||
width = _CGRectGetWidth([self bounds]),
|
||||
y = index > 0 ? CGRectGetMaxY([_itemViews[index - 1] frame]) : 0.0;
|
||||
|
||||
// Do this now (instead of after looping), so that if we are made dirty again in the middle we don't blow this value away.
|
||||
@@ -293,7 +258,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
y = CGRectGetMaxY([itemView frame]);
|
||||
}
|
||||
|
||||
[self setFrameSize:CGSizeMake(CGRectGetWidth([self frame]), y)];
|
||||
[self setFrameSize:_CGSizeMake(_CGRectGetWidth([self frame]), y)];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -310,7 +275,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
|
||||
- (id)initWithAccordionView:(CPAccordionView)anAccordionView
|
||||
{
|
||||
self = [super initWithFrame:CGRectMakeZero()];
|
||||
self = [super initWithFrame:_CGRectMakeZero()];
|
||||
|
||||
if (self)
|
||||
{
|
||||
@@ -376,22 +341,22 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
|
||||
- (void)setFrameY:(float)aY width:(float)aWidth
|
||||
{
|
||||
var headerHeight = CGRectGetHeight([_headerView frame]);
|
||||
var headerHeight = _CGRectGetHeight([_headerView frame]);
|
||||
|
||||
// Size to fit or something?
|
||||
[_headerView setFrameSize:CGSizeMake(aWidth, headerHeight)];
|
||||
[_contentView setFrameOrigin:CGPointMake(0.0, headerHeight)];
|
||||
[_headerView setFrameSize:_CGSizeMake(aWidth, headerHeight)];
|
||||
[_contentView setFrameOrigin:_CGPointMake(0.0, headerHeight)];
|
||||
|
||||
if ([self isCollapsed])
|
||||
[self setFrame:CGRectMake(0.0, aY, aWidth, headerHeight)];
|
||||
[self setFrame:_CGRectMake(0.0, aY, aWidth, headerHeight)];
|
||||
|
||||
else
|
||||
{
|
||||
var contentHeight = CGRectGetHeight([_contentView frame]);
|
||||
var contentHeight = _CGRectGetHeight([_contentView frame]);
|
||||
|
||||
[_contentView setFrameSize:CGSizeMake(aWidth, contentHeight)];
|
||||
[self setFrame:CGRectMake(0.0, aY, aWidth, contentHeight + headerHeight)];
|
||||
}
|
||||
[_contentView setFrameSize:_CGSizeMake(aWidth, contentHeight)];
|
||||
[self setFrame:_CGRectMake(0.0, aY, aWidth, contentHeight + headerHeight)];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)resizeSubviewsWithOldSize:(CGSize)aSize
|
||||
@@ -408,7 +373,7 @@ var secondItem = [[CPAccordionViewItem alloc] initWithIdentifier:@"secondSection
|
||||
/*
|
||||
else if (aKeyPath === "itemHeaderPrototype")
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
+165
-713
File diff suppressed because it is too large
Load Diff
+84
-251
@@ -21,43 +21,41 @@
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPTimer.j>
|
||||
|
||||
@import "CAMediaTimingFunction.j"
|
||||
|
||||
|
||||
@protocol CPAnimationDelegate <CPObject>
|
||||
|
||||
@optional
|
||||
- (BOOL)animationShouldStart:(CPAnimation)animation;
|
||||
- (float)animation:(CPAnimation)animation valueForProgress:(float)progress;
|
||||
- (void)animationDidEnd:(CPAnimation)animation;
|
||||
- (void)animationDidStop:(CPAnimation)animation;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
var CPAnimationDelegate_animationShouldStart_ = 1 << 1,
|
||||
CPAnimationDelegate_animation_valueForProgress_ = 1 << 2,
|
||||
CPAnimationDelegate_animationDidEnd_ = 1 << 3,
|
||||
CPAnimationDelegate_animationDidStop_ = 1 << 4;
|
||||
|
||||
@typedef CPAnimationCurve
|
||||
/*
|
||||
@global
|
||||
@group CPAnimationCurve
|
||||
*/
|
||||
CPAnimationEaseInOut = 0;
|
||||
/*
|
||||
@global
|
||||
@group CPAnimationCurve
|
||||
*/
|
||||
CPAnimationEaseIn = 1;
|
||||
/*
|
||||
@global
|
||||
@group CPAnimationCurve
|
||||
*/
|
||||
CPAnimationEaseOut = 2;
|
||||
/*
|
||||
@global
|
||||
@group CPAnimationCurve
|
||||
*/
|
||||
CPAnimationLinear = 3;
|
||||
|
||||
ACTUAL_FRAME_RATE = 0;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPAnimation
|
||||
|
||||
Manages an animation. Contains timing and progress information.
|
||||
|
||||
@par Delegate Methods
|
||||
|
||||
|
||||
@delegate -(BOOL)animationShouldStart:(CPAnimation)animation;
|
||||
Called at the beginning of \c -startAnimation.
|
||||
@param animation the animation that will start
|
||||
@@ -81,18 +79,17 @@ ACTUAL_FRAME_RATE = 0;
|
||||
*/
|
||||
@implementation CPAnimation : CPObject
|
||||
{
|
||||
CPTimeInterval _lastTime;
|
||||
CPTimeInterval _duration;
|
||||
|
||||
CPAnimationCurve _animationCurve;
|
||||
CAMediaTimingFunction _timingFunction;
|
||||
|
||||
float _frameRate;
|
||||
float _progress;
|
||||
|
||||
id <CPAnimationDelegate> _delegate;
|
||||
CPTimer _timer;
|
||||
unsigned _implementedDelegateMethods;
|
||||
CPTimeInterval _lastTime;
|
||||
CPTimeInterval _duration;
|
||||
|
||||
CPAnimationCurve _animationCurve;
|
||||
CAMediaTimingFunction _timingFunction;
|
||||
|
||||
float _frameRate;
|
||||
float _progress;
|
||||
|
||||
id _delegate;
|
||||
CPTimer _timer;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -104,7 +101,7 @@ ACTUAL_FRAME_RATE = 0;
|
||||
- (id)initWithDuration:(float)aDuration animationCurve:(CPAnimationCurve)anAnimationCurve
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_progress = 0.0;
|
||||
@@ -113,43 +110,36 @@ ACTUAL_FRAME_RATE = 0;
|
||||
|
||||
[self setAnimationCurve:anAnimationCurve];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the animation's pace.
|
||||
@param anAnimationCurve the animation's pace
|
||||
@throws CPInvalidArgumentException if an invalid animation curve is specified
|
||||
@throws CPInvalidArgumentException if an invalid animation curve is specified
|
||||
*/
|
||||
- (void)setAnimationCurve:(CPAnimationCurve)anAnimationCurve
|
||||
{
|
||||
var timingFunctionName;
|
||||
|
||||
switch (anAnimationCurve)
|
||||
{
|
||||
case CPAnimationEaseInOut:
|
||||
timingFunctionName = kCAMediaTimingFunctionEaseInEaseOut;
|
||||
break;
|
||||
case CPAnimationEaseInOut: timingFunctionName = kCAMediaTimingFunctionEaseInEaseOut;
|
||||
break;
|
||||
|
||||
case CPAnimationEaseIn: timingFunctionName = kCAMediaTimingFunctionEaseIn;
|
||||
break;
|
||||
|
||||
case CPAnimationEaseOut: timingFunctionName = kCAMediaTimingFunctionEaseOut;
|
||||
break;
|
||||
|
||||
case CPAnimationLinear: timingFunctionName = kCAMediaTimingFunctionLinear;
|
||||
break;
|
||||
|
||||
case CPAnimationEaseIn:
|
||||
timingFunctionName = kCAMediaTimingFunctionEaseIn;
|
||||
break;
|
||||
|
||||
case CPAnimationEaseOut:
|
||||
timingFunctionName = kCAMediaTimingFunctionEaseOut;
|
||||
break;
|
||||
|
||||
case CPAnimationLinear:
|
||||
timingFunctionName = kCAMediaTimingFunctionLinear;
|
||||
break;
|
||||
|
||||
default:
|
||||
[CPException raise:CPInvalidArgumentException
|
||||
reason:@"Invalid value provided for animation curve"];
|
||||
break;
|
||||
default: [CPException raise:CPInvalidArgumentException
|
||||
reason:"Invalid value provided for animation curve"];
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
_animationCurve = anAnimationCurve;
|
||||
_timingFunction = [CAMediaTimingFunction functionWithName:timingFunctionName];
|
||||
}
|
||||
@@ -171,7 +161,7 @@ ACTUAL_FRAME_RATE = 0;
|
||||
{
|
||||
if (aDuration < 0)
|
||||
[CPException raise:CPInvalidArgumentException reason:"aDuration can't be negative"];
|
||||
|
||||
|
||||
_duration = aDuration;
|
||||
}
|
||||
|
||||
@@ -192,7 +182,7 @@ ACTUAL_FRAME_RATE = 0;
|
||||
{
|
||||
if (frameRate < 0)
|
||||
[CPException raise:CPInvalidArgumentException reason:"frameRate can't be negative"];
|
||||
|
||||
|
||||
_frameRate = frameRate;
|
||||
}
|
||||
|
||||
@@ -216,25 +206,9 @@ ACTUAL_FRAME_RATE = 0;
|
||||
Sets the animation's delegate.
|
||||
@param aDelegate the new delegate
|
||||
*/
|
||||
- (void)setDelegate:(id <CPAnimationDelegate>)aDelegate
|
||||
- (void)setDelegate:(id)aDelegate
|
||||
{
|
||||
if (_delegate === aDelegate)
|
||||
return;
|
||||
|
||||
_delegate = aDelegate;
|
||||
_implementedDelegateMethods = 0;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animationShouldStart:)])
|
||||
_implementedDelegateMethods |= CPAnimationDelegate_animationShouldStart_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animationDidEnd:)])
|
||||
_implementedDelegateMethods |= CPAnimationDelegate_animationDidEnd_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animationDidStop:)])
|
||||
_implementedDelegateMethods |= CPAnimationDelegate_animationDidStop_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animation:valueForProgress:)])
|
||||
_implementedDelegateMethods |= CPAnimationDelegate_animation_valueForProgress_;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -245,18 +219,16 @@ ACTUAL_FRAME_RATE = 0;
|
||||
- (void)startAnimation
|
||||
{
|
||||
// If we're already animating, or our delegate stops us, animate.
|
||||
if (_timer || ![self _sendDelegateAnimationShouldStart])
|
||||
if (_timer || _delegate && [_delegate respondsToSelector:@selector(animationShouldStart:)] && ![_delegate animationShouldStart:self])
|
||||
return;
|
||||
|
||||
|
||||
if (_progress === 1.0)
|
||||
_progress = 0.0;
|
||||
|
||||
|
||||
ACTUAL_FRAME_RATE = 0;
|
||||
_lastTime = new Date();
|
||||
|
||||
var timerInterval = _frameRate <= 0.0 ? 0.0001 : 1.0 / _frameRate;
|
||||
|
||||
_timer = [CPTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:@selector(animationTimerDidFire:) userInfo:nil repeats:YES];
|
||||
|
||||
_timer = [CPTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(animationTimerDidFire:) userInfo:nil repeats:YES];
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -270,15 +242,16 @@ ACTUAL_FRAME_RATE = 0;
|
||||
_lastTime = currentTime;
|
||||
|
||||
++ACTUAL_FRAME_RATE;
|
||||
|
||||
|
||||
[self setCurrentProgress:progress];
|
||||
|
||||
|
||||
if (progress === 1.0)
|
||||
{
|
||||
[_timer invalidate];
|
||||
_timer = nil;
|
||||
|
||||
[self _sendDelegateAnimationDidEnd];
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animationDidEnd:)])
|
||||
[_delegate animationDidEnd:self];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,11 +262,12 @@ ACTUAL_FRAME_RATE = 0;
|
||||
{
|
||||
if (!_timer)
|
||||
return;
|
||||
|
||||
|
||||
[_timer invalidate];
|
||||
_timer = nil;
|
||||
|
||||
[self _sendDelegateAnimationDidStop];
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animationDidStop:)])
|
||||
[_delegate animationDidStop:self];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -328,82 +302,17 @@ ACTUAL_FRAME_RATE = 0;
|
||||
- (float)currentValue
|
||||
{
|
||||
var t = [self currentProgress];
|
||||
|
||||
if ([self _delegateRespondsToAnimationValueForProgress])
|
||||
return [self _sendDelegateAnimationValueForProgress:t];
|
||||
|
||||
if (_animationCurve == CPAnimationLinear)
|
||||
return t;
|
||||
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(animation:valueForProgress:)])
|
||||
return [_delegate animation:self valueForProgress:t];
|
||||
|
||||
var c1 = [],
|
||||
c2 = [];
|
||||
|
||||
|
||||
[_timingFunction getControlPointAtIndex:1 values:c1];
|
||||
[_timingFunction getControlPointAtIndex:2 values:c2];
|
||||
|
||||
return CubicBezierAtTime(t, c1[0], c1[1], c2[0], c2[1], _duration);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation CPAnimation (CPAnimationDelegate)
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Check if the delegate responds to animation:valueForProgress:
|
||||
*/
|
||||
- (BOOL)_delegateRespondsToAnimationValueForProgress
|
||||
{
|
||||
return _implementedDelegateMethods & CPAnimationDelegate_animation_valueForProgress_;
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate animationShouldStart:
|
||||
*/
|
||||
- (BOOL)_sendDelegateAnimationShouldStart
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPAnimationDelegate_animationShouldStart_))
|
||||
return YES;
|
||||
|
||||
return [_delegate animationShouldStart:self];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate animation:valueForProgress:
|
||||
*/
|
||||
- (float)_sendDelegateAnimationValueForProgress:(float)aProgress
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPAnimationDelegate_animation_valueForProgress_))
|
||||
return aProgress;
|
||||
|
||||
return [_delegate animation:self valueForProgress:aProgress];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate animationDidEnd:
|
||||
*/
|
||||
- (void)_sendDelegateAnimationDidEnd
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPAnimationDelegate_animationDidEnd_))
|
||||
return;
|
||||
|
||||
[_delegate animationDidEnd:self];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate animationDidStop:
|
||||
*/
|
||||
- (void)_sendDelegateAnimationDidStop
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPAnimationDelegate_animationDidStop_))
|
||||
return;
|
||||
|
||||
[_delegate animationDidStop:self];
|
||||
|
||||
return CubicBezierAtTime(t,c1[0],c1[1],c2[0],c2[1],_duration);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -411,104 +320,28 @@ 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(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 = x,
|
||||
x2,
|
||||
d2,
|
||||
i = 0;
|
||||
|
||||
function solveCurveX(x,epsilon) {var t0,t1,t2,x2,d2,i;
|
||||
function fabs(n) {if(n>=0) {return n;}else {return 0-n;}};
|
||||
// First try a few iterations of Newton's method -- normally very fast.
|
||||
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;
|
||||
}
|
||||
|
||||
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;}
|
||||
// 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 (ABS(x2 - x) < epsilon)
|
||||
return t2;
|
||||
|
||||
if (x > x2)
|
||||
t0 = t2;
|
||||
|
||||
else
|
||||
t1 = t2;
|
||||
|
||||
t2 = (t1 - t0) * 0.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(fabs(x2-x)<epsilon) {return t2;} if(x>x2) {t0=t2;}else {t1=t2;} t2=(t1-t0)*.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,162 +0,0 @@
|
||||
/*
|
||||
* CPAppearance.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Antoine Mercadal.
|
||||
* Copyright 2015, Cappuccino Project.
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
@import "CPTheme.j"
|
||||
|
||||
CPAppearanceNameAqua = @"CPAppearanceNameAqua";
|
||||
CPAppearanceNameLightContent = @"CPAppearanceNameLightContent";
|
||||
CPAppearanceNameVibrantDark = @"CPAppearanceNameVibrantDark";
|
||||
CPAppearanceNameVibrantLight = @"CPAppearanceNameVibrantLight";
|
||||
|
||||
var _CPAppearanceCurrent = nil,
|
||||
_CPAppearancesRegistry = @{};
|
||||
|
||||
|
||||
@protocol CPAppearanceCustomization <CPObject>
|
||||
|
||||
@required
|
||||
- (CPAppearance)appearance;
|
||||
- (void)setAppearance:(CPAppearance)appearance;
|
||||
- (CPAppearance)effectiveAppearance;
|
||||
- (void)setEffectiveAppearance:(CPAppearance)appearance;
|
||||
|
||||
@end
|
||||
|
||||
CPThemeStateAppearanceAqua = CPThemeState("appearance-aqua");
|
||||
CPThemeStateAppearanceLightContent = CPThemeState("appearance-light-content");
|
||||
CPThemeStateAppearanceVibrantLight = CPThemeState("appearance-vibrant-light");
|
||||
CPThemeStateAppearanceVibrantDark = CPThemeState("appearance-vibrant-dark");
|
||||
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
|
||||
A CPAppareance represents the appearance of an to a subset of UI elements.
|
||||
This is a very lightweight implementation of the NSAppearance system, but
|
||||
We are using it for compliance, and especially for the CPVisualEffectView
|
||||
*/
|
||||
@implementation CPAppearance : CPObject
|
||||
{
|
||||
BOOL _allowsVibrancy @accessors(property=allowsVibrancy);
|
||||
|
||||
CPString _name;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Class Methods
|
||||
|
||||
/*! Returns the current default CPAppearance
|
||||
*/
|
||||
+ (CPAppearance)currentAppearance
|
||||
{
|
||||
if (!_CPAppearanceCurrent)
|
||||
_CPAppearanceCurrent = [CPAppearance appearanceNamed:CPAppearanceNameAqua];
|
||||
|
||||
return _CPAppearanceCurrent;
|
||||
}
|
||||
|
||||
/*! Sets the current default CPAppearance
|
||||
@param appearance the new current appearance
|
||||
*/
|
||||
+ (void)setCurrentAppearance:(CPAppearance)anAppearance
|
||||
{
|
||||
_CPAppearanceCurrent = anAppearance;
|
||||
}
|
||||
|
||||
/*! Returns the CPAppearance object with the given name
|
||||
@param name the name of the appearance
|
||||
*/
|
||||
+ (CPAppearance)appearanceNamed:(CPString)aName
|
||||
{
|
||||
if (![_CPAppearancesRegistry containsKey:aName])
|
||||
{
|
||||
[_CPAppearancesRegistry setObject:[[CPAppearance alloc] initWithAppearanceNamed:aName bundle:nil]
|
||||
forKey:aName];
|
||||
}
|
||||
|
||||
return [_CPAppearancesRegistry objectForKey:aName];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Initialization
|
||||
|
||||
/*! Creates a CPAppearance object initialized to the specified appearance file in the specified bundle
|
||||
This method does actually nothing special. It just creates a default appearance object
|
||||
*/
|
||||
- (id)initWithAppearanceNamed:(CPString)aName bundle:(CPBundle)bundle
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_name = aName;
|
||||
_allowsVibrancy = YES;
|
||||
|
||||
if ([_CPAppearancesRegistry containsKey:aName])
|
||||
[CPException raise:CPInternalInconsistencyException reason:"Appearance with name '" + aName + "' is already declared."];
|
||||
|
||||
[_CPAppearancesRegistry setObject:self forKey:aName];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Implementation
|
||||
|
||||
- (BOOL)isEqual:(id)anObject
|
||||
{
|
||||
if (![anObject isKindOfClass:CPAppearance])
|
||||
return NO;
|
||||
|
||||
return self._name == anObject._name;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return @"<CPAppearance @" + [self UID] + @" name: " + _name + ">";
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark CPCoding
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_name = [aCoder decodeObjectForKey:@"_name"];
|
||||
_allowsVibrancy = [aCoder decodeBoolForKey:@"_allowsVibrancy"];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[aCoder encodeObject:_name forKey:@"_name"];
|
||||
[aCoder encodeBool:_allowsVibrancy forKey:@"_allowsVibrancy"];
|
||||
}
|
||||
|
||||
@end
|
||||
+344
-611
File diff suppressed because it is too large
Load Diff
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* CPApplication_Constants.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Aparajita Fishman.
|
||||
* Copyright 2013 The Cappuccino Project
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
|
||||
CPApp = nil;
|
||||
|
||||
CPApplicationWillFinishLaunchingNotification = @"CPApplicationWillFinishLaunchingNotification";
|
||||
CPApplicationDidFinishLaunchingNotification = @"CPApplicationDidFinishLaunchingNotification";
|
||||
CPApplicationWillTerminateNotification = @"CPApplicationWillTerminateNotification";
|
||||
CPApplicationWillBecomeActiveNotification = @"CPApplicationWillBecomeActiveNotification";
|
||||
CPApplicationDidBecomeActiveNotification = @"CPApplicationDidBecomeActiveNotification";
|
||||
CPApplicationWillResignActiveNotification = @"CPApplicationWillResignActiveNotification";
|
||||
CPApplicationDidResignActiveNotification = @"CPApplicationDidResignActiveNotification";
|
||||
CPApplicationDidChangeScreenParametersNotification = @"CPApplicationDidChangeScreenParametersNotification";
|
||||
|
||||
@typedef CPApplicationTerminateReply
|
||||
CPTerminateNow = YES;
|
||||
CPTerminateCancel = NO;
|
||||
CPTerminateLater = -1; // not currently supported
|
||||
|
||||
CPRunStoppedResponse = -1000;
|
||||
CPRunAbortedResponse = -1001;
|
||||
CPRunContinuesResponse = -1002;
|
||||
File diff suppressed because it is too large
Load Diff
+17
-106
@@ -4,7 +4,7 @@
|
||||
* Created by Ross Boucher.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* Adapted from Kevin Wojniak, portions Copyright 2009 Kevin Wojniak.
|
||||
* Adapted from Kevin Wojniak, portions Copyright 2009 Kevin Wojniak.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
@@ -20,26 +20,26 @@
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
* Copyright 2009 280 North, Inc.
|
||||
|
||||
*/
|
||||
|
||||
@import <AppKit/CPGraphicsContext.j>
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
@import "CPGraphicsContext.j"
|
||||
|
||||
|
||||
// Class defaults
|
||||
|
||||
var DefaultLineWidth = 1.0;
|
||||
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPBezierPath
|
||||
|
||||
A CPBezierPath allows you to create paths for drawing to the screen using a simpler API than CoreGraphics.
|
||||
Paths can form any shape, including regular polygons like squares and triangles; circles, arcs; or complex
|
||||
line segments.
|
||||
|
||||
Paths can form any shape, including regular polgyons like squares and triangles; circles, arcs; or complex
|
||||
line segments.
|
||||
|
||||
A path can be stroked and filled using the relevant method. The currently active fill and stroke color will
|
||||
be used, which can be set by calling setFill: and setStroke: on any CPColor object (or set: for both).
|
||||
*/
|
||||
@@ -48,8 +48,6 @@ var DefaultLineWidth = 1.0;
|
||||
{
|
||||
CGPath _path;
|
||||
float _lineWidth;
|
||||
CPArray _lineDashes;
|
||||
float _lineDashesPhase;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -63,33 +61,24 @@ var DefaultLineWidth = 1.0;
|
||||
/*!
|
||||
Create a new CPBezierPath object initialized with an oval path drawn within a rectangular path.
|
||||
*/
|
||||
+ (CPBezierPath)bezierPathWithOvalInRect:(CGRect)aRect
|
||||
+ (CPBezierPath)bezierPathWithOvalInRect:(CGRect)rect
|
||||
{
|
||||
var path = [self bezierPath];
|
||||
|
||||
[path appendBezierPathWithOvalInRect:aRect];
|
||||
|
||||
|
||||
[path appendBezierPathWithOvalInRect:rect];
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/*!
|
||||
Create a new CPBezierPath object initialized with a rectangular path.
|
||||
*/
|
||||
+ (CPBezierPath)bezierPathWithRect:(CGRect)aRect
|
||||
+ (CPBezierPath)bezierPathWithRect:(CGRect)rect
|
||||
{
|
||||
var path = [self bezierPath];
|
||||
|
||||
[path appendBezierPathWithRect:aRect];
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
+ (CPBezierPath)bezierPathWithRoundedRect:(CGRect)aRect xRadius:(float)xRadius yRadius:(float)yRadius
|
||||
{
|
||||
var path = [self bezierPath];
|
||||
|
||||
[path appendBezierPathWithRoundedRect:aRect xRadius:xRadius yRadius:yRadius];
|
||||
|
||||
|
||||
[path appendBezierPathWithRect:rect];
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -147,8 +136,6 @@ var DefaultLineWidth = 1.0;
|
||||
{
|
||||
_path = CGPathCreateMutable();
|
||||
_lineWidth = [[self class] defaultLineWidth];
|
||||
_lineDashesPhase = 0;
|
||||
_lineDashes = [];
|
||||
}
|
||||
|
||||
return self;
|
||||
@@ -178,19 +165,6 @@ var DefaultLineWidth = 1.0;
|
||||
CGPathAddCurveToPoint(_path, nil, controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, endPoint.x, endPoint.y);
|
||||
}
|
||||
|
||||
- (CGRect)bounds
|
||||
{
|
||||
// TODO: this should return this. The controlPointBounds is not a tight fit.
|
||||
// return CGPathGetBoundingBox(_path);
|
||||
|
||||
return [self controlPointBounds];
|
||||
}
|
||||
|
||||
- (CGRect)controlPointBounds
|
||||
{
|
||||
return CGPathGetBoundingBox(_path);
|
||||
}
|
||||
|
||||
/*!
|
||||
Create a line segment between the first and last points in the subpath, closing it.
|
||||
*/
|
||||
@@ -209,7 +183,7 @@ var DefaultLineWidth = 1.0;
|
||||
CGContextBeginPath(ctx);
|
||||
CGContextAddPath(ctx, _path);
|
||||
CGContextSetLineWidth(ctx, [self lineWidth]);
|
||||
CGContextSetLineDash(ctx, _lineDashesPhase, _lineDashes);
|
||||
CGContextClosePath(ctx);
|
||||
CGContextStrokePath(ctx);
|
||||
}
|
||||
|
||||
@@ -223,50 +197,10 @@ var DefaultLineWidth = 1.0;
|
||||
CGContextBeginPath(ctx);
|
||||
CGContextAddPath(ctx, _path);
|
||||
CGContextSetLineWidth(ctx, [self lineWidth]);
|
||||
CGContextSetLineDash(ctx, _lineDashesPhase, _lineDashes);
|
||||
CGContextClosePath(ctx);
|
||||
CGContextFillPath(ctx);
|
||||
}
|
||||
|
||||
/*!
|
||||
Cocoa compatibility.
|
||||
*/
|
||||
- (void)getLineDash:(CPArrayRef)patternRef count:(CPInteger)count phase:(CGFloatRef)phaseRef
|
||||
{
|
||||
return [self getLineDash:patternRef phase:phaseRef];
|
||||
}
|
||||
|
||||
/*!
|
||||
Retrieve the line dash pattern and phase and write them into the provided references.
|
||||
*/
|
||||
- (void)getLineDash:(CPArrayRef)patternRef phase:(CGFloatRef)phaseRef
|
||||
{
|
||||
if (patternRef)
|
||||
@deref(patternRef) = [_lineDashes copy];
|
||||
if (phaseRef)
|
||||
@deref(phaseRef) = _lineDashesPhase;
|
||||
}
|
||||
|
||||
/*!
|
||||
Cocoa compatibility.
|
||||
*/
|
||||
- (void)setLineDash:(CPArray)aPattern count:(CPInteger)count phase:(CGFloat)aPhase
|
||||
{
|
||||
[self setLineDash:aPattern phase:aPhase];
|
||||
}
|
||||
|
||||
/*!
|
||||
Set stroke line dash pattern.
|
||||
|
||||
@param aPattern an array of stroke-skip lengths such as [2, 2, 4, 4]
|
||||
@param aPhase amount of shift for the starting position of the first stroke
|
||||
*/
|
||||
- (void)setLineDash:(CPArray)aPattern phase:(CGFloat)aPhase
|
||||
{
|
||||
_lineDashes = aPattern;
|
||||
_lineDashesPhase = aPhase;
|
||||
}
|
||||
|
||||
/*!
|
||||
Get the line width.
|
||||
*/
|
||||
@@ -339,19 +273,13 @@ var DefaultLineWidth = 1.0;
|
||||
CGPathAddPath(_path, nil, CGPathWithRoundedRectangleInRect(rect, xRadius, yRadius, YES, YES, YES, YES));
|
||||
}
|
||||
|
||||
- (void)appendBezierPathWithArcFromPoint:(CGPoint)fromPoint toPoint:(CGPoint)toPoint radius:(float)radius
|
||||
{
|
||||
CGPathAddArcToPoint(_path, null, fromPoint.x, fromPoint.y, toPoint.x, toPoint.y, radius);
|
||||
}
|
||||
|
||||
/*!
|
||||
Append the contents of a CPBezierPath object.
|
||||
*/
|
||||
- (void)appendBezierPath:(CPBezierPath)other
|
||||
- (void)appendBezierPath:(NSBezierPath *)other
|
||||
{
|
||||
CGPathAddPath(_path, nil, other._path);
|
||||
}
|
||||
|
||||
/*!
|
||||
Remove all path elements; clears path.
|
||||
*/
|
||||
@@ -360,21 +288,4 @@ var DefaultLineWidth = 1.0;
|
||||
_path = CGPathCreateMutable();
|
||||
}
|
||||
|
||||
- (void)addClip
|
||||
{
|
||||
var ctx = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
CGContextAddPath(ctx, _path);
|
||||
CGContextClip(ctx);
|
||||
}
|
||||
|
||||
- (void)setClip
|
||||
{
|
||||
var ctx = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
CGContextBeginPath(ctx);
|
||||
CGContextAddPath(ctx, _path);
|
||||
CGContextClip(ctx);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+98
-806
File diff suppressed because it is too large
Load Diff
+178
-474
@@ -20,156 +20,102 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPIndexSet.j>
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "CPImage.j"
|
||||
@import "CPScrollView.j"
|
||||
@import "CPTableView.j"
|
||||
@import "CPTextField.j"
|
||||
@import "CPScrollView.j"
|
||||
|
||||
@global CPApp
|
||||
|
||||
@protocol CPBrowserDelegate <CPObject>
|
||||
|
||||
@optional
|
||||
- (BOOL)browser:(CPBrowser)browser acceptDrop:(id)info atRow:(CPInteger)row column:(CPInteger)column dropOperation:(CPTableViewDropOperation)dropOperation;
|
||||
- (BOOL)browser:(CPBrowser)browser canDragRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)column withEvent:(CPEvent )event;
|
||||
- (BOOL)browser:(CPBrowser)browser isLeafItem:(id)item;
|
||||
- (BOOL)browser:(CPBrowser)browser shouldSelectRowIndexes:(CPIndexSet)anIndexSet inColumn:(CPInteger)column;
|
||||
- (BOOL)browser:(CPBrowser)browser writeRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)column toPasteboard:(CPPasteboard)pasteboard;
|
||||
- (CPDragOperation)browser:(CPBrowser)browser validateDrop:(id)info proposedRow:(CPInteger)row column:(CPInteger)column dropOperation:(CPTableViewDropOperation)dropOperation;
|
||||
- (CPImage)browser:(CPBrowser)browser imageValueForItem:(id)anItem;
|
||||
- (CPImage)browser:(CPBrowser)browser draggingImageForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)column withEvent:(CPEvent)event offset:(CGPoint)dragImageOffset;
|
||||
- (CPIndexSet)browser:(CPBrowser)browser selectionIndexesForProposedSelection:(CPIndexSet)proposedSelectionIndexes inColumn:(CPInteger)column;
|
||||
- (CPInteger)browser:(CPBrowser)browser numberOfChildrenOfItem:(id)item;
|
||||
- (CPView)browser:(CPBrowser)browser draggingViewForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)column withEvent:(CPEvent)event offset:(CGPoint)dragImageOffset;
|
||||
- (id)browser:(CPBrowser)browser child:(CPInteger)index ofItem:(id)item;
|
||||
- (id)browser:(CPBrowser)browser objectValueForItem:(id)item;
|
||||
- (id)rootItemForBrowser:(CPBrowser)browser;
|
||||
- (void)browser:(CPBrowser)browser didChangeLastColumn:(CPInteger)oldLastColumn toColumn:(CPInteger)column;
|
||||
- (void)browser:(CPBrowser)browser didResizeColumn:(CPInteger)column;
|
||||
- (void)browserSelectionIsChanging:(CPBrowser)browser;
|
||||
- (void)browserSelectionDidChange:(CPBrowser)browser;
|
||||
|
||||
@end
|
||||
|
||||
var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_ = 1 << 1,
|
||||
CPBrowserDelegate_browser_canDragRowsWithIndexes_inColumn_withEvent_ = 1 << 2,
|
||||
CPBrowserDelegate_browser_isLeafItem_ = 1 << 3,
|
||||
CPBrowserDelegate_browser_shouldSelectRowIndexes_inColumn_ = 1 << 4,
|
||||
CPBrowserDelegate_browser_writeRowsWithIndexes_inColumn_toPasteboard_ = 1 << 5,
|
||||
CPBrowserDelegate_browser_validateDrop_proposedRow_column_dropOperation_ = 1 << 6,
|
||||
CPBrowserDelegate_browser_draggingImageForRowsWithIndexes_inColumn_withEvent_offset_ = 1 << 7,
|
||||
CPBrowserDelegate_browser_imageValueForItem_ = 1 << 8,
|
||||
CPBrowserDelegate_browser_selectionIndexesForProposedSelection_inColumn_ = 1 << 9,
|
||||
CPBrowserDelegate_browser_numberOfChildrenOfItem_ = 1 << 10,
|
||||
CPBrowserDelegate_browser_draggingViewForRowsWithIndexes_inColumn_withEvent_offset_ = 1 << 11,
|
||||
CPBrowserDelegate_browser_child_ofItem_ = 1 << 12,
|
||||
CPBrowserDelegate_browser_objectValueForItem_ = 1 << 13,
|
||||
CPBrowserDelegate_rootItemForBrowser_ = 1 << 14,
|
||||
CPBrowserDelegate_browser_didChangeLastColumn_toColumn_ = 1 << 15,
|
||||
CPBrowserDelegate_browser_didResizeColumn_ = 1 << 16,
|
||||
CPBrowserDelegate_browserSelectionIsChanging_ = 1 << 17,
|
||||
CPBrowserDelegate_browserSelectionDidChange_ = 1 << 18;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPBrowser
|
||||
@class CPBrowser
|
||||
*/
|
||||
|
||||
@implementation CPBrowser : CPControl
|
||||
{
|
||||
id <CPBrowserDelegate> _delegate;
|
||||
CPString _pathSeparator;
|
||||
unsigned _implementedDelegateMethods;
|
||||
id _delegate;
|
||||
CPString _pathSeparator;
|
||||
|
||||
CPView _contentView;
|
||||
CPScrollView _horizontalScrollView;
|
||||
CPView _prototypeView;
|
||||
CPView _contentView;
|
||||
CPScrollView _horizontalScrollView;
|
||||
CPView _prototypeView;
|
||||
|
||||
CPArray _tableViews;
|
||||
CPArray _tableDelegates;
|
||||
CPArray _tableViews;
|
||||
CPArray _tableDelegates;
|
||||
|
||||
id _rootItem;
|
||||
id _rootItem;
|
||||
|
||||
BOOL _delegateSupportsImages;
|
||||
BOOL _delegateSupportsImages;
|
||||
|
||||
SEL _doubleAction @accessors(property=doubleAction);
|
||||
SEL _doubleAction @accessors(property=doubleAction);
|
||||
|
||||
BOOL _allowsMultipleSelection;
|
||||
BOOL _allowsEmptySelection;
|
||||
BOOL _allowsMultipleSelection;
|
||||
BOOL _allowsEmptySelection;
|
||||
|
||||
Class _tableViewClass @accessors(property=tableViewClass);
|
||||
Class _tableViewClass @accessors(property=tableViewClass);
|
||||
|
||||
float _rowHeight;
|
||||
float _imageWidth;
|
||||
float _leafWidth;
|
||||
float _minColumnWidth;
|
||||
float _defaultColumnWidth @accessors(property=defaultColumnWidth);
|
||||
float _rowHeight;
|
||||
float _imageWidth;
|
||||
float _leafWidth;
|
||||
float _minColumnWidth;
|
||||
float _defaultColumnWidth @accessors(property=defaultColumnWidth);
|
||||
|
||||
CPArray _columnWidths;
|
||||
CPArray _columnWidths;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (CPImage)branchImage
|
||||
{
|
||||
return "browser";
|
||||
return [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[self class]]
|
||||
pathForResource:"browser-leaf.png"]
|
||||
size:CGSizeMake(9,9)];
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
+ (CPImage)highlightedBranchImage
|
||||
{
|
||||
return @{
|
||||
@"image-control-resize": [CPNull null],
|
||||
@"image-control-leaf": [CPNull null],
|
||||
@"image-control-leaf-pressed": [CPNull null]
|
||||
};
|
||||
return [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[self class]]
|
||||
pathForResource:"browser-leaf-highlighted.png"]
|
||||
size:CGSizeMake(9,9)];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
[self _init];
|
||||
_rowHeight = 23.0;
|
||||
_defaultColumnWidth = 140.0;
|
||||
_minColumnWidth = 80.0;
|
||||
_imageWidth = 23.0;
|
||||
_leafWidth = 13.0;
|
||||
_columnWidths = [];
|
||||
|
||||
_pathSeparator = "/";
|
||||
_tableViews = [];
|
||||
_tableDelegates = [];
|
||||
_allowsMultipleSelection = YES;
|
||||
_allowsEmptySelection = YES;
|
||||
_tableViewClass = [_CPBrowserTableView class];
|
||||
|
||||
_prototypeView = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
|
||||
[_prototypeView setVerticalAlignment:CPCenterVerticalTextAlignment];
|
||||
[_prototypeView setValue:[CPColor whiteColor] forThemeAttribute:"text-color" inState:CPThemeStateSelected];
|
||||
[_prototypeView setLineBreakMode:CPLineBreakByTruncatingTail];
|
||||
|
||||
_horizontalScrollView = [[CPScrollView alloc] initWithFrame:[self bounds]];
|
||||
|
||||
[_horizontalScrollView setHasVerticalScroller:NO];
|
||||
[_horizontalScrollView setAutohidesScrollers:YES];
|
||||
[_horizontalScrollView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
|
||||
|
||||
_contentView = [[CPView alloc] initWithFrame:CGRectMake(0, 0, 0, CGRectGetHeight([self bounds]))];
|
||||
[_contentView setAutoresizingMask:CPViewHeightSizable];
|
||||
|
||||
[_horizontalScrollView setDocumentView:_contentView];
|
||||
|
||||
[self addSubview:_horizontalScrollView];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_init
|
||||
{
|
||||
_rowHeight = 23.0;
|
||||
_defaultColumnWidth = 140.0;
|
||||
_minColumnWidth = 80.0;
|
||||
_imageWidth = 23.0;
|
||||
_leafWidth = 13.0;
|
||||
_columnWidths = [];
|
||||
|
||||
_pathSeparator = "/";
|
||||
_tableViews = [];
|
||||
_tableDelegates = [];
|
||||
_allowsMultipleSelection = YES;
|
||||
_allowsEmptySelection = YES;
|
||||
_tableViewClass = [_CPBrowserTableView class];
|
||||
|
||||
_prototypeView = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
|
||||
[_prototypeView setVerticalAlignment:CPCenterVerticalTextAlignment];
|
||||
[_prototypeView setValue:[CPColor whiteColor] forThemeAttribute:"text-color" inState:CPThemeStateSelectedDataView];
|
||||
[_prototypeView setLineBreakMode:CPLineBreakByTruncatingTail];
|
||||
|
||||
_horizontalScrollView = [[CPScrollView alloc] initWithFrame:[self bounds]];
|
||||
|
||||
[_horizontalScrollView setHasVerticalScroller:NO];
|
||||
[_horizontalScrollView setAutohidesScrollers:YES];
|
||||
[_horizontalScrollView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
|
||||
|
||||
_contentView = [[CPView alloc] initWithFrame:CGRectMake(0, 0, 0, CGRectGetHeight([self bounds]))];
|
||||
[_contentView setAutoresizingMask:CPViewHeightSizable];
|
||||
|
||||
[_horizontalScrollView setDocumentView:_contentView];
|
||||
|
||||
[self addSubview:_horizontalScrollView];
|
||||
}
|
||||
|
||||
- (void)setPrototypeView:(CPView)aPrototypeView
|
||||
{
|
||||
_prototypeView = [CPKeyedUnarchiver unarchiveObjectWithData:
|
||||
@@ -182,71 +128,10 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[CPKeyedArchiver archivedDataWithRootObject:_prototypeView]];
|
||||
}
|
||||
|
||||
- (void)setDelegate:(id <CPBrowserDelegate>)anObject
|
||||
{
|
||||
if (_delegate === anObject)
|
||||
return;
|
||||
|
||||
- (void)setDelegate:(id)anObject
|
||||
{
|
||||
_delegate = anObject;
|
||||
_implementedDelegateMethods = 0;
|
||||
_delegateSupportsImages = NO;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:acceptDrop:atRow:column:dropOperation:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:canDragRowsWithIndexes:inColumn:withEvent:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_canDragRowsWithIndexes_inColumn_withEvent_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:isLeafItem:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_isLeafItem_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:shouldSelectRowIndexes:inColumn:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_shouldSelectRowIndexes_inColumn_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:writeRowsWithIndexes:inColumn:toPasteboard:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_writeRowsWithIndexes_inColumn_toPasteboard_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:validateDrop:proposedRow:column:dropOperation:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_validateDrop_proposedRow_column_dropOperation_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:draggingImageForRowsWithIndexes:inColumn:withEvent:offset:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_draggingImageForRowsWithIndexes_inColumn_withEvent_offset_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:imageValueForItem:)])
|
||||
{
|
||||
_delegateSupportsImages = YES;
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_imageValueForItem_;
|
||||
}
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:selectionIndexesForProposedSelection:inColumn:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_selectionIndexesForProposedSelection_inColumn_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:numberOfChildrenOfItem:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_numberOfChildrenOfItem_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:draggingViewForRowsWithIndexes:inColumn:withEvent:offset:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_draggingViewForRowsWithIndexes_inColumn_withEvent_offset_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:child:ofItem:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_child_ofItem_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:objectValueForItem:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_objectValueForItem_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(rootItemForBrowser:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_rootItemForBrowser_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:didChangeLastColumn:toColumn:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_didChangeLastColumn_toColumn_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browser:didChangeLastColumn:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browser_didResizeColumn_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browserSelectionIsChanging:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browserSelectionIsChanging_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(browserSelectionDidChange:)])
|
||||
_implementedDelegateMethods |= CPBrowserDelegate_browserSelectionDidChange_;
|
||||
_delegateSupportsImages = [_delegate respondsToSelector:@selector(browser:imageValueForItem:)];
|
||||
|
||||
[self loadColumnZero];
|
||||
}
|
||||
@@ -268,32 +153,33 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
|
||||
- (void)loadColumnZero
|
||||
{
|
||||
_rootItem = [self _sendDelegateRootItemForBrowser];
|
||||
if ([_delegate respondsToSelector:@selector(rootItemForBrowser:)])
|
||||
_rootItem = [_delegate rootItemForBrowser:self];
|
||||
else
|
||||
_rootItem = nil;
|
||||
|
||||
[self setLastColumn:-1];
|
||||
[self addColumn];
|
||||
}
|
||||
|
||||
- (void)setLastColumn:(CPInteger)columnIndex
|
||||
- (void)setLastColumn:(int)columnIndex
|
||||
{
|
||||
if (columnIndex >= _tableViews.length)
|
||||
return;
|
||||
|
||||
var oldValue = _tableViews.length - 1,
|
||||
indexPlusOne = columnIndex + 1; // unloads all later columns.
|
||||
var oldValue = _tableViews.length - 1;
|
||||
|
||||
if (columnIndex > 0)
|
||||
[_tableViews[columnIndex - 1] setNeedsDisplay:YES];
|
||||
// unloads all later columns.
|
||||
var indexPlusOne = columnIndex + 1;
|
||||
|
||||
[_tableViews[columnIndex] setNeedsDisplay:YES];
|
||||
|
||||
[[_tableViews.slice(indexPlusOne) valueForKey:"enclosingScrollView"]
|
||||
[[_tableViews.slice(indexPlusOne) valueForKey:"enclosingScrollView"]
|
||||
makeObjectsPerformSelector:@selector(removeFromSuperview)];
|
||||
|
||||
_tableViews = _tableViews.slice(0, indexPlusOne);
|
||||
_tableDelegates = _tableDelegates.slice(0, indexPlusOne);
|
||||
|
||||
[self _sendDelegateBrowserDidChangeLastColumn:oldValue toColumn:columnIndex];
|
||||
if ([_delegate respondsToSelector:@selector(browser:didChangeLastColumn:toColumn:)])
|
||||
[_delegate browser:self didChangeLastColumn:oldValue toColumn:columnIndex];
|
||||
|
||||
[self tile];
|
||||
}
|
||||
@@ -310,10 +196,10 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
selectionIndexes = [lastColumn selectedRowIndexes];
|
||||
|
||||
if (lastIndex >= 0 && [selectionIndexes count] > 1)
|
||||
[CPException raise:CPInvalidArgumentException
|
||||
[CPException raise:CPInvalidArgumentException
|
||||
reason:"Can't add column, column "+lastIndex+" has invalid selection."];
|
||||
|
||||
var index = lastIndex + 1,
|
||||
var index = lastIndex+1,
|
||||
item = index === 0 ? _rootItem : [_tableDelegates[lastIndex] childAtIndex:[selectionIndexes firstIndex]];
|
||||
|
||||
if (index > 0 && item && [self isLeafItem:item])
|
||||
@@ -327,6 +213,8 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[table setAllowsEmptySelection:_allowsEmptySelection];
|
||||
[table registerForDraggedTypes:[self registeredDraggedTypes]];
|
||||
|
||||
[self setNextResponder:table];
|
||||
|
||||
[self _addTableColumnsToTableView:table forColumnIndex:index];
|
||||
|
||||
var delegate = [[_CPBrowserTableDelegate alloc] init];
|
||||
@@ -345,7 +233,7 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[table setAction:@selector(_tableViewClicked:)];
|
||||
[table setDoubleAction:@selector(_tableViewDoubleClicked:)];
|
||||
[table setDraggingDestinationFeedbackStyle:CPTableViewDraggingDestinationFeedbackStyleRegular];
|
||||
|
||||
|
||||
var scrollView = [[_CPBrowserScrollView alloc] initWithFrame:CGRectMakeZero()];
|
||||
[scrollView _setBrowser:self];
|
||||
[scrollView setDocumentView:table];
|
||||
@@ -366,7 +254,7 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
var column = [[CPTableColumn alloc] initWithIdentifier:@"Image"],
|
||||
view = [[CPImageView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[view setImageScaling:CPImageScaleProportionallyDown];
|
||||
[view setImageScaling:CPScaleProportionally];
|
||||
|
||||
[column setDataView:view];
|
||||
[column setResizingMask:CPTableColumnNoResizing];
|
||||
@@ -384,16 +272,16 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
var column = [[CPTableColumn alloc] initWithIdentifier:@"Leaf"],
|
||||
view = [[_CPBrowserLeafView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[view setBranchImage:[self valueForThemeAttribute:@"image-control-leaf"]];
|
||||
[view setHighlightedBranchImage:[self valueForThemeAttribute:@"image-control-leaf-pressed"]];
|
||||
|
||||
[view setBranchImage:[[self class] branchImage]];
|
||||
[view setHighlightedBranchImage:[[self class] highlightedBranchImage]];
|
||||
|
||||
[column setDataView:view];
|
||||
[column setResizingMask:CPTableColumnNoResizing];
|
||||
|
||||
|
||||
[aTableView addTableColumn:column];
|
||||
}
|
||||
|
||||
- (void)reloadColumn:(CPInteger)column
|
||||
- (void)reloadColumn:(int)column
|
||||
{
|
||||
[[self tableViewInColumn:column] reloadData];
|
||||
}
|
||||
@@ -412,7 +300,7 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
tableHeight = CGRectGetHeight([tableView bounds]);
|
||||
|
||||
[[tableView tableColumnWithIdentifier:"Image"] setWidth:_imageWidth];
|
||||
[[tableView tableColumnWithIdentifier:"Content"] setWidth:[self columnContentWidthForColumnWidth:width]];
|
||||
[[tableView tableColumnWithIdentifier:"Content"] setWidth:width - (_leafWidth + _delegateSupportsImages ? _imageWidth : 0) - scrollerWidth - scrollerWidth];
|
||||
[[tableView tableColumnWithIdentifier:"Leaf"] setWidth:_leafWidth];
|
||||
|
||||
[tableView setRowHeight:_rowHeight];
|
||||
@@ -426,54 +314,21 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[_contentView setFrameSize:CGSizeMake(xOrigin, height)];
|
||||
}
|
||||
|
||||
- (unsigned)rowAtPoint:(CGPoint)aPoint
|
||||
{
|
||||
var column = [self columnAtPoint:aPoint];
|
||||
if (column === -1)
|
||||
return -1;
|
||||
|
||||
var tableView = _tableViews[column];
|
||||
return [tableView rowAtPoint:[tableView convertPoint:aPoint fromView:self]];
|
||||
}
|
||||
|
||||
- (unsigned)columnAtPoint:(CGPoint)aPoint
|
||||
{
|
||||
var adjustedPoint = [_contentView convertPoint:aPoint fromView:self];
|
||||
|
||||
for (var i = 0, count = _tableViews.length; i < count; i++)
|
||||
{
|
||||
var frame = [[_tableViews[i] enclosingScrollView] frame];
|
||||
if (CGRectContainsPoint(frame, adjustedPoint))
|
||||
return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
- (CGRect)rectOfRow:(unsigned)aRow inColumn:(unsigned)aColumn
|
||||
{
|
||||
var tableView = _tableViews[aColumn],
|
||||
rect = [tableView rectOfRow:aRow];
|
||||
|
||||
rect.origin = [self convertPoint:rect.origin fromView:tableView];
|
||||
return rect;
|
||||
}
|
||||
|
||||
// ITEMS
|
||||
|
||||
- (id)itemAtRow:(CPInteger)row inColumn:(CPInteger)column
|
||||
- (id)itemAtRow:(int)row inColumn:(int)column
|
||||
{
|
||||
return [_tableDelegates[column] childAtIndex:row] || nil;
|
||||
return [_tableDelegates[column] childAtIndex:row];
|
||||
}
|
||||
|
||||
- (BOOL)isLeafItem:(id)item
|
||||
{
|
||||
return (_implementedDelegateMethods & CPBrowserDelegate_browser_isLeafItem_) && [_delegate browser:self isLeafItem:item];
|
||||
return [_delegate respondsToSelector:@selector(browser:isLeafItem:)] && [_delegate browser:self isLeafItem:item];
|
||||
}
|
||||
|
||||
- (id)parentForItemsInColumn:(CPInteger)column
|
||||
- (id)parentForItemsInColumn:(int)column
|
||||
{
|
||||
return [_tableDelegates[column] _item] || nil;
|
||||
return [_tableDelegates[column] _item];
|
||||
}
|
||||
|
||||
- (CPSet)selectedItems
|
||||
@@ -502,10 +357,6 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
|
||||
// CLICK EVENTS
|
||||
|
||||
- (void)trackMouse:(CPEvent)anEvent
|
||||
{
|
||||
}
|
||||
|
||||
- (void)_column:(unsigned)columnIndex clickedRow:(unsigned)rowIndex
|
||||
{
|
||||
[self setLastColumn:columnIndex];
|
||||
@@ -531,42 +382,16 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[self sendAction:_doubleAction to:_target];
|
||||
}
|
||||
|
||||
- (void)keyDown:(CPEvent)anEvent
|
||||
{
|
||||
var key = [anEvent charactersIgnoringModifiers],
|
||||
column = [self selectedColumn];
|
||||
|
||||
if (column === CPNotFound)
|
||||
return;
|
||||
|
||||
if (key === CPLeftArrowFunctionKey || key === CPRightArrowFunctionKey)
|
||||
{
|
||||
if (key === CPLeftArrowFunctionKey)
|
||||
{
|
||||
var previousColumn = column - 1,
|
||||
selectedRow = [self selectedRowInColumn:previousColumn];
|
||||
|
||||
[self selectRow:selectedRow inColumn:previousColumn];
|
||||
}
|
||||
else
|
||||
[self selectRow:0 inColumn:column + 1];
|
||||
}
|
||||
else
|
||||
[_tableViews[column] keyDown:anEvent];
|
||||
}
|
||||
|
||||
// SIZING
|
||||
|
||||
- (float)columnContentWidthForColumnWidth:(float)aWidth
|
||||
{
|
||||
var columnSpacing = [_tableViews[0] intercellSpacing].width;
|
||||
return aWidth - (_leafWidth + columnSpacing + (_delegateSupportsImages ? _imageWidth + columnSpacing : 0)) - columnSpacing - [CPScroller scrollerWidth];
|
||||
return aWidth - (_leafWidth + _delegateSupportsImages ? _imageWidth : 0) - [CPScroller scrollerWidth];
|
||||
}
|
||||
|
||||
- (float)columnWidthForColumnContentWidth:(float)aWidth
|
||||
{
|
||||
var columnSpacing = [_tableViews[0] intercellSpacing].width;
|
||||
return aWidth + (_leafWidth + columnSpacing + (_delegateSupportsImages ? _imageWidth + columnSpacing: 0)) + columnSpacing + [CPScroller scrollerWidth];
|
||||
return aWidth + (_leafWidth + _delegateSupportsImages ? _imageWidth : 0) + [CPScroller scrollerWidth];
|
||||
}
|
||||
|
||||
- (void)setImageWidth:(float)aWidth
|
||||
@@ -595,7 +420,9 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
{
|
||||
_columnWidths[column] = aWidth;
|
||||
|
||||
[self _sendDelegateBrowserDidResizeColumn:column];
|
||||
if ([_delegate respondsToSelector:@selector(browser:didResizeColumn:)])
|
||||
[_delegate browser:self didResizeColumn:column];
|
||||
|
||||
[self tile];
|
||||
}
|
||||
|
||||
@@ -626,7 +453,7 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[_contentView scrollRectToVisible:[[[self tableViewInColumn:columnIndex] enclosingScrollView] frame]];
|
||||
}
|
||||
|
||||
- (void)scrollRowToVisible:(unsigned)rowIndex inColumn:(unsigned)columnIndex
|
||||
– (void)scrollRowToVisible:(unsigned)rowIndex inColumn:(unsigned)columnIndex
|
||||
{
|
||||
[self scrollColumnToVisible:columnIndex];
|
||||
[[self tableViewInColumn:columnIndex] scrollRowToVisible:rowIndex];
|
||||
@@ -699,9 +526,6 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
|
||||
- (CPIndexSet)selectedRowIndexesInColumn:(unsigned)column
|
||||
{
|
||||
if (column < 0 || column > [self lastColumn] +1)
|
||||
return [CPIndexSet indexSet];
|
||||
|
||||
return [[self tableViewInColumn:column] selectedRowIndexes];
|
||||
}
|
||||
|
||||
@@ -710,12 +534,15 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
if (column < 0 || column > [self lastColumn] + 1)
|
||||
return;
|
||||
|
||||
indexSet = [self _sendDelegateBrowserSelectionIndexesForProposedSelection:indexSet inColumn:column];
|
||||
if ([_delegate respondsToSelector:@selector(browser:selectionIndexesForProposedSelection:inColumn:)])
|
||||
indexSet = [_delegate browser:self selectionIndexesForProposedSelection:indexSet inColumn:column];
|
||||
|
||||
if (![self _sendDelegateBrowserShouldSelectRowIndexes:indexSet inColumn:column])
|
||||
if ([_delegate respondsToSelector:@selector(browser:shouldSelectRowIndexes:inColumn:)] &&
|
||||
![_delegate browser:self shouldSelectRowIndexes:indexSet inColumn:column])
|
||||
return;
|
||||
|
||||
[self _sendDelegateBrowserSelectionIsChanging];
|
||||
if ([_delegate respondsToSelector:@selector(browserSelectionIsChanging:)])
|
||||
[_delegate browserSelectionIsChanging:self];
|
||||
|
||||
if (column > [self lastColumn])
|
||||
[self addColumn];
|
||||
@@ -724,9 +551,12 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
|
||||
[[self tableViewInColumn:column] selectRowIndexes:indexSet byExtendingSelection:NO];
|
||||
|
||||
[self setNextResponder:[self tableViewInColumn:[self lastColumn]]];
|
||||
|
||||
[self scrollColumnToVisible:column];
|
||||
|
||||
[self _sendDelegateBrowserSelectionDidChange];
|
||||
if ([_delegate respondsToSelector:@selector(browserSelectionDidChange:)])
|
||||
[_delegate browserSelectionDidChange:self];
|
||||
}
|
||||
|
||||
- (void)setBackgroundColor:(CPColor)aColor
|
||||
@@ -748,55 +578,32 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[_tableViews makeObjectsPerformSelector:@selector(registerForDraggedTypes:) withObject:types];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPBrowser (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
- (BOOL)canDragRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(int)columnIndex withEvent:(CPEvent)dragEvent
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
if ([_delegate respondsToSelector:@selector(browser:canDragRowsWithIndexes:inColumn:withEvent:)])
|
||||
return [_delegate browser:self canDragRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent];
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self _init];
|
||||
|
||||
_allowsEmptySelection = [aCoder decodeBoolForKey:@"CPBrowserAllowsEmptySelectionKey"];
|
||||
_allowsMultipleSelection = [aCoder decodeBoolForKey:@"CPBrowserAllowsMultipleSelectionKey"];
|
||||
_prototypeView = [aCoder decodeObjectForKey:@"CPBrowserPrototypeViewKey"];
|
||||
_rowHeight = [aCoder decodeFloatForKey:@"CPBrowserRowHeightKey"];
|
||||
_imageWidth = [aCoder decodeFloatForKey:@"CPBrowserImageWidthKey"];
|
||||
_minColumnWidth = [aCoder decodeFloatForKey:@"CPBrowserMinColumnWidthKey"];
|
||||
_columnWidths = [aCoder decodeObjectForKey:@"CPBrowserColumnWidthsKey"];
|
||||
|
||||
[self setDelegate:[aCoder decodeObjectForKey:@"CPBrowserDelegateKey"]];
|
||||
[self setAutohidesScroller:[aCoder decodeBoolForKey:@"CPBrowserAutohidesScrollerKey"]];
|
||||
}
|
||||
|
||||
return self;
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
- (CPImage)draggingImageForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(int)columnIndex withEvent:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
|
||||
{
|
||||
// Don't encode the subviews, they're transient and will be recreated from data.
|
||||
var actualSubviews = _subviews;
|
||||
_subviews = [];
|
||||
[super encodeWithCoder:aCoder];
|
||||
_subviews = actualSubviews;
|
||||
if ([_delegate respondsToSelector:@selector(browser:draggingImageForRowsWithIndexes:inColumn:withEvent:offset:)])
|
||||
return [_delegate browser:self draggingImageForRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent offset:dragImageOffset];
|
||||
|
||||
[aCoder encodeBool:[self autohidesScroller] forKey:@"CPBrowserAutohidesScrollerKey"];
|
||||
[aCoder encodeBool:_allowsEmptySelection forKey:@"CPBrowserAllowsEmptySelectionKey"];
|
||||
[aCoder encodeBool:_allowsMultipleSelection forKey:@"CPBrowserAllowsMultipleSelectionKey"];
|
||||
[aCoder encodeObject:_delegate forKey:@"CPBrowserDelegateKey"];
|
||||
[aCoder encodeObject:_prototypeView forKey:@"CPBrowserPrototypeViewKey"];
|
||||
[aCoder encodeFloat:_rowHeight forKey:@"CPBrowserRowHeightKey"];
|
||||
[aCoder encodeFloat:_imageWidth forKey:@"CPBrowserImageWidthKey"];
|
||||
[aCoder encodeFloat:_minColumnWidth forKey:@"CPBrowserMinColumnWidthKey"];
|
||||
[aCoder encodeObject:_columnWidths forKey:@"CPBrowserColumnWidthsKey"];
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (CPView)draggingViewForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(int)columnIndex withEvent:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
|
||||
{
|
||||
if ([_delegate respondsToSelector:@selector(browser:draggingViewForRowsWithIndexes:inColumn:withEvent:offset:)])
|
||||
return [_delegate browser:self draggingViewForRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent offset:dragImageOffset];
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation _CPBrowserResizeControl : CPView
|
||||
{
|
||||
CGPoint _mouseDownX;
|
||||
@@ -805,18 +612,6 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
unsigned _width;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
var browser = [[CPBrowser alloc] init];
|
||||
[self setBackgroundColor:[CPColor colorWithPatternImage:[browser valueForThemeAttribute:@"image-control-resize"]]];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
_mouseDownX = [anEvent locationInWindow].x;
|
||||
@@ -831,23 +626,34 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[_browser setWidth:_width + deltaX ofColumn:_index];
|
||||
}
|
||||
|
||||
- (void)mouseUp:(CPEvent)anEvent
|
||||
{
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var _CPBrowserResizeControlBackgroundImage = nil;
|
||||
|
||||
@implementation _CPBrowserScrollView : CPScrollView
|
||||
{
|
||||
_CPBrowserResizeControl _resizeControl;
|
||||
CPBrowser _browser @accessors;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
+ (CPImage)backgroundImage
|
||||
{
|
||||
if (!_CPBrowserResizeControlBackgroundImage)
|
||||
{
|
||||
var path = [[CPBundle bundleForClass:[self class]] pathForResource:"browser-resize-control.png"];
|
||||
_CPBrowserResizeControlBackgroundImage = [[CPImage alloc] initWithContentsOfFile:path
|
||||
size:CGSizeMake(15, 14)];
|
||||
}
|
||||
|
||||
return _CPBrowserResizeControlBackgroundImage;
|
||||
}
|
||||
|
||||
- (void)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_resizeControl = [[_CPBrowserResizeControl alloc] initWithFrame:CGRectMakeZero()];
|
||||
[_resizeControl setBackgroundColor:[CPColor colorWithPatternImage:[[self class] backgroundImage]]];
|
||||
[self addSubview:_resizeControl];
|
||||
}
|
||||
|
||||
@@ -897,26 +703,18 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
return _browser;
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (BOOL)_isFocused
|
||||
{
|
||||
return ([super _isFocused] || [_browser tableViewInColumn:[_browser selectedColumn]] === self);
|
||||
}
|
||||
|
||||
- (BOOL)canDragRowsWithIndexes:(CPIndexSet)rowIndexes atPoint:(CGPoint)mouseDownPoint
|
||||
{
|
||||
return [_browser canDragRowsWithIndexes:rowIndexes inColumn:[_browser columnOfTableView:self] withEvent:[CPApp currentEvent]];
|
||||
}
|
||||
|
||||
- (CPImage)dragImageForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
|
||||
- (CPImage)dragImageForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CPPointPointer)dragImageOffset
|
||||
{
|
||||
return [_browser draggingImageForRowsWithIndexes:dragRows inColumn:[_browser columnOfTableView:self] withEvent:dragEvent offset:dragImageOffset] ||
|
||||
[super dragImageForRowsWithIndexes:dragRows tableColumns:theTableColumns event:dragEvent offset:dragImageOffset];
|
||||
}
|
||||
|
||||
- (CPView)dragViewForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CGPoint)dragViewOffset
|
||||
- (CPView)dragViewForRowsWithIndexes:(CPIndexSet)dragRows tableColumns:(CPArray)theTableColumns event:(CPEvent)dragEvent offset:(CPPoint)dragViewOffset
|
||||
{
|
||||
var count = theTableColumns.length;
|
||||
while (count--)
|
||||
@@ -929,6 +727,30 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[super dragViewForRowsWithIndexes:dragRows tableColumns:theTableColumns event:dragEvent offset:dragViewOffset];
|
||||
}
|
||||
|
||||
- (void)moveUp:(id)sender
|
||||
{
|
||||
[super moveUp:sender];
|
||||
[_browser selectRow:[self selectedRow] inColumn:[_browser selectedColumn]];
|
||||
}
|
||||
|
||||
- (void)moveDown:(id)sender
|
||||
{
|
||||
[super moveDown:sender];
|
||||
[_browser selectRow:[self selectedRow] inColumn:[_browser selectedColumn]];
|
||||
}
|
||||
|
||||
- (void)moveLeft:(id)sender
|
||||
{
|
||||
var previousColumn = [_browser selectedColumn] - 1,
|
||||
selectedRow = [_browser selectedRowInColumn:previousColumn];
|
||||
|
||||
[_browser selectRow:selectedRow inColumn:previousColumn];
|
||||
}
|
||||
|
||||
- (void)moveRight:(id)sender
|
||||
{
|
||||
[_browser selectRow:0 inColumn:[_browser selectedColumn] + 1];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -966,36 +788,30 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[_browser _column:_index clickedRow:[selectedIndexes count] === 1 ? [selectedIndexes firstIndex] : -1];
|
||||
}
|
||||
|
||||
- (void)tableViewSelectionDidChange:(CPNotification)aNotification
|
||||
{
|
||||
var selectedIndexes = [[aNotification object] selectedRowIndexes];
|
||||
[_browser selectRowIndexes:selectedIndexes inColumn:_index];
|
||||
}
|
||||
|
||||
- (id)childAtIndex:(CPUInteger)index
|
||||
- (id)childAtIndex:(unsigned)index
|
||||
{
|
||||
return [_delegate browser:_browser child:index ofItem:_item];
|
||||
}
|
||||
|
||||
- (BOOL)tableView:(CPTableView)aTableView acceptDrop:(id)info row:(CPInteger)row dropOperation:(CPTableViewDropOperation)operation
|
||||
- (BOOL)tableView:(CPTableView)aTableView acceptDrop:(id)info row:(int)row dropOperation:(CPTableViewDropOperation)operation
|
||||
{
|
||||
if (_browser._implementedDelegateMethods & CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_)
|
||||
if ([_delegate respondsToSelector:@selector(browser:acceptDrop:atRow:column:dropOperation:)])
|
||||
return [_delegate browser:_browser acceptDrop:info atRow:row column:_index dropOperation:operation];
|
||||
else
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (CPDragOperation)tableView:(CPTableView)aTableView validateDrop:(id)info proposedRow:(CPInteger)row proposedDropOperation:(CPTableViewDropOperation)operation
|
||||
- (CPDragOperation)tableView:(CPTableView)aTableView validateDrop:(id)info proposedRow:(int)row proposedDropOperation:(CPTableViewDropOperation)operation
|
||||
{
|
||||
if (_browser._implementedDelegateMethods & CPBrowserDelegate_browser_validateDrop_proposedRow_column_dropOperation_)
|
||||
return [_delegate browser:_browser validateDrop:info proposedRow:row column:_index dropOperation:operation];
|
||||
if ([_delegate respondsToSelector:@selector(browser:validateDrop:proposedRow:column:dropOperation:)])
|
||||
[_delegate browser:_browser validateDrop:info proposedRow:row column:_index dropOperation:operation];
|
||||
else
|
||||
return CPDragOperationNone;
|
||||
}
|
||||
|
||||
- (BOOL)tableView:(CPTableView)aTableView writeRowsWithIndexes:(CPIndexSet)rowIndexes toPasteboard:(CPPasteboard)pboard
|
||||
{
|
||||
if (_browser._implementedDelegateMethods & CPBrowserDelegate_browser_writeRowsWithIndexes_inColumn_toPasteboard_)
|
||||
if ([_delegate respondsToSelector:@selector(browser:writeRowsWithIndexes:inColumn:toPasteboard:)])
|
||||
return [_delegate browser:_browser writeRowsWithIndexes:rowIndexes inColumn:_index toPasteboard:pboard];
|
||||
else
|
||||
return NO;
|
||||
@@ -1049,11 +865,11 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
{
|
||||
var imageView = [self layoutEphemeralSubviewNamed:@"image-view"
|
||||
positioned:CPWindowAbove
|
||||
relativeToEphemeralSubviewNamed:nil],
|
||||
isHighlighted = [self hasThemeState:CPThemeStateSelectedDataView];
|
||||
relativeToEphemeralSubviewNamed:nil];
|
||||
|
||||
var isHighlighted = [self themeState] & CPThemeStateSelected;
|
||||
[imageView setImage: _isLeaf ? (isHighlighted ? _highlightedBranchImage : _branchImage) : nil];
|
||||
[imageView setImageScaling:CPImageScaleNone];
|
||||
[imageView setImageScaling:CPScaleNone];
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
@@ -1065,7 +881,7 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
[aCoder encodeObject:_highlightedBranchImage forKey:"_CPBrowserLeafViewHighlightedBranchImageKey"];
|
||||
}
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
- (void)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
if (self = [super initWithCoder:aCoder])
|
||||
{
|
||||
@@ -1078,115 +894,3 @@ var CPBrowserDelegate_browser_acceptDrop_atRow_column_dropOperation_
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPBrowser (CPBrowserDelegate)
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate rootItemForBrowser:
|
||||
*/
|
||||
- (id)_sendDelegateRootItemForBrowser
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_rootItemForBrowser_))
|
||||
return nil;
|
||||
|
||||
return [_delegate rootItemForBrowser:self];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate browser:didChangeLastColumn:toColumn:
|
||||
*/
|
||||
- (void)_sendDelegateBrowserDidChangeLastColumn:(CPInteger)lastColumn toColumn:(CPInteger)newColumn
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_browser_didChangeLastColumn_toColumn_))
|
||||
return;
|
||||
|
||||
[_delegate browser:self didChangeLastColumn:lastColumn toColumn:newColumn];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate browser:didResizeColumn:
|
||||
*/
|
||||
- (void)_sendDelegateBrowserDidResizeColumn:(CPInteger)column
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_browser_didResizeColumn_))
|
||||
return;
|
||||
|
||||
[_delegate browser:self didResizeColumn:column];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate browserSelectionIsChanging:
|
||||
*/
|
||||
- (void)_sendDelegateBrowserSelectionIsChanging
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_browserSelectionIsChanging_))
|
||||
return;
|
||||
|
||||
[_delegate browserSelectionIsChanging:self];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate browser:shouldSelectRowIndexes:inColumn:
|
||||
*/
|
||||
- (BOOL)_sendDelegateBrowserShouldSelectRowIndexes:(CPIndexSet)anIndexSet inColumn:(CPInteger)aColumn
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_browser_shouldSelectRowIndexes_inColumn_))
|
||||
return YES;
|
||||
|
||||
return [_delegate browser:self shouldSelectRowIndexes:anIndexSet inColumn:aColumn];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate browser:selectionIndexesForProposedSelection:inColumn:
|
||||
*/
|
||||
- (CPIndexSet)_sendDelegateBrowserSelectionIndexesForProposedSelection:(CPIndexSet)anIndexSet inColumn:(CPInteger)aColumn
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_browser_selectionIndexesForProposedSelection_inColumn_))
|
||||
return anIndexSet;
|
||||
|
||||
return [_delegate browser:self selectionIndexesForProposedSelection:anIndexSet inColumn:aColumn];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate browserSelectionDidChange
|
||||
*/
|
||||
- (void)_sendDelegateBrowserSelectionDidChange
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPBrowserDelegate_browserSelectionDidChange_))
|
||||
return;
|
||||
|
||||
[_delegate browserSelectionDidChange:self];
|
||||
}
|
||||
|
||||
- (BOOL)canDragRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)columnIndex withEvent:(CPEvent)dragEvent
|
||||
{
|
||||
if (_implementedDelegateMethods & CPBrowserDelegate_browser_canDragRowsWithIndexes_inColumn_withEvent_)
|
||||
return [_delegate browser:self canDragRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (CPImage)draggingImageForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)columnIndex withEvent:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
|
||||
{
|
||||
if (_implementedDelegateMethods & CPBrowserDelegate_browser_draggingImageForRowsWithIndexes_inColumn_withEvent_offset_)
|
||||
return [_delegate browser:self draggingImageForRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent offset:dragImageOffset];
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (CPView)draggingViewForRowsWithIndexes:(CPIndexSet)rowIndexes inColumn:(CPInteger)columnIndex withEvent:(CPEvent)dragEvent offset:(CGPoint)dragImageOffset
|
||||
{
|
||||
if (_implementedDelegateMethods & CPBrowserDelegate_browser_draggingViewForRowsWithIndexes_inColumn_withEvent_offset_)
|
||||
return [_delegate browser:self draggingViewForRowsWithIndexes:rowIndexes inColumn:columnIndex withEvent:dragEvent offset:dragImageOffset];
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+200
-687
File diff suppressed because it is too large
Load Diff
+31
-124
@@ -1,35 +1,8 @@
|
||||
/*
|
||||
* CPButtonBar.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPView.j"
|
||||
@import "CPWindow_Constants.j"
|
||||
@import <AppKit/CPView.j>
|
||||
|
||||
@class CPSplitView
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
@global CPPopUpButtonStatePullsDown
|
||||
@global CPKeyValueChangeOldKey
|
||||
@global CPKeyValueChangeNewKey
|
||||
@global CPKeyValueObservingOptionNew
|
||||
@global CPKeyValueObservingOptionOld
|
||||
|
||||
@implementation CPButtonBar : CPView
|
||||
{
|
||||
@@ -41,9 +14,8 @@
|
||||
+ (id)plusButton
|
||||
{
|
||||
var button = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, 35, 25)],
|
||||
image = [[CPTheme defaultTheme] valueForAttributeWithName:@"button-image-plus" forClass:[CPButtonBar class]];
|
||||
image = [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:self] pathForResource:@"plus_button.png"] size:CGSizeMake(11, 12)];
|
||||
|
||||
[button setBordered:NO];
|
||||
[button setImage:image];
|
||||
[button setImagePosition:CPImageOnly];
|
||||
|
||||
@@ -53,48 +25,23 @@
|
||||
+ (id)minusButton
|
||||
{
|
||||
var button = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, 35, 25)],
|
||||
image = [[CPTheme defaultTheme] valueForAttributeWithName:@"button-image-minus" forClass:[CPButtonBar class]];
|
||||
image = [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:self] pathForResource:@"minus_button.png"] size:CGSizeMake(11, 4)];
|
||||
|
||||
[button setBordered:NO];
|
||||
[button setImage:image];
|
||||
[button setImagePosition:CPImageOnly];
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
+ (id)actionPopupButton
|
||||
{
|
||||
var button = [[CPPopUpButton alloc] initWithFrame:CGRectMake(0, 0, 35, 25)],
|
||||
image = [[CPTheme defaultTheme] valueForAttributeWithName:@"button-image-action" forClass:[CPButtonBar class]];
|
||||
|
||||
[button addItemWithTitle:nil];
|
||||
[[button lastItem] setImage:image];
|
||||
[button setImagePosition:CPImageOnly];
|
||||
[button setValue:CGInsetMake(0, 0, 0, 0) forThemeAttribute:"content-inset" inState:CPPopUpButtonStatePullsDown];
|
||||
|
||||
[button setPullsDown:YES];
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (CPString)themeClass
|
||||
{
|
||||
return @"button-bar";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
+ (id)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"resize-control-inset": CGInsetMake(0.0, 0.0, 0.0, 0.0),
|
||||
@"resize-control-size": CGSizeMakeZero(),
|
||||
@"resize-control-color": [CPNull null],
|
||||
@"bezel-color": [CPNull null],
|
||||
@"button-bezel-color": [CPNull null],
|
||||
@"button-text-color": [CPNull null],
|
||||
@"button-image-plus": [CPNull null],
|
||||
@"button-image-minus": [CPNull null],
|
||||
@"button-image-action": [CPNull null],
|
||||
};
|
||||
return [CPDictionary dictionaryWithObjects:[CGInsetMake(0.0, 0.0, 0.0, 0.0), CGSizeMakeZero(), [CPNull null], [CPNull null], [CPNull null]]
|
||||
forKeys:[@"resize-control-inset", @"resize-control-size", @"resize-control-color", @"bezel-color", @"button-bezel-color"]];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
@@ -112,8 +59,6 @@
|
||||
|
||||
- (void)awakeFromCib
|
||||
{
|
||||
[super awakeFromCib];
|
||||
|
||||
var view = [self superview],
|
||||
subview = self;
|
||||
|
||||
@@ -134,21 +79,28 @@
|
||||
|
||||
- (void)setButtons:(CPArray)buttons
|
||||
{
|
||||
for (var i = [_buttons count] - 1; i >= 0; i--)
|
||||
{
|
||||
[_buttons[i] removeFromSuperview];
|
||||
[_buttons[i] removeObserver:self forKeyPath:@"hidden"];
|
||||
}
|
||||
|
||||
|
||||
_buttons = [CPArray arrayWithArray:buttons];
|
||||
|
||||
for (var i = [_buttons count] - 1; i >= 0; i--)
|
||||
for (var i = 0, count = [_buttons count]; i < count; i++)
|
||||
{
|
||||
[_buttons[i] addObserver:self forKeyPath:@"hidden" options:CPKeyValueObservingOptionNew | CPKeyValueObservingOptionOld context:nil];
|
||||
[_buttons[i] setBordered:YES];
|
||||
}
|
||||
var button = _buttons[i];
|
||||
|
||||
var normalColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateNormal],
|
||||
highlightedColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateHighlighted],
|
||||
disabledColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateDisabled];
|
||||
|
||||
[button setValue:normalColor forThemeAttribute:@"bezel-color" inState:CPThemeStateNormal|CPThemeStateBordered];
|
||||
[button setValue:highlightedColor forThemeAttribute:@"bezel-color" inState:CPThemeStateHighlighted|CPThemeStateBordered];
|
||||
[button setValue:disabledColor forThemeAttribute:@"bezel-color" inState:CPThemeStateDisabled|CPThemeStateBordered];
|
||||
|
||||
// FIXME shouldn't need this
|
||||
[button setValue:normalColor forThemeAttribute:@"bezel-color" inState:CPThemeStateNormal|CPThemeStateBordered|CPPopUpButtonStatePullsDown];
|
||||
[button setValue:highlightedColor forThemeAttribute:@"bezel-color" inState:CPThemeStateHighlighted|CPThemeStateBordered|CPPopUpButtonStatePullsDown];
|
||||
[button setValue:disabledColor forThemeAttribute:@"bezel-color" inState:CPThemeStateDisabled|CPThemeStateBordered|CPPopUpButtonStatePullsDown];
|
||||
|
||||
[button setBordered:YES];
|
||||
}
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
@@ -224,43 +176,21 @@
|
||||
{
|
||||
[self setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
|
||||
|
||||
var normalColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateNormal],
|
||||
highlightedColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateHighlighted],
|
||||
disabledColor = [self valueForThemeAttribute:@"button-bezel-color" inState:CPThemeStateDisabled],
|
||||
textColor = [self valueForThemeAttribute:@"button-text-color" inState:CPThemeStateNormal];
|
||||
|
||||
var buttonsNotHidden = [CPArray arrayWithArray:_buttons],
|
||||
count = [buttonsNotHidden count];
|
||||
|
||||
while (count--)
|
||||
{
|
||||
var button = buttonsNotHidden[count];
|
||||
|
||||
if ([button isHidden])
|
||||
{
|
||||
[button removeFromSuperview];
|
||||
[buttonsNotHidden removeObject:button];
|
||||
}
|
||||
}
|
||||
if ([buttonsNotHidden[count] isHidden])
|
||||
[buttonsNotHidden removeObject:buttonsNotHidden[count]];
|
||||
|
||||
var currentButtonOffset = _resizeControlIsLeftAligned ? CGRectGetMaxX([self bounds]) + 1 : -1,
|
||||
bounds = [self bounds],
|
||||
height = CGRectGetHeight(bounds) - 1,
|
||||
frameWidth = CGRectGetWidth(bounds),
|
||||
resizeRect = _hasResizeControl ? [self rectForEphemeralSubviewNamed:"resize-control-view"] : CGRectMakeZero(),
|
||||
resizeWidth = CGRectGetWidth(resizeRect),
|
||||
availableWidth = frameWidth - resizeWidth - 1;
|
||||
height = CGRectGetHeight([self bounds]) - 1;
|
||||
|
||||
for (var i = 0, count = [buttonsNotHidden count]; i < count; i++)
|
||||
{
|
||||
{
|
||||
var button = buttonsNotHidden[i],
|
||||
width = CGRectGetWidth([button frame]);
|
||||
|
||||
if (availableWidth > width)
|
||||
availableWidth -= width;
|
||||
else
|
||||
break;
|
||||
|
||||
if (_resizeControlIsLeftAligned)
|
||||
{
|
||||
[button setFrame:CGRectMake(currentButtonOffset - width, 1, width, height)];
|
||||
@@ -272,16 +202,6 @@
|
||||
currentButtonOffset += width - 1;
|
||||
}
|
||||
|
||||
[button setValue:normalColor forThemeAttribute:@"bezel-color" inStates:[CPThemeStateNormal, CPThemeStateBordered]];
|
||||
[button setValue:highlightedColor forThemeAttribute:@"bezel-color" inStates:[CPThemeStateHighlighted, CPThemeStateBordered, ]];
|
||||
[button setValue:disabledColor forThemeAttribute:@"bezel-color" inStates:[CPThemeStateDisabled, CPThemeStateBordered]];
|
||||
[button setValue:textColor forThemeAttribute:@"text-color" inState:CPThemeStateBordered];
|
||||
|
||||
// FIXME shouldn't need this
|
||||
[button setValue:normalColor forThemeAttribute:@"bezel-color" inStates:[CPThemeStateNormal, CPThemeStateBordered, CPPopUpButtonStatePullsDown]];
|
||||
[button setValue:highlightedColor forThemeAttribute:@"bezel-color" inStates:[CPThemeStateHighlighted, CPThemeStateBordered, CPPopUpButtonStatePullsDown]];
|
||||
[button setValue:disabledColor forThemeAttribute:@"bezel-color" inStates:[CPThemeStateDisabled, CPThemeStateBordered, CPPopUpButtonStatePullsDown]];
|
||||
|
||||
[self addSubview:button];
|
||||
}
|
||||
|
||||
@@ -296,20 +216,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)keyPath ofObject:(id)object change:(CPDictionary)change context:(id)context
|
||||
{
|
||||
if ([change objectForKey:CPKeyValueChangeOldKey] == [change objectForKey:CPKeyValueChangeNewKey])
|
||||
return;
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setFrameSize:(CGSize)aSize
|
||||
{
|
||||
[super setFrameSize:aSize];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPButtonBarHasResizeControlKey = @"CPButtonBarHasResizeControlKey",
|
||||
@@ -340,3 +246,4 @@ var CPButtonBarHasResizeControlKey = @"CPButtonBarHasResizeControlKey",
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
+2
-133
@@ -23,8 +23,6 @@
|
||||
@import "CPButton.j"
|
||||
|
||||
|
||||
CPCheckBoxImageOffset = 4.0;
|
||||
|
||||
@implementation CPCheckBox : CPButton
|
||||
{
|
||||
}
|
||||
@@ -39,19 +37,11 @@ CPCheckBoxImageOffset = 4.0;
|
||||
return [self buttonWithTitle:aTitle];
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (CPString)themeClass
|
||||
{
|
||||
return @"check-box";
|
||||
}
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding === CPValueBinding)
|
||||
return [_CPCheckBoxValueBinder class];
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
@@ -65,131 +55,10 @@ CPCheckBoxImageOffset = 4.0;
|
||||
[self setImagePosition:CPImageLeft];
|
||||
[self setAlignment:CPLeftTextAlignment];
|
||||
|
||||
[self setBordered:NO];
|
||||
[self setBordered:YES];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)takeStateFromKeyPath:(CPString)aKeyPath ofObjects:(CPArray)objects
|
||||
{
|
||||
var count = objects.length,
|
||||
value = [objects[0] valueForKeyPath:aKeyPath] ? CPOnState : CPOffState;
|
||||
|
||||
[self setAllowsMixedState:NO];
|
||||
[self setState:value];
|
||||
|
||||
while (count-- > 1)
|
||||
{
|
||||
if (value !== ([objects[count] valueForKeyPath:aKeyPath] ? CPOnState : CPOffState))
|
||||
{
|
||||
[self setAllowsMixedState:YES];
|
||||
[self setState:CPMixedState];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)takeValueFromKeyPath:(CPString)aKeyPath ofObjects:(CPArray)objects
|
||||
{
|
||||
[self takeStateFromKeyPath:aKeyPath ofObjects:objects];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Override methods from CPButton
|
||||
|
||||
- (CGSize)_minimumFrameSize
|
||||
{
|
||||
var size = [super _minimumFrameSize],
|
||||
contentView = [self ephemeralSubviewNamed:@"content-view"];
|
||||
|
||||
if (!contentView && [[self title] length])
|
||||
{
|
||||
var minSize = [self currentValueForThemeAttribute:@"min-size"],
|
||||
maxSize = [self currentValueForThemeAttribute:@"max-size"];
|
||||
|
||||
// Here we always add the min size to the control which is the size of the view of the checkBox
|
||||
size.width += minSize.width + CPCheckBoxImageOffset;
|
||||
|
||||
if (maxSize.width >= 0.0)
|
||||
size.width = MIN(size.width, maxSize.width);
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
- (CPThemeState)_contentVisualState
|
||||
{
|
||||
// Note : Behavior differs from CPButton as title doesn't follow the highlightsBy content flag
|
||||
|
||||
var visualState = [self themeState] || CPThemeStateNormal, // Needed during theme compilation
|
||||
currentState = [self state];
|
||||
|
||||
if ((currentState !== CPOffState) && (_showsStateBy & CPContentsCellMask))
|
||||
visualState = visualState.and((currentState === CPOnState) ? CPThemeStateSelected : CPButtonStateMixed);
|
||||
|
||||
return visualState;
|
||||
}
|
||||
|
||||
- (CPThemeState)_imageVisualState
|
||||
{
|
||||
// Note : Behavior differs from CPButton as we don't force "not selected" theme state
|
||||
// when button is highglighted and selected
|
||||
|
||||
var visualState = [self themeState] || CPThemeStateNormal, // Needed during theme compilation
|
||||
currentState = [self state];
|
||||
|
||||
if (_isHighlighted && (_highlightsBy & CPContentsCellMask))
|
||||
visualState = visualState.and(CPThemeStateHighlighted);
|
||||
|
||||
if ((currentState !== CPOffState) && (_showsStateBy & CPContentsCellMask))
|
||||
visualState = visualState.and((currentState === CPOnState) ? CPThemeStateSelected : CPButtonStateMixed);
|
||||
|
||||
return visualState;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPCheckBoxValueBinder : CPBinder
|
||||
{
|
||||
}
|
||||
|
||||
- (void)_updatePlaceholdersWithOptions:(CPDictionary)options
|
||||
{
|
||||
[super _updatePlaceholdersWithOptions:options];
|
||||
|
||||
[self _setPlaceholder:CPMixedState forMarker:CPMultipleValuesMarker isDefault:YES];
|
||||
[self _setPlaceholder:CPOffState forMarker:CPNoSelectionMarker isDefault:YES];
|
||||
[self _setPlaceholder:CPOffState forMarker:CPNotApplicableMarker isDefault:YES];
|
||||
[self _setPlaceholder:CPOffState forMarker:CPNullMarker isDefault:YES];
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source setAllowsMixedState:(aValue === CPMixedState)];
|
||||
[_source setState:aValue];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source setState:aValue];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation CPCheckBox (TableDataView)
|
||||
|
||||
// We overide here _CPObject+Theme setValue:forThemeAttribute as CPCheckBox can be used as tableView data view
|
||||
// So, when outside a table data view, setValue:forThemeAttribute should store the value with the CPThemeStateNormal (default behavior)
|
||||
// When inside a table data view, it should store the value with the CPThemeStateTableDataView. If not, the value won't be used if the
|
||||
// theme defined a value for this attribute for state CPThemeStateTableDataView
|
||||
|
||||
- (void)setValue:(id)aValue forThemeAttribute:(CPString)aName
|
||||
{
|
||||
[super setValue:aValue forThemeAttribute:aName];
|
||||
[super setValue:aValue forThemeAttribute:aName inState:CPThemeStateTableDataView];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+58
-57
@@ -22,13 +22,14 @@
|
||||
|
||||
@import "CPView.j"
|
||||
|
||||
@class CPScrollView
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
/*!
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPClipView
|
||||
|
||||
CPClipView allows you to define a clip rect and display only that portion of its containing view.
|
||||
CPClipView allows you to define a clip rect and display only that portion of its containing view.
|
||||
It is used to hold the document view in a CPScrollView.
|
||||
*/
|
||||
@implementation CPClipView : CPView
|
||||
@@ -45,13 +46,44 @@
|
||||
if (_documentView == aView)
|
||||
return;
|
||||
|
||||
var defaultCenter = [CPNotificationCenter defaultCenter];
|
||||
|
||||
if (_documentView)
|
||||
{
|
||||
[defaultCenter
|
||||
removeObserver:self
|
||||
name:CPViewFrameDidChangeNotification
|
||||
object:_documentView];
|
||||
|
||||
[defaultCenter
|
||||
removeObserver:self
|
||||
name:CPViewBoundsDidChangeNotification
|
||||
object:_documentView];
|
||||
|
||||
[_documentView removeFromSuperview];
|
||||
|
||||
}
|
||||
|
||||
_documentView = aView;
|
||||
|
||||
|
||||
if (_documentView)
|
||||
{
|
||||
[self addSubview:_documentView];
|
||||
|
||||
[_documentView setPostsFrameChangedNotifications:YES];
|
||||
[_documentView setPostsBoundsChangedNotifications:YES];
|
||||
|
||||
[defaultCenter
|
||||
addObserver:self
|
||||
selector:@selector(viewFrameChanged:)
|
||||
name:CPViewFrameDidChangeNotification
|
||||
object:_documentView];
|
||||
|
||||
[defaultCenter
|
||||
addObserver:self
|
||||
selector:@selector(viewBoundsChanged:)
|
||||
name:CPViewBoundsDidChangeNotification
|
||||
object:_documentView];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -71,21 +103,21 @@
|
||||
- (CGPoint)constrainScrollPoint:(CGPoint)aPoint
|
||||
{
|
||||
if (!_documentView)
|
||||
return CGPointMakeZero();
|
||||
return _CGPointMakeZero();
|
||||
|
||||
var documentFrame = [_documentView frame];
|
||||
|
||||
aPoint.x = MAX(0.0, MIN(aPoint.x, MAX(CGRectGetWidth(documentFrame) - CGRectGetWidth(_bounds), 0.0)));
|
||||
aPoint.y = MAX(0.0, MIN(aPoint.y, MAX(CGRectGetHeight(documentFrame) - CGRectGetHeight(_bounds), 0.0)));
|
||||
|
||||
aPoint.x = MAX(0.0, MIN(aPoint.x, MAX(_CGRectGetWidth(documentFrame) - _CGRectGetWidth(_bounds), 0.0)));
|
||||
aPoint.y = MAX(0.0, MIN(aPoint.y, MAX(_CGRectGetHeight(documentFrame) - _CGRectGetHeight(_bounds), 0.0)));
|
||||
|
||||
return aPoint;
|
||||
}
|
||||
|
||||
- (void)setBoundsOrigin:(CGPoint)aPoint
|
||||
{
|
||||
if (CGPointEqualToPoint(_bounds.origin, aPoint))
|
||||
if (_CGPointEqualToPoint(_bounds.origin, aPoint))
|
||||
return;
|
||||
|
||||
|
||||
[super setBoundsOrigin:aPoint];
|
||||
|
||||
var superview = [self superview],
|
||||
@@ -94,7 +126,7 @@
|
||||
// FIXME: Should CPScrollView be finding out about this on its own somehow?
|
||||
scrollViewClass = objj_getClass("CPScrollView");
|
||||
|
||||
if ([superview isKindOfClass:scrollViewClass])
|
||||
if([superview isKindOfClass:scrollViewClass])
|
||||
[superview reflectScrolledClipView:self];
|
||||
}
|
||||
|
||||
@@ -134,12 +166,12 @@
|
||||
- (void)_constrainScrollPoint
|
||||
{
|
||||
var oldScrollPoint = [self bounds].origin;
|
||||
|
||||
// Call scrollToPoint: because the current scroll point may no longer make
|
||||
|
||||
// Call scrollToPoint: because the current scroll point may no longer make
|
||||
// sense given the new frame of the document view.
|
||||
[self scrollToPoint:oldScrollPoint];
|
||||
|
||||
// scrollToPoint: takes care of reflectScrollClipView: for us, so bail if
|
||||
|
||||
// scrollToPoint: takes care of reflectScrollClipView: for us, so bail if
|
||||
// the scroll points are not equal (meaning scrollToPoint: didn't early bail).
|
||||
if (!CGPointEqualToPoint(oldScrollPoint, [self bounds].origin))
|
||||
return;
|
||||
@@ -155,47 +187,20 @@
|
||||
[superview reflectScrolledClipView:self];
|
||||
}
|
||||
|
||||
- (BOOL)autoscroll:(CPEvent)anEvent
|
||||
- (BOOL)autoscroll:(CPEvent)anEvent
|
||||
{
|
||||
var bounds = [self bounds],
|
||||
eventLocation = [self convertPoint:[anEvent locationInWindow] fromView:nil],
|
||||
superview = [self superview],
|
||||
deltaX = 0,
|
||||
deltaY = 0;
|
||||
eventLocation = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
|
||||
if (CGRectContainsPoint(bounds, eventLocation))
|
||||
if (CPRectContainsPoint(bounds, eventLocation))
|
||||
return NO;
|
||||
|
||||
if (![superview isKindOfClass:[CPScrollView class]] || [superview hasVerticalScroller])
|
||||
{
|
||||
if (eventLocation.y < CGRectGetMinY(bounds))
|
||||
deltaY = CGRectGetMinY(bounds) - eventLocation.y;
|
||||
else if (eventLocation.y > CGRectGetMaxY(bounds))
|
||||
deltaY = CGRectGetMaxY(bounds) - eventLocation.y;
|
||||
if (deltaY < -bounds.size.height)
|
||||
deltaY = -bounds.size.height;
|
||||
if (deltaY > bounds.size.height)
|
||||
deltaY = bounds.size.height;
|
||||
}
|
||||
var newRect = CGRectMakeZero();
|
||||
|
||||
if (![superview isKindOfClass:[CPScrollView class]] || [superview hasHorizontalScroller])
|
||||
{
|
||||
if (eventLocation.x < CGRectGetMinX(bounds))
|
||||
deltaX = CGRectGetMinX(bounds) - eventLocation.x;
|
||||
else if (eventLocation.x > CGRectGetMaxX(bounds))
|
||||
deltaX = CGRectGetMaxX(bounds) - eventLocation.x;
|
||||
if (deltaX < -bounds.size.width)
|
||||
deltaX = -bounds.size.width;
|
||||
if (deltaX > bounds.size.width)
|
||||
deltaX = bounds.size.width;
|
||||
}
|
||||
newRect.origin = eventLocation;
|
||||
newRect.size = CPSizeMake(10, 10);
|
||||
|
||||
return [self scrollToPoint:CGPointMake(bounds.origin.x - deltaX, bounds.origin.y - deltaY)];
|
||||
}
|
||||
|
||||
- (CGRect)documentVisibleRect
|
||||
{
|
||||
return [_documentView visibleRect];
|
||||
return [_documentView scrollRectToVisible:newRect];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -208,19 +213,15 @@ var CPClipViewDocumentViewKey = @"CPScrollViewDocumentView";
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
if (self = [super initWithCoder:aCoder])
|
||||
{
|
||||
// Don't call setDocumentView: here. It calls addSubview:, but it's A) not necessary since the
|
||||
// view hierarchy is fully encoded and B) dangerous if the subview is not fully decoded.
|
||||
_documentView = [aCoder decodeObjectForKey:CPClipViewDocumentViewKey];
|
||||
}
|
||||
|
||||
[self setDocumentView:[aCoder decodeObjectForKey:CPClipViewDocumentViewKey]];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
|
||||
[aCoder encodeObject:_documentView forKey:CPClipViewDocumentViewKey];
|
||||
}
|
||||
|
||||
|
||||
+277
-1023
File diff suppressed because it is too large
Load Diff
@@ -28,32 +28,6 @@
|
||||
@implementation CPCollectionViewItem : CPViewController
|
||||
{
|
||||
BOOL _isSelected;
|
||||
CPData _cachedArchive;
|
||||
}
|
||||
|
||||
- (id)copy
|
||||
{
|
||||
var cibName = [self cibName],
|
||||
copy;
|
||||
|
||||
if (cibName)
|
||||
{
|
||||
copy = [[[self class] alloc] initWithCibName:cibName bundle:[self cibBundle]];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!_cachedArchive)
|
||||
_cachedArchive = [CPKeyedArchiver archivedDataWithRootObject:self];
|
||||
|
||||
copy = [CPKeyedUnarchiver unarchiveObjectWithData:_cachedArchive];
|
||||
|
||||
// copy connections
|
||||
}
|
||||
|
||||
[copy setRepresentedObject:[self representedObject]];
|
||||
[copy setSelected:_isSelected];
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
// Setting the Represented Object
|
||||
|
||||
+139
-1132
File diff suppressed because it is too large
Load Diff
+135
-145
@@ -23,33 +23,8 @@
|
||||
@import "CPButton.j"
|
||||
@import "CPCookie.j"
|
||||
@import "CPPanel.j"
|
||||
@import "CPPasteboard.j"
|
||||
@import "CPView.j"
|
||||
|
||||
@class CPSlider
|
||||
@class _CPColorPanelToolbar
|
||||
@class _CPColorPanelSwatches
|
||||
@class _CPColorPanelPreview
|
||||
|
||||
@global CPApp
|
||||
|
||||
/*
|
||||
A color wheel
|
||||
@global
|
||||
@group CPColorPanelMode
|
||||
*/
|
||||
CPWheelColorPickerMode = 1;
|
||||
|
||||
/*
|
||||
Slider based picker
|
||||
@global
|
||||
@group CPColorPanelMode
|
||||
*/
|
||||
CPSliderColorPickerMode = 2;
|
||||
|
||||
CPColorPickerViewWidth = 265;
|
||||
CPColorPickerViewHeight = 370;
|
||||
|
||||
CPColorPanelColorDidChangeNotification = @"CPColorPanelColorDidChangeNotification";
|
||||
|
||||
var PREVIEW_HEIGHT = 20.0,
|
||||
@@ -60,8 +35,24 @@ var PREVIEW_HEIGHT = 20.0,
|
||||
|
||||
var SharedColorPanel = nil,
|
||||
ColorPickerClasses = [];
|
||||
|
||||
/*
|
||||
A color wheel
|
||||
@global
|
||||
@group CPColorPanelMode
|
||||
*/
|
||||
CPWheelColorPickerMode = 1;
|
||||
/*
|
||||
Slider based picker
|
||||
@global
|
||||
@group CPColorPanelMode
|
||||
*/
|
||||
CPSliderColorPickerMode = 2;
|
||||
|
||||
/*!
|
||||
CPColorPickerViewWidth = 265,
|
||||
CPColorPickerViewHeight = 370;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPColorPanel
|
||||
|
||||
@@ -70,7 +61,8 @@ var SharedColorPanel = nil,
|
||||
obtain the panel, call the \c +sharedColorPanel method.
|
||||
*/
|
||||
@implementation CPColorPanel : CPPanel
|
||||
{
|
||||
{
|
||||
_CPColorPanelToolbar _toolbar;
|
||||
_CPColorPanelSwatches _swatchView;
|
||||
_CPColorPanelPreview _previewView;
|
||||
|
||||
@@ -88,8 +80,8 @@ var SharedColorPanel = nil,
|
||||
int _mode;
|
||||
}
|
||||
|
||||
/*!
|
||||
A list of color pickers is collected here, and any color panel created will contain
|
||||
/*!
|
||||
A list of color pickers is collected here, and any color panel created will contain
|
||||
any picker in this list up to this point. In other words, call before creating a color panel.
|
||||
*/
|
||||
+ (void)provideColorPickerClass:(Class)aColorPickerSubclass
|
||||
@@ -104,7 +96,7 @@ var SharedColorPanel = nil,
|
||||
{
|
||||
if (!SharedColorPanel)
|
||||
SharedColorPanel = [[CPColorPanel alloc] init];
|
||||
|
||||
|
||||
return SharedColorPanel;
|
||||
}
|
||||
|
||||
@@ -115,7 +107,7 @@ var SharedColorPanel = nil,
|
||||
+ (void)setPickerMode:(CPColorPanelMode)mode
|
||||
{
|
||||
var panel = [CPColorPanel sharedColorPanel];
|
||||
[panel setMode:mode];
|
||||
[panel setMode: mode];
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -124,23 +116,23 @@ var SharedColorPanel = nil,
|
||||
*/
|
||||
- (id)init
|
||||
{
|
||||
self = [super initWithContentRect:CGRectMake(500.0, 50.0, 219.0, 370.0)
|
||||
self = [super initWithContentRect:CGRectMake(500.0, 50.0, 219.0, 370.0)
|
||||
styleMask:(CPTitledWindowMask | CPClosableWindowMask | CPResizableWindowMask)];
|
||||
|
||||
if (self)
|
||||
{
|
||||
//[[self contentView] setBackgroundColor:[CPColor colorWithWhite:0.95 alpha:1.0]];
|
||||
[[self contentView] setBackgroundColor:[CPColor colorWithWhite:0.95 alpha:1.0]];
|
||||
|
||||
[self setTitle:@"Color Panel"];
|
||||
[self setLevel:CPFloatingWindowLevel];
|
||||
|
||||
|
||||
[self setFloatingPanel:YES];
|
||||
[self setBecomesKeyOnlyIfNeeded:YES];
|
||||
|
||||
[self setMinSize:CGSizeMake(219.0, 363.0)];
|
||||
|
||||
[self setMinSize:CGSizeMake(219.0, 342.0)];
|
||||
[self setMaxSize:CGSizeMake(323.0, 537.0)];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -150,13 +142,13 @@ var SharedColorPanel = nil,
|
||||
- (void)setColor:(CPColor)aColor
|
||||
{
|
||||
_color = aColor;
|
||||
[_previewView setBackgroundColor:_color];
|
||||
|
||||
[_previewView setBackgroundColor: _color];
|
||||
|
||||
[CPApp sendAction:@selector(changeColor:) to:nil from:self];
|
||||
|
||||
if (_target && _action)
|
||||
[CPApp sendAction:_action to:_target from:self];
|
||||
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPColorPanelColorDidChangeNotification
|
||||
object:self];
|
||||
@@ -173,7 +165,7 @@ var SharedColorPanel = nil,
|
||||
- (void)setColor:(CPColor)aColor updatePicker:(BOOL)bool
|
||||
{
|
||||
[self setColor:aColor];
|
||||
|
||||
|
||||
if (bool)
|
||||
[_activePicker setColor:_color];
|
||||
}
|
||||
@@ -240,30 +232,30 @@ var SharedColorPanel = nil,
|
||||
{
|
||||
var picker = _colorPickers[[sender tag]],
|
||||
view = [picker provideNewView:NO];
|
||||
|
||||
|
||||
if (!view)
|
||||
view = [picker provideNewView:YES];
|
||||
|
||||
|
||||
if (view == _currentView)
|
||||
return;
|
||||
|
||||
|
||||
if (_currentView)
|
||||
[view setFrame:[_currentView frame]];
|
||||
else
|
||||
{
|
||||
var height = (TOOLBAR_HEIGHT + 10 + PREVIEW_HEIGHT + 5 + SWATCH_HEIGHT + 32),
|
||||
var height = (TOOLBAR_HEIGHT+10+PREVIEW_HEIGHT+5+SWATCH_HEIGHT+32),
|
||||
bounds = [[self contentView] bounds];
|
||||
|
||||
[view setFrameSize:CGSizeMake(bounds.size.width - 10, bounds.size.height - height)];
|
||||
[view setFrameOrigin:CGPointMake(5, height)];
|
||||
[view setFrameSize: CPSizeMake(bounds.size.width - 10, bounds.size.height - height)];
|
||||
[view setFrameOrigin: CPPointMake(5, height)];
|
||||
}
|
||||
|
||||
|
||||
[_currentView removeFromSuperview];
|
||||
[[self contentView] addSubview:view];
|
||||
|
||||
|
||||
_currentView = view;
|
||||
_activePicker = picker;
|
||||
|
||||
|
||||
[picker setColor:[self color]];
|
||||
}
|
||||
|
||||
@@ -293,7 +285,7 @@ var SharedColorPanel = nil,
|
||||
_colorPickers = [];
|
||||
|
||||
var count = [ColorPickerClasses count];
|
||||
for (var i = 0; i < count; i++)
|
||||
for (var i=0; i<count; i++)
|
||||
{
|
||||
var currentPickerClass = ColorPickerClasses[i],
|
||||
currentPicker = [[currentPickerClass alloc] initWithPickerMask:0 colorPanel:self];
|
||||
@@ -305,29 +297,29 @@ var SharedColorPanel = nil,
|
||||
bounds = [contentView bounds];
|
||||
|
||||
_toolbar = [[CPView alloc] initWithFrame:CGRectMake(0, 6, CGRectGetWidth(bounds), TOOLBAR_HEIGHT)];
|
||||
[_toolbar setAutoresizingMask:CPViewWidthSizable];
|
||||
[_toolbar setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
var totalToolbarWidth = count * ICON_WIDTH + (count - 1) * ICON_PADDING,
|
||||
leftOffset = (CGRectGetWidth(bounds) - totalToolbarWidth) / 2.0,
|
||||
buttonForLater = nil;
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
for (var i=0; i<count; i++)
|
||||
{
|
||||
var image = [_colorPickers[i] provideNewButtonImage],
|
||||
highlightImage = [_colorPickers[i] provideNewAlternateButtonImage],
|
||||
button = [[CPButton alloc] initWithFrame:CGRectMake(leftOffset + i * (ICON_WIDTH + ICON_PADDING), 0, ICON_WIDTH, ICON_WIDTH)];
|
||||
|
||||
button = [[CPButton alloc] initWithFrame:CGRectMake(leftOffset + i*(ICON_WIDTH+ICON_PADDING), 0, ICON_WIDTH, ICON_WIDTH)];
|
||||
|
||||
[button setTag:i];
|
||||
[button setTarget:self];
|
||||
[button setAction:@selector(_setPicker:)];
|
||||
[button setBordered:NO];
|
||||
[button setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin];
|
||||
|
||||
[button setAutoresizingMask:CPViewMinXMargin|CPViewMaxXMargin];
|
||||
|
||||
[button setImage:image];
|
||||
[button setAlternateImage:highlightImage];
|
||||
|
||||
|
||||
[_toolbar addSubview:button];
|
||||
|
||||
|
||||
if (!buttonForLater)
|
||||
buttonForLater = button;
|
||||
}
|
||||
@@ -338,15 +330,15 @@ var SharedColorPanel = nil,
|
||||
_previewView = [[_CPColorPanelPreview alloc] initWithFrame:CGRectInset([previewBox bounds], 2.0, 2.0)];
|
||||
|
||||
[_previewView setColorPanel:self];
|
||||
[_previewView setAutoresizingMask:CPViewWidthSizable];
|
||||
[_previewView setAutoresizingMask:CPViewWidthSizable];
|
||||
|
||||
[previewBox setBackgroundColor:[CPColor colorWithWhite:0.8 alpha:1.0]];
|
||||
[previewBox setAutoresizingMask:CPViewWidthSizable];
|
||||
|
||||
[previewBox addSubview:_previewView];
|
||||
|
||||
var _previewLabel = [[CPTextField alloc] initWithFrame:CGRectMake(10, TOOLBAR_HEIGHT + 10, 60, 15)];
|
||||
[_previewLabel setStringValue:"Preview:"];
|
||||
var _previewLabel = [[CPTextField alloc] initWithFrame: CPRectMake(10, TOOLBAR_HEIGHT + 10, 60, 15)];
|
||||
[_previewLabel setStringValue: "Preview:"];
|
||||
[_previewLabel setTextColor:[CPColor blackColor]];
|
||||
[_previewLabel setAlignment:CPRightTextAlignment];
|
||||
|
||||
@@ -358,27 +350,26 @@ var SharedColorPanel = nil,
|
||||
|
||||
_swatchView = [[_CPColorPanelSwatches alloc] initWithFrame:CGRectInset([swatchBox bounds], 1.0, 1.0)];
|
||||
|
||||
[_swatchView setColorPanel:self];
|
||||
[_swatchView setAutoresizingMask:CPViewWidthSizable];
|
||||
[_swatchView setColorPanel: self];
|
||||
[_swatchView setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
[swatchBox addSubview:_swatchView];
|
||||
|
||||
var _swatchLabel = [[CPTextField alloc] initWithFrame:CGRectMake(10, TOOLBAR_HEIGHT + 8 + PREVIEW_HEIGHT + 6, 60, 15)];
|
||||
[_swatchLabel setStringValue:"Swatches:"];
|
||||
var _swatchLabel = [[CPTextField alloc] initWithFrame: CPRectMake(10, TOOLBAR_HEIGHT + 8 + PREVIEW_HEIGHT + 6, 60, 15)];
|
||||
[_swatchLabel setStringValue: "Swatches:"];
|
||||
[_swatchLabel setTextColor:[CPColor blackColor]];
|
||||
[_swatchLabel setAlignment:CPRightTextAlignment];
|
||||
|
||||
|
||||
var opacityLabel = [[CPTextField alloc] initWithFrame:CGRectMake(10, TOOLBAR_HEIGHT + PREVIEW_HEIGHT + 35, 60, 20)];
|
||||
[opacityLabel setStringValue:"Opacity:"];
|
||||
var opacityLabel = [[CPTextField alloc] initWithFrame: CPRectMake(10, TOOLBAR_HEIGHT + PREVIEW_HEIGHT + 35, 60, 20)];
|
||||
[opacityLabel setStringValue: "Opacity:"];
|
||||
[opacityLabel setTextColor:[CPColor blackColor]];
|
||||
[opacityLabel setAlignment:CPRightTextAlignment];
|
||||
|
||||
_opacitySlider = [[CPSlider alloc] initWithFrame:CGRectMake(76, TOOLBAR_HEIGHT + PREVIEW_HEIGHT + 34, CGRectGetWidth(bounds) - 86, 20.0)];
|
||||
|
||||
|
||||
[_opacitySlider setMinValue:0.0];
|
||||
[_opacitySlider setMaxValue:1.0];
|
||||
[_opacitySlider setAutoresizingMask:CPViewWidthSizable];
|
||||
|
||||
[_opacitySlider setTarget:self];
|
||||
[_opacitySlider setAction:@selector(setOpacity:)];
|
||||
@@ -395,7 +386,7 @@ var SharedColorPanel = nil,
|
||||
_action = nil;
|
||||
_activePicker = nil;
|
||||
|
||||
[_previewView setBackgroundColor:_color];
|
||||
[_previewView setBackgroundColor: _color];
|
||||
|
||||
if (buttonForLater)
|
||||
[self _setPicker:buttonForLater];
|
||||
@@ -413,49 +404,48 @@ var SharedColorPanel = nil,
|
||||
|
||||
|
||||
CPColorDragType = "CPColorDragType";
|
||||
|
||||
var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
|
||||
/* @ignore */
|
||||
@implementation _CPColorPanelSwatches : CPView
|
||||
{
|
||||
CPArray _swatches;
|
||||
CPView[] _swatches;
|
||||
CPColor _dragColor;
|
||||
CPColorPanel _colorPanel;
|
||||
CPCookie _swatchCookie;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
-(id)initWithFrame:(CPRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
[self setBackgroundColor:[CPColor grayColor]];
|
||||
|
||||
|
||||
[self setBackgroundColor: [CPColor grayColor]];
|
||||
|
||||
[self registerForDraggedTypes:[CPArray arrayWithObjects:CPColorDragType]];
|
||||
|
||||
var whiteColor = [CPColor whiteColor];
|
||||
|
||||
_swatchCookie = [[CPCookie alloc] initWithName:CPColorPanelSwatchesCookie];
|
||||
_swatchCookie = [[CPCookie alloc] initWithName: CPColorPanelSwatchesCookie];
|
||||
var colorList = [self startingColorList];
|
||||
|
||||
|
||||
_swatches = [];
|
||||
|
||||
for (var i = 0; i < 50; i++)
|
||||
|
||||
for(var i=0; i < 50; i++)
|
||||
{
|
||||
// FIXME: http://280north.lighthouseapp.com/projects/13294-cappuccino/tickets/25-implement-cpbox
|
||||
var view = [[CPView alloc] initWithFrame:CGRectMake(13 * i + 1, 1, 12, 12)],
|
||||
var view = [[CPView alloc] initWithFrame: CPRectMake(13*i+1, 1, 12, 12)],
|
||||
fillView = [[CPView alloc] initWithFrame:CGRectInset([view bounds], 1.0, 1.0)];
|
||||
|
||||
|
||||
[view setBackgroundColor:whiteColor];
|
||||
[fillView setBackgroundColor:(i < colorList.length) ? colorList[i] : whiteColor];
|
||||
[fillView setBackgroundColor: (i < colorList.length) ? colorList[i] : whiteColor];
|
||||
|
||||
[view addSubview:fillView];
|
||||
|
||||
[self addSubview:view];
|
||||
|
||||
[self addSubview: view];
|
||||
|
||||
_swatches.push(view);
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -467,8 +457,7 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
- (CPArray)startingColorList
|
||||
{
|
||||
var cookieValue = [_swatchCookie value];
|
||||
|
||||
if (!cookieValue)
|
||||
if(cookieValue == "")
|
||||
{
|
||||
return [
|
||||
[CPColor blackColor],
|
||||
@@ -482,26 +471,27 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
[CPColor yellowColor]
|
||||
];
|
||||
}
|
||||
|
||||
var cookieValue = eval(cookieValue);
|
||||
var result = [];
|
||||
|
||||
for(var i=0; i<cookieValue.length; i++)
|
||||
result.push([CPColor colorWithHexString: cookieValue[i]]);
|
||||
|
||||
var cookieValue = JSON.parse(cookieValue);
|
||||
|
||||
return [cookieValue arrayByApplyingBlock:function(value)
|
||||
{
|
||||
return [CPColor colorWithHexString:value];
|
||||
}];
|
||||
return result;
|
||||
}
|
||||
|
||||
- (CPArray)saveColorList
|
||||
{
|
||||
var result = [];
|
||||
// FIXME: http://280north.lighthouseapp.com/projects/13294-cappuccino/tickets/25-implement-cpbox
|
||||
for (var i = 0; i < _swatches.length; i++)
|
||||
for(var i=0; i<_swatches.length; i++)
|
||||
result.push([[[_swatches[i] subviews][0] backgroundColor] hexString]);
|
||||
|
||||
|
||||
var future = new Date();
|
||||
future.setYear(2019);
|
||||
|
||||
[_swatchCookie setValue:JSON.stringify(result) expires:future domain:nil];
|
||||
|
||||
[_swatchCookie setValue: JSON.stringify(result) expires:future domain: nil];
|
||||
}
|
||||
|
||||
- (void)setColorPanel:(CPColorPanel)panel
|
||||
@@ -530,63 +520,63 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
{
|
||||
var point = [self convertPoint:[anEvent locationInWindow] fromView:nil],
|
||||
bounds = [self bounds];
|
||||
|
||||
if (!CGRectContainsPoint(bounds, point) || point.x > [self bounds].size.width - 1 || point.x < 1)
|
||||
|
||||
if(!CGRectContainsPoint(bounds, point) || point.x > [self bounds].size.width - 1 || point.x < 1)
|
||||
return NO;
|
||||
|
||||
[_colorPanel setColor:[self colorAtIndex:FLOOR(point.x / 13)] updatePicker:YES];
|
||||
[_colorPanel setColor: [self colorAtIndex:FLOOR(point.x / 13)] updatePicker: YES];
|
||||
}
|
||||
|
||||
- (void)mouseDragged:(CPEvent)anEvent
|
||||
{
|
||||
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];
|
||||
|
||||
|
||||
var swatch = _swatches[FLOOR(point.x / 13)];
|
||||
|
||||
|
||||
// FIXME: http://280north.lighthouseapp.com/projects/13294-cappuccino/tickets/25-implement-cpbox
|
||||
_dragColor = [[swatch subviews][0] backgroundColor];
|
||||
|
||||
var bounds = CGRectMakeCopy([swatch bounds]);
|
||||
|
||||
var bounds = CPRectCreateCopy([swatch bounds]);
|
||||
|
||||
// FIXME: http://280north.lighthouseapp.com/projects/13294-cappuccino/tickets/25-implement-cpbox
|
||||
var dragView = [[CPView alloc] initWithFrame:bounds],
|
||||
var dragView = [[CPView alloc] initWithFrame: bounds];
|
||||
dragFillView = [[CPView alloc] initWithFrame:CGRectInset(bounds, 1.0, 1.0)];
|
||||
|
||||
|
||||
[dragView setBackgroundColor:[CPColor blackColor]];
|
||||
[dragFillView setBackgroundColor:_dragColor];
|
||||
|
||||
|
||||
[dragView addSubview:dragFillView];
|
||||
|
||||
[self dragView:dragView
|
||||
at:CGPointMake(point.x - bounds.size.width / 2.0, point.y - bounds.size.height / 2.0)
|
||||
offset:CGPointMake(0.0, 0.0)
|
||||
event:anEvent
|
||||
pasteboard:nil
|
||||
source:self
|
||||
slideBack:YES];
|
||||
[self dragView: dragView
|
||||
at: CPPointMake(point.x - bounds.size.width / 2.0, point.y - bounds.size.height / 2.0)
|
||||
offset: CPPointMake(0.0, 0.0)
|
||||
event: anEvent
|
||||
pasteboard: nil
|
||||
source: self
|
||||
slideBack: YES];
|
||||
}
|
||||
|
||||
- (void)pasteboard:(CPPasteboard)aPasteboard provideDataForType:(CPString)aType
|
||||
{
|
||||
if (aType == CPColorDragType)
|
||||
if(aType == CPColorDragType)
|
||||
[aPasteboard setData:[CPKeyedArchiver archivedDataWithRootObject:_dragColor] forType:aType];
|
||||
}
|
||||
|
||||
- (void)performDragOperation:(id /*<CPDraggingInfo>*/)aSender
|
||||
{
|
||||
- (void)performDragOperation:(id <CPDraggingInfo>)aSender
|
||||
{
|
||||
var location = [self convertPoint:[aSender draggingLocation] fromView:nil],
|
||||
pasteboard = [aSender draggingPasteboard],
|
||||
swatch = nil;
|
||||
|
||||
if (![pasteboard availableTypeFromArray:[CPColorDragType]] || location.x > [self bounds].size.width - 1 || location.x < 1)
|
||||
if(![pasteboard availableTypeFromArray:[CPColorDragType]] || location.x > [self bounds].size.width - 1 || location.x < 1)
|
||||
return NO;
|
||||
|
||||
[self setColor:[CPKeyedUnarchiver unarchiveObjectWithData:[pasteboard dataForType:CPColorDragType]] atIndex:FLOOR(location.x / 13)];
|
||||
|
||||
[self setColor:[CPKeyedUnarchiver unarchiveObjectWithData:[pasteboard dataForType:CPColorDragType]] atIndex: FLOOR(location.x / 13)];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -597,12 +587,12 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
CPColorPanel _colorPanel;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
- (id)initWithFrame:(CPRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
|
||||
[self registerForDraggedTypes:[CPArray arrayWithObjects:CPColorDragType]];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -616,13 +606,13 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
return _colorPanel;
|
||||
}
|
||||
|
||||
- (void)performDragOperation:(id /*<CPDraggingInfo>*/)aSender
|
||||
- (void)performDragOperation:(id <CPDraggingInfo>)aSender
|
||||
{
|
||||
var pasteboard = [aSender draggingPasteboard];
|
||||
|
||||
if (![pasteboard availableTypeFromArray:[CPColorDragType]])
|
||||
if(![pasteboard availableTypeFromArray:[CPColorDragType]])
|
||||
return NO;
|
||||
|
||||
|
||||
var color = [CPKeyedUnarchiver unarchiveObjectWithData:[pasteboard dataForType:CPColorDragType]];
|
||||
[_colorPanel setColor:color updatePicker:YES];
|
||||
}
|
||||
@@ -636,31 +626,31 @@ var CPColorPanelSwatchesCookie = "CPColorPanelSwatchesCookie";
|
||||
{
|
||||
var point = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
|
||||
[[CPPasteboard pasteboardWithName:CPDragPboard] declareTypes:[CPColorDragType] owner:self];
|
||||
|
||||
var bounds = CGRectMake(0, 0, 15, 15);
|
||||
|
||||
[[CPPasteboard pasteboardWithName:CPDragPboard] declareTypes:[CPColorDragType] owner:self];
|
||||
|
||||
var bounds = CPRectMake(0, 0, 15, 15);
|
||||
|
||||
// FIXME: http://280north.lighthouseapp.com/projects/13294-cappuccino/tickets/25-implement-cpbox
|
||||
var dragView = [[CPView alloc] initWithFrame:bounds],
|
||||
var dragView = [[CPView alloc] initWithFrame: bounds];
|
||||
dragFillView = [[CPView alloc] initWithFrame:CGRectInset(bounds, 1.0, 1.0)];
|
||||
|
||||
|
||||
[dragView setBackgroundColor:[CPColor blackColor]];
|
||||
[dragFillView setBackgroundColor:[self backgroundColor]];
|
||||
|
||||
|
||||
[dragView addSubview:dragFillView];
|
||||
|
||||
[self dragView:dragView
|
||||
at:CGPointMake(point.x - bounds.size.width / 2.0, point.y - bounds.size.height / 2.0)
|
||||
offset:CGPointMake(0.0, 0.0)
|
||||
event:anEvent
|
||||
pasteboard:nil
|
||||
source:self
|
||||
slideBack:YES];
|
||||
|
||||
[self dragView: dragView
|
||||
at: CPPointMake(point.x - bounds.size.width / 2.0, point.y - bounds.size.height / 2.0)
|
||||
offset: CPPointMake(0.0, 0.0)
|
||||
event: anEvent
|
||||
pasteboard: nil
|
||||
source: self
|
||||
slideBack: YES];
|
||||
}
|
||||
|
||||
- (void)pasteboard:(CPPasteboard)aPasteboard provideDataForType:(CPString)aType
|
||||
{
|
||||
if (aType == CPColorDragType)
|
||||
if(aType == CPColorDragType)
|
||||
[aPasteboard setData:[CPKeyedArchiver archivedDataWithRootObject:[self backgroundColor]] forType:aType];
|
||||
}
|
||||
|
||||
|
||||
+82
-92
@@ -21,19 +21,11 @@
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import "CPColorPanel.j"
|
||||
|
||||
@import "CPView.j"
|
||||
#include "Platform/Platform.h"
|
||||
|
||||
@class CPSlider
|
||||
@class CPColorPanel
|
||||
@class __CPColorWheel
|
||||
|
||||
@global CPColorPickerViewWidth
|
||||
@global CPColorPickerViewHeight
|
||||
@global CPWheelColorPickerMode
|
||||
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPColorPicker
|
||||
|
||||
@@ -52,11 +44,10 @@
|
||||
*/
|
||||
- (id)initWithPickerMask:(int)aMask colorPanel:(CPColorPanel)aPanel
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_panel = aPanel;
|
||||
_mask = aMask;
|
||||
}
|
||||
self = [super init];
|
||||
|
||||
_panel = aPanel;
|
||||
_mask = aMask;
|
||||
|
||||
return self;
|
||||
}
|
||||
@@ -85,6 +76,7 @@
|
||||
*/
|
||||
- (void)setMode:(CPColorPanelMode)mode
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -93,6 +85,7 @@
|
||||
*/
|
||||
- (void)setColor:(CPColor)aColor
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -109,24 +102,23 @@
|
||||
|
||||
CPColor _cachedColor;
|
||||
}
|
||||
|
||||
- (id)initWithPickerMask:(int)mask colorPanel:(CPColorPanel)owningColorPanel
|
||||
|
||||
- (id)initWithPickerMask:(int)mask colorPanel:(CPColorPanel)owningColorPanel
|
||||
{
|
||||
return [super initWithPickerMask:mask colorPanel: owningColorPanel];
|
||||
}
|
||||
|
||||
- (id)initView
|
||||
-(id)initView
|
||||
{
|
||||
var aFrame = CGRectMake(0, 0, CPColorPickerViewWidth, CPColorPickerViewHeight);
|
||||
aFrame = CPRectMake(0, 0, CPColorPickerViewWidth, CPColorPickerViewHeight);
|
||||
|
||||
_pickerView = [[CPView alloc] initWithFrame:aFrame];
|
||||
[_pickerView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
|
||||
[_pickerView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
|
||||
|
||||
_brightnessSlider = [[CPSlider alloc] initWithFrame:CGRectMake(0, (aFrame.size.height - 34), aFrame.size.width, 15)];
|
||||
|
||||
[_brightnessSlider setValue:15.0 forThemeAttribute:@"track-width"];
|
||||
var brightnessImage = [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[CPColorPicker class]] pathForResource:@"brightness_bar.png"] size:CGSizeMake(272, 20)];
|
||||
[_brightnessSlider setValue:[CPColor colorWithPatternImage:brightnessImage] forThemeAttribute:@"track-color"];
|
||||
[_brightnessSlider setValue:[CPColor colorWithPatternImage:[[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[CPColorPicker class]] pathForResource:@"brightness_bar.png"]]] forThemeAttribute:@"track-color"];
|
||||
|
||||
[_brightnessSlider setMinValue:0.0];
|
||||
[_brightnessSlider setMaxValue:100.0];
|
||||
@@ -136,37 +128,37 @@
|
||||
[_brightnessSlider setAction:@selector(brightnessSliderDidChange:)];
|
||||
[_brightnessSlider setAutoresizingMask:CPViewWidthSizable | CPViewMinYMargin];
|
||||
|
||||
_hueSaturationView = [[__CPColorWheel alloc] initWithFrame:CGRectMake(0, 0, aFrame.size.width, aFrame.size.height - 38)];
|
||||
[_hueSaturationView setDelegate:self];
|
||||
[_hueSaturationView setAutoresizingMask:(CPViewWidthSizable | CPViewHeightSizable)];
|
||||
_hueSaturationView = [[__CPColorWheel alloc] initWithFrame: CPRectMake(0, 0, aFrame.size.width, aFrame.size.height - 38)];
|
||||
[_hueSaturationView setDelegate: self];
|
||||
[_hueSaturationView setAutoresizingMask: (CPViewWidthSizable | CPViewHeightSizable)];
|
||||
|
||||
[_pickerView addSubview:_hueSaturationView];
|
||||
[_pickerView addSubview:_brightnessSlider];
|
||||
}
|
||||
|
||||
- (void)brightnessSliderDidChange:(id)sender
|
||||
-(void)brightnessSliderDidChange:(id)sender
|
||||
{
|
||||
[self updateColor];
|
||||
}
|
||||
|
||||
- (void)colorWheelDidChange:(id)sender
|
||||
-(void)colorWheelDidChange:(id)sender
|
||||
{
|
||||
[self updateColor];
|
||||
}
|
||||
|
||||
- (void)updateColor
|
||||
-(void)updateColor
|
||||
{
|
||||
var hue = [_hueSaturationView angle],
|
||||
saturation = [_hueSaturationView distance],
|
||||
brightness = [_brightnessSlider floatValue];
|
||||
|
||||
[_hueSaturationView setWheelBrightness:brightness / 100.0];
|
||||
[_brightnessSlider setBackgroundColor:[CPColor colorWithHue:hue / 360.0 saturation:saturation / 100.0 brightness:1]];
|
||||
[_brightnessSlider setBackgroundColor:[CPColor colorWithHue:hue saturation:saturation brightness:100]];
|
||||
|
||||
var colorPanel = [self colorPanel],
|
||||
opacity = [colorPanel opacity];
|
||||
|
||||
_cachedColor = [CPColor colorWithHue:hue / 360.0 saturation:saturation / 100.0 brightness:brightness / 100.0 alpha:opacity];
|
||||
_cachedColor = [CPColor colorWithHue:hue saturation:saturation brightness:brightness alpha:opacity];
|
||||
|
||||
[[self colorPanel] setColor:_cachedColor];
|
||||
}
|
||||
@@ -197,10 +189,10 @@
|
||||
var hsb = [newColor hsbComponents];
|
||||
|
||||
[_hueSaturationView setPositionToColor:newColor];
|
||||
[_brightnessSlider setFloatValue:hsb[2] * 100.0];
|
||||
[_hueSaturationView setWheelBrightness:hsb[2]];
|
||||
[_brightnessSlider setFloatValue:hsb[2]];
|
||||
[_hueSaturationView setWheelBrightness:hsb[2] / 100.0];
|
||||
|
||||
[_brightnessSlider setBackgroundColor:[CPColor colorWithHue:hsb[0] saturation:hsb[1] brightness:1]];
|
||||
[_brightnessSlider setBackgroundColor:[CPColor colorWithHue:hsb[0] saturation:hsb[1] brightness:100]];
|
||||
}
|
||||
|
||||
- (CPImage)provideNewButtonImage
|
||||
@@ -231,64 +223,60 @@
|
||||
float _radius;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
-(id)initWithFrame:(CPRect)aFrame
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
var path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel.png"];
|
||||
|
||||
_wheelImage = new Image();
|
||||
_wheelImage.src = path;
|
||||
_wheelImage.style.position = "absolute";
|
||||
|
||||
path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel_black.png"];
|
||||
|
||||
_blackWheelImage = new Image();
|
||||
_blackWheelImage.src = path;
|
||||
_blackWheelImage.style.opacity = "0";
|
||||
_blackWheelImage.style.filter = "alpha(opacity=0)"
|
||||
_blackWheelImage.style.position = "absolute";
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
var path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel.png"];
|
||||
|
||||
_wheelImage = new Image();
|
||||
_wheelImage.src = path;
|
||||
_wheelImage.style.position = "absolute";
|
||||
|
||||
path = [[CPBundle bundleForClass:CPColorPicker] pathForResource:@"wheel_black.png"];
|
||||
|
||||
_blackWheelImage = new Image();
|
||||
_blackWheelImage.src = path;
|
||||
_blackWheelImage.style.opacity = "0";
|
||||
_blackWheelImage.style.filter = "alpha(opacity=0)";
|
||||
_blackWheelImage.style.position = "absolute";
|
||||
|
||||
_DOMElement.appendChild(_wheelImage);
|
||||
_DOMElement.appendChild(_blackWheelImage);
|
||||
_DOMElement.appendChild(_wheelImage);
|
||||
_DOMElement.appendChild(_blackWheelImage);
|
||||
#endif
|
||||
|
||||
[self setWheelSize:aFrame.size];
|
||||
[self setWheelSize:aFrame.size];
|
||||
|
||||
_crosshair = [[CPView alloc] initWithFrame:CGRectMake(_radius - 2, _radius - 2, 4, 4)];
|
||||
[_crosshair setBackgroundColor:[CPColor blackColor]];
|
||||
_crosshair = [[CPView alloc] initWithFrame:CPRectMake(_radius - 2, _radius - 2, 4, 4)];
|
||||
[_crosshair setBackgroundColor:[CPColor blackColor]];
|
||||
|
||||
var view = [[CPView alloc] initWithFrame:CGRectInset([_crosshair bounds], 1.0, 1.0)];
|
||||
[view setBackgroundColor:[CPColor whiteColor]];
|
||||
var view = [[CPView alloc] initWithFrame:CGRectInset([_crosshair bounds], 1.0, 1.0)];
|
||||
[view setBackgroundColor:[CPColor whiteColor]];
|
||||
|
||||
[_crosshair addSubview:view];
|
||||
[_crosshair addSubview:view];
|
||||
|
||||
[self addSubview:_crosshair];
|
||||
}
|
||||
[self addSubview:_crosshair];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setWheelBrightness:(float)brightness
|
||||
-(void)setWheelBrightness:(float)brightness
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
_blackWheelImage.style.opacity = 1.0 - brightness;
|
||||
_blackWheelImage.style.filter = "alpha(opacity=" + (1.0 - brightness) * 100 + ")"
|
||||
#endif
|
||||
_blackWheelImage.style.filter = "alpha(opacity=" + (1.0 - brightness)*100 + ")"
|
||||
}
|
||||
|
||||
- (void)setFrameSize:(CGSize)aSize
|
||||
-(void)setFrameSize:(CPSize)aSize
|
||||
{
|
||||
[super setFrameSize:aSize];
|
||||
[self setWheelSize:aSize];
|
||||
}
|
||||
|
||||
- (void)setWheelSize:(CGSize)aSize
|
||||
-(void)setWheelSize:(CPSize)aSize
|
||||
{
|
||||
var min = MIN(aSize.width, aSize.height);
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_blackWheelImage.style.width = min;
|
||||
_blackWheelImage.style.height = min;
|
||||
_blackWheelImage.width = min;
|
||||
@@ -302,85 +290,87 @@
|
||||
_wheelImage.height = min;
|
||||
_wheelImage.style.top = (aSize.height - min) / 2.0 + "px";
|
||||
_wheelImage.style.left = (aSize.width - min) / 2.0 + "px";
|
||||
#endif
|
||||
|
||||
_radius = min / 2.0;
|
||||
|
||||
[self setAngle:[self degreesToRadians:_angle] distance:(_distance / 100.0) * _radius];
|
||||
}
|
||||
|
||||
- (void)setDelegate:(id)aDelegate
|
||||
-(void)setDelegate:(id)aDelegate
|
||||
{
|
||||
_delegate = aDelegate;
|
||||
}
|
||||
|
||||
- (id)delegate
|
||||
-(id)delegate
|
||||
{
|
||||
return _delegate;
|
||||
}
|
||||
|
||||
- (float)angle
|
||||
-(float)angle
|
||||
{
|
||||
return _angle;
|
||||
}
|
||||
|
||||
- (float)distance
|
||||
-(float)distance
|
||||
{
|
||||
return _distance;
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
-(void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
[self reposition:anEvent];
|
||||
}
|
||||
|
||||
- (void)mouseDragged:(CPEvent)anEvent
|
||||
-(void)mouseDragged:(CPEvent)anEvent
|
||||
{
|
||||
[self reposition:anEvent];
|
||||
}
|
||||
|
||||
- (void)reposition:(CPEvent)anEvent
|
||||
-(void)reposition:(CPEvent)anEvent
|
||||
{
|
||||
var bounds = [self bounds],
|
||||
location = [self convertPoint:[anEvent locationInWindow] fromView:nil],
|
||||
midX = CGRectGetMidX(bounds),
|
||||
midY = CGRectGetMidY(bounds),
|
||||
distance = MIN(SQRT((location.x - midX) * (location.x - midX) + (location.y - midY) * (location.y - midY)), _radius),
|
||||
angle = ATAN2(location.y - midY, location.x - midX);
|
||||
location = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
|
||||
var midX = CGRectGetMidX(bounds);
|
||||
var midY = CGRectGetMidY(bounds);
|
||||
|
||||
var distance = MIN(SQRT((location.x - midX)*(location.x - midX) + (location.y - midY)*(location.y - midY)), _radius);
|
||||
var angle = ATAN2(location.y - midY, location.x - midX);
|
||||
|
||||
[self setAngle:angle distance:distance];
|
||||
|
||||
[_delegate colorWheelDidChange:self];
|
||||
}
|
||||
|
||||
- (void)setAngle:(int)angle distance:(float)distance
|
||||
-(void)setAngle:(int)angle distance:(float)distance
|
||||
{
|
||||
var bounds = [self bounds],
|
||||
midX = CGRectGetMidX(bounds),
|
||||
midY = CGRectGetMidY(bounds);
|
||||
var bounds = [self bounds];
|
||||
var midX = CGRectGetMidX(bounds);
|
||||
var midY = CGRectGetMidY(bounds);
|
||||
|
||||
_angle = [self radiansToDegrees:angle];
|
||||
_distance = (distance / _radius) * 100.0;
|
||||
|
||||
[_crosshair setFrameOrigin:CGPointMake(COS(angle) * distance + midX - 2.0, SIN(angle) * distance + midY - 2.0)];
|
||||
[_crosshair setFrameOrigin:CPPointMake(COS(angle) * distance + midX - 2.0, SIN(angle) * distance + midY - 2.0)];
|
||||
}
|
||||
|
||||
- (void)setPositionToColor:(CPColor)aColor
|
||||
-(void)setPositionToColor:(CPColor)aColor
|
||||
{
|
||||
var hsb = [aColor hsbComponents],
|
||||
bounds = [self bounds],
|
||||
angle = [self degreesToRadians:hsb[0] * 360.0],
|
||||
distance = hsb[1] * _radius;
|
||||
bounds = [self bounds];
|
||||
|
||||
var angle = [self degreesToRadians:hsb[0]],
|
||||
distance = (hsb[1] / 100.0) * _radius;
|
||||
|
||||
[self setAngle:angle distance:distance];
|
||||
}
|
||||
|
||||
- (int)radiansToDegrees:(float)radians
|
||||
-(int)radiansToDegrees:(float)radians
|
||||
{
|
||||
return ((-radians / PI) * 180 + 360) % 360;
|
||||
}
|
||||
|
||||
- (float)degreesToRadians:(float)degrees
|
||||
-(float)degreesToRadians:(float)degrees
|
||||
{
|
||||
return -(((degrees - 360) / 180) * PI);
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
/*
|
||||
* CPColorSpace.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexander Ljungberg.
|
||||
* Copyright 2012, SlevenBits Ltd.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
|
||||
var sRGBColorSpace = nil;
|
||||
|
||||
/*!
|
||||
Represent color spaces.
|
||||
*/
|
||||
@implementation CPColorSpace : CPObject
|
||||
{
|
||||
CGColorSpace _cgColorSpace;
|
||||
}
|
||||
|
||||
/*!
|
||||
Return an object representing the standard sRGB color space.
|
||||
*/
|
||||
+ (CPColorSpace)sRGBColorSpace
|
||||
{
|
||||
if (!sRGBColorSpace)
|
||||
sRGBColorSpace = [[self alloc] initWithCGColorSpace:CGColorSpaceCreateDeviceRGB()];
|
||||
return sRGBColorSpace;
|
||||
}
|
||||
|
||||
- (id)initWithCGColorSpace:(CGColorSpace)cgColorSpace
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_cgColorSpace = cgColorSpace;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Return a Core Graphics color space representing the receiver.
|
||||
*/
|
||||
- (CGColorSpace)CGColorSpace
|
||||
{
|
||||
return _cgColorSpace;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+94
-207
@@ -29,7 +29,7 @@
|
||||
|
||||
var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiveNotification";
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPColorWell
|
||||
|
||||
@@ -41,57 +41,31 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
{
|
||||
BOOL _active;
|
||||
BOOL _bordered;
|
||||
|
||||
|
||||
CPColor _color;
|
||||
}
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding == CPValueBinding)
|
||||
return [CPColorWellValueBinder class];
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return @"colorwell";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"bezel-inset": CGInsetMakeZero(),
|
||||
@"bezel-color": [CPNull null],
|
||||
@"content-inset": CGInsetMake(3.0, 3.0, 3.0, 3.0),
|
||||
@"content-border-inset": CGInsetMakeZero(),
|
||||
@"content-border-color": [CPNull null],
|
||||
};
|
||||
}
|
||||
|
||||
- (void)_reverseSetBinding
|
||||
{
|
||||
var binderClass = [[self class] _binderClassForBinding:CPValueBinding],
|
||||
theBinding = [binderClass getBinding:CPValueBinding forObject:self];
|
||||
|
||||
[theBinding reverseSetValueFor:@"color"];
|
||||
CPView _wellView;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_active = NO;
|
||||
_bordered = YES;
|
||||
_color = [CPColor whiteColor];
|
||||
[self setBordered:YES];
|
||||
|
||||
[self drawBezelWithHighlight:NO];
|
||||
[self drawWellInside:CGRectInset([self bounds], 3.0, 3.0)];
|
||||
|
||||
[self _registerForNotifications];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_registerNotifications
|
||||
- (void)_registerForNotifications
|
||||
{
|
||||
var defaultCenter = [CPNotificationCenter defaultCenter];
|
||||
|
||||
@@ -108,39 +82,25 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
object:[CPColorPanel sharedColorPanel]];
|
||||
}
|
||||
|
||||
- (void)_removeNotifications
|
||||
{
|
||||
var defaultCenter = [CPNotificationCenter defaultCenter];
|
||||
|
||||
[defaultCenter
|
||||
removeObserver:self
|
||||
name:_CPColorWellDidBecomeExclusiveNotification
|
||||
object:nil];
|
||||
|
||||
[defaultCenter
|
||||
removeObserver:self
|
||||
name:CPWindowWillCloseNotification
|
||||
object:[CPColorPanel sharedColorPanel]];
|
||||
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets whether the color well is bordered.
|
||||
*/
|
||||
- (void)setBordered:(BOOL)shouldBeBordered
|
||||
{
|
||||
if (shouldBeBordered)
|
||||
[self setThemeState:CPThemeStateBordered];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateBordered];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns whether the color well is bordered
|
||||
*/
|
||||
- (BOOL)isBordered
|
||||
{
|
||||
return [self hasThemeState:CPThemeStateBordered];
|
||||
return _bordered;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the color well's current color.
|
||||
*/
|
||||
- (void)setBordered:(BOOL)bordered
|
||||
{
|
||||
if (_bordered == bordered)
|
||||
return;
|
||||
|
||||
_bordered = bordered;
|
||||
|
||||
[self drawWellInside:CGRectInset([self bounds], 3.0, 3.0)];
|
||||
}
|
||||
|
||||
// Managing Color From Color Wells
|
||||
@@ -160,10 +120,10 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
{
|
||||
if (_color == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_color = aColor;
|
||||
|
||||
[self setNeedsLayout];
|
||||
|
||||
[self drawWellInside:CGRectInset([self bounds], 3.0, 3.0)];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -177,7 +137,7 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
|
||||
// Activating and Deactivating Color Wells
|
||||
/*!
|
||||
Activates the color well, displays the color panel, and makes the panel's current color the same as its own.
|
||||
Activates the color well, displays the color panel, and makes the panel's current color the same as its own.
|
||||
If exclusive is \c YES, deactivates any other CPColorWells. \c NO, keeps them active.
|
||||
@param shouldBeExclusive whether other color wells should be deactivated.
|
||||
*/
|
||||
@@ -192,9 +152,9 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
|
||||
if ([self isActive])
|
||||
return;
|
||||
|
||||
|
||||
_active = YES;
|
||||
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
addObserver:self
|
||||
selector:@selector(colorPanelDidChangeColor:)
|
||||
@@ -209,9 +169,9 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
{
|
||||
if (![self isActive])
|
||||
return;
|
||||
|
||||
|
||||
_active = NO;
|
||||
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
removeObserver:self
|
||||
name:CPColorPanelColorDidChangeNotification
|
||||
@@ -226,10 +186,35 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
return _active;
|
||||
}
|
||||
|
||||
// Drawing a Color Well
|
||||
|
||||
- (void)drawBezelWithHighlight:(BOOL)shouldHighlight
|
||||
{
|
||||
}
|
||||
|
||||
/*!
|
||||
Draws the colored area inside the color well without borders.
|
||||
@param aRect the location at which to draw
|
||||
*/
|
||||
- (void)drawWellInside:(CGRect)aRect
|
||||
{
|
||||
if (!_wellView)
|
||||
{
|
||||
_wellView = [[CPView alloc] initWithFrame:aRect];
|
||||
[_wellView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
|
||||
|
||||
[self addSubview:_wellView];
|
||||
}
|
||||
else
|
||||
[_wellView setFrame:aRect];
|
||||
|
||||
[_wellView setBackgroundColor:_color];
|
||||
}
|
||||
|
||||
- (void)colorPanelDidChangeColor:(CPNotification)aNotification
|
||||
{
|
||||
[self takeColorFrom:[aNotification object]];
|
||||
|
||||
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
}
|
||||
|
||||
@@ -244,143 +229,31 @@ var _CPColorWellDidBecomeExclusiveNotification = @"_CPColorWellDidBecomeExclusiv
|
||||
[self deactivate];
|
||||
}
|
||||
|
||||
- (void)stopTracking:(CGPoint)lastPoint at:(CGPoint)aPoint mouseIsUp:(BOOL)mouseIsUp
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
[self highlight:NO];
|
||||
[self drawBezelWithHighlight:YES];
|
||||
}
|
||||
|
||||
if (!mouseIsUp || !CGRectContainsPoint([self bounds], aPoint) || ![self isEnabled])
|
||||
- (void)mouseDragged:(CPEvent)anEvent
|
||||
{
|
||||
[self drawBezelWithHighlight:CGRectContainsPoint([self bounds], [self convertPoint:[anEvent locationInWindow] fromView:nil])];
|
||||
}
|
||||
|
||||
-(void)mouseUp:(CPEvent)anEvent
|
||||
{
|
||||
[self drawBezelWithHighlight:NO];
|
||||
|
||||
if (!CGRectContainsPoint([self bounds], [self convertPoint:[anEvent locationInWindow] fromView:nil]))
|
||||
return;
|
||||
|
||||
|
||||
[self activate:YES];
|
||||
|
||||
var colorPanel = [CPColorPanel sharedColorPanel];
|
||||
|
||||
[colorPanel setPlatformWindow:[[self window] platformWindow]];
|
||||
|
||||
|
||||
[colorPanel setColor:_color];
|
||||
[colorPanel orderFront:self];
|
||||
}
|
||||
|
||||
- (CGRect)contentRectForBounds:(CGRect)bounds
|
||||
{
|
||||
var contentInset = [self currentValueForThemeAttribute:@"content-inset"];
|
||||
|
||||
return CGRectInsetByInset(bounds, contentInset);
|
||||
}
|
||||
|
||||
- (CGRect)bezelRectForBounds:(CGRect)bounds
|
||||
{
|
||||
var bezelInset = [self currentValueForThemeAttribute:@"bezel-inset"];
|
||||
|
||||
return CGRectInsetByInset(bounds, bezelInset);
|
||||
}
|
||||
|
||||
- (CGRect)contentBorderRectForBounds:(CGRect)bounds
|
||||
{
|
||||
var contentBorderInset = [self currentValueForThemeAttribute:@"content-border-inset"];
|
||||
|
||||
return CGRectInsetByInset(bounds, contentBorderInset);
|
||||
}
|
||||
|
||||
- (CGRect)rectForEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
switch (aName)
|
||||
{
|
||||
case "bezel-view":
|
||||
return [self bezelRectForBounds:[self bounds]];
|
||||
case "content-view":
|
||||
return [self contentRectForBounds:[self bounds]];
|
||||
case "content-border-view":
|
||||
return [self contentBorderRectForBounds:[self bounds]];
|
||||
}
|
||||
|
||||
return [super rectForEphemeralSubviewNamed:aName];
|
||||
}
|
||||
|
||||
- (CPView)createEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
var view = [[CPView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[view setHitTests:NO];
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
var bezelView = [self layoutEphemeralSubviewNamed:@"bezel-view"
|
||||
positioned:CPWindowBelow
|
||||
relativeToEphemeralSubviewNamed:@"content-view"];
|
||||
|
||||
[bezelView setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
|
||||
|
||||
var contentView = [self layoutEphemeralSubviewNamed:@"content-view"
|
||||
positioned:CPWindowAbove
|
||||
relativeToEphemeralSubviewNamed:@"bezel-view"];
|
||||
|
||||
|
||||
[contentView setBackgroundColor:_color];
|
||||
|
||||
var contentBorderView = [self layoutEphemeralSubviewNamed:@"content-border-view"
|
||||
positioned:CPWindowAbove
|
||||
relativeToEphemeralSubviewNamed:@"content-view"];
|
||||
|
||||
[contentBorderView setBackgroundColor:[self currentValueForThemeAttribute:@"content-border-color"]];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Observers method
|
||||
|
||||
- (void)_addObservers
|
||||
{
|
||||
if (_isObserving)
|
||||
return;
|
||||
|
||||
[super _addObservers];
|
||||
[self _registerNotifications];
|
||||
}
|
||||
|
||||
- (void)_removeObservers
|
||||
{
|
||||
if (!_isObserving)
|
||||
return;
|
||||
|
||||
[super _removeObservers];
|
||||
[self _removeNotifications];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPColorWellValueBinder : CPBinder
|
||||
{
|
||||
}
|
||||
|
||||
- (void)_updatePlaceholdersWithOptions:(CPDictionary)options
|
||||
{
|
||||
var placeholderColor = [CPColor blackColor];
|
||||
|
||||
[self _setPlaceholder:placeholderColor forMarker:CPMultipleValuesMarker isDefault:YES];
|
||||
[self _setPlaceholder:placeholderColor forMarker:CPNoSelectionMarker isDefault:YES];
|
||||
[self _setPlaceholder:placeholderColor forMarker:CPNotApplicableMarker isDefault:YES];
|
||||
[self _setPlaceholder:placeholderColor forMarker:CPNullMarker isDefault:YES];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
return [_source color];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)theBinding
|
||||
{
|
||||
[_source setColor:aValue];
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source setColor:aValue];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPColorWellColorKey = "CPColorWellColorKey",
|
||||
@@ -395,14 +268,19 @@ var CPColorWellColorKey = "CPColorWellColorKey",
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_active = NO;
|
||||
_bordered = [aCoder decodeObjectForKey:CPColorWellBorderedKey];
|
||||
_color = [aCoder decodeObjectForKey:CPColorWellColorKey];
|
||||
[self setBordered:[aCoder decodeBoolForKey:CPColorWellBorderedKey]];
|
||||
}
|
||||
|
||||
[self drawBezelWithHighlight:NO];
|
||||
[self drawWellInside:CGRectInset([self bounds], 3.0, 3.0)];
|
||||
|
||||
[self _registerForNotifications];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -412,10 +290,19 @@ var CPColorWellColorKey = "CPColorWellColorKey",
|
||||
*/
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
// We do this in order to avoid encoding the _wellView, which
|
||||
// should just automatically be created programmatically as needed.
|
||||
var actualSubviews = _subviews;
|
||||
|
||||
_subviews = [_subviews copy];
|
||||
[_subviews removeObjectIdenticalTo:_wellView];
|
||||
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
|
||||
_subviews = actualSubviews;
|
||||
|
||||
[aCoder encodeObject:_color forKey:CPColorWellColorKey];
|
||||
[aCoder encodeObject:[self isBordered] forKey:CPColorWellBorderedKey];
|
||||
[aCoder encodeObject:_bordered forKey:CPColorWellBorderedKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
-1299
File diff suppressed because it is too large
Load Diff
+78
-360
@@ -20,19 +20,16 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPEvent_Constants.j"
|
||||
@import "CPEvent.j"
|
||||
@import "CPPlatform.j"
|
||||
|
||||
|
||||
// Browser Engines
|
||||
CPUnknownBrowserEngine = 0;
|
||||
CPGeckoBrowserEngine = 1 << 0;
|
||||
CPInternetExplorerBrowserEngine = 1 << 1;
|
||||
CPKHTMLBrowserEngine = 1 << 2;
|
||||
CPOperaBrowserEngine = 1 << 3;
|
||||
CPWebKitBrowserEngine = 1 << 4; // Safari + Chrome
|
||||
CPBlinkBrowserEngine = 1 << 5; // Recent Chrome
|
||||
CPEdgeBrowserEngine = 1 << 6;
|
||||
CPGeckoBrowserEngine = 1;
|
||||
CPInternetExplorerBrowserEngine = 2;
|
||||
CPKHTMLBrowserEngine = 3;
|
||||
CPOperaBrowserEngine = 4;
|
||||
CPWebKitBrowserEngine = 5;
|
||||
|
||||
// Operating Systems
|
||||
CPMacOperatingSystem = 0;
|
||||
@@ -40,149 +37,86 @@ CPWindowsOperatingSystem = 1;
|
||||
CPOtherOperatingSystem = 2;
|
||||
|
||||
// Features
|
||||
CPCSSRGBAFeature = 5;
|
||||
CPCSSRGBAFeature = 1 << 5;
|
||||
|
||||
CPHTMLCanvasFeature = 6;
|
||||
CPHTMLContentEditableFeature = 7;
|
||||
CPHTMLDragAndDropFeature = 8;
|
||||
CPHTMLCanvasFeature = 1 << 6;
|
||||
CPHTMLContentEditableFeature = 1 << 7;
|
||||
CPHTMLDragAndDropFeature = 1 << 8;
|
||||
|
||||
CPJavaScriptInnerTextFeature = 9;
|
||||
CPJavaScriptTextContentFeature = 10;
|
||||
// In onpaste, oncopy and oncut events, the event has an event.clipboardData from which the current pasteboard contents can be read with event.clipboardData.getData.
|
||||
CPJavaScriptClipboardEventsFeature = 11;
|
||||
// window.clipboardData exists and can be read and written to at any time using window.clipboardData.getData/setData.
|
||||
CPJavaScriptClipboardAccessFeature = 12;
|
||||
CPJavaScriptCanvasDrawFeature = 13;
|
||||
CPJavaScriptCanvasTransformFeature = 14;
|
||||
CPJavascriptInnerTextFeature = 1 << 9;
|
||||
CPJavascriptTextContentFeature = 1 << 10;
|
||||
CPJavascriptClipboardEventsFeature = 1 << 11;
|
||||
CPJavascriptClipboardAccessFeature = 1 << 12;
|
||||
CPJavaScriptCanvasDrawFeature = 1 << 13;
|
||||
CPJavaScriptCanvasTransformFeature = 1 << 14;
|
||||
|
||||
CPVMLFeature = 15;
|
||||
CPVMLFeature = 1 << 15;
|
||||
|
||||
CPJavaScriptRemedialKeySupport = 16;
|
||||
CPJavaScriptShadowFeature = 20;
|
||||
CPJavascriptRemedialKeySupport = 1 << 16;
|
||||
CPJavaScriptShadowFeature = 1 << 20;
|
||||
|
||||
CPJavaScriptNegativeMouseWheelValues = 22;
|
||||
CPJavaScriptMouseWheelValues_8_15 = 23;
|
||||
CPJavaScriptNegativeMouseWheelValues = 1 << 22;
|
||||
CPJavaScriptMouseWheelValues_8_15 = 1 << 23
|
||||
|
||||
CPOpacityRequiresFilterFeature = 24;
|
||||
CPOpacityRequiresFilterFeature = 1 << 24;
|
||||
|
||||
// Internet explorer does not allow dynamically changing the type of an input element
|
||||
CPInputTypeCanBeChangedFeature = 25;
|
||||
CPHTML5DragAndDropSourceYOffBy1 = 26;
|
||||
//Internet explorer does not allow dynamically changing the type of an input element
|
||||
CPInputTypeCanBeChangedFeature = 1 << 25;
|
||||
CPHTML5DragAndDropSourceYOffBy1 = 1 << 26;
|
||||
|
||||
CPSOPDisabledFromFileURLs = 27;
|
||||
|
||||
// element.style.font can be set for an element not in the DOM.
|
||||
CPInputSetFontOutsideOfDOM = 28;
|
||||
|
||||
// Input elements have 1 px of extra padding on the left regardless of padding setting.
|
||||
CPInput1PxLeftPadding = 29;
|
||||
CPInputOnInputEventFeature = 30;
|
||||
|
||||
CPFileAPIFeature = 31;
|
||||
|
||||
CPAltEnterTextAreaFeature = 32;
|
||||
|
||||
CPCSSAnimationFeature = 33;
|
||||
|
||||
CPBackspaceTriggersPageBack = 34;
|
||||
/*
|
||||
When an absolutely positioned div (CPView) with an absolutely positioned canvas in it (CPView with drawRect:) moves things on top of the canvas (subviews) don't redraw correctly. E.g. if you have a bunch of text fields in a CPBox in a sheet which animates in, some of the text fields might not be visible because the CPBox has a canvas at the bottom and the box moved form offscreen to onscreen. This bug is probably very related: https://bugs.webkit.org/show_bug.cgi?id=67203
|
||||
*/
|
||||
CPCanvasParentDrawErrorsOnMovementBug = 1 << 0;
|
||||
|
||||
// The paste event is only sent if an input or textarea has focus.
|
||||
CPJavaScriptPasteRequiresEditableTarget = 1 << 1;
|
||||
// Redirecting the focus of the browser on keydown to an input for Cmd-V or Ctrl-V makes the paste fail.
|
||||
CPJavaScriptPasteCantRefocus = 1 << 2;
|
||||
|
||||
/*
|
||||
Safari calculates incorrect text size unless you set the canvas font even if it is already set
|
||||
You can see the bug after disabling the workaround and opening any panel while typing.
|
||||
You can use the font panel in the manual test for CPTextView.
|
||||
Look out for a displaced cursor, i.e. after typing letters of small width, such as the 'i'.
|
||||
https://bugs.webkit.org/show_bug.cgi?id=150224
|
||||
*/
|
||||
CPTextSizingAlwaysNeedsSetFontBug = 1 << 3;
|
||||
|
||||
|
||||
var USER_AGENT = "",
|
||||
PLATFORM_ENGINE = CPUnknownBrowserEngine,
|
||||
PLATFORM_FEATURES = [],
|
||||
PLATFORM_BUGS = 0,
|
||||
PLATFORM_STYLE_JS_PROPERTIES = {};
|
||||
PLATFORM_FEATURES = 0;
|
||||
|
||||
// default these features to true
|
||||
PLATFORM_FEATURES[CPInputTypeCanBeChangedFeature] = YES;
|
||||
PLATFORM_FEATURES[CPInputSetFontOutsideOfDOM] = YES;
|
||||
PLATFORM_FEATURES[CPAltEnterTextAreaFeature] = YES;
|
||||
|
||||
if (typeof window !== "undefined" && typeof window.navigator !== "undefined")
|
||||
PLATFORM_FEATURES |= CPInputTypeCanBeChangedFeature;
|
||||
|
||||
if (typeof window != "undfined" && typeof window.navigator != "undefined")
|
||||
USER_AGENT = window.navigator.userAgent;
|
||||
|
||||
// Opera
|
||||
if (typeof window !== "undefined" && window.opera)
|
||||
if (window.opera)
|
||||
{
|
||||
PLATFORM_ENGINE |= CPOperaBrowserEngine;
|
||||
|
||||
PLATFORM_FEATURES[CPJavaScriptCanvasDrawFeature] = YES;
|
||||
PLATFORM_ENGINE = CPOperaBrowserEngine;
|
||||
|
||||
PLATFORM_FEATURES |= CPJavaScriptCanvasDrawFeature;
|
||||
}
|
||||
|
||||
// Internet Explorer
|
||||
else if (typeof window !== "undefined" && (window.attachEvent || (!(window.ActiveXObject) && "ActiveXObject" in window))) // Must follow Opera check.
|
||||
else if (window.attachEvent) // Must follow Opera check.
|
||||
{
|
||||
PLATFORM_ENGINE |= CPInternetExplorerBrowserEngine;
|
||||
|
||||
PLATFORM_ENGINE = CPInternetExplorerBrowserEngine;
|
||||
|
||||
// Features we can only be sure of with IE (no known independent tests)
|
||||
PLATFORM_FEATURES[CPVMLFeature] = YES;
|
||||
PLATFORM_FEATURES[CPJavaScriptRemedialKeySupport] = YES;
|
||||
PLATFORM_FEATURES[CPJavaScriptShadowFeature] = YES;
|
||||
PLATFORM_FEATURES |= CPVMLFeature;
|
||||
PLATFORM_FEATURES |= CPJavascriptRemedialKeySupport;
|
||||
PLATFORM_FEATURES |= CPJavaScriptShadowFeature;
|
||||
|
||||
PLATFORM_FEATURES |= CPOpacityRequiresFilterFeature;
|
||||
|
||||
PLATFORM_FEATURES[CPOpacityRequiresFilterFeature] = YES;
|
||||
|
||||
PLATFORM_FEATURES[CPInputTypeCanBeChangedFeature] = NO;
|
||||
|
||||
// Tested in Internet Explore 8 and 9.
|
||||
PLATFORM_FEATURES[CPInputSetFontOutsideOfDOM] = NO;
|
||||
|
||||
// IE allows free clipboard access.
|
||||
PLATFORM_FEATURES[CPJavaScriptClipboardAccessFeature] = YES;
|
||||
PLATFORM_FEATURES &= ~CPInputTypeCanBeChangedFeature;
|
||||
}
|
||||
|
||||
// Edge
|
||||
else if (USER_AGENT.indexOf("Edge/") != -1)
|
||||
{
|
||||
PLATFORM_ENGINE |= CPEdgeBrowserEngine;
|
||||
|
||||
PLATFORM_FEATURES[CPCSSRGBAFeature] = YES;
|
||||
PLATFORM_FEATURES[CPHTMLContentEditableFeature] = YES;
|
||||
|
||||
PLATFORM_FEATURES[CPJavaScriptClipboardEventsFeature] = YES;
|
||||
PLATFORM_FEATURES[CPJavaScriptClipboardAccessFeature] = NO;
|
||||
PLATFORM_FEATURES[CPJavaScriptShadowFeature] = YES;
|
||||
|
||||
var versionStart = USER_AGENT.indexOf("Edge/") + "Edge/".length,
|
||||
versionEnd = USER_AGENT.indexOf(" ", versionStart),
|
||||
versionString = USER_AGENT.substring(versionStart, versionEnd),
|
||||
versionDivision = versionString.indexOf('.'),
|
||||
majorVersion = parseInt(versionString.substring(0, versionDivision)),
|
||||
minorVersion = parseInt(versionString.substr(versionDivision + 1));
|
||||
|
||||
PLATFORM_FEATURES[CPJavaScriptRemedialKeySupport] = YES;
|
||||
}
|
||||
|
||||
// Safari + Chrome (WebKit and Blink)
|
||||
// WebKit
|
||||
else if (USER_AGENT.indexOf("AppleWebKit/") != -1)
|
||||
{
|
||||
PLATFORM_ENGINE |= CPWebKitBrowserEngine;
|
||||
|
||||
PLATFORM_ENGINE = CPWebKitBrowserEngine;
|
||||
|
||||
// Features we can only be sure of with WebKit (no known independent tests)
|
||||
PLATFORM_FEATURES[CPCSSRGBAFeature] = YES;
|
||||
PLATFORM_FEATURES[CPHTMLContentEditableFeature] = YES;
|
||||
PLATFORM_FEATURES |= CPCSSRGBAFeature;
|
||||
PLATFORM_FEATURES |= CPHTMLContentEditableFeature;
|
||||
|
||||
PLATFORM_FEATURES[CPJavaScriptClipboardEventsFeature] = YES;
|
||||
PLATFORM_FEATURES[CPJavaScriptClipboardAccessFeature] = NO;
|
||||
PLATFORM_FEATURES[CPJavaScriptShadowFeature] = YES;
|
||||
if (USER_AGENT.indexOf("Chrome") === -1)
|
||||
PLATFORM_FEATURES |= CPHTMLDragAndDropFeature;
|
||||
|
||||
PLATFORM_FEATURES |= CPJavascriptClipboardEventsFeature;
|
||||
PLATFORM_FEATURES |= CPJavascriptClipboardAccessFeature;
|
||||
PLATFORM_FEATURES |= CPJavaScriptShadowFeature;
|
||||
|
||||
var versionStart = USER_AGENT.indexOf("AppleWebKit/") + "AppleWebKit/".length,
|
||||
versionEnd = USER_AGENT.indexOf(" ", versionStart),
|
||||
versionString = USER_AGENT.substring(versionStart, versionEnd),
|
||||
@@ -190,144 +124,74 @@ else if (USER_AGENT.indexOf("AppleWebKit/") != -1)
|
||||
majorVersion = parseInt(versionString.substring(0, versionDivision)),
|
||||
minorVersion = parseInt(versionString.substr(versionDivision + 1));
|
||||
|
||||
if ((USER_AGENT.indexOf("Safari") !== CPNotFound && (majorVersion > 525 || (majorVersion === 525 && minorVersion > 14))) || USER_AGENT.indexOf("Chrome") !== CPNotFound)
|
||||
PLATFORM_FEATURES[CPJavaScriptRemedialKeySupport] = YES;
|
||||
if((USER_AGENT.indexOf("Safari") !== CPNotFound && (majorVersion > 525 || (majorVersion === 525 && minorVersion > 14))) || USER_AGENT.indexOf("Chrome") !== CPNotFound)
|
||||
PLATFORM_FEATURES |= CPJavascriptRemedialKeySupport;
|
||||
|
||||
// FIXME this is a terrible hack to get around this bug:
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=21548
|
||||
if (![CPPlatform isBrowser])
|
||||
PLATFORM_FEATURES[CPJavaScriptRemedialKeySupport] = YES;
|
||||
PLATFORM_FEATURES |= CPJavascriptRemedialKeySupport;
|
||||
|
||||
if (majorVersion < 532 || (majorVersion === 532 && minorVersion < 6))
|
||||
PLATFORM_FEATURES[CPHTML5DragAndDropSourceYOffBy1] = YES;
|
||||
|
||||
// This is supposedly fixed in webkit r123603. Seems to work in Chrome 21 but not Safari 6.0.
|
||||
if (majorVersion < 537)
|
||||
PLATFORM_FEATURES[CPInput1PxLeftPadding] = YES;
|
||||
|
||||
if (USER_AGENT.indexOf("Chrome") === CPNotFound)
|
||||
{
|
||||
PLATFORM_FEATURES[CPSOPDisabledFromFileURLs] = YES;
|
||||
PLATFORM_FEATURES[CPHTMLDragAndDropFeature] = YES;
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=75891
|
||||
PLATFORM_BUGS |= CPJavaScriptPasteRequiresEditableTarget;
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=39689
|
||||
PLATFORM_BUGS |= CPJavaScriptPasteCantRefocus;
|
||||
PLATFORM_BUGS |= CPTextSizingAlwaysNeedsSetFontBug;
|
||||
}
|
||||
else if ((window.chrome || (window.Intl && Intl.v8BreakIterator)) && 'CSS' in window)
|
||||
PLATFORM_ENGINE |= CPBlinkBrowserEngine;
|
||||
|
||||
// Assume this bug was introduced around Safari 5.1/Chrome 16. This could probably be tighter.
|
||||
if (majorVersion > 533)
|
||||
PLATFORM_BUGS |= CPCanvasParentDrawErrorsOnMovementBug;
|
||||
PLATFORM_FEATURES |= CPHTML5DragAndDropSourceYOffBy1;
|
||||
}
|
||||
|
||||
// KHTML
|
||||
else if (USER_AGENT.indexOf("KHTML") != -1) // Must follow WebKit check.
|
||||
{
|
||||
PLATFORM_ENGINE |= CPKHTMLBrowserEngine;
|
||||
PLATFORM_ENGINE = CPKHTMLBrowserEngine;
|
||||
}
|
||||
|
||||
// Gecko
|
||||
else if (USER_AGENT.indexOf("Gecko") !== -1) // Must follow KHTML check.
|
||||
{
|
||||
PLATFORM_ENGINE |= CPGeckoBrowserEngine;
|
||||
|
||||
PLATFORM_FEATURES[CPJavaScriptCanvasDrawFeature] = YES;
|
||||
PLATFORM_FEATURES[CPBackspaceTriggersPageBack] = YES;
|
||||
|
||||
PLATFORM_ENGINE = CPGeckoBrowserEngine;
|
||||
|
||||
PLATFORM_FEATURES |= CPJavaScriptCanvasDrawFeature;
|
||||
|
||||
var index = USER_AGENT.indexOf("Firefox"),
|
||||
version = (index === -1) ? 2.0 : parseFloat(USER_AGENT.substring(index + "Firefox".length + 1));
|
||||
|
||||
|
||||
if (version >= 3.0)
|
||||
PLATFORM_FEATURES[CPCSSRGBAFeature] = YES;
|
||||
PLATFORM_FEATURES |= CPCSSRGBAFeature;
|
||||
|
||||
if (version < 3.0)
|
||||
PLATFORM_FEATURES[CPJavaScriptMouseWheelValues_8_15] = YES;
|
||||
|
||||
if (version >= 66)
|
||||
PLATFORM_FEATURES[CPJavaScriptRemedialKeySupport] = YES;
|
||||
|
||||
// Some day this might be fixed and should be version prefixed. No known fixed version yet.
|
||||
PLATFORM_FEATURES[CPInput1PxLeftPadding] = YES;
|
||||
|
||||
PLATFORM_FEATURES[CPAltEnterTextAreaFeature] = NO;
|
||||
// This was supposed to be added in Firefox 22, but when testing with the latest beta as of 2013-06-14
|
||||
// it does not seem to work. It seems to exhibit the CPJavaScriptPasteRequiresEditableTarget problem,
|
||||
// and in addition doesn't seem to work with our native copy code either.
|
||||
/*if (version >= 22.0)
|
||||
{
|
||||
PLATFORM_FEATURES[CPJavaScriptClipboardEventsFeature] = YES;
|
||||
// TODO File a bug at https://bugzilla.mozilla.org/. In other browsers, one can return "false" from the
|
||||
// beforepaste event to indicate a paste should be enabled even that the DOMEvent.target is not editable.
|
||||
PLATFORM_BUGS |= CPJavaScriptPasteRequiresEditableTarget;
|
||||
}*/
|
||||
PLATFORM_FEATURES |= CPJavaScriptMouseWheelValues_8_15;
|
||||
}
|
||||
|
||||
// Feature-specific checks
|
||||
// Feature Specific Checks
|
||||
if (typeof document != "undefined")
|
||||
{
|
||||
var canvasElement = document.createElement("canvas");
|
||||
|
||||
// Detect canvas support
|
||||
// Detect Canvas Support
|
||||
if (canvasElement && canvasElement.getContext)
|
||||
{
|
||||
PLATFORM_FEATURES[CPHTMLCanvasFeature] = YES;
|
||||
|
||||
// Any browser that supports canvas supports CSS opacity
|
||||
PLATFORM_FEATURES[CPOpacityRequiresFilterFeature] = NO;
|
||||
|
||||
// Detect canvas setTransform/transform support
|
||||
PLATFORM_FEATURES |= CPHTMLCanvasFeature;
|
||||
|
||||
// Detect Canvas setTransform/transform support
|
||||
var context = document.createElement("canvas").getContext("2d");
|
||||
|
||||
|
||||
if (context && context.setTransform && context.transform)
|
||||
PLATFORM_FEATURES[CPJavaScriptCanvasTransformFeature] = YES;
|
||||
PLATFORM_FEATURES |= CPJavaScriptCanvasTransformFeature;
|
||||
}
|
||||
|
||||
|
||||
var DOMElement = document.createElement("div");
|
||||
|
||||
|
||||
// Detect whether we have innerText or textContent (or neither)
|
||||
if (DOMElement.innerText != undefined)
|
||||
PLATFORM_FEATURES[CPJavaScriptInnerTextFeature] = YES;
|
||||
PLATFORM_FEATURES |= CPJavascriptInnerTextFeature;
|
||||
else if (DOMElement.textContent != undefined)
|
||||
PLATFORM_FEATURES[CPJavaScriptTextContentFeature] = YES;
|
||||
|
||||
var DOMInputElement = document.createElement("input");
|
||||
|
||||
if ("oninput" in DOMInputElement)
|
||||
PLATFORM_FEATURES[CPInputOnInputEventFeature] = YES;
|
||||
else if (typeof DOMInputElement.setAttribute === "function")
|
||||
{
|
||||
DOMInputElement.setAttribute("oninput", "return;");
|
||||
|
||||
if (typeof DOMInputElement.oninput === "function")
|
||||
PLATFORM_FEATURES[CPInputOnInputEventFeature] = YES;
|
||||
}
|
||||
|
||||
// Detect FileAPI support
|
||||
if (typeof DOMInputElement.setAttribute === "function")
|
||||
{
|
||||
DOMInputElement.setAttribute("type", "file");
|
||||
PLATFORM_FEATURES[CPFileAPIFeature] = !!DOMInputElement["files"];
|
||||
}
|
||||
else
|
||||
PLATFORM_FEATURES[CPFileAPIFeature] = NO;
|
||||
PLATFORM_FEATURES |= CPJavascriptTextContentFeature;
|
||||
}
|
||||
|
||||
function CPFeatureIsCompatible(aFeature)
|
||||
{
|
||||
return !!PLATFORM_FEATURES[aFeature];
|
||||
}
|
||||
|
||||
function CPPlatformHasBug(aBug)
|
||||
{
|
||||
return PLATFORM_BUGS & aBug;
|
||||
return PLATFORM_FEATURES & aFeature;
|
||||
}
|
||||
|
||||
function CPBrowserIsEngine(anEngine)
|
||||
{
|
||||
return PLATFORM_ENGINE & anEngine;
|
||||
return PLATFORM_ENGINE === anEngine;
|
||||
}
|
||||
|
||||
function CPBrowserIsOperatingSystem(anOperatingSystem)
|
||||
@@ -362,149 +226,3 @@ else
|
||||
CPUndoKeyEquivalentModifierMask = CPControlKeyMask;
|
||||
CPRedoKeyEquivalentModifierMask = CPControlKeyMask;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets a feature with the given value.
|
||||
*/
|
||||
function CPSetPlatformFeature(aFeature, aBool)
|
||||
{
|
||||
PLATFORM_FEATURES[aFeature] = aBool;
|
||||
}
|
||||
|
||||
/*!
|
||||
Return the properly prefixed JS property for the given name. E.g. in a webkit browser,
|
||||
CPBrowserStyleProperty('transition') -> WebkitTransition
|
||||
|
||||
While technically not a style property, style related event handler names are also supported.
|
||||
CPBrowserStyleProperty('transitionend') -> 'webkitTransitionEnd'
|
||||
|
||||
CSS is only available in platform(dom), so don't rely too heavily on it.
|
||||
*/
|
||||
function CPBrowserStyleProperty(aProperty)
|
||||
{
|
||||
var lowerProperty = aProperty.toLowerCase();
|
||||
|
||||
if (PLATFORM_STYLE_JS_PROPERTIES[lowerProperty] === undefined)
|
||||
{
|
||||
var r = nil;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
var testElement = document.createElement('div');
|
||||
|
||||
switch (lowerProperty)
|
||||
{
|
||||
case 'transitionend':
|
||||
var candidates = {
|
||||
'WebkitTransition' : 'webkitTransitionEnd',
|
||||
'MozTransition' : 'transitionend',
|
||||
'OTransition' : 'oTransitionEnd',
|
||||
'msTransition' : 'MSTransitionEnd',
|
||||
'transition' : 'transitionend'
|
||||
};
|
||||
|
||||
r = candidates[PLATFORM_STYLE_JS_PROPERTIES['transition']] || nil;
|
||||
break;
|
||||
|
||||
case 'transformorigin':
|
||||
|
||||
var candidates = {
|
||||
'WebkitTransform' : 'WebkitTransformOrigin',
|
||||
'MozTransform' : 'MozTransformOrigin',
|
||||
'OTransform' : 'OTransformOrigin',
|
||||
'msTransform' : 'MSTransformOrigin',
|
||||
'transform' : 'transformOrigin'
|
||||
};
|
||||
|
||||
r = candidates[PLATFORM_STYLE_JS_PROPERTIES['transform']] || nil;
|
||||
break;
|
||||
|
||||
case 'animationend':
|
||||
var candidates = {
|
||||
'WebkitAnimation' : 'webkitAnimationEnd',
|
||||
'MozAnimation' : 'animationend',
|
||||
'OAnimation' : 'oAnimationEnd',
|
||||
'msAnimation' : 'MSAnimationEnd',
|
||||
'animation' : 'animationend'
|
||||
};
|
||||
|
||||
r = candidates[PLATFORM_STYLE_JS_PROPERTIES['animation']] || nil;
|
||||
break;
|
||||
|
||||
default:
|
||||
var prefixes = ["Webkit", "Moz", "O", "ms"],
|
||||
strippedProperty = aProperty.split('-').join(' '),
|
||||
capProperty = [strippedProperty capitalizedString].split(' ').join('');
|
||||
|
||||
for (var i = 0; i < prefixes.length; i++)
|
||||
{
|
||||
// First check if the property is already valid without being formatted, otherwise try the capitalized property
|
||||
if (prefixes[i] + aProperty in testElement.style)
|
||||
{
|
||||
r = prefixes[i] + aProperty;
|
||||
break;
|
||||
}
|
||||
else if (prefixes[i] + capProperty in testElement.style)
|
||||
{
|
||||
r = prefixes[i] + capProperty;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!r && lowerProperty in testElement.style)
|
||||
r = lowerProperty;
|
||||
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
|
||||
PLATFORM_STYLE_JS_PROPERTIES[lowerProperty] = r;
|
||||
}
|
||||
|
||||
return PLATFORM_STYLE_JS_PROPERTIES[lowerProperty];
|
||||
}
|
||||
|
||||
function CPBrowserCSSProperty(aProperty)
|
||||
{
|
||||
var browserProperty = CPBrowserStyleProperty(aProperty);
|
||||
|
||||
if (!browserProperty)
|
||||
return nil;
|
||||
|
||||
var prefixes = {
|
||||
'Webkit': '-webkit-',
|
||||
'Moz': '-moz-',
|
||||
'O': '-o-',
|
||||
'ms': '-ms-'
|
||||
};
|
||||
|
||||
for (var prefix in prefixes)
|
||||
{
|
||||
if (browserProperty.substring(0, prefix.length) == prefix)
|
||||
{
|
||||
var browserPropertyWithoutPrefix = browserProperty.substring(prefix.length),
|
||||
parts = browserPropertyWithoutPrefix.match(/[A-Z][a-z]+/g);
|
||||
|
||||
// If there were any capitalized words in the browserProperty, insert a "-" between each one
|
||||
if (parts && parts.length > 0)
|
||||
browserPropertyWithoutPrefix = parts.join("-");
|
||||
|
||||
return prefixes[prefix] + browserPropertyWithoutPrefix.toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
var parts = browserProperty.match(/[A-Z][a-z]+/g);
|
||||
|
||||
if (parts && parts.length > 0)
|
||||
browserProperty = parts.join("-");
|
||||
|
||||
return browserProperty.toLowerCase();
|
||||
}
|
||||
|
||||
function CPBrowserBackingStorePixelRatio(context)
|
||||
{
|
||||
return context.webkitBackingStorePixelRatio ||
|
||||
context.mozBackingStorePixelRatio ||
|
||||
context.msBackingStorePixelRatio ||
|
||||
context.oBackingStorePixelRatio ||
|
||||
context.backingStorePixelRatio || 1;
|
||||
}
|
||||
|
||||
+178
-718
File diff suppressed because it is too large
Load Diff
@@ -1,88 +0,0 @@
|
||||
//
|
||||
// CPController.j
|
||||
// AppKit
|
||||
//
|
||||
// Created by Ross Boucher 1/15/09
|
||||
// Copyright 280 North
|
||||
//
|
||||
// Adapted from GNUStep
|
||||
// Copyright (C) 2007 Free Software Foundation, Inc
|
||||
// Released under the LGPL.
|
||||
//
|
||||
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
var CPControllerDeclaredKeysKey = @"CPControllerDeclaredKeysKey";
|
||||
|
||||
@implementation CPController : CPObject
|
||||
{
|
||||
CPArray _editors;
|
||||
CPArray _declaredKeys;
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_editors = [];
|
||||
_declaredKeys = [];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
if ([_declaredKeys count] > 0)
|
||||
[aCoder encodeObject:_declaredKeys forKey:CPControllerDeclaredKeysKey];
|
||||
}
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aDecoder
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_editors = [];
|
||||
_declaredKeys = [aDecoder decodeObjectForKey:CPControllerDeclaredKeysKey] || [];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)isEditing
|
||||
{
|
||||
return [_editors count] > 0;
|
||||
}
|
||||
|
||||
- (BOOL)commitEditing
|
||||
{
|
||||
var index = 0,
|
||||
count = _editors.length;
|
||||
|
||||
for (; index < count; ++index)
|
||||
if (![[_editors objectAtIndex:index] commitEditing])
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)discardEditing
|
||||
{
|
||||
[_editors makeObjectsPerformSelector:@selector(discardEditing)];
|
||||
}
|
||||
|
||||
- (void)objectDidBeginEditing:(id)anEditor
|
||||
{
|
||||
[_editors addObject:anEditor];
|
||||
}
|
||||
|
||||
- (void)objectDidEndEditing:(id)anEditor
|
||||
{
|
||||
[_editors removeObject:anEditor];
|
||||
}
|
||||
|
||||
@end
|
||||
+20
-33
@@ -24,7 +24,7 @@
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPCookie
|
||||
CPCookie is the Cappuccino interface to a web browser cookie. You can set the name
|
||||
@@ -33,7 +33,7 @@
|
||||
{
|
||||
CPString _cookieName;
|
||||
CPString _cookieValue;
|
||||
|
||||
|
||||
CPString _expires;
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
- (id)initWithName:(CPString)aName
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
_cookieName = aName;
|
||||
_cookieValue = [self _readCookieValue];
|
||||
|
||||
@@ -83,43 +83,30 @@
|
||||
*/
|
||||
- (void)setValue:(CPString)value expires:(CPDate)date domain:(CPString)domain
|
||||
{
|
||||
if (date)
|
||||
var expires = "; expires=" + date.toGMTString();
|
||||
else
|
||||
if(date)
|
||||
var expires = "; expires="+date.toGMTString();
|
||||
else
|
||||
var expires = "";
|
||||
|
||||
if (domain)
|
||||
domain = "; domain=" + domain;
|
||||
else
|
||||
|
||||
if(domain)
|
||||
domain = "; domain="+domain;
|
||||
else
|
||||
domain = "";
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
document.cookie = _cookieName + "=" + value + expires + "; path=/" + domain;
|
||||
#else
|
||||
_cookieValue = value;
|
||||
_expires = expires;
|
||||
#endif
|
||||
|
||||
document.cookie = _cookieName+"="+value+expires+"; path=/"+domain;
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (CPString)_readCookieValue
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
var nameEQ = _cookieName + "=",
|
||||
ca = document.cookie.split(';');
|
||||
|
||||
for (var i = 0; i < ca.length; i++)
|
||||
{
|
||||
var c = ca[i];
|
||||
|
||||
while (c.charAt(0) == ' ')
|
||||
c = c.substring(1, c.length);
|
||||
|
||||
if (c.indexOf(nameEQ) == 0)
|
||||
return c.substring(nameEQ.length, c.length);
|
||||
}
|
||||
#endif
|
||||
return "";
|
||||
var nameEQ = _cookieName + "=";
|
||||
var ca = document.cookie.split(';');
|
||||
for(var i=0;i < ca.length;i++) {
|
||||
var c = ca[i];
|
||||
while (c.charAt(0)==' ') c = c.substring(1,c.length);
|
||||
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
Regular → Executable
+197
-329
@@ -1,64 +1,34 @@
|
||||
/*
|
||||
Cursor support by browser:
|
||||
OS X 10.6/Chrome 8 : All
|
||||
OS X 10.6/Safari 5 : All
|
||||
OS X 10.6/Firefox 3 : All except disappearingItemCursor (no url() support)
|
||||
OS X 10.6/Firefox 3.5 : All except disappearingItemCursor (no url() support)
|
||||
OS X 10.6/Firefox 3.6 : All except disappearingItemCursor, contextualMenuCursor, dragLinkCursor, dragCopyCursor, operationNotAllowedCursor (no url() support)
|
||||
OS X 10.6/Firefox 4.0b10 : All
|
||||
OS X/Opera 9 : All except disappearingItemCursor, closedHandCursor, openHandCursor, contextualMenuCursor, dragLinkCursor, dragCopyCursor, operationNotAllowedCursor, resizeUpDownCursor, resizeLeftRightCursor (no url() support)
|
||||
OS X/Opera 10 : All except disappearingItemCursor, closedHandCursor, contextualMenuCursor, dragLinkCursor, dragCopyCursor, operationNotAllowedCursor (no url() support)
|
||||
OS X/Opera 11 : All except disappearingItemCursor, closedHandCursor, contextualMenuCursor, dragLinkCursor, dragCopyCursor, operationNotAllowedCursor (no url() support)
|
||||
Win XP/Chrome 8 : All
|
||||
Win XP/Safari 5 : All
|
||||
Win XP/Firefox 3 : All
|
||||
Win XP/Firefox 3.5 : All
|
||||
Win XP/Firefox 3.6 : All
|
||||
Win XP/Firefox 4.0b10 : All
|
||||
Win XP/Opera 10 : All except disappearingItemCursor, closedHandCursor, openHandCursor, contextualMenuCursor, dragLinkCursor, dragCopyCursor, operationNotAllowedCursor, resizeUpDownCursor, resizeLeftRightCursor (no url() support)
|
||||
Win XP/Opera 11 : All except disappearingItemCursor, closedHandCursor, openHandCursor, contextualMenuCursor, dragLinkCursor, dragCopyCursor, operationNotAllowedCursor, resizeUpDownCursor, resizeLeftRightCursor (no url() support)
|
||||
Win XP/IE 7 : All
|
||||
Win XP/IE 8 : All
|
||||
Testing browsers:
|
||||
WebKit r50235 (Safari 4.0.3+)
|
||||
FireFox 3.5
|
||||
Opera 10.0.0
|
||||
|
||||
Implemented class methods:
|
||||
Webkit : All
|
||||
IE : All
|
||||
FireFox Win : All
|
||||
FireFox Mac : All except closedHandCursor disappearingItemCursor // Firefox mac does not support url cursors
|
||||
Opera : All except resizeLeftRightCursor resizeUpDownCursor operationNotAllowedCursor dragCopyCursor dragLinkCursor contextualMenuCursor openHandCursor closedHandCursor disappearingItemCursor // Opera does not support url cursors so these won't work with images
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import "CPImage.j"
|
||||
@import "CPCompatibility.j"
|
||||
|
||||
@global CPApp
|
||||
#include "Platform/Platform.h"
|
||||
|
||||
var currentCursor = nil,
|
||||
cursorStack = [],
|
||||
cursors = {},
|
||||
ieCursorMap = {};
|
||||
|
||||
@typedef CPCursorPlatform
|
||||
CPCursorPlatformNone = 0;
|
||||
CPCursorPlatformMac = 1;
|
||||
CPCursorPlatformWindows = 2;
|
||||
CPCursorPlatformBoth = 3;
|
||||
cursorURLFormat = nil;
|
||||
|
||||
@implementation CPCursor : CPObject
|
||||
{
|
||||
CPString _cssString @accessors(readonly);
|
||||
CPString _hotSpot @accessors(readonly, getter=hotSpot);
|
||||
CPImage _image @accessors(readonly, getter=image);
|
||||
CPString _cssString;
|
||||
BOOL _isSetOnMouseEntered @accessors(readwrite, getter=isSetOnMouseEntered, setter=setOnMouseEntered:);
|
||||
BOOL _isSetOnMouseExited @accessors(readwrite, getter=isSetOnMouseExited, setter=setOnMouseExited:);
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
+ (CPCursor)currentCursor
|
||||
{
|
||||
if (self !== CPCursor)
|
||||
return;
|
||||
|
||||
// IE < 9 does not support some CSS cursors, we map them to supported ones
|
||||
ieCursorMap = {
|
||||
"ew-resize": "e-resize",
|
||||
"ns-resize": "n-resize",
|
||||
"nesw-resize": "ne-resize",
|
||||
"nwse-resize": "nw-resize"
|
||||
};
|
||||
return currentCursor;
|
||||
}
|
||||
|
||||
- (id)initWithCSSString:(CPString)aString
|
||||
@@ -69,35 +39,161 @@ CPCursorPlatformBoth = 3;
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Init a cursor with the given image and hotspot.
|
||||
hotspot is supported in CSS3 (but not IE).
|
||||
*/
|
||||
- (id)initWithImage:(CPImage)image hotSpot:(CGPoint)hotSpot
|
||||
+ (CPCursor)cursorWithCSSString:(CPString)cssString
|
||||
{
|
||||
_hotSpot = hotSpot;
|
||||
_image = image;
|
||||
return [self initWithCSSString:"url(" + [_image filename] + ")" + hotSpot.x + " " + hotSpot.y + ", auto"];
|
||||
var cursor = cursors[cssString];
|
||||
|
||||
if (typeof cursor == 'undefined')
|
||||
{
|
||||
cursor = [[CPCursor alloc] initWithCSSString:cssString];
|
||||
cursors[cssString] = cursor;
|
||||
}
|
||||
|
||||
return cursor;
|
||||
}
|
||||
|
||||
/*!
|
||||
Init a cursor with the given image and hotspot. This is provided
|
||||
for compliance with Cocoa. Note that foregroundColor and backgroundColor are ignored
|
||||
(as they are in Cocoa). See http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSCursor_Class/Reference/Reference.html
|
||||
*/
|
||||
- (id)initWithImage:(CPImage)image foregroundColorHint:(CPColor)foregroundColor backgroundColorHint:(CPColor)backgroundColor hotSpot:(CGPoint)aHotSpot
|
||||
+ (CPCursor)cursorWithImageNamed:(CPString)imageName
|
||||
{
|
||||
return [self initWithImage:image hotSpot:aHotSpot];
|
||||
if (!cursorURLFormat)
|
||||
{
|
||||
cursorURLFormat = @"url(" + [[CPBundle bundleForClass:self] resourcePath] + @"/CPCursor/%@.cur)";
|
||||
|
||||
if (CPBrowserIsEngine(CPGeckoBrowserEngine))
|
||||
cursorURLFormat += ", default";
|
||||
}
|
||||
|
||||
var url = [CPString stringWithFormat:cursorURLFormat, imageName];
|
||||
|
||||
return [[CPCursor alloc] initWithCSSString:url];
|
||||
}
|
||||
|
||||
- (CPString)_cssString
|
||||
{
|
||||
return _cssString;
|
||||
}
|
||||
|
||||
+ (CPCursor)arrowCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"default"]; // WebKit | FF | opera | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)crosshairCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"crosshair"]; // WebKit | FF | opera | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)IBeamCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"text"]; // WebKit | FF | opera | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)pointingHandCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"pointer"]; // WebKit | FF | opera | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeDownCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:"s-resize"]; // WebKit | FF | opera
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeUpCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:@"n-resize"]; // WebKit | FF | opera
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeLeftCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:@"w-resize"]; // WebKit | FF | opera
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeRightCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:@"e-resize"]; // WebKit | FF | opera
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeLeftRightCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"col-resize"]; // WebKit | FF | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeUpDownCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"row-resize"]; // WebKit | FF | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)operationNotAllowedCursor
|
||||
{
|
||||
return [CPCursor cursorWithCSSString:@"not-allowed"]; // WebKit | FF | IE
|
||||
}
|
||||
|
||||
+ (CPCursor)dragCopyCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:@"copy"]; // WebKit | FF
|
||||
}
|
||||
|
||||
+ (CPCursor)dragLinkCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:@"alias"]; // WebKit | FF
|
||||
}
|
||||
|
||||
+ (CPCursor)contextualMenuCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)];
|
||||
|
||||
return [CPCursor cursorWithCSSString:@"context-menu"]; // WebKit | FF Mac . Not impl FF Win.
|
||||
}
|
||||
|
||||
+ (CPCursor)openHandCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPWebKitBrowserEngine))
|
||||
return [CPCursor cursorWithCSSString:@"-webkit-grab"];
|
||||
else if (CPBrowserIsEngine(CPGeckoBrowserEngine) || CPBrowserIsEngine(CPOperaBrowserEngine))
|
||||
return [CPCursor cursorWithCSSString:@"move"];
|
||||
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)]; // WebKit only. move in FFMac|Opera
|
||||
}
|
||||
|
||||
+ (CPCursor)closedHandCursor
|
||||
{
|
||||
if (CPBrowserIsEngine(CPWebKitBrowserEngine))
|
||||
return [CPCursor cursorWithCSSString:@"-webkit-grabbing"];
|
||||
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)]; // WebKit only
|
||||
}
|
||||
|
||||
+ (CPCursor)disappearingItemCursor
|
||||
{
|
||||
return [CPCursor cursorWithImageNamed:CPStringFromSelector(_cmd)]; // None
|
||||
}
|
||||
|
||||
+ (void)hide
|
||||
{
|
||||
[self _setCursorCSS:@"none"]; // Not supported in IE < 9
|
||||
[self _setCursorCSS:"none"]; // Not supported in IE
|
||||
}
|
||||
|
||||
+ (void)unhide
|
||||
{
|
||||
[self _setCursorCSS:[currentCursor _cssString]];
|
||||
[self _setCursorCSS:[currentCursor _cssString]]
|
||||
}
|
||||
|
||||
+ (void)setHiddenUntilMouseMoves:(BOOL)flag
|
||||
@@ -108,6 +204,43 @@ CPCursorPlatformBoth = 3;
|
||||
[CPCursor unhide];
|
||||
}
|
||||
|
||||
- (id)initWithImage:(CPImage)image hotSpot:(CPPoint)hotSpot
|
||||
{
|
||||
return [self initWithCSSString:"url(" + [image filename] + ")"];
|
||||
}
|
||||
|
||||
- (void)mouseEntered:(CPEvent)event
|
||||
{
|
||||
}
|
||||
|
||||
- (void)mouseExited:(CPEvent)event
|
||||
{
|
||||
}
|
||||
|
||||
- (void)set
|
||||
{
|
||||
currentCursor = self;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
[[self class] _setCursorCSS:_cssString];
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
+ (void)_setCursorCSS:(CPString)aString
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
var platformWindows = [[CPPlatformWindow visiblePlatformWindows] allObjects];
|
||||
for (var i = 0, count = [platformWindows count]; i < count; i++)
|
||||
platformWindows[i]._DOMBodyElement.style.cursor = aString;
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)push
|
||||
{
|
||||
currentCursor = cursorStack.push(self);
|
||||
}
|
||||
|
||||
- (void)pop
|
||||
{
|
||||
[CPCursor pop];
|
||||
@@ -122,272 +255,6 @@ CPCursorPlatformBoth = 3;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)push
|
||||
{
|
||||
cursorStack.push(self);
|
||||
currentCursor = self;
|
||||
}
|
||||
|
||||
- (void)set
|
||||
{
|
||||
if (currentCursor === self)
|
||||
return;
|
||||
|
||||
currentCursor = self;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
[[self class] _setCursorCSS:_cssString];
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)mouseEntered:(CPEvent)event
|
||||
{
|
||||
}
|
||||
|
||||
- (void)mouseExited:(CPEvent)event
|
||||
{
|
||||
}
|
||||
|
||||
+ (CPCursor)currentCursor
|
||||
{
|
||||
return currentCursor;
|
||||
}
|
||||
|
||||
+ (void)_setCursorCSS:(CPString)aString
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
var platformWindows = [[CPPlatformWindow visiblePlatformWindows] allObjects];
|
||||
|
||||
for (var i = 0, count = [platformWindows count]; i < count; i++)
|
||||
platformWindows[i]._DOMBodyElement.style.cursor = aString;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Internal method that is used to return the system cursors. Caches the system cursors for performance.
|
||||
+ (CPCursor)_nativeSystemCursorWithName:(CPString)cursorName cssString:(CPString)aString
|
||||
{
|
||||
var cursor = cursors[cursorName];
|
||||
|
||||
if (typeof cursor === "undefined")
|
||||
{
|
||||
var cssString;
|
||||
|
||||
// IE <= 8 does not support some cursors, map them to supported cursors
|
||||
var ieLessThan9 = CPBrowserIsEngine(CPInternetExplorerBrowserEngine) && !CPFeatureIsCompatible(CPHTMLCanvasFeature);
|
||||
|
||||
if (ieLessThan9)
|
||||
cssString = ieCursorMap[aString] || aString;
|
||||
else
|
||||
cssString = aString;
|
||||
|
||||
cursors[cursorName] = cursor = [[CPCursor alloc] initWithCSSString:cssString];
|
||||
}
|
||||
|
||||
return cursor;
|
||||
}
|
||||
|
||||
+ (CPCursor)_imageCursorWithName:(CPString)cursorName cssString:(CPString)aString
|
||||
{
|
||||
var cursor = cursors[cursorName];
|
||||
|
||||
if (typeof cursor === "undefined")
|
||||
{
|
||||
var themeResourcePath = [[[CPApp themeBlend] bundle] resourcePath],
|
||||
extension = CPBrowserIsOperatingSystem(CPWindowsOperatingSystem) ? @"cur" : @"png",
|
||||
cssString = [CPString stringWithFormat:@"url(%@cursors/%@.%@), %@", themeResourcePath, cursorName, extension, aString];
|
||||
|
||||
cursors[cursorName] = cursor = [[CPCursor alloc] initWithCSSString:cssString];
|
||||
}
|
||||
|
||||
return cursor;
|
||||
}
|
||||
|
||||
+ (CPCursor)_tryUsingNativeSystemCursorWithName:(CPString)cursorName cssString:(CPString)cssName onPlatform:(CPCursorPlatform)shouldUseNativeCursorOn fallingBackWithImageAndCSSPointer:(CPString)aString
|
||||
{
|
||||
var useNativeSystemCursor = (((shouldUseNativeCursorOn == CPCursorPlatformBoth) ||
|
||||
((shouldUseNativeCursorOn == CPCursorPlatformMac) && CPBrowserIsOperatingSystem(CPMacOperatingSystem)) ||
|
||||
((shouldUseNativeCursorOn == CPCursorPlatformWindows) && CPBrowserIsOperatingSystem(CPWindowsOperatingSystem)))
|
||||
&& [CPCursor _nativeCursorExists:cssName]);
|
||||
|
||||
if (useNativeSystemCursor)
|
||||
return [CPCursor _nativeSystemCursorWithName:cursorName cssString:cssName];
|
||||
else
|
||||
return [CPCursor _imageCursorWithName:cursorName cssString:aString];
|
||||
}
|
||||
|
||||
+ (BOOL)_nativeCursorExists:(CPString)cursorCSSName
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
|
||||
// FIXME: Trick until FF/Win & Chrome/Win correctly implement context-menu cursor
|
||||
// They will answer that they implement it but they actually don't
|
||||
|
||||
if ([cursorCSSName isEqualToString:@"context-menu"] && CPBrowserIsOperatingSystem(CPWindowsOperatingSystem) && !CPBrowserIsEngine(CPInternetExplorerBrowserEngine) && !CPBrowserIsEngine(CPEdgeBrowserEngine))
|
||||
return NO;
|
||||
|
||||
// Normal usage : try to set the cursor and check if resulting cursor is the one we tried to set.
|
||||
// If yes, then the browser implements the cursor. If no (and usually we get "default"), then it doesn't.
|
||||
|
||||
var platformWindows = [[CPPlatformWindow visiblePlatformWindows] allObjects],
|
||||
count = [platformWindows count];
|
||||
|
||||
if (count > 0)
|
||||
{
|
||||
var currentPlatformCursor = platformWindows[0]._DOMBodyElement.style.cursor;
|
||||
platformWindows[0]._DOMBodyElement.style.cursor = cursorCSSName;
|
||||
var doesExist = (platformWindows[0]._DOMBodyElement.style.cursor == cursorCSSName);
|
||||
platformWindows[0]._DOMBodyElement.style.cursor = currentPlatformCursor;
|
||||
|
||||
return doesExist;
|
||||
}
|
||||
#endif
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
+ (CPCursor)arrowCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"default"];
|
||||
}
|
||||
|
||||
+ (CPCursor)crosshairCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"crosshair"];
|
||||
}
|
||||
|
||||
+ (CPCursor)IBeamCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"text"];
|
||||
}
|
||||
|
||||
+ (CPCursor)pointingHandCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"pointer"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeNorthwestCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"nw-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeNorthwestSoutheastCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"nwse-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeNortheastCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"ne-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeNortheastSouthwestCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"nesw-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeSouthwestCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"sw-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeSoutheastCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"se-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeDownCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"s-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeUpCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"n-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeLeftCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"w-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeRightCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"e-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeLeftRightCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"col-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeEastWestCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"ew-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeUpDownCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"row-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)resizeNorthSouthCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"ns-resize"];
|
||||
}
|
||||
|
||||
+ (CPCursor)operationNotAllowedCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"not-allowed"];
|
||||
}
|
||||
|
||||
+ (CPCursor)dragCopyCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"copy"];
|
||||
}
|
||||
|
||||
+ (CPCursor)dragLinkCursor
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"alias"];
|
||||
}
|
||||
|
||||
+ (CPCursor)contextualMenuCursor
|
||||
{
|
||||
return [CPCursor _tryUsingNativeSystemCursorWithName:CPStringFromSelector(_cmd)
|
||||
cssString:@"context-menu"
|
||||
onPlatform:CPCursorPlatformBoth
|
||||
fallingBackWithImageAndCSSPointer:@"default"];
|
||||
}
|
||||
|
||||
+ (CPCursor)openHandCursor
|
||||
{
|
||||
return [CPCursor _tryUsingNativeSystemCursorWithName:CPStringFromSelector(_cmd)
|
||||
cssString:@"grab"
|
||||
onPlatform:CPCursorPlatformMac
|
||||
fallingBackWithImageAndCSSPointer:@"default"];
|
||||
}
|
||||
|
||||
+ (CPCursor)closedHandCursor
|
||||
{
|
||||
return [CPCursor _tryUsingNativeSystemCursorWithName:CPStringFromSelector(_cmd)
|
||||
cssString:@"grabbing"
|
||||
onPlatform:CPCursorPlatformMac
|
||||
fallingBackWithImageAndCSSPointer:@"default"];
|
||||
}
|
||||
|
||||
+ (CPCursor)disappearingItemCursor
|
||||
{
|
||||
return [CPCursor _imageCursorWithName:CPStringFromSelector(_cmd) cssString:@"default"];
|
||||
}
|
||||
|
||||
+ (CPCursor)IBeamCursorForVerticalLayout
|
||||
{
|
||||
return [CPCursor _nativeSystemCursorWithName:CPStringFromSelector(_cmd) cssString:@"vertical-text"];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPCursor(CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)coder
|
||||
{
|
||||
if (self = [super init])
|
||||
@@ -402,3 +269,4 @@ CPCursorPlatformBoth = 3;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@@ -1,837 +0,0 @@
|
||||
/* CPDatePicker.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 "CPControl.j"
|
||||
@import "CPFont.j"
|
||||
@import "CPTextField.j"
|
||||
@import "_CPDatePickerTextField.j"
|
||||
@import "_CPDatePickerCalendar.j"
|
||||
|
||||
@import <Foundation/CPArray.j>
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPDate.j>
|
||||
@import <Foundation/CPLocale.j>
|
||||
@import <Foundation/CPTimeZone.j>
|
||||
|
||||
@class CPStepper
|
||||
@class CPApp
|
||||
|
||||
@global CPLocaleLanguageCode
|
||||
@global CPDateFormatterShortStyle
|
||||
|
||||
var CPDatePicker_validateProposedDateValue_timeInterval = 1 << 1;
|
||||
|
||||
CPSingleDateMode = 0;
|
||||
CPRangeDateMode = 1;
|
||||
|
||||
CPTextFieldAndStepperDatePickerStyle = 0;
|
||||
CPClockAndCalendarDatePickerStyle = 1;
|
||||
CPTextFieldDatePickerStyle = 2;
|
||||
|
||||
CPHourMinuteDatePickerElementFlag = 0x000c;
|
||||
CPHourMinuteSecondDatePickerElementFlag = 0x000e;
|
||||
CPTimeZoneDatePickerElementFlag = 0x0010;
|
||||
CPYearMonthDatePickerElementFlag = 0x00c0;
|
||||
CPYearMonthDayDatePickerElementFlag = 0x00e0;
|
||||
CPEraDatePickerElementFlag = 0x0100;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
This control displays a datepicker in a Cappuccino application
|
||||
*/
|
||||
@implementation CPDatePicker : CPControl
|
||||
{
|
||||
BOOL _isBordered @accessors(getter=isBordered, setter=setBordered:);
|
||||
BOOL _isBezeled @accessors(getter=isBezeled, setter=setBezeled:);
|
||||
BOOL _drawsBackground @accessors(property=drawsBackground);
|
||||
CPDate _dateValue @accessors(property=dateValue);
|
||||
CPDate _minDate @accessors(property=minDate);
|
||||
CPDate _maxDate @accessors(property=maxDate);
|
||||
CPFont _textFont @accessors(property=textFont);
|
||||
CPLocale _locale @accessors(property=locale);
|
||||
//CPCalendar _calendar @accessors(property=calendar);
|
||||
CPTimeZone _timeZone @accessors(property=timeZone);
|
||||
id _delegate @accessors(property=delegate);
|
||||
CPInteger _datePickerElements @accessors(property=datePickerElements);
|
||||
CPInteger _datePickerMode @accessors(property=datePickerMode);
|
||||
CPInteger _datePickerStyle @accessors(property=datePickerStyle);
|
||||
CPInteger _timeInterval @accessors(property=timeInterval);
|
||||
|
||||
BOOL _invokedByUserEvent;
|
||||
unsigned _implementedCDatePickerDelegateMethods;
|
||||
BOOL _isTextual;
|
||||
id _datePickerComponent;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Theme methods
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return @"datePicker";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"bezel-color": [CPColor clearColor],
|
||||
@"border-width" : 1.0,
|
||||
@"border-color": [CPColor clearColor],
|
||||
@"content-inset": CGInsetMakeZero(),
|
||||
@"bezel-inset": CGInsetMakeZero(),
|
||||
@"datepicker-textfield-bezel-color": [CPColor clearColor],
|
||||
@"min-size-datepicker-textfield": CGSizeMakeZero(),
|
||||
@"content-inset-datepicker-textfield": CGInsetMakeZero(),
|
||||
@"content-inset-datepicker-textfield-separator": CGInsetMakeZero(),
|
||||
@"separator-content-inset": CGInsetMakeZero(),
|
||||
@"date-hour-margin": 5.0,
|
||||
@"stepper-margin": 5.0,
|
||||
@"bezel-color-calendar": [CPColor clearColor],
|
||||
@"title-text-color": [CPColor blackColor],
|
||||
@"title-text-shadow-color": [CPColor clearColor],
|
||||
@"title-text-shadow-offset": CGSizeMakeZero(),
|
||||
@"title-font": [CPNull null],
|
||||
@"weekday-text-color": [CPColor blackColor],
|
||||
@"weekday-text-shadow-color": [CPColor clearColor],
|
||||
@"weekday-text-shadow-offset": CGSizeMakeZero(),
|
||||
@"weekday-font": [CPNull null],
|
||||
@"arrow-image-left": [CPNull null],
|
||||
@"arrow-image-right": [CPNull null],
|
||||
@"arrow-image-left-highlighted": [CPNull null],
|
||||
@"arrow-image-right-highlighted": [CPNull null],
|
||||
@"arrow-inset": CGInsetMakeZero(),
|
||||
@"circle-image": [CPNull null],
|
||||
@"circle-image-highlighted": [CPNull null],
|
||||
@"tile-text-color": [CPColor blackColor],
|
||||
@"tile-text-shadow-color": [CPColor clearColor],
|
||||
@"tile-text-shadow-offset": CGSizeMakeZero(),
|
||||
@"tile-font": [CPNull null],
|
||||
@"size-tile": CGSizeMakeZero(),
|
||||
@"size-calendar": CGSizeMakeZero(),
|
||||
@"size-header": CGSizeMakeZero(),
|
||||
@"min-size-calendar": CGSizeMakeZero(),
|
||||
@"max-size-calendar": CGSizeMakeZero(),
|
||||
@"bezel-color-clock": [CPColor clearColor],
|
||||
@"clock-text-color": [CPColor blackColor],
|
||||
@"clock-text-shadow-color": [CPColor clearColor],
|
||||
@"clock-text-shadow-offset": CGSizeMakeZero(),
|
||||
@"clock-font": [CPNull null],
|
||||
@"second-hand-image": [CPNull null],
|
||||
@"hour-hand-image": [CPNull null],
|
||||
@"middle-hand-image": [CPNull null],
|
||||
@"minute-hand-image": [CPNull null],
|
||||
@"size-clock": CGSizeMakeZero(),
|
||||
@"second-hand-size": CGSizeMakeZero(),
|
||||
@"hour-hand-size": CGSizeMakeZero(),
|
||||
@"middle-hand-size": CGSizeMakeZero(),
|
||||
@"minute-hand-size": CGSizeMakeZero(),
|
||||
@"previous-button-size": CGSizeMakeZero(),
|
||||
@"current-button-size": CGSizeMakeZero(),
|
||||
@"next-button-size": CGSizeMakeZero(),
|
||||
@"title-inset": [CPNull null],
|
||||
@"day-label-inset": [CPNull null],
|
||||
@"tile-content-inset": CGInsetMakeZero(),
|
||||
@"tile-margin": [CPNull null],
|
||||
@"tile-inset": CGInsetMakeZero(),
|
||||
@"separator-color": [CPNull null],
|
||||
@"separator-margin-width": 0,
|
||||
@"separator-height": 0,
|
||||
@"bezel-color-calendar-left": [CPNull null],
|
||||
@"bezel-color-calendar-middle": [CPNull null],
|
||||
@"bezel-color-calendar-right": [CPNull null],
|
||||
@"tile-vertical-alignment": CPCenterVerticalTextAlignment,
|
||||
@"tile-text-alignment": CPCenterTextAlignment,
|
||||
@"hour-ampm-margin": 2,
|
||||
@"time-separator-content-inset": CGInsetMakeZero(),
|
||||
@"clock-second-hand-over": NO,
|
||||
@"clock-draws-hours": NO,
|
||||
@"clock-hours-font": [CPNull null],
|
||||
@"clock-hours-text-color": [CPColor clearColor],
|
||||
@"clock-hours-radius": 0,
|
||||
@"calendar-clock-margin": 10,
|
||||
@"clock-only-nib2cib-adjustment-frame": CPRectMakeZero(),
|
||||
@"uses-focus-ring": NO
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Binding methods
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)theBinding
|
||||
{
|
||||
if (theBinding == CPValueBinding || theBinding == CPMinValueBinding || theBinding == CPMaxValueBinding)
|
||||
return [_CPDatePickerValueBinder class];
|
||||
|
||||
return [super _binderClassForBinding:theBinding];
|
||||
}
|
||||
|
||||
- (CPString)_replacementKeyPathForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding == CPValueBinding)
|
||||
return @"dateValue";
|
||||
|
||||
if (aBinding == CPMinValueBinding)
|
||||
return @"minDate";
|
||||
|
||||
if (aBinding == CPMaxValueBinding)
|
||||
return @"maxDate";
|
||||
|
||||
return [super _replacementKeyPathForBinding:aBinding];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Init methods
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_drawsBackground = YES;
|
||||
_datePickerStyle = CPTextFieldAndStepperDatePickerStyle;
|
||||
_datePickerMode = CPSingleDateMode;
|
||||
_datePickerElements = CPYearMonthDayDatePickerElementFlag | CPHourMinuteSecondDatePickerElementFlag;
|
||||
_timeInterval = 0;
|
||||
_implementedCDatePickerDelegateMethods = 0;
|
||||
|
||||
[self setObjectValue:[CPDate date]];
|
||||
_minDate = [CPDate distantPast];
|
||||
_maxDate = [CPDate distantFuture];
|
||||
|
||||
[self setBezeled:YES];
|
||||
[self setBordered:YES];
|
||||
|
||||
[self _init];
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
- (void)_init
|
||||
{
|
||||
if (!_locale)
|
||||
_locale = [CPLocale currentLocale];
|
||||
|
||||
_datePickerComponent = nil;
|
||||
|
||||
[self _createComponents];
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)_createComponents
|
||||
{
|
||||
_isTextual = (_datePickerStyle == CPTextFieldAndStepperDatePickerStyle) || (_datePickerStyle == CPTextFieldDatePickerStyle);
|
||||
|
||||
if (_datePickerComponent)
|
||||
{
|
||||
[_datePickerComponent removeFromSuperview];
|
||||
|
||||
_datePickerComponent = nil;
|
||||
}
|
||||
|
||||
_datePickerComponent = [[(_isTextual ? _CPDatePickerTextField : _CPDatePickerCalendar) alloc] initWithFrame:[self bounds] withDatePicker:self];
|
||||
|
||||
[_datePickerComponent setDateValue:_dateValue];
|
||||
[_datePickerComponent setControlSize:[self controlSize]];
|
||||
[_datePickerComponent setDatePickerElements:_datePickerElements];
|
||||
|
||||
// FIXME: Don't know why but next line will cause theme compilation to fail...
|
||||
// Workaround: added "if PLATFORM(DOM)"
|
||||
#if PLATFORM(DOM)
|
||||
[_datePickerComponent setEnabled:[self isEnabled]];
|
||||
#endif
|
||||
|
||||
if (_isTextual)
|
||||
// We need to transmit text color to the text field version (Cocoa doesn't permit adapting the calendar view text color)
|
||||
[_datePickerComponent setTextColor:[self textColor]];
|
||||
|
||||
[self addSubview:_datePickerComponent];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Control Size
|
||||
|
||||
- (void)setControlSize:(CPControlSize)aControlSize
|
||||
{
|
||||
[super setControlSize:aControlSize];
|
||||
|
||||
[_datePickerComponent setControlSize:aControlSize];
|
||||
|
||||
if (_isTextual)
|
||||
[self _sizeToControlSize];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Delegate methods
|
||||
|
||||
/*! Set the delegate of the datePicker
|
||||
@param aDelegate delegate of the datePicker
|
||||
*/
|
||||
- (void)setDelegate:(id)aDelegate
|
||||
{
|
||||
_delegate = aDelegate;
|
||||
_implementedCDatePickerDelegateMethods = 0;
|
||||
|
||||
// Look if the delegate implements or not the delegate methods
|
||||
if ([_delegate respondsToSelector:@selector(datePicker:validateProposedDateValue:timeInterval:)])
|
||||
_implementedCDatePickerDelegateMethods |= CPDatePicker_validateProposedDateValue_timeInterval;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Layout method
|
||||
|
||||
/*! Layout the subviews
|
||||
*/
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[_datePickerComponent setNeedsLayout];
|
||||
[_datePickerComponent setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Setter
|
||||
|
||||
/*! Return the objectValue of the datePicker. The objectValue should take the timeZoneEffect
|
||||
*/
|
||||
- (id)objectValue
|
||||
{
|
||||
// TODO : add timeZone effect. How to do it because js ???
|
||||
return _dateValue
|
||||
}
|
||||
|
||||
/*! Set the objectValue of the datePicker. It has to be a CPDate
|
||||
@param aDateValue the dateValue
|
||||
*/
|
||||
- (void)setObjectValue:(CPDate)aValue
|
||||
{
|
||||
if (![aValue isKindOfClass:[CPDate class]])
|
||||
return;
|
||||
|
||||
[self setDateValue:aValue];
|
||||
}
|
||||
|
||||
/* Set the dateValue of the datePicker
|
||||
@param aDateValue the dateValue
|
||||
*/
|
||||
- (void)setDateValue:(CPDate)aDateValue
|
||||
{
|
||||
if (aDateValue == nil)
|
||||
return;
|
||||
|
||||
_invokedByUserEvent = NO;
|
||||
[self _setDateValue:aDateValue timeInterval:_timeInterval];
|
||||
}
|
||||
|
||||
/*! Set the dateValue and the timeInterval. This method checks the min and max date of the datePicker also. It will call the delegate if possible.
|
||||
@param aDateValue the dateValue
|
||||
@param aTimeInterval the timeInterval
|
||||
*/
|
||||
- (void)_setDateValue:(CPDate)aDateValue timeInterval:(CPTimeInterval)aTimeInterval
|
||||
{
|
||||
// Make sure to have a valid date and avoid NaN values
|
||||
if (!isFinite(aDateValue))
|
||||
{
|
||||
[CPException raise:CPInvalidArgumentException
|
||||
reason:@"aDateValue is not valid"];
|
||||
return;
|
||||
}
|
||||
|
||||
if (_minDate)
|
||||
aDateValue = new Date (MAX(aDateValue, _minDate));
|
||||
|
||||
if (_maxDate)
|
||||
aDateValue = new Date (MIN(aDateValue, _maxDate));
|
||||
|
||||
aTimeInterval = MAX(MIN(aTimeInterval, [_maxDate timeIntervalSinceDate:aDateValue]), [_minDate timeIntervalSinceDate:aDateValue]);
|
||||
|
||||
if ([aDateValue isEqualToDate:_dateValue] && aTimeInterval == _timeInterval)
|
||||
{
|
||||
[_datePickerComponent setDateValue:_dateValue];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (_implementedCDatePickerDelegateMethods & CPDatePicker_validateProposedDateValue_timeInterval)
|
||||
{
|
||||
// constrain timeInterval also
|
||||
var aStartDateRef = function(x){if (typeof x == 'undefined') return aDateValue; aDateValue = x;};
|
||||
var aTimeIntervalRef = function(x){if (typeof x == 'undefined') return aTimeInterval; aTimeInterval = x;};
|
||||
|
||||
[_delegate datePicker:self validateProposedDateValue:aStartDateRef timeInterval:aTimeIntervalRef];
|
||||
}
|
||||
|
||||
[self willChangeValueForKey:@"objectValue"];
|
||||
[self willChangeValueForKey:@"dateValue"];
|
||||
_dateValue = aDateValue;
|
||||
[super setObjectValue:_dateValue];
|
||||
[self didChangeValueForKey:@"objectValue"];
|
||||
[self didChangeValueForKey:@"dateValue"];
|
||||
|
||||
[self willChangeValueForKey:@"timeInterval"];
|
||||
_timeInterval = (_datePickerMode == CPSingleDateMode)? 0 : aTimeInterval;
|
||||
[self didChangeValueForKey:@"timeInterval"];
|
||||
|
||||
if (_invokedByUserEvent)
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
|
||||
[_datePickerComponent setDateValue:_dateValue];
|
||||
}
|
||||
|
||||
/*! Set the minDate of the datePicker
|
||||
@param aMinDate the minDate
|
||||
*/
|
||||
- (void)setMinDate:(CPDate)aMinDate
|
||||
{
|
||||
if (_minDate === aMinDate)
|
||||
return;
|
||||
|
||||
[self willChangeValueForKey:@"minDate"];
|
||||
_minDate = aMinDate;
|
||||
[self didChangeValueForKey:@"minDate"];
|
||||
|
||||
[self _setDateValue:_dateValue timeInterval:_timeInterval];
|
||||
}
|
||||
|
||||
/*! Set the maxDate of the datePicker
|
||||
@param aMaxDate the maxDate
|
||||
*/
|
||||
- (void)setMaxDate:(CPDate)aMaxDate
|
||||
{
|
||||
if (_maxDate === aMaxDate)
|
||||
return;
|
||||
|
||||
[self willChangeValueForKey:@"maxDate"];
|
||||
_maxDate = aMaxDate;
|
||||
[self didChangeValueForKey:@"maxDate"];
|
||||
|
||||
[self _setDateValue:_dateValue timeInterval:_timeInterval];
|
||||
}
|
||||
|
||||
/*! Set the syle of the datePicker
|
||||
@param aDatePickerStyle the datePicker style
|
||||
*/
|
||||
- (void)setDatePickerStyle:(CPInteger)aDatePickerStyle
|
||||
{
|
||||
if (_datePickerStyle === aDatePickerStyle)
|
||||
return;
|
||||
|
||||
_datePickerStyle = aDatePickerStyle;
|
||||
|
||||
// This is needed in order to specify different theme attributes values for textual / graphical date picker
|
||||
if (_datePickerStyle === CPClockAndCalendarDatePickerStyle)
|
||||
[self setThemeState:CPThemeStateAlternateState];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateAlternateState];
|
||||
|
||||
// This is needed in order to specify different theme attributes values for with / without stepper textual date picker
|
||||
if (_datePickerStyle === CPTextFieldAndStepperDatePickerStyle)
|
||||
[self setThemeState:CPThemeStateComposedControl];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateComposedControl];
|
||||
|
||||
[self setControlSize:[self controlSize]];
|
||||
|
||||
if (_datePickerComponent)
|
||||
{
|
||||
// We already have a component so we need to update it
|
||||
[_datePickerComponent resignFirstResponder];
|
||||
[self _createComponents];
|
||||
}
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*! Set the elements of the datePicker
|
||||
@param aDatePickerElements the datePicker elements
|
||||
*/
|
||||
- (void)setDatePickerElements:(CPInteger)aDatePickerElements
|
||||
{
|
||||
if (_datePickerElements === aDatePickerElements)
|
||||
return;
|
||||
|
||||
_datePickerElements = aDatePickerElements;
|
||||
|
||||
// Notify the component of the new value
|
||||
[_datePickerComponent setDatePickerElements:_datePickerElements];
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*! Set the mode of the datePicker
|
||||
@param aDatePickerMode the datePicker mode
|
||||
*/
|
||||
- (void)setDatePickerMode:(CPInteger)aDatePickerMode
|
||||
{
|
||||
if (_datePickerMode === aDatePickerMode)
|
||||
return;
|
||||
|
||||
_datePickerMode = aDatePickerMode;
|
||||
|
||||
if (_datePickerMode == CPSingleDateMode)
|
||||
[self _setDateValue:[self dateValue] timeInterval:0];
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*! Set the timeInterval of the datePicker
|
||||
@param aTimeInterval the timeInterval of the datePicker
|
||||
*/
|
||||
- (void)setTimeInterval:(CPInteger)aTimeInterval
|
||||
{
|
||||
if (_datePickerMode == CPSingleDateMode)
|
||||
return;
|
||||
|
||||
[self _setDateValue:[self dateValue] timeInterval:aTimeInterval];
|
||||
}
|
||||
|
||||
/*! Set the locale of the datePicker. This update laso the locale of the formatter.
|
||||
@param aLocale the locale
|
||||
*/
|
||||
- (void)setLocale:(CPLocale)aLocale
|
||||
{
|
||||
if (_locale === aLocale)
|
||||
return;
|
||||
|
||||
_locale = aLocale;
|
||||
|
||||
if (_formatter)
|
||||
{
|
||||
[self willChangeValueForKey:@"locale"];
|
||||
[_formatter setLocale:_locale];
|
||||
[self didChangeValueForKey:@"locale"];
|
||||
}
|
||||
|
||||
// This will update the textFields (usefull when changing with a date with pm and am)
|
||||
if (_isTextual)
|
||||
[_datePickerComponent setDateValue:_dateValue];
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets whether the datepicker will have a bezeled border.
|
||||
@param shouldBeBezeled \c YES means the datepicker will draw a bezeled border
|
||||
*/
|
||||
- (void)setBezeled:(BOOL)shouldBeBezeled
|
||||
{
|
||||
if (_isBezeled === shouldBeBezeled)
|
||||
return;
|
||||
|
||||
_isBezeled = shouldBeBezeled;
|
||||
|
||||
if (shouldBeBezeled)
|
||||
[self setThemeState:CPThemeStateBezeled];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateBezeled];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets whether the datepicker will have a border drawn. (actually it does nothing)
|
||||
@param shouldBeBordered \c YES makes the datepicker draw a border
|
||||
*/
|
||||
- (void)setBordered:(BOOL)shouldBeBordered
|
||||
{
|
||||
if (_isBordered === shouldBeBordered)
|
||||
return;
|
||||
|
||||
_isBordered = shouldBeBordered;
|
||||
|
||||
if (shouldBeBordered)
|
||||
[self setThemeState:CPThemeStateBordered];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateBordered];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the font of the control.
|
||||
@param aFont
|
||||
*/
|
||||
- (void)setTextFont:(CPFont)aFont
|
||||
{
|
||||
[self setFont:aFont];
|
||||
|
||||
if (_isTextual)
|
||||
[_datePickerComponent setTextFont:aFont];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the color of the control.
|
||||
@param aColor
|
||||
*/
|
||||
- (void)setTextColor:(CPColor)aColor
|
||||
{
|
||||
[super setTextColor:aColor];
|
||||
|
||||
if (_isTextual)
|
||||
[_datePickerComponent setTextColor:aColor];
|
||||
// REM: in Cocoa, setTextColor has no effect on calendar view
|
||||
}
|
||||
|
||||
/*! Sets the enabled status of the control. Controls that are not enabled can not be used by the user and obtain the CPThemeStateDisabled theme state.
|
||||
@param a boolean. YES if the control should be enabled, otherwise NO.
|
||||
*/
|
||||
- (void)setEnabled:(BOOL)aBoolean
|
||||
{
|
||||
[super setEnabled:aBoolean];
|
||||
|
||||
[_datePickerComponent setEnabled:aBoolean];
|
||||
|
||||
if (!aBoolean)
|
||||
[self resignFirstResponder];
|
||||
}
|
||||
|
||||
/*! Set the background color of the datePicker
|
||||
@param aColor
|
||||
*/
|
||||
- (void)setBackgroundColor:(CPColor)aColor
|
||||
{
|
||||
_backgroundColor = aColor;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*! Set the boolean drawsBackgroundColor
|
||||
@param aBoolean
|
||||
*/
|
||||
- (void)setDrawsBackground:(BOOL)aBoolean
|
||||
{
|
||||
if (_drawsBackground === aBoolean)
|
||||
return;
|
||||
|
||||
[self willChangeValueForKey:@"drawsBackground"];
|
||||
_drawsBackground = aBoolean;
|
||||
[self didChangeValueForKey:@"drawsBackground"];
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*! Set the timeZone
|
||||
@param aTimeZone
|
||||
*/
|
||||
- (void)setTimeZone:(CPTimeZone)aTimeZone
|
||||
{
|
||||
if (_timeZone === aTimeZone)
|
||||
return;
|
||||
|
||||
[self willChangeValueForKey:@"timeZone"];
|
||||
_timeZone = aTimeZone;
|
||||
[self didChangeValueForKey:@"timeZone"];
|
||||
|
||||
[self setNeedsLayout];
|
||||
|
||||
[_datePickerComponent setDateValue:_dateValue];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark First responder methods
|
||||
|
||||
/*! Return YES if style is set to CPTextFieldAndStepperDatePickerStyle or CPTextFieldDatePickerStyle
|
||||
*/
|
||||
- (BOOL)becomeFirstResponder
|
||||
{
|
||||
if (_isTextual)
|
||||
{
|
||||
if (![super becomeFirstResponder])
|
||||
return NO;
|
||||
|
||||
[_datePickerComponent _selectTextFieldWithFlags:[[CPApp currentEvent] modifierFlags]];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
/*! Return YES
|
||||
*/
|
||||
- (BOOL)acceptsFirstResponder
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
/*! Return YES
|
||||
*/
|
||||
- (BOOL)resignFirstResponder
|
||||
{
|
||||
if (_isTextual)
|
||||
[_datePickerComponent resignFirstResponder];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark getter
|
||||
|
||||
/*!
|
||||
Returns \c YES if the textfield is bezeled.
|
||||
*/
|
||||
- (BOOL)isBezeled
|
||||
{
|
||||
return [self hasThemeState:CPThemeStateBezeled];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the textfield has a border.
|
||||
*/
|
||||
- (BOOL)isBordered
|
||||
{
|
||||
return [self hasThemeState:CPThemeStateBordered];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the font of the control.
|
||||
*/
|
||||
- (CPFont)textFont
|
||||
{
|
||||
return [self font];
|
||||
}
|
||||
|
||||
/*! Check if we are in the american format or not. Depending on the locale
|
||||
*/
|
||||
- (BOOL)_isAmericanFormat
|
||||
{
|
||||
return [[_locale objectForKey:CPLocaleCountryCode] isEqualToString:@"US"];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Key event
|
||||
|
||||
/*! Key down event
|
||||
@param anEvent
|
||||
*/
|
||||
- (void)keyDown:(CPEvent)anEvent
|
||||
{
|
||||
if (_isTextual)
|
||||
[_datePickerComponent keyDown:anEvent];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPDatePickerModeKey = @"CPDatePickerModeKey",
|
||||
CPIntervalKey = @"CPIntervalKey",
|
||||
CPMinDateKey = @"CPMinDateKey",
|
||||
CPMaxDateKey = @"CPMaxDateKey",
|
||||
CPBackgroundColorKey = @"CPBackgroundColorKey",
|
||||
CPDrawsBackgroundKey = @"CPDrawsBackgroundKey",
|
||||
CPTextFontKey = @"CPTextFontKey",
|
||||
CPDatePickerElementsKey = @"CPDatePickerElementsKey",
|
||||
CPDatePickerStyleKey = @"CPDatePickerStyleKey",
|
||||
CPLocaleKey = @"CPLocaleKey",
|
||||
CPBorderedKey = @"CPBorderedKey",
|
||||
CPDateValueKey = @"CPDateValueKey";
|
||||
|
||||
@implementation CPDatePicker (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_backgroundColor = [aCoder decodeObjectForKey:CPBackgroundColorKey];
|
||||
[self setBordered:[aCoder decodeBoolForKey:CPBorderedKey]];
|
||||
[self setDrawsBackground:[aCoder decodeBoolForKey:CPDrawsBackgroundKey]];
|
||||
|
||||
[self setDatePickerElements:[aCoder decodeIntForKey:CPDatePickerElementsKey]];
|
||||
[self setDatePickerMode:[aCoder decodeIntForKey:CPDatePickerModeKey]];
|
||||
[self setDatePickerStyle:[aCoder decodeIntForKey:CPDatePickerStyleKey]];
|
||||
[self setMinDate:[aCoder decodeObjectForKey:CPMinDateKey] || [CPDate distantPast]];
|
||||
[self setMaxDate:[aCoder decodeObjectForKey:CPMaxDateKey] || [CPDate distantFuture]];
|
||||
[self setLocale:[aCoder decodeObjectForKey:CPLocaleKey]];
|
||||
|
||||
[self _init];
|
||||
|
||||
[self setTextFont:[aCoder decodeObjectForKey:CPTextFontKey]];
|
||||
[self setTimeInterval:[aCoder decodeDoubleForKey:CPIntervalKey]];
|
||||
[self setDateValue:[aCoder decodeObjectForKey:CPDateValueKey]];
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
// Before encoding, we remove all subviews as we'll recreate them at loading
|
||||
while ([[self subviews] count] > 0)
|
||||
[[[self subviews] lastObject] removeFromSuperview];
|
||||
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
[aCoder encodeDouble:_timeInterval forKey:CPIntervalKey];
|
||||
[aCoder encodeInt:_datePickerMode forKey:CPDatePickerModeKey];
|
||||
[aCoder encodeInt:_datePickerStyle forKey:CPDatePickerStyleKey];
|
||||
[aCoder encodeInt:_datePickerElements forKey:CPDatePickerElementsKey];
|
||||
[aCoder encodeObject:_minDate forKey:CPMinDateKey];
|
||||
[aCoder encodeObject:_maxDate forKey:CPMaxDateKey];
|
||||
[aCoder encodeObject:_dateValue forKey:CPDateValueKey];
|
||||
[aCoder encodeObject:_textFont forKey:CPTextFontKey];
|
||||
[aCoder encodeObject:_locale forKey:CPLocaleKey];
|
||||
[aCoder encodeObject:_backgroundColor forKey:CPBackgroundColorKey];
|
||||
[aCoder encodeObject:_drawsBackground forKey:CPDrawsBackgroundKey];
|
||||
[aCoder encodeObject:_isBordered forKey:CPBorderedKey];
|
||||
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
// FIXME: add support for CPEditorRegistrationProtocol as implemented for CPTextField
|
||||
@implementation _CPDatePickerValueBinder : CPBinder
|
||||
{
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPDate (CPDatePickerAdditions)
|
||||
|
||||
- (int)_daysInMonth
|
||||
{
|
||||
return 32 - new Date(self.getFullYear(), self.getMonth(), 32).getDate();
|
||||
}
|
||||
|
||||
- (void)_resetToMidnight
|
||||
{
|
||||
self.setHours(0);
|
||||
self.setMinutes(0);
|
||||
self.setSeconds(0);
|
||||
self.setMilliseconds(0);
|
||||
}
|
||||
|
||||
- (void)_resetToLastSeconds
|
||||
{
|
||||
self.setHours(23);
|
||||
self.setMinutes(59);
|
||||
self.setSeconds(59);
|
||||
self.setMilliseconds(99);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,98 +0,0 @@
|
||||
/* _CPDatePickerBox.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
@import "CPView.j"
|
||||
|
||||
@class CPDatePicker
|
||||
|
||||
@implementation _CPDatePickerBox : CPView
|
||||
{
|
||||
CPDatePicker _datePicker @accessors(property=datePicker);
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
[super drawRect:aRect];
|
||||
|
||||
if ([_datePicker isCSSBased])
|
||||
return;
|
||||
|
||||
if ([_datePicker isBordered])
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
borderWidth = [_datePicker valueForThemeAttribute:@"border-width"] / 2;
|
||||
|
||||
CGContextBeginPath(context);
|
||||
CGContextSetStrokeColor(context, [_datePicker valueForThemeAttribute:@"border-color" inState:[_datePicker themeState]]);
|
||||
CGContextSetLineWidth(context, [_datePicker valueForThemeAttribute:@"border-width"]);
|
||||
|
||||
CGContextMoveToPoint(context, borderWidth, borderWidth);
|
||||
CGContextAddLineToPoint(context, aRect.size.width - borderWidth, borderWidth);
|
||||
CGContextAddLineToPoint(context, aRect.size.width - borderWidth, aRect.size.height - borderWidth);
|
||||
CGContextAddLineToPoint(context, borderWidth, aRect.size.height - borderWidth);
|
||||
CGContextAddLineToPoint(context, borderWidth,borderWidth);
|
||||
|
||||
CGContextStrokePath(context);
|
||||
CGContextClosePath(context);
|
||||
}
|
||||
}
|
||||
|
||||
- (CGRect)rectForEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
if (aName === "bezel-view")
|
||||
return [self bounds];
|
||||
|
||||
return [super rectForEphemeralSubviewNamed:aName];
|
||||
}
|
||||
|
||||
- (CPView)createEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
if (aName === "bezel-view")
|
||||
{
|
||||
var view = [[CPView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[view setHitTests:NO];
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
return [super createEphemeralSubviewNamed:aName];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
if ([_datePicker isCSSBased])
|
||||
{
|
||||
var bezelView = [self layoutEphemeralSubviewNamed:@"bezel-view"
|
||||
positioned:CPWindowBelow
|
||||
relativeToEphemeralSubviewNamed:nil];
|
||||
|
||||
[bezelView setBackgroundColor:[_datePicker currentValueForThemeAttribute:@"bezel-color"]];
|
||||
}
|
||||
|
||||
if ([_datePicker drawsBackground])
|
||||
[self setBackgroundColor:[_datePicker backgroundColor]];
|
||||
else
|
||||
[self setBackgroundColor:[CPColor clearColor]];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,294 +0,0 @@
|
||||
/* _CPDatePickerCalendar.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
|
||||
@import "_CPDatePickerClock.j"
|
||||
@import "_CPDatePickerBox.j"
|
||||
@import "_CPDatePickerMonthView.j"
|
||||
@import "_CPDatePickerHeaderView.j"
|
||||
|
||||
@class CPDatePicker
|
||||
|
||||
@global CPApp
|
||||
@global CPHourMinuteDatePickerElementFlag
|
||||
@global CPHourMinuteSecondDatePickerElementFlag
|
||||
@global CPTimeZoneDatePickerElementFlag
|
||||
@global CPYearMonthDatePickerElementFlag
|
||||
@global CPYearMonthDayDatePickerElementFlag
|
||||
@global CPEraDatePickerElementFlag
|
||||
|
||||
@implementation _CPDatePickerCalendar : CPControl
|
||||
{
|
||||
_CPDatePickerMonthView _monthView;
|
||||
_CPDatePickerHeaderView _headerView;
|
||||
_CPDatePickerClock _datePickerClock;
|
||||
_CPDatePickerBox _box;
|
||||
CPDatePicker _datePicker;
|
||||
CPInteger _startSelectionIndex;
|
||||
CPInteger _currentSelectionIndex;
|
||||
BOOL _hasClock;
|
||||
BOOL _hasCalendar;
|
||||
BOOL _isClockOnly;
|
||||
CPInteger _datePickerElements @accessors(getter=datePickerElements);
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Init method
|
||||
|
||||
/*! Init a _CPDatePickerCalendar
|
||||
@param aFrame
|
||||
@param aDatePicker
|
||||
@return a new instance of _CPDatePickerCalendar
|
||||
*/
|
||||
- (id)initWithFrame:(CGRect)aFrame withDatePicker:(CPDatePicker)aDatePicker
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_datePicker = aDatePicker;
|
||||
_datePickerElements = [_datePicker datePickerElements];
|
||||
|
||||
[self _init];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*! Init the object
|
||||
*/
|
||||
- (void)_init
|
||||
{
|
||||
var sizeHeader = [_datePicker valueForThemeAttribute:@"size-header"],
|
||||
sizeCalendar = [_datePicker valueForThemeAttribute:@"size-calendar"],
|
||||
sizeClock = [_datePicker valueForThemeAttribute:@"size-clock"],
|
||||
calendarClockMargin = [_datePicker valueForThemeAttribute:@"calendar-clock-margin"];
|
||||
|
||||
_hasClock = (_datePickerElements & CPHourMinuteSecondDatePickerElementFlag) || (_datePickerElements & CPHourMinuteDatePickerElementFlag);
|
||||
_hasCalendar = (_datePickerElements & CPYearMonthDayDatePickerElementFlag) || (_datePickerElements & CPYearMonthDatePickerElementFlag);
|
||||
_isClockOnly = _hasClock && !_hasCalendar;
|
||||
|
||||
if (_hasCalendar && !_box)
|
||||
{
|
||||
_box = [[_CPDatePickerBox alloc] initWithFrame:CGRectMake(0, 0, sizeCalendar.width, sizeHeader.height + sizeCalendar.height)];
|
||||
[_box setDatePicker:_datePicker];
|
||||
[self addSubview:_box];
|
||||
|
||||
_headerView = [[_CPDatePickerHeaderView alloc] initWithFrame:CGRectMake(0, 0, sizeHeader.width, sizeHeader.height) datePicker:_datePicker delegate:self];
|
||||
[_box addSubview:_headerView];
|
||||
|
||||
_monthView = [[_CPDatePickerMonthView alloc] initWithFrame:CGRectMake(0, sizeHeader.height, sizeCalendar.width, sizeCalendar.height) datePicker:_datePicker delegate:self];
|
||||
[_box addSubview:_monthView];
|
||||
}
|
||||
|
||||
if (_hasClock && !_datePickerClock)
|
||||
{
|
||||
_datePickerClock = [[_CPDatePickerClock alloc] initWithFrame:CGRectMake(0, 0, sizeClock.width, sizeClock.height) datePicker:_datePicker];
|
||||
[self addSubview:_datePickerClock];
|
||||
}
|
||||
|
||||
if (_hasClock)
|
||||
[_datePickerClock setDatePickerElements:_datePickerElements];
|
||||
|
||||
[self setDateValue:[_datePicker dateValue]];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Responder methods
|
||||
|
||||
- (BOOL)acceptsFirstResponder
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Getter Setter methods
|
||||
|
||||
/*! Set the date value of the component. It sets the dateValue of the header and the monthView also
|
||||
@param aDateValue
|
||||
*/
|
||||
- (void)setDateValue:(CPDate)aDateValue
|
||||
{
|
||||
var dateValue = [aDateValue copy];
|
||||
[dateValue _dateWithTimeZone:[_datePicker timeZone]];
|
||||
|
||||
[_monthView setMonthForDate:dateValue];
|
||||
[_headerView setMonthForDate:[_monthView monthDate]];
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
/*! Set enabled
|
||||
@param aBoolean
|
||||
*/
|
||||
- (void)setEnabled:(BOOL)aBoolean
|
||||
{
|
||||
[super setEnabled:aBoolean];
|
||||
|
||||
[_datePickerClock setEnabled:aBoolean];
|
||||
[_headerView setEnabled:aBoolean];
|
||||
[_monthView setEnabled:aBoolean];
|
||||
}
|
||||
|
||||
- (void)setDatePickerElements:(CPInteger)aDatePickerElements
|
||||
{
|
||||
if (_datePickerElements === aDatePickerElements)
|
||||
return;
|
||||
|
||||
_datePickerElements = aDatePickerElements;
|
||||
|
||||
[self _init];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Layout methods
|
||||
|
||||
/*! Manager the subviews. It hides or not the clock.
|
||||
*/
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
var minSize = [_datePicker valueForThemeAttribute:@"min-size-calendar"],
|
||||
sizeHeader = [_datePicker valueForThemeAttribute:@"size-header"],
|
||||
sizeCalendar = [_datePicker valueForThemeAttribute:@"size-calendar"],
|
||||
sizeClock = [_datePicker valueForThemeAttribute:@"size-clock"],
|
||||
calendarClockMargin = [_datePicker valueForThemeAttribute:@"calendar-clock-margin"];
|
||||
|
||||
if (_hasClock)
|
||||
{
|
||||
if (!_isClockOnly)
|
||||
{
|
||||
var frameSize = CGSizeMakeCopy(minSize);
|
||||
frameSize.width += sizeClock.width + calendarClockMargin;
|
||||
|
||||
[_datePicker setFrameSize:frameSize];
|
||||
[_datePickerClock setFrameOrigin:CGPointMake(sizeCalendar.width + calendarClockMargin, [self bounds].size.height / 2 - sizeClock.height / 2)];
|
||||
}
|
||||
else
|
||||
{
|
||||
[_datePicker setFrameSize:sizeClock];
|
||||
[_datePickerClock setFrameOrigin:CGPointMake(0, 0)];
|
||||
}
|
||||
|
||||
[_datePickerClock setHidden:NO];
|
||||
[_datePickerClock setFrameSize:sizeClock];
|
||||
[_datePickerClock setNeedsLayout];
|
||||
}
|
||||
else
|
||||
{
|
||||
[_datePicker setFrameSize:minSize];
|
||||
[_datePickerClock setHidden:YES];
|
||||
}
|
||||
|
||||
if (_hasCalendar)
|
||||
{
|
||||
[_box setHidden:NO];
|
||||
[_headerView setHidden:NO];
|
||||
[_monthView setHidden:NO];
|
||||
[_box setNeedsLayout];
|
||||
[_box setNeedsDisplay:YES];
|
||||
[_headerView setNeedsLayout];
|
||||
[_monthView setNeedsLayout];
|
||||
[_monthView setNeedsDisplay:YES];
|
||||
}
|
||||
else
|
||||
{
|
||||
[_box setHidden:YES];
|
||||
[_headerView setHidden:YES];
|
||||
[_monthView setHidden:YES];
|
||||
}
|
||||
|
||||
[self setFrameSize:[_datePicker frameSize]];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Action methods
|
||||
|
||||
/*! Move to the nextMonth without changing the dateValue of the datePicker
|
||||
*/
|
||||
- (void)_clickArrowNext:(id)sender
|
||||
{
|
||||
var currentEvent = [CPApp currentEvent],
|
||||
modifierFlags = [currentEvent modifierFlags];
|
||||
|
||||
if (modifierFlags & (CPCommandKeyMask | CPControlKeyMask | CPAlternateKeyMask))
|
||||
{
|
||||
var date = [[_monthView monthDate] copy];
|
||||
date.setDate(1);
|
||||
|
||||
if (modifierFlags & CPAlternateKeyMask)
|
||||
date.setUTCFullYear(date.getUTCFullYear() + 10);
|
||||
else
|
||||
date.setUTCFullYear(date.getUTCFullYear() + 1);
|
||||
|
||||
[self setDateValue:date];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self _displayNextMonth];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_displayNextMonth
|
||||
{
|
||||
[self setDateValue:[_monthView nextMonth]];
|
||||
}
|
||||
|
||||
- (void)_displayPreviousMonth
|
||||
{
|
||||
[self setDateValue:[_monthView previousMonth]];
|
||||
}
|
||||
|
||||
/*! Move to the previous month without changing the dateValue of the datePicker
|
||||
*/
|
||||
- (void)_clickArrowPrevious:(id)sender
|
||||
{
|
||||
var currentEvent = [CPApp currentEvent],
|
||||
modifierFlags = [currentEvent modifierFlags];
|
||||
|
||||
if (modifierFlags & (CPCommandKeyMask | CPControlKeyMask | CPAlternateKeyMask))
|
||||
{
|
||||
var date = [[_monthView monthDate] copy];
|
||||
date.setDate(1);
|
||||
|
||||
if (modifierFlags & CPAlternateKeyMask)
|
||||
date.setUTCFullYear(date.getUTCFullYear() - 10);
|
||||
else
|
||||
date.setUTCFullYear(date.getUTCFullYear() - 1);
|
||||
|
||||
[self setDateValue:date];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self _displayPreviousMonth];
|
||||
}
|
||||
}
|
||||
|
||||
/*! Move to the current selected day
|
||||
*/
|
||||
- (void)_currentMonth:(id)sender
|
||||
{
|
||||
[self setDateValue:[_datePicker dateValue]];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,611 +0,0 @@
|
||||
/*
|
||||
* _CPDatePickerClock.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/CPKeyedArchiver.j>
|
||||
@import <Foundation/CPKeyedUnarchiver.j>
|
||||
@import "CPView.j"
|
||||
@import "CPTextField.j"
|
||||
@import "CPImage.j"
|
||||
@import "CALayer.j"
|
||||
|
||||
@class _CPCibCustomResource
|
||||
@class CPDatePicker
|
||||
@class HandImageLayer
|
||||
@class HoursLayer
|
||||
@class HandLayer
|
||||
|
||||
@global CPHourMinuteSecondDatePickerElementFlag
|
||||
@global CPTextFieldAndStepperDatePickerStyle
|
||||
@global CPTextFieldDatePickerStyle
|
||||
|
||||
var RADIANS = Math.PI / 180;
|
||||
|
||||
@typedef _CPDatePickerClockHand
|
||||
_CPDatePickerClockHours = 1;
|
||||
_CPDatePickerClockMinutes = 2;
|
||||
_CPDatePickerClockSeconds = 3;
|
||||
|
||||
@implementation _CPDatePickerClock : CPControl
|
||||
{
|
||||
BOOL _isEnabled;
|
||||
HoursLayer _rootLayer;
|
||||
HandLayer _hourHandLayer;
|
||||
HandLayer _minuteHandLayer;
|
||||
HandLayer _secondHandLayer;
|
||||
CALayer _middleHandLayer;
|
||||
CPDatePicker _datePicker;
|
||||
CPTextField _PMAMTextField;
|
||||
|
||||
CALayer _currentHandLayer;
|
||||
_CPDatePickerClockHand _currentHand;
|
||||
CPInteger _currentRepresentedValue;
|
||||
float _currentValueShift;
|
||||
CPInteger _numberOfUnits;
|
||||
BOOL _trackingHand;
|
||||
|
||||
CPInteger _representedHours;
|
||||
CPInteger _representedMinutes;
|
||||
CPInteger _representedSeconds;
|
||||
BOOL _representedHourIsPM;
|
||||
|
||||
CPInteger _datePickerElements @accessors(getter=datePickerElements);
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Init methods
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame datePicker:(CPDatePicker)aDatePicker
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_datePicker = aDatePicker;
|
||||
_datePickerElements = [_datePicker datePickerElements];
|
||||
_trackingHand = NO;
|
||||
|
||||
_PMAMTextField = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-font" inState:CPThemeStateNormal] forThemeAttribute:@"font" inState:CPThemeStateNormal];
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-text-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-color" inState:CPThemeStateNormal];
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-text-shadow-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateNormal];
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-text-shadow-offset" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateNormal];
|
||||
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-font" inState:CPThemeStateDisabled] forThemeAttribute:@"font" inState:CPThemeStateDisabled];
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-text-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-color" inState:CPThemeStateDisabled];
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-text-shadow-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateDisabled];
|
||||
[_PMAMTextField setValue:[_datePicker valueForThemeAttribute:@"clock-text-shadow-offset" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateDisabled];
|
||||
|
||||
[self addSubview:_PMAMTextField];
|
||||
|
||||
var middleHandSize = [_datePicker valueForThemeAttribute:@"middle-hand-size"],
|
||||
minuteHandSize = [_datePicker valueForThemeAttribute:@"minute-hand-size"],
|
||||
hourHandSize = [_datePicker valueForThemeAttribute:@"hour-hand-size"],
|
||||
secondHandSize = [_datePicker valueForThemeAttribute:@"second-hand-size"];
|
||||
|
||||
// We use layer to make the rotation possible
|
||||
_hourHandLayer = [[HandLayer alloc] initWithSize:hourHandSize];
|
||||
[_hourHandLayer setBounds:CGRectMake(0, 0, aFrame.size.width, aFrame.size.height)];
|
||||
[_hourHandLayer setAnchorPoint:CGPointMakeZero()];
|
||||
[_hourHandLayer setPosition:CGPointMake(0.0, 0.0)];
|
||||
|
||||
_minuteHandLayer = [[HandLayer alloc] initWithSize:minuteHandSize];
|
||||
[_minuteHandLayer setBounds:CGRectMake(0, 0, aFrame.size.width, aFrame.size.height)];
|
||||
[_minuteHandLayer setAnchorPoint:CGPointMakeZero()];
|
||||
[_minuteHandLayer setPosition:CGPointMake(0.0, 0.0)];
|
||||
|
||||
_secondHandLayer = [[HandLayer alloc] initWithSize:secondHandSize];
|
||||
[_secondHandLayer setBounds:CGRectMake(0, 0, aFrame.size.width, aFrame.size.height)];
|
||||
[_secondHandLayer setAnchorPoint:CGPointMakeZero()];
|
||||
[_secondHandLayer setPosition:CGPointMake(0.0, 0.0)];
|
||||
|
||||
_middleHandLayer = [[HandLayer alloc] initWithSize:middleHandSize];
|
||||
[_middleHandLayer setBounds:CGRectMake(0, 0, aFrame.size.width, aFrame.size.height)];
|
||||
[_middleHandLayer setAnchorPoint:CGPointMakeZero()];
|
||||
[_middleHandLayer setPosition:CGPointMake(0.0, 0.0)];
|
||||
|
||||
_rootLayer = [[HoursLayer alloc] init];
|
||||
[self setWantsLayer:YES];
|
||||
[self setLayer:_rootLayer];
|
||||
|
||||
[self _initHands];
|
||||
|
||||
[_rootLayer addSublayer:_hourHandLayer];
|
||||
[_rootLayer addSublayer:_minuteHandLayer];
|
||||
|
||||
if ([_datePicker valueForThemeAttribute:@"clock-second-hand-over"])
|
||||
{
|
||||
[_rootLayer addSublayer:_middleHandLayer];
|
||||
[_rootLayer addSublayer:_secondHandLayer];
|
||||
}
|
||||
else
|
||||
{
|
||||
[_rootLayer addSublayer:_secondHandLayer];
|
||||
[_rootLayer addSublayer:_middleHandLayer];
|
||||
}
|
||||
|
||||
[_rootLayer setDrawsHours:[_datePicker valueForThemeAttribute:@"clock-draws-hours"]];
|
||||
[_rootLayer setNeedsDisplay];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_initHands
|
||||
{
|
||||
var middleHandImage = [_datePicker currentValueForThemeAttribute:@"middle-hand-image"],
|
||||
hourHandImage = [_datePicker currentValueForThemeAttribute:@"hour-hand-image"],
|
||||
minuteHandImage = [_datePicker currentValueForThemeAttribute:@"minute-hand-image"],
|
||||
secondHandImage = [_datePicker currentValueForThemeAttribute:@"second-hand-image"];
|
||||
|
||||
// If hand images are true CPImage, we have to duplicate them to avoid
|
||||
// the multiple delegates bug when multiple clocks are displayed
|
||||
|
||||
if ([middleHandImage isKindOfClass:[CPImage class]])
|
||||
middleHandImage = [middleHandImage duplicate];
|
||||
|
||||
if ([hourHandImage isKindOfClass:[CPImage class]])
|
||||
hourHandImage = [hourHandImage duplicate];
|
||||
|
||||
if ([minuteHandImage isKindOfClass:[CPImage class]])
|
||||
minuteHandImage = [minuteHandImage duplicate];
|
||||
|
||||
if ([secondHandImage isKindOfClass:[CPImage class]])
|
||||
secondHandImage = [secondHandImage duplicate];
|
||||
|
||||
[_middleHandLayer setImage:middleHandImage];
|
||||
[_hourHandLayer setImage:hourHandImage];
|
||||
[_minuteHandLayer setImage:minuteHandImage];
|
||||
[_secondHandLayer setImage:secondHandImage];
|
||||
|
||||
[_hourHandLayer setNeedsDisplay];
|
||||
[_middleHandLayer setNeedsDisplay];
|
||||
[_secondHandLayer setNeedsDisplay];
|
||||
[_minuteHandLayer setNeedsDisplay];
|
||||
|
||||
[_rootLayer setFont:[_datePicker currentValueForThemeAttribute:@"clock-hours-font"]];
|
||||
[_rootLayer setTextColor:[_datePicker currentValueForThemeAttribute:@"clock-hours-text-color"]];
|
||||
[_rootLayer setRadius:[_datePicker currentValueForThemeAttribute:@"clock-hours-radius"]];
|
||||
|
||||
[_rootLayer setNeedsDisplay];
|
||||
}
|
||||
|
||||
- (void)setDatePickerElements:(CPInteger)aDatePickerElements
|
||||
{
|
||||
_datePickerElements = aDatePickerElements;
|
||||
|
||||
// Check if we have to display the hand second
|
||||
// FIXME: Don't know why but next line will cause theme compilation to fail...
|
||||
// Workaround: added "if PLATFORM(DOM)"
|
||||
#if PLATFORM(DOM)
|
||||
[_secondHandLayer setHidden:!((_datePickerElements & CPHourMinuteSecondDatePickerElementFlag) == CPHourMinuteSecondDatePickerElementFlag)];
|
||||
#endif
|
||||
}
|
||||
|
||||
#pragma mark Layout methods
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
// While tracking a hand, we don't want the whole thing to be relayouted at each mouse movement
|
||||
if (_trackingHand)
|
||||
return;
|
||||
|
||||
[self setBackgroundColor:[_datePicker currentValueForThemeAttribute:@"bezel-color-clock"]];
|
||||
|
||||
var dateValue = [[_datePicker dateValue] copy];
|
||||
|
||||
[dateValue _dateWithTimeZone:[_datePicker timeZone]];
|
||||
|
||||
_representedHours = dateValue.getHours();
|
||||
_representedMinutes = dateValue.getMinutes();
|
||||
_representedSeconds = dateValue.getSeconds();
|
||||
_representedHourIsPM = (_representedHours > 11);
|
||||
|
||||
// Hours are expressed in 24 hours format, we need 12 hours format
|
||||
_representedHours -= (_representedHourIsPM ? 12 : 0);
|
||||
|
||||
[self _updateHands];
|
||||
|
||||
// FIXME: Workaround. Seems that CALayer doesn't redraw without an event
|
||||
[CALayer runLoopUpdateLayers];
|
||||
}
|
||||
|
||||
- (void)_updateHands
|
||||
{
|
||||
var bounds = [self bounds];
|
||||
|
||||
[_PMAMTextField setStringValue:_representedHourIsPM ? @"PM" : @"AM"];
|
||||
[_PMAMTextField sizeToFit];
|
||||
[_PMAMTextField setFrameOrigin:CGPointMake(bounds.size.width / 2 - [_PMAMTextField frameSize].width / 2, bounds.size.height / 2 + 15)];
|
||||
|
||||
[_hourHandLayer setRotationRadians:(360 * (_representedHours + _representedMinutes / 60) / 12) * RADIANS];
|
||||
[_minuteHandLayer setRotationRadians:(360 * (_representedMinutes + _representedSeconds / 60) / 60) * RADIANS];
|
||||
[_secondHandLayer setRotationRadians:(360 * _representedSeconds / 60) * RADIANS];
|
||||
|
||||
[_hourHandLayer setNeedsDisplay];
|
||||
[_minuteHandLayer setNeedsDisplay];
|
||||
[_secondHandLayer setNeedsDisplay];
|
||||
// [_middleHandLayer setNeedsDisplay];
|
||||
}
|
||||
|
||||
#pragma mark Accessors
|
||||
|
||||
- (void)setEnabled:(BOOL)shouldEnable
|
||||
{
|
||||
shouldEnable = !!shouldEnable;
|
||||
|
||||
if (shouldEnable === _isEnabled)
|
||||
return;
|
||||
|
||||
_isEnabled = shouldEnable;
|
||||
|
||||
[self _initHands];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
#pragma mark Mouse actions
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
if (!_isEnabled)
|
||||
return;
|
||||
|
||||
var currentLocation = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
|
||||
if ([_secondHandLayer handIsHitAtPoint:currentLocation])
|
||||
{
|
||||
_currentHandLayer = _secondHandLayer;
|
||||
_currentHand = _CPDatePickerClockSeconds;
|
||||
_currentRepresentedValue = _representedSeconds;
|
||||
_currentValueShift = 0;
|
||||
_numberOfUnits = 60;
|
||||
}
|
||||
else if ([_minuteHandLayer handIsHitAtPoint:currentLocation])
|
||||
{
|
||||
_currentHandLayer = _minuteHandLayer;
|
||||
_currentHand = _CPDatePickerClockMinutes;
|
||||
_currentRepresentedValue = _representedMinutes;
|
||||
_currentValueShift = _representedSeconds / 60;
|
||||
_numberOfUnits = 60;
|
||||
}
|
||||
else if ([_hourHandLayer handIsHitAtPoint:currentLocation])
|
||||
{
|
||||
_currentHandLayer = _hourHandLayer;
|
||||
_currentHand = _CPDatePickerClockHours;
|
||||
_currentRepresentedValue = _representedHours;
|
||||
_currentValueShift = _representedMinutes / 60;
|
||||
_numberOfUnits = 12;
|
||||
}
|
||||
else
|
||||
{
|
||||
_currentHandLayer = nil;
|
||||
_currentHand = CPNotFound;
|
||||
_currentRepresentedValue = CPNotFound;
|
||||
_currentValueShift = CPNotFound;
|
||||
_numberOfUnits = CPNotFound;
|
||||
}
|
||||
|
||||
if (_currentHandLayer)
|
||||
[self trackMouse:anEvent];
|
||||
}
|
||||
|
||||
- (BOOL)tracksMouseOutsideOfFrame
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)startTrackingAt:(CGPoint)aPoint
|
||||
{
|
||||
_trackingHand = YES;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)continueTracking:(CGPoint)lastPoint at:(CGPoint)aPoint
|
||||
{
|
||||
var dx = aPoint.x -_bounds.size.width / 2,
|
||||
dy = _bounds.size.height / 2 - aPoint.y,
|
||||
angle = (PI_2 - ATAN2(dy,dx) + PI2) % PI2,
|
||||
value = ROUND(angle * _numberOfUnits / PI2 - _currentValueShift) % _numberOfUnits;
|
||||
|
||||
if (value !== _currentRepresentedValue)
|
||||
{
|
||||
var movedForward = (_currentRepresentedValue > _numberOfUnits * 3/4) && (value < _numberOfUnits / 4),
|
||||
movedBackward = (_currentRepresentedValue < _numberOfUnits / 4) && (value > _numberOfUnits * 3/4),
|
||||
dateValue = [[_datePicker dateValue] copy];
|
||||
|
||||
[dateValue _dateWithTimeZone:[_datePicker timeZone]];
|
||||
|
||||
switch (_currentHand)
|
||||
{
|
||||
case _CPDatePickerClockHours:
|
||||
|
||||
if (movedForward || movedBackward)
|
||||
{
|
||||
_representedHourIsPM = !_representedHourIsPM;
|
||||
|
||||
if (movedForward && !_representedHourIsPM)
|
||||
// Day++
|
||||
dateValue.setDate(dateValue.getDate() + 1);
|
||||
|
||||
else if (movedBackward && _representedHourIsPM)
|
||||
// Day--
|
||||
dateValue.setDate(dateValue.getDate() - 1);
|
||||
}
|
||||
|
||||
dateValue.setHours(value + (_representedHourIsPM ? 12 : 0));
|
||||
break;
|
||||
|
||||
case _CPDatePickerClockMinutes:
|
||||
|
||||
if (movedForward)
|
||||
// Hours++
|
||||
dateValue.setHours(dateValue.getHours() + 1);
|
||||
|
||||
else if (movedBackward)
|
||||
// Hours--
|
||||
dateValue.setHours(dateValue.getHours() - 1);
|
||||
|
||||
dateValue.setMinutes(value);
|
||||
break;
|
||||
|
||||
case _CPDatePickerClockSeconds:
|
||||
|
||||
if (movedForward)
|
||||
// Minutes++
|
||||
dateValue.setMinutes(dateValue.getMinutes() + 1);
|
||||
|
||||
else if (movedBackward)
|
||||
// Minutes--
|
||||
dateValue.setMinutes(dateValue.getMinutes() - 1);
|
||||
|
||||
dateValue.setSeconds(value);
|
||||
break;
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = YES;
|
||||
#endif
|
||||
[_datePicker _setDateValue:dateValue timeInterval:[_datePicker timeInterval]];
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = NO;
|
||||
#endif
|
||||
|
||||
// We have to adapt represented values
|
||||
_representedHours = dateValue.getHours();
|
||||
_representedMinutes = dateValue.getMinutes();
|
||||
_representedSeconds = dateValue.getSeconds();
|
||||
_representedHourIsPM = (_representedHours > 11);
|
||||
|
||||
// Hours are expressed in 24 hours format, we need 12 hours format
|
||||
_representedHours -= (_representedHourIsPM ? 12 : 0);
|
||||
|
||||
switch (_currentHand) {
|
||||
case _CPDatePickerClockHours:
|
||||
_currentRepresentedValue = _representedHours;
|
||||
break;
|
||||
|
||||
case _CPDatePickerClockMinutes:
|
||||
_currentRepresentedValue = _representedMinutes;
|
||||
break;
|
||||
|
||||
case _CPDatePickerClockSeconds:
|
||||
_currentRepresentedValue = _representedSeconds;
|
||||
break;
|
||||
}
|
||||
|
||||
[self _updateHands];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)stopTracking:(CGPoint)lastPoint at:(CGPoint)aPoint mouseIsUp:(BOOL)mouseIsUp
|
||||
{
|
||||
_trackingHand = NO;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation HandLayer : CALayer
|
||||
{
|
||||
CPImage _image;
|
||||
HandImageLayer _imageLayer;
|
||||
float _rotationRadians;
|
||||
}
|
||||
|
||||
#pragma mark Init methods
|
||||
|
||||
- (id)initWithSize:(CGSize)aSize
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_imageLayer = [HandImageLayer layer];
|
||||
_rotationRadians = 0;
|
||||
|
||||
[_imageLayer setDelegate:self];
|
||||
[_imageLayer setBounds:CGRectMake(0.0, 0.0, aSize.width, aSize.height)];
|
||||
|
||||
[self addSublayer:_imageLayer];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Setter Getter methods
|
||||
|
||||
/*!
|
||||
Set the bounds of the layer. The imageLayer will be at the center of this bounds.
|
||||
*/
|
||||
- (void)setBounds:(CGRect)aRect
|
||||
{
|
||||
[super setBounds:aRect];
|
||||
|
||||
[_imageLayer setPosition:CGPointMake(CGRectGetMidX(aRect), CGRectGetMidY(aRect))];
|
||||
}
|
||||
|
||||
- (void)setImage:(CPImage)anImage
|
||||
{
|
||||
if (_image === anImage)
|
||||
return;
|
||||
|
||||
if ([anImage isKindOfClass:[_CPCibCustomResource class]])
|
||||
_image = [anImage imageFromCoder:nil];
|
||||
else
|
||||
_image = anImage;
|
||||
|
||||
[_imageLayer setNeedsDisplay];
|
||||
}
|
||||
|
||||
- (void)setRotationRadians:(float)radians
|
||||
{
|
||||
if (_rotationRadians === radians)
|
||||
return;
|
||||
|
||||
_rotationRadians = radians;
|
||||
|
||||
[_imageLayer setAffineTransform:CGAffineTransformScale(
|
||||
CGAffineTransformMakeRotation(_rotationRadians),
|
||||
1.0, 1.0)];
|
||||
}
|
||||
|
||||
- (void)imageDidLoad:(CPImage)anImage
|
||||
{
|
||||
[_imageLayer setNeedsDisplay];
|
||||
}
|
||||
|
||||
- (void)drawLayer:(CALayer)aLayer inContext:(CGContext)aContext
|
||||
{
|
||||
if ([_image loadStatus] != CPImageLoadStatusCompleted)
|
||||
[_image setDelegate:self];
|
||||
else
|
||||
CGContextDrawImage(aContext, [aLayer bounds], _image);
|
||||
}
|
||||
|
||||
- (BOOL)handIsHitAtPoint:(CGPoint)aPoint
|
||||
{
|
||||
return (!_isHidden && [_imageLayer hitTest:aPoint] === _imageLayer);
|
||||
}
|
||||
|
||||
- (void)setNeedsDisplay
|
||||
{
|
||||
[super setNeedsDisplay];
|
||||
[_imageLayer setNeedsDisplay];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation HandImageLayer : CALayer
|
||||
{
|
||||
CGRect _handBounds;
|
||||
}
|
||||
|
||||
// We have to adapt hitTest so it only takes the hand into account (that's the top half of the image layer)
|
||||
// We are also sure there's no sublayers
|
||||
- (CALayer)hitTest:(CGPoint)aPoint
|
||||
{
|
||||
if (_isHidden)
|
||||
return nil;
|
||||
|
||||
var point = CGPointApplyAffineTransform(aPoint, _transformToLayer);
|
||||
|
||||
return CGRectContainsPoint(_handBounds, point) ? self : nil;
|
||||
}
|
||||
|
||||
- (void)setBounds:(CGRect)aBounds
|
||||
{
|
||||
if (CGRectEqualToRect(_bounds, aBounds))
|
||||
return;
|
||||
|
||||
_handBounds = CGRectMakeCopy(aBounds);
|
||||
|
||||
_handBounds.size.height = _handBounds.size.height / 2;
|
||||
|
||||
[super setBounds:aBounds];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation HoursLayer : CALayer
|
||||
{
|
||||
BOOL _drawsHours;
|
||||
|
||||
CPFont _font @accessors(property=font);
|
||||
CPColor _textColor @accessors(property=textColor);
|
||||
float _radius @accessors(property=radius);
|
||||
}
|
||||
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_drawsHours = NO;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setDrawsHours:(BOOL)shouldDrawHours
|
||||
{
|
||||
shouldDrawHours = !!shouldDrawHours;
|
||||
|
||||
if (_drawsHours === shouldDrawHours)
|
||||
return;
|
||||
|
||||
_drawsHours = shouldDrawHours;
|
||||
[self setNeedsDisplay];
|
||||
}
|
||||
|
||||
- (void)drawInContext:(CGContext)aContext
|
||||
{
|
||||
[super drawInContext:aContext];
|
||||
|
||||
if (_drawsHours)
|
||||
{
|
||||
var bounds = [self bounds],
|
||||
centerX = bounds.size.width / 2,
|
||||
centerY = bounds.size.height / 2;
|
||||
|
||||
CGContextSelectFont(aContext, _font);
|
||||
CGContextSetFillColor(aContext, _textColor);
|
||||
aContext.textBaseline = @"middle";
|
||||
aContext.textAlign = @"center";
|
||||
|
||||
for (var i = 1, angle = 60.0, x, y; i < 13; i++, angle -= 30.0)
|
||||
{
|
||||
x = centerX + _radius * COS(angle * RADIANS);
|
||||
y = centerY - _radius * SIN(angle * RADIANS);
|
||||
|
||||
aContext.fillText(i, x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,280 +0,0 @@
|
||||
/* _CPDatePickerDayView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
|
||||
@import "_CPDatePickerDayViewTextField.j"
|
||||
|
||||
@class CPDatePicker
|
||||
|
||||
@implementation _CPDatePickerDayView : CPControl
|
||||
{
|
||||
CPDate _date @accessors(property=date);
|
||||
|
||||
BOOL _isDisabled;
|
||||
BOOL _isHighlighted;
|
||||
BOOL _isSelected;
|
||||
CPDatePicker _datePicker;
|
||||
CPTextField _textField;
|
||||
|
||||
CPInteger _dayInWeek @accessors(property=dayInWeek);
|
||||
BOOL _firstSelected @accessors(property=firstSelected);
|
||||
BOOL _lastSelected @accessors(property=lastSelected);
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Init methods
|
||||
|
||||
/*! Create a new instance of _CPDatePickerDayView
|
||||
@param aFrame
|
||||
@param aDatePicker
|
||||
@return a new instance of _CPDatePickerDayView
|
||||
*/
|
||||
- (id)initWithFrame:(CGRect)aFrame withDatePicker:(CPDatePicker)aDatePicker
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
[self setHitTests:NO];
|
||||
|
||||
_datePicker = aDatePicker;
|
||||
|
||||
// FIXME: Beginning with Aristo3, the text field is directly themed based on a new class _CPDatePickerDayViewTextField
|
||||
if ([self isCSSBased])
|
||||
{
|
||||
_textField = [[_CPDatePickerDayViewTextField alloc] initWithFrame:aFrame];
|
||||
}
|
||||
else
|
||||
{
|
||||
_textField = [[CPTextField alloc] initWithFrame:aFrame];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-alignment"] forThemeAttribute:@"alignment"];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-vertical-alignment"] forThemeAttribute:@"vertical-alignment"];
|
||||
|
||||
var contentInset = [_datePicker valueForThemeAttribute:@"tile-content-inset"];
|
||||
|
||||
if (contentInset)
|
||||
[_textField setValue:contentInset forThemeAttribute:@"content-inset"];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inState:CPThemeStateNormal] forThemeAttribute:@"font" inState:CPThemeStateNormal];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-color" inState:CPThemeStateNormal];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateNormal];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateNormal];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inState:CPThemeStateSelected] forThemeAttribute:@"font" inState:CPThemeStateSelected];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inState:CPThemeStateSelected] forThemeAttribute:@"text-color" inState:CPThemeStateSelected];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inState:CPThemeStateSelected] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateSelected];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inState:CPThemeStateSelected] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateSelected];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inState:CPThemeStateDisabled] forThemeAttribute:@"font" inState:CPThemeStateDisabled];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-color" inState:CPThemeStateDisabled];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateDisabled];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateDisabled];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inStates:[CPThemeStateDisabled, CPThemeStateSelected]] forThemeAttribute:@"font" inStates:[CPThemeStateDisabled, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inStates:[CPThemeStateDisabled, CPThemeStateSelected]]forThemeAttribute:@"text-color" inStates:[CPThemeStateDisabled, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inStates:[CPThemeStateDisabled, CPThemeStateSelected]] forThemeAttribute:@"text-shadow-color" inStates:[CPThemeStateDisabled, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inStates:[CPThemeStateDisabled, CPThemeStateSelected]] forThemeAttribute:@"text-shadow-offset" inStates:[CPThemeStateDisabled, CPThemeStateSelected]];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inState:CPThemeStateHighlighted] forThemeAttribute:@"font" inState:CPThemeStateHighlighted];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inState:CPThemeStateHighlighted] forThemeAttribute:@"text-color" inState:CPThemeStateHighlighted];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inState:CPThemeStateHighlighted] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateHighlighted];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inState:CPThemeStateHighlighted] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateHighlighted];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"font" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"text-color" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"text-shadow-color" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"text-shadow-offset" inStates:[CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"font" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"text-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"text-shadow-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]] forThemeAttribute:@"text-shadow-offset" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted, CPThemeStateSelected]];
|
||||
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-font" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]] forThemeAttribute:@"font" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]] forThemeAttribute:@"text-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]] forThemeAttribute:@"text-shadow-color" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]];
|
||||
[_textField setValue:[_datePicker valueForThemeAttribute:@"tile-text-shadow-offset" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]] forThemeAttribute:@"text-shadow-offset" inStates:[CPThemeStateDisabled, CPThemeStateHighlighted]];
|
||||
}
|
||||
|
||||
[self addSubview:_textField];
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Theme methods
|
||||
|
||||
/*! Set a theme
|
||||
*/
|
||||
- (BOOL)setThemeState:(ThemeState)aState
|
||||
{
|
||||
[_textField setThemeState:aState];
|
||||
[super setThemeState:aState];
|
||||
}
|
||||
|
||||
/*! Unset a theme
|
||||
*/
|
||||
- (BOOL)unsetThemeState:(ThemeState)aState
|
||||
{
|
||||
[_textField unsetThemeState:aState];
|
||||
[super unsetThemeState:aState];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Getter methods
|
||||
|
||||
/*! Select the tile
|
||||
*/
|
||||
- (void)setSelected:(BOOL)shouldBeSelected
|
||||
{
|
||||
if (_isSelected === shouldBeSelected)
|
||||
return;
|
||||
|
||||
_isSelected = shouldBeSelected;
|
||||
|
||||
if (_isSelected)
|
||||
[self setThemeState:CPThemeStateSelected];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateSelected];
|
||||
}
|
||||
|
||||
/*! Disabled the tile (used for previous and next month tile)
|
||||
*/
|
||||
- (void)setDisabled:(BOOL)shouldBeDisabled
|
||||
{
|
||||
if (_isDisabled === shouldBeDisabled)
|
||||
return;
|
||||
|
||||
_isDisabled = shouldBeDisabled;
|
||||
|
||||
if (_isDisabled)
|
||||
[self setThemeState:CPThemeStateDisabled];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateDisabled];
|
||||
}
|
||||
|
||||
- (BOOL)isDisabled
|
||||
{
|
||||
return _isDisabled;
|
||||
}
|
||||
|
||||
/*! Highlight the tile (used for current day)
|
||||
*/
|
||||
- (void)setHighlighted:(BOOL)shouldBeHighlighted
|
||||
{
|
||||
if (_isHighlighted === shouldBeHighlighted)
|
||||
return;
|
||||
|
||||
_isHighlighted = shouldBeHighlighted;
|
||||
|
||||
if (_isHighlighted)
|
||||
[self setThemeState:CPThemeStateHighlighted];
|
||||
else
|
||||
[self unsetThemeState:CPThemeStateHighlighted];
|
||||
}
|
||||
|
||||
/*! Set the stringValue of the tile
|
||||
@param aStringValue
|
||||
*/
|
||||
- (void)setStringValue:(CPString)aStringValue
|
||||
{
|
||||
[_textField setStringValue:aStringValue];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Layout methods
|
||||
|
||||
/*! Layout the subviews
|
||||
*/
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
if ([_datePicker isCSSBased])
|
||||
{
|
||||
var attributeName = @"bezel-color-calendar";
|
||||
|
||||
if (_isSelected)
|
||||
{
|
||||
if (_firstSelected && !_lastSelected)
|
||||
attributeName = @"bezel-color-calendar-left";
|
||||
else if (_lastSelected && !_firstSelected)
|
||||
attributeName = @"bezel-color-calendar-right";
|
||||
else if (!_firstSelected && !_lastSelected)
|
||||
{
|
||||
if (_dayInWeek == 0)
|
||||
attributeName = @"bezel-color-calendar-left";
|
||||
else if (_dayInWeek == 6)
|
||||
attributeName = @"bezel-color-calendar-right";
|
||||
else
|
||||
attributeName = @"bezel-color-calendar-middle";
|
||||
}
|
||||
}
|
||||
|
||||
[self setBackgroundColor:[_datePicker valueForThemeAttribute:attributeName inState:[self themeState]]];
|
||||
return;
|
||||
}
|
||||
|
||||
var bounds = [self bounds];
|
||||
[_textField sizeToFit];
|
||||
[_textField setFrameOrigin:CGPointMake(bounds.size.width / 2 - [_textField frameSize].width / 2 + [_datePicker valueForThemeAttribute:@"border-width"], bounds.size.height / 2 - [_textField frameSize].height / 2)];
|
||||
}
|
||||
|
||||
- (void)setFrame:(CGRect)aFrame
|
||||
{
|
||||
[super setFrame:aFrame];
|
||||
[_textField setFrame:CGRectMake(0, 0, aFrame.size.width, aFrame.size.height)];
|
||||
}
|
||||
|
||||
/*! Drawrect
|
||||
*/
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
[super drawRect:aRect];
|
||||
|
||||
if ([_datePicker isCSSBased])
|
||||
return;
|
||||
|
||||
var themeState = [self themeState],
|
||||
context = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
if (themeState.hasThemeState(CPThemeStateSelected))
|
||||
{
|
||||
[self setBackgroundColor:[_datePicker valueForThemeAttribute:@"bezel-color-calendar" inState:themeState]];
|
||||
CGContextSetLineWidth(context, [_datePicker valueForThemeAttribute:@"border-width"]);
|
||||
CGContextSetStrokeColor(context, [_datePicker valueForThemeAttribute:@"border-color" inState:themeState]);
|
||||
CGContextAddRect(context, [self bounds]);
|
||||
CGContextStrokeRect(context, [self bounds]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Clear color, because the original color of a tile is handle by his superview
|
||||
[self setBackgroundColor:[CPColor clearColor]];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
/* _CPDatePickerDayViewTextField.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
|
||||
@import "CPTextField.j"
|
||||
|
||||
@implementation _CPDatePickerDayViewTextField : CPTextField
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return @"datePickerDayViewTextField";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"min-size": CGSizeMakeZero(),
|
||||
@"content-inset": CGInsetMakeZero(),
|
||||
@"text-color": [CPColor blackColor],
|
||||
@"text-shadow-color": [CPColor clearColor],
|
||||
@"text-shadow-offset": CGSizeMakeZero(),
|
||||
@"font": [CPNull null],
|
||||
@"vertical-alignment": CPCenterVerticalTextAlignment,
|
||||
@"alignment": CPCenterTextAlignment,
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,577 +0,0 @@
|
||||
/* _CPDatePickerElementTextField.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 "CPTextField.j"
|
||||
|
||||
@class CPDatePicker
|
||||
@class _CPDatePickerElementView
|
||||
|
||||
CPDatePickerElementTextFieldBecomeFirstResponder = @"CPDatePickerElementTextFieldBecomeFirstResponder";
|
||||
CPDatePickerElementTextFieldAMPMChangedNotification = @"CPDatePickerElementTextFieldAMPMChangedNotification";
|
||||
|
||||
var CPZeroKeyCode = 48,
|
||||
CPNineKeyCode = 57,
|
||||
CPMajAKeyCode = 65,
|
||||
CPMajPKeyCode = 80,
|
||||
CPAKeyCode = 97,
|
||||
CPPKeyCode = 112;
|
||||
|
||||
CPMonthDateType = 0;
|
||||
CPDayDateType = 1;
|
||||
CPYearDateType = 2;
|
||||
CPHourDateType = 3;
|
||||
CPSecondDateType = 4;
|
||||
CPMinuteDateType = 5;
|
||||
CPAMPMDateType = 6;
|
||||
|
||||
/*! An element textField
|
||||
*/
|
||||
@implementation _CPDatePickerElementTextField : CPTextField
|
||||
{
|
||||
_CPDatePickerElementTextField _nextTextField @accessors(property=nextTextField);
|
||||
_CPDatePickerElementTextField _previousTextField @accessors(property=previousTextField);
|
||||
_CPDatePickerElementView _datePickerElementView @accessors(property=datePickerElementView);
|
||||
|
||||
CPDatePicker _datePicker @accessors(setter=setDatePicker:);
|
||||
|
||||
int _dateType @accessors(getter=dateType);
|
||||
int _maxNumber @accessors(getter=maxNumber);
|
||||
int _minNumber @accessors(getter=minNumber);
|
||||
|
||||
BOOL _firstEvent;
|
||||
CPTimer _timerEdition;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return @"datePickerElementTextField";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"content-inset": CGInsetMake(1.0, 0.0, 0.0, 0.0),
|
||||
@"bezel-color": [CPNull null],
|
||||
@"min-size": CGSizeMakeZero()
|
||||
};
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_firstEvent = YES;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (BOOL)acceptsFirstResponder
|
||||
{
|
||||
return [_datePicker isEnabled];
|
||||
}
|
||||
|
||||
/*! Set the dateType of the textField
|
||||
*/
|
||||
- (void)setDateType:(int)aDateType
|
||||
{
|
||||
_dateType = aDateType;
|
||||
|
||||
switch (aDateType)
|
||||
{
|
||||
case CPMonthDateType:
|
||||
_minNumber = 1;
|
||||
_maxNumber = 12;
|
||||
break;
|
||||
|
||||
case CPDayDateType:
|
||||
_minNumber = 1;
|
||||
_maxNumber = 31;
|
||||
break;
|
||||
|
||||
case CPYearDateType:
|
||||
_minNumber = 0;
|
||||
_maxNumber = 9999;
|
||||
break;
|
||||
|
||||
case CPHourDateType:
|
||||
_minNumber = 0;
|
||||
_maxNumber = 23;
|
||||
break;
|
||||
|
||||
case CPSecondDateType:
|
||||
_minNumber = 0;
|
||||
_maxNumber = 59;
|
||||
break;
|
||||
|
||||
case CPMinuteDateType:
|
||||
_minNumber = 0;
|
||||
_maxNumber = 59;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/*! Return the maxNumber of the textField
|
||||
*/
|
||||
- (int)maxNumber
|
||||
{
|
||||
if (_dateType == CPDayDateType)
|
||||
return [[_datePicker dateValue] _daysInMonth];
|
||||
|
||||
return _maxNumber;
|
||||
}
|
||||
|
||||
/*! Return the maxNumber of the textField depending of the maxDate
|
||||
*/
|
||||
- (int)_maxNumberWithMaxDate
|
||||
{
|
||||
var maxDate = [_datePicker maxDate],
|
||||
date = [_datePicker dateValue];
|
||||
|
||||
if (maxDate)
|
||||
{
|
||||
switch (_dateType)
|
||||
{
|
||||
case CPMonthDateType:
|
||||
if (maxDate.getFullYear() == date.getFullYear())
|
||||
return maxDate.getMonth();
|
||||
break;
|
||||
|
||||
case CPDayDateType:
|
||||
if (maxDate.getFullYear() == date.getFullYear() && maxDate.getMonth() == date.getMonth())
|
||||
return maxDate.getDate();
|
||||
break;
|
||||
|
||||
case CPYearDateType:
|
||||
return maxDate.getFullYear();
|
||||
|
||||
case CPHourDateType:
|
||||
if (maxDate.getFullYear() == date.getFullYear() && maxDate.getMonth() == date.getMonth() && maxDate.getDate() == date.getDate())
|
||||
return maxDate.getHours();
|
||||
break;
|
||||
|
||||
case CPSecondDateType:
|
||||
if (maxDate.getFullYear() == date.getFullYear() && maxDate.getMonth() == date.getMonth() && maxDate.getDate() == date.getDate() && maxDate.getHours() == date.getHours() && maxDate.getMinutes() == date.getMinutes())
|
||||
return maxDate.getSeconds();
|
||||
break;
|
||||
|
||||
case CPMinuteDateType:
|
||||
if (maxDate.getFullYear() == date.getFullYear() && maxDate.getMonth() == date.getMonth() && maxDate.getDate() == date.getDate() && maxDate.getHours() == date.getHours())
|
||||
return maxDate.getMinutes();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return _maxNumber;
|
||||
}
|
||||
|
||||
/*! Set the stringValue of the textField. This is going to check if there is 2 or 4 letters. If not it adds a space. Check also the maxDate
|
||||
It's called when the user is editing with the keyboard
|
||||
@param aStringValue a CPString
|
||||
*/
|
||||
- (void)setValueForKeyEvent:(CPEvent)anEvent
|
||||
{
|
||||
var keyCode = [anEvent keyCode];
|
||||
|
||||
if (keyCode != CPDeleteKeyCode && keyCode != CPDeleteForwardKeyCode && keyCode < CPZeroKeyCode || keyCode > CPNineKeyCode)
|
||||
return;
|
||||
|
||||
var newValue = [self stringValue].replace(/\s/g, ''),
|
||||
length = [newValue length],
|
||||
eventKeyValue = parseInt([anEvent characters]).toString();
|
||||
|
||||
if (keyCode == CPDeleteKeyCode || keyCode == CPDeleteForwardKeyCode)
|
||||
{
|
||||
[_timerEdition invalidate];
|
||||
_timerEdition = nil;
|
||||
newValue = [newValue substringToIndex:(length - 1)];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!_timerEdition)
|
||||
{
|
||||
_timerEdition = [CPTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(_timerKeyEvent:) userInfo:nil repeats:NO];
|
||||
|
||||
if (_firstEvent || !length)
|
||||
newValue = eventKeyValue;
|
||||
else
|
||||
newValue = parseInt(newValue).toString() + eventKeyValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
var newFireDate = [CPDate date];
|
||||
|
||||
newFireDate.setSeconds(newFireDate.getSeconds() + 2);
|
||||
[_timerEdition setFireDate:newFireDate];
|
||||
|
||||
newValue = parseInt(newValue).toString() + eventKeyValue;
|
||||
}
|
||||
}
|
||||
|
||||
if (parseInt(newValue) > [self _maxNumberWithMaxDate] || ([_datePicker _isAmericanFormat] && _dateType == CPHourDateType && parseInt(newValue) > 12))
|
||||
return;
|
||||
|
||||
_firstEvent = NO;
|
||||
|
||||
[super setObjectValue:newValue];
|
||||
}
|
||||
|
||||
/*!
|
||||
End of the timer
|
||||
*/
|
||||
- (void)_timerKeyEvent:(id)sender
|
||||
{
|
||||
var stringValue = [self stringValue];
|
||||
|
||||
_timerEdition = nil;
|
||||
|
||||
if ([stringValue length])
|
||||
{
|
||||
if ([_datePicker _isAmericanFormat] && [self dateType] == CPHourDateType)
|
||||
{
|
||||
var isAMHour = [[self superview] _isAMHour];
|
||||
|
||||
if (!isAMHour && stringValue != 12)
|
||||
stringValue = parseInt(stringValue) + 12;
|
||||
|
||||
if (stringValue == 12 && !isAMHour)
|
||||
stringValue = 12;
|
||||
else if (stringValue == 12)
|
||||
stringValue = 0;
|
||||
}
|
||||
|
||||
[self setObjectValue:stringValue];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
We force to end the timer
|
||||
*/
|
||||
- (void)_invalidTimer
|
||||
{
|
||||
if (_timerEdition)
|
||||
{
|
||||
[_timerEdition invalidate];
|
||||
_timerEdition = nil;
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
We force to end the timer and to update the objectValue of the datePicker
|
||||
*/
|
||||
- (void)_endEditing
|
||||
{
|
||||
if (_timerEdition)
|
||||
[_timerEdition invalidate];
|
||||
|
||||
_timerEdition = nil;
|
||||
|
||||
var objectValue = [self stringValue];
|
||||
|
||||
if (![objectValue length])
|
||||
objectValue = [self objectValue];
|
||||
|
||||
if ([_datePicker _isAmericanFormat] && [self dateType] == CPHourDateType)
|
||||
{
|
||||
var isAMHour = [[self superview] _isAMHour];
|
||||
|
||||
if (!isAMHour && objectValue != 12)
|
||||
objectValue = parseInt(objectValue) + 12;
|
||||
|
||||
if (objectValue == 12 && !isAMHour)
|
||||
objectValue = 12;
|
||||
else if (objectValue == 12)
|
||||
objectValue = 0;
|
||||
}
|
||||
|
||||
[self setObjectValue:objectValue];
|
||||
}
|
||||
|
||||
/*! Set the stringValue of the TextField. Add some zeros of there isn't 2/4 letters in the value. It's called at the end of the editing process
|
||||
@param aStringValue a CPString
|
||||
*/
|
||||
- (void)setStringValue:(CPString)aStringValue
|
||||
{
|
||||
if (_dateType == CPYearDateType)
|
||||
{
|
||||
while ([aStringValue length] < 4)
|
||||
aStringValue = "0" + aStringValue;
|
||||
}
|
||||
else if (_dateType != CPAMPMDateType)
|
||||
{
|
||||
if (_dateType == CPHourDateType && [_datePicker _isAmericanFormat])
|
||||
{
|
||||
var value = parseInt(aStringValue);
|
||||
|
||||
if (value == 0)
|
||||
value = 12;
|
||||
else if (value > 12)
|
||||
value = value - 12;
|
||||
|
||||
aStringValue = value.toString();
|
||||
}
|
||||
|
||||
while ([aStringValue length] < 2)
|
||||
{
|
||||
if (_dateType == CPSecondDateType || _dateType == CPMinuteDateType)
|
||||
aStringValue = @"0" + aStringValue;
|
||||
else
|
||||
aStringValue = @" " + aStringValue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[super setObjectValue:aStringValue];
|
||||
}
|
||||
|
||||
/*! Set the objectValue. This will update the dateValue of the datePicker also. It's called with the binding of the stepper or arrows
|
||||
This is not going to update the objectValue of the control !!! It updates the dateValue of the datePicker who's going to update the datePickerTextField if necessary
|
||||
It's a bit tricky
|
||||
@param aObjectValue
|
||||
*/
|
||||
- (void)setObjectValue:(id)anObjectValue
|
||||
{
|
||||
var dateValue = [[_datePicker dateValue] copy],
|
||||
lengthString = [[self stringValue] length],
|
||||
objectValue = parseInt(anObjectValue);
|
||||
|
||||
switch (_dateType)
|
||||
{
|
||||
case CPMonthDateType:
|
||||
|
||||
if (objectValue == 0 || !lengthString)
|
||||
{
|
||||
[self setStringValue:(dateValue.getMonth() + 1).toString()];
|
||||
return;
|
||||
}
|
||||
|
||||
var dateNextMonth = [dateValue copy];
|
||||
|
||||
dateNextMonth.setDate(1);
|
||||
dateNextMonth.setMonth(parseInt(anObjectValue) - 1);
|
||||
|
||||
var numberDayNextMonth = [dateNextMonth _daysInMonth];
|
||||
|
||||
if (numberDayNextMonth < [dateValue _daysInMonth] && dateValue.getDate() > numberDayNextMonth)
|
||||
[_datePickerElementView setDayDateValue:numberDayNextMonth.toString()];
|
||||
|
||||
[super setObjectValue:objectValue];
|
||||
break;
|
||||
|
||||
case CPDayDateType:
|
||||
|
||||
if (objectValue == 0 || !lengthString)
|
||||
{
|
||||
[self setStringValue:dateValue.getDate().toString()];
|
||||
return;
|
||||
}
|
||||
|
||||
[super setObjectValue:objectValue];
|
||||
break;
|
||||
|
||||
case CPYearDateType:
|
||||
|
||||
if (objectValue == 0 || !lengthString)
|
||||
{
|
||||
[self setStringValue:dateValue.getFullYear().toString()];
|
||||
return;
|
||||
}
|
||||
|
||||
[super setObjectValue:objectValue];
|
||||
break;
|
||||
|
||||
case CPHourDateType:
|
||||
|
||||
if (!lengthString)
|
||||
{
|
||||
[self setStringValue:dateValue.getHours().toString()];
|
||||
return;
|
||||
}
|
||||
|
||||
[super setObjectValue:objectValue];
|
||||
break;
|
||||
|
||||
case CPSecondDateType:
|
||||
|
||||
if (!lengthString)
|
||||
{
|
||||
[self setStringValue:dateValue.getSeconds().toString()];
|
||||
return;
|
||||
}
|
||||
|
||||
[super setObjectValue:objectValue];
|
||||
break;
|
||||
|
||||
case CPMinuteDateType:
|
||||
|
||||
if (!lengthString)
|
||||
{
|
||||
[self setStringValue:dateValue.getMinutes().toString()];
|
||||
return;
|
||||
}
|
||||
|
||||
[super setObjectValue:objectValue];
|
||||
break;
|
||||
}
|
||||
|
||||
var newDateValue = [_datePickerElementView dateValue],
|
||||
timeZone = [_datePicker timeZone];
|
||||
|
||||
if (timeZone)
|
||||
{
|
||||
var secondsFromGMT = [timeZone secondsFromGMTForDate:newDateValue],
|
||||
secondsFromGMTTimeZone = [timeZone secondsFromGMT];
|
||||
|
||||
newDateValue.setSeconds(newDateValue.getSeconds() + secondsFromGMT - secondsFromGMTTimeZone);
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = YES;
|
||||
#endif
|
||||
[_datePicker _setDateValue:newDateValue timeInterval:[_datePicker timeInterval]];
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = NO;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Mouse event
|
||||
|
||||
/*! Mouse down event. Launch a notification to notif the new first responder textField
|
||||
*/
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEnabled])
|
||||
return;
|
||||
|
||||
[super mouseDown:anEvent];
|
||||
[[CPNotificationCenter defaultCenter] postNotificationName:CPDatePickerElementTextFieldBecomeFirstResponder object:[[self superview] superview] userInfo:[CPDictionary dictionaryWithObject:self forKey:@"textField"]];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Theme functions
|
||||
|
||||
/*! Set the theme CPThemeStateSelected
|
||||
*/
|
||||
- (void)makeSelectable
|
||||
{
|
||||
[self setThemeState:CPThemeStateSelected];
|
||||
[_datePicker setThemeState:CPThemeStateEditing];
|
||||
}
|
||||
|
||||
/*! Unsert the theme CPThemeStateSelected
|
||||
*/
|
||||
- (void)makeDeselectable
|
||||
{
|
||||
_firstEvent = YES;
|
||||
[self unsetThemeState:CPThemeStateSelected];
|
||||
[_datePicker unsetThemeState:CPThemeStateEditing];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Override
|
||||
|
||||
/*!
|
||||
We override this method to get all the time the good width
|
||||
*/
|
||||
- (CGSize)_minimumFrameSize
|
||||
{
|
||||
var frameSize = [self frameSize],
|
||||
contentInset = [self currentValueForThemeAttribute:@"content-inset"],
|
||||
minSize = [self currentValueForThemeAttribute:@"min-size"],
|
||||
maxSize = [self currentValueForThemeAttribute:@"max-size"],
|
||||
lineBreakMode = [self lineBreakMode],
|
||||
text = (_dateType == CPYearDateType) ? @"0000" : (_dateType == CPMonthDateType) ? @"10" : @"00",
|
||||
textSize = CGSizeMakeCopy(frameSize),
|
||||
font = [self currentValueForThemeAttribute:@"font"];
|
||||
|
||||
textSize.width -= contentInset.left + contentInset.right;
|
||||
textSize.height -= contentInset.top + contentInset.bottom;
|
||||
|
||||
if (_dateType == CPAMPMDateType)
|
||||
text = [self stringValue];
|
||||
|
||||
if (frameSize.width !== 0 &&
|
||||
![self isBezeled] &&
|
||||
(lineBreakMode === CPLineBreakByWordWrapping || lineBreakMode === CPLineBreakByCharWrapping))
|
||||
{
|
||||
textSize = [text sizeWithFont:font inWidth:textSize.width];
|
||||
}
|
||||
else
|
||||
{
|
||||
textSize = [text sizeWithFont:font];
|
||||
|
||||
// Account for possible fractional pixels at right edge
|
||||
textSize.width += 1;
|
||||
}
|
||||
|
||||
// Account for possible fractional pixels at bottom edge
|
||||
textSize.height += 1;
|
||||
|
||||
frameSize.height = textSize.height + contentInset.top + contentInset.bottom;
|
||||
|
||||
if ([self isBezeled])
|
||||
{
|
||||
frameSize.height = MAX(frameSize.height, minSize.height);
|
||||
|
||||
if (maxSize.width > 0.0)
|
||||
frameSize.width = MIN(frameSize.width, maxSize.width);
|
||||
|
||||
if (maxSize.height > 0.0)
|
||||
frameSize.height = MIN(frameSize.height, maxSize.height);
|
||||
}
|
||||
else
|
||||
frameSize.width = textSize.width + contentInset.left + contentInset.right;
|
||||
|
||||
frameSize.width = MAX(frameSize.width, minSize.width);
|
||||
|
||||
return frameSize;
|
||||
}
|
||||
|
||||
- (CGRect)bezelRectForBounds:(CGRect)bounds
|
||||
{
|
||||
return CGRectMakeCopy(bounds);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPDatePickerElementSeparator : CPTextField
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return @"datePickerElementSeparator";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"content-inset": CGInsetMake(1.0, 0.0, 0.0, 0.0),
|
||||
@"min-size": CGSizeMakeZero()
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,306 +0,0 @@
|
||||
/* _CPDatePickerHeaderView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "CPTextField.j"
|
||||
@import "CPButton.j"
|
||||
|
||||
@class CPDatePicker
|
||||
|
||||
var CPShortWeekDayNameArrayEn = [@"Mo", @"Tu", @"We", @"Th", @"Fr", @"Sa", @"Su"],
|
||||
CPShortWeekDayNameArrayUS = [@"Su", @"Mo", @"Tu", @"We", @"Th", @"Fr", @"Sa"],
|
||||
CPShortWeekDayNameArrayFr = [@"L", @"M", @"M", @"J", @"V", @"S", @"D"],
|
||||
CPShortWeekDayNameArrayDe = [@"M", @"D", @"M", @"D", @"F", @"S", @"S"],
|
||||
CPShortWeekDayNameArrayEs = [@"L", @"M", @"X", @"J", @"V", @"S", @"D"],
|
||||
CPShortMonthNameArrayEn = [@"Jan", @"Feb", @"Mar", @"Apr", @"May", @"Jun", @"Jul", @"Aug", @"Sep", @"Oct", @"Nov", @"Dec"],
|
||||
CPShortMonthNameArrayFr = [@"janv.", String.fromCharCode(102, 233, 118, 46), @"mars", @"apr.", @"mai", @"juin", @"juil.", String.fromCharCode(97, 111, 251, 116), @"sept.", @"oct.", @"nov.", String.fromCharCode(100, 233, 99, 46)],
|
||||
CPShortMonthNameArrayDe = [@"Jan", @"Feb", String.fromCharCode(77, 228, 114), @"Apr", @"Mai", @"Jun", @"Jul", @"Aug", @"Sep", @"Okt", @"Nov", @"Dez"],
|
||||
CPShortMonthNameArrayEs = [@"ene", @"feb", @"mar", @"abr", @"may", @"jun", @"jul", @"ago", @"sep", @"oct", @"nov", @"dic"];
|
||||
|
||||
@implementation _CPDatePickerHeaderView : CPControl
|
||||
{
|
||||
CPArray _dayLabels;
|
||||
CPArray _monthNames;
|
||||
CPButton _nextButton;
|
||||
CPButton _previousButton;
|
||||
CPButton _currentButton;
|
||||
CPDatePicker _datePicker;
|
||||
CPDate _date;
|
||||
CPTextField _title;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Init methods
|
||||
|
||||
/*! Init a new instance of _CPDatePickerHeaderView
|
||||
@param aFrame
|
||||
@param aDatePicker
|
||||
@return a new instance of _CPDatePickerHeaderView
|
||||
*/
|
||||
- (id)initWithFrame:(CGRect)aFrame datePicker:(CPDatePicker)aDatePicker delegate:(id)aDelegate
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_datePicker = aDatePicker;
|
||||
|
||||
// Title
|
||||
_title = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-font" inState:CPThemeStateNormal] forThemeAttribute:@"font" inState:CPThemeStateNormal];
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-text-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-color" inState:CPThemeStateNormal];
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-text-shadow-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateNormal];
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-text-shadow-offset" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateNormal];
|
||||
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-font" inState:CPThemeStateDisabled] forThemeAttribute:@"font" inState:CPThemeStateDisabled];
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-text-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-color" inState:CPThemeStateDisabled];
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-text-shadow-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateDisabled];
|
||||
[_title setValue:[_datePicker valueForThemeAttribute:@"title-text-shadow-offset" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateDisabled];
|
||||
|
||||
[self addSubview:_title];
|
||||
|
||||
_dayLabels = [CPArray array];
|
||||
|
||||
// Days
|
||||
for (var i = 0, count = [[self _dayNames] count]; i < count; i++)
|
||||
{
|
||||
var label = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"tile-text-alignment"] forThemeAttribute:@"alignment"];
|
||||
|
||||
var contentInset = [_datePicker valueForThemeAttribute:@"tile-content-inset"];
|
||||
|
||||
if (contentInset)
|
||||
[label setValue:contentInset forThemeAttribute:@"content-inset"];
|
||||
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-font" inState:CPThemeStateNormal] forThemeAttribute:@"font" inState:CPThemeStateNormal];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-text-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-color" inState:CPThemeStateNormal];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-text-shadow-color" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateNormal];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-text-shadow-offset" inState:CPThemeStateNormal] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateNormal];
|
||||
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-font" inState:CPThemeStateDisabled] forThemeAttribute:@"font" inState:CPThemeStateDisabled];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-text-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-color" inState:CPThemeStateDisabled];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-text-shadow-color" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-color" inState:CPThemeStateDisabled];
|
||||
[label setValue:[_datePicker valueForThemeAttribute:@"weekday-text-shadow-offset" inState:CPThemeStateDisabled] forThemeAttribute:@"text-shadow-offset" inState:CPThemeStateDisabled];
|
||||
|
||||
[_dayLabels addObject:label];
|
||||
[self addSubview:label];
|
||||
}
|
||||
|
||||
// Arrows
|
||||
var size = [_datePicker valueForThemeAttribute:@"previous-button-size"];
|
||||
|
||||
_previousButton = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
|
||||
[_previousButton setButtonType:CPMomentaryChangeButton];
|
||||
[_previousButton setBordered:NO];
|
||||
[_previousButton setImage:[_datePicker valueForThemeAttribute:@"arrow-image-left"]];
|
||||
[_previousButton setAlternateImage:[_datePicker valueForThemeAttribute:@"arrow-image-left-highlighted"]];
|
||||
[self addSubview:_previousButton];
|
||||
|
||||
size = [_datePicker valueForThemeAttribute:@"next-button-size"];
|
||||
|
||||
_nextButton = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
|
||||
[_nextButton setButtonType:CPMomentaryChangeButton];
|
||||
[_nextButton setBordered:NO];
|
||||
[_nextButton setImage:[_datePicker valueForThemeAttribute:@"arrow-image-right"]];
|
||||
[_nextButton setAlternateImage:[_datePicker valueForThemeAttribute:@"arrow-image-right-highlighted"]];
|
||||
[self addSubview:_nextButton];
|
||||
|
||||
size = [_datePicker valueForThemeAttribute:@"current-button-size"];
|
||||
|
||||
_currentButton = [[CPButton alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
|
||||
[_currentButton setButtonType:CPMomentaryChangeButton];
|
||||
[_currentButton setBordered:NO];
|
||||
[_currentButton setImage:[_datePicker valueForThemeAttribute:@"circle-image"]];
|
||||
[_currentButton setAlternateImage:[_datePicker valueForThemeAttribute:@"circle-image-highlighted"]];
|
||||
[self addSubview:_currentButton];
|
||||
|
||||
[_previousButton setTarget:aDelegate];
|
||||
[_previousButton setAction:@selector(_clickArrowPrevious:)];
|
||||
[_previousButton setContinuous:YES];
|
||||
|
||||
[_nextButton setTarget:aDelegate];
|
||||
[_nextButton setAction:@selector(_clickArrowNext:)];
|
||||
[_nextButton setContinuous:YES];
|
||||
|
||||
[_currentButton setTarget:aDelegate];
|
||||
[_currentButton setAction:@selector(_currentMonth:)];
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Getter Setter methods
|
||||
|
||||
/*! Return the day names depending on the CPLocale of the datePicker
|
||||
@return an array
|
||||
*/
|
||||
- (CPArray)_dayNames
|
||||
{
|
||||
switch ([[_datePicker locale] objectForKey:CPLocaleLanguageCode])
|
||||
{
|
||||
case @"en":
|
||||
|
||||
// Check if it's in the american format. If yes the week will begin the sunday
|
||||
if ([_datePicker _isAmericanFormat])
|
||||
return CPShortWeekDayNameArrayUS;
|
||||
else
|
||||
return CPShortWeekDayNameArrayEn;
|
||||
break;
|
||||
|
||||
case @"es":
|
||||
return CPShortWeekDayNameArrayEs;
|
||||
break;
|
||||
|
||||
case @"de":
|
||||
return CPShortWeekDayNameArrayDe;
|
||||
break;
|
||||
|
||||
case @"fr":
|
||||
return CPShortWeekDayNameArrayFr;
|
||||
break;
|
||||
|
||||
default:
|
||||
return CPShortWeekDayNameArrayEn;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/*! Return the month names depending on the CPLocale of the datePicker
|
||||
@return an array
|
||||
*/
|
||||
- (CPArray)_monthNames
|
||||
{
|
||||
switch ([[_datePicker locale] objectForKey:CPLocaleLanguageCode])
|
||||
{
|
||||
case @"en":
|
||||
return CPShortMonthNameArrayEn;
|
||||
break;
|
||||
|
||||
case @"es":
|
||||
return CPShortMonthNameArrayEs;
|
||||
break;
|
||||
|
||||
case @"de":
|
||||
return CPShortMonthNameArrayDe;
|
||||
break;
|
||||
|
||||
case @"fr":
|
||||
return CPShortMonthNameArrayFr;
|
||||
break;
|
||||
|
||||
default:
|
||||
return CPShortMonthNameArrayEn;
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*! Set the monthDate of the header
|
||||
@aMonthDate the new monthDate
|
||||
*/
|
||||
- (void)setMonthForDate:(CPDate)aMonthDate
|
||||
{
|
||||
_date = aMonthDate;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*! Set enabled
|
||||
@param aBoolean
|
||||
*/
|
||||
- (void)setEnabled:(BOOL)aBoolean
|
||||
{
|
||||
[_previousButton setEnabled:aBoolean];
|
||||
[_nextButton setEnabled:aBoolean];
|
||||
[_currentButton setEnabled:aBoolean];
|
||||
[_dayLabels makeObjectsPerformSelector:@selector(setEnabled:) withObject:aBoolean];
|
||||
[_title setEnabled:aBoolean];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Layout methods
|
||||
|
||||
/*! Layout the subviews
|
||||
*/
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
var bounds = [self bounds],
|
||||
dayNames = [self _dayNames],
|
||||
width = CGRectGetWidth(bounds),
|
||||
buttonInset = [_datePicker valueForThemeAttribute:@"arrow-inset"],
|
||||
numberOfLabels = [_dayLabels count],
|
||||
labelWidth = width / numberOfLabels,
|
||||
sizeButtonLeft = [[_datePicker valueForThemeAttribute:@"arrow-image-left"] size],
|
||||
sizeButtonRight = [[_datePicker valueForThemeAttribute:@"arrow-image-right"] size],
|
||||
sizeButtonCircle = [[_datePicker valueForThemeAttribute:@"circle-image"] size],
|
||||
sizeTileWidth = [_datePicker valueForThemeAttribute:@"size-tile"].width,
|
||||
titleInset = [_datePicker valueForThemeAttribute:@"title-inset"],
|
||||
dayLabelInset = [_datePicker valueForThemeAttribute:@"day-label-inset"];
|
||||
|
||||
// Arrows
|
||||
[_nextButton setFrame:CGRectMake(width - [_nextButton frameSize].width - buttonInset.right, buttonInset.top, sizeButtonRight.width, sizeButtonRight.height)];
|
||||
[_currentButton setFrame:CGRectMake(CGRectGetMinX([_nextButton frame]) - sizeButtonCircle.width - buttonInset.left - buttonInset.right, buttonInset.top, sizeButtonCircle.width, sizeButtonCircle.height)];
|
||||
[_previousButton setFrame:CGRectMake(CGRectGetMinX([_currentButton frame]) - sizeButtonLeft.width - buttonInset.left - buttonInset.right, buttonInset.top, sizeButtonLeft.width, sizeButtonLeft.height)];
|
||||
|
||||
var firstDayTileX;
|
||||
|
||||
// Weekday label
|
||||
for (var i = 0; i < numberOfLabels; i++)
|
||||
{
|
||||
var dayLabel = _dayLabels[i];
|
||||
|
||||
[dayLabel setStringValue:dayNames[i]];
|
||||
|
||||
if (dayLabelInset) // Beginning with Aristo3
|
||||
{
|
||||
var thisWidth = ROUND((i+1) * sizeTileWidth) - ROUND(i * sizeTileWidth);
|
||||
|
||||
[dayLabel sizeToFit];
|
||||
[dayLabel setFrame:CGRectMake(dayLabelInset.left + ROUND(i * sizeTileWidth), dayLabelInset.top, thisWidth, [dayLabel frameSize].height)];
|
||||
}
|
||||
else
|
||||
{
|
||||
[dayLabel sizeToFit];
|
||||
[dayLabel setFrameOrigin:CGPointMake(sizeTileWidth * (i + 1) - sizeTileWidth / 2 - [dayLabel frameSize].width / 2, 23)];
|
||||
|
||||
if (i == 0)
|
||||
firstDayTileX = sizeTileWidth * (i + 1) - sizeTileWidth / 2 - [dayLabel frameSize].width / 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Title
|
||||
[_title setStringValue:[CPString stringWithFormat:@"%s %i", [self _monthNames][_date.getMonth()], _date.getFullYear()]];
|
||||
[_title sizeToFit];
|
||||
|
||||
if (titleInset) // Beginning with Aristo3
|
||||
[_title setFrameOrigin:CGPointMake(titleInset.left, titleInset.top)];
|
||||
else
|
||||
[_title setFrameOrigin:CGPointMake(firstDayTileX, 6)];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,636 +0,0 @@
|
||||
/* _CPDatePickerMonthView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 <Foundation/Foundation.j>
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "_CPDatePickerDayView.j"
|
||||
|
||||
@class CPDatePicker
|
||||
|
||||
@global CPSingleDateMode
|
||||
@global CPRangeDateMode
|
||||
|
||||
@implementation _CPDatePickerMonthView : CPControl
|
||||
{
|
||||
BOOL _isMonthJustChanged;
|
||||
CPArray _dayTiles;
|
||||
CPDate _clickDate;
|
||||
CPDate _dragDate;
|
||||
CPDate _date;
|
||||
CPDate _previousMonth @accessors(property=previousMonth);
|
||||
CPDate _nextMonth @accessors(property=nextMonth);
|
||||
CPDatePicker _datePicker;
|
||||
CPEvent _eventDragged;
|
||||
CPTimer _timerMonth;
|
||||
id _delegate;
|
||||
int _indexDayTile;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Init methods
|
||||
|
||||
/*! Init a _CPDatePickerMonthView
|
||||
@param aFrame
|
||||
@param aDatePicker
|
||||
@return a new _CPDatePickerMonthView
|
||||
*/
|
||||
- (id)initWithFrame:(CGRect)aFrame datePicker:(CPDatePicker)aDatePicker delegate:(id)aDelegate
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_delegate = aDelegate;
|
||||
_isMonthJustChanged = NO;
|
||||
_indexDayTile = -1;
|
||||
_datePicker = aDatePicker;
|
||||
_dayTiles = [CPArray array];
|
||||
|
||||
// Create tiles
|
||||
for (var i = 0; i < 42; i++)
|
||||
{
|
||||
var dayView = [[_CPDatePickerDayView alloc] initWithFrame:CGRectMakeZero() withDatePicker:_datePicker];
|
||||
[self addSubview:dayView];
|
||||
[_dayTiles addObject:dayView];
|
||||
}
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Getter Setter methods
|
||||
|
||||
/*! Set the monthDate of the component
|
||||
@param aDate
|
||||
*/
|
||||
- (void)setMonthForDate:(CPDate)aDate
|
||||
{
|
||||
if (_dragDate)
|
||||
{
|
||||
if (_dragDate.getMonth() != _date.getMonth())
|
||||
_isMonthJustChanged = YES;
|
||||
|
||||
_date = [_dragDate copy];
|
||||
}
|
||||
else
|
||||
{
|
||||
_date = [aDate copy];
|
||||
}
|
||||
|
||||
if (![aDate isEqualToDate:[CPDate distantFuture]])
|
||||
{
|
||||
// Reset the date to the first day of the month & midnight
|
||||
_date.setDate(1);
|
||||
[_date _resetToMidnight];
|
||||
|
||||
// There must be a better way to do this.
|
||||
var firstDay = [_date copy];
|
||||
firstDay.setDate(1);
|
||||
|
||||
// Set the previous and next month date. This is usefull for the tile of the next/previous month
|
||||
_previousMonth = new Date(firstDay.getTime() - 86400000);
|
||||
_previousMonth.setDate(1);
|
||||
|
||||
_nextMonth = new Date(firstDay.getTime() + (([_date _daysInMonth] + 1) * 86400000));
|
||||
_nextMonth.setDate(1);
|
||||
}
|
||||
|
||||
[self reloadData];
|
||||
|
||||
if (_isMonthJustChanged)
|
||||
{
|
||||
var dayTile = [_dayTiles objectAtIndex:_indexDayTile];
|
||||
|
||||
if ([dayTile date].getMonth() == _date.getMonth())
|
||||
{
|
||||
[self mouseDragged:_eventDragged];
|
||||
}
|
||||
else
|
||||
{
|
||||
if ([dayTile date].getMonth() - _date.getMonth() == 1 || [dayTile date].getFullYear() - _date.getFullYear() == 1)
|
||||
_timerMonth = [CPTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(_timerNextMonthEvent:) userInfo:nil repeats:NO];
|
||||
else
|
||||
_timerMonth = [CPTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(_timerPreviousMonthEvent:) userInfo:nil repeats:NO];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)monthDate
|
||||
{
|
||||
return _date;
|
||||
}
|
||||
|
||||
/*! Return the size of a tile
|
||||
*/
|
||||
- (CGSize)tileSize
|
||||
{
|
||||
return [_datePicker valueForThemeAttribute:@"size-tile"];
|
||||
}
|
||||
|
||||
/*! Return the first index day of the month
|
||||
*/
|
||||
- (int)startOfWeekForDate:(CPDate)aDate
|
||||
{
|
||||
var day = aDate.getDay();
|
||||
|
||||
// American people begins the week the sunday
|
||||
if (![_datePicker _isAmericanFormat])
|
||||
return (day + 6) % 7;
|
||||
|
||||
return day;
|
||||
}
|
||||
|
||||
/*! Set enabled
|
||||
@param aBoolean
|
||||
*/
|
||||
- (void)setEnabled:(BOOL)aBoolean
|
||||
{
|
||||
[super setEnabled:aBoolean];
|
||||
[self reloadData];
|
||||
}
|
||||
|
||||
|
||||
/*! Return the index of tile depending of the giving event
|
||||
@param anEvent
|
||||
@return an index
|
||||
*/
|
||||
- (CPInteger)indexOfTileForEvent:(CPEvent)anEvent
|
||||
{
|
||||
var locationInView = [self convertPoint:[anEvent locationInWindow] fromView:nil],
|
||||
tileSize = [self tileSize],
|
||||
borderWidth = [_datePicker valueForThemeAttribute:@"border-width"],
|
||||
margin = [_datePicker valueForThemeAttribute:@"tile-margin"] || CGSizeMakeZero(),
|
||||
tileInset = [_datePicker valueForThemeAttribute:@"tile-inset"] || CGInsetMakeZero();
|
||||
|
||||
// Get the week row
|
||||
var rowIndex = FLOOR((locationInView.y - tileInset.top - margin.height) / (tileSize.height + 2 * margin.height + borderWidth)),
|
||||
columnIndex = FLOOR((locationInView.x - tileInset.left) / (tileSize.width + 2 * margin.width + borderWidth));
|
||||
|
||||
columnIndex = MIN(MAX(columnIndex, 0), 6);
|
||||
rowIndex = MIN(MAX(rowIndex, 0), 5);
|
||||
|
||||
var tileIndex = (rowIndex * 7) + columnIndex;
|
||||
|
||||
return tileIndex;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Reload data
|
||||
|
||||
/*! Reload the data
|
||||
*/
|
||||
- (void)reloadData
|
||||
{
|
||||
if (!_date)
|
||||
return;
|
||||
|
||||
var currentMonth = _date,
|
||||
startOfMonthDay = [self startOfWeekForDate:currentMonth],
|
||||
daysInPreviousMonth = [_previousMonth _daysInMonth],
|
||||
firstDayToShowInPreviousMonth = daysInPreviousMonth - startOfMonthDay,
|
||||
currentDate = new Date(_previousMonth.getFullYear(), _previousMonth.getMonth(), firstDayToShowInPreviousMonth),
|
||||
now = [CPDate date],
|
||||
dateValue = [_datePicker dateValue];
|
||||
|
||||
// Update the tiles
|
||||
for (var i = 0; i < [_dayTiles count]; i++)
|
||||
{
|
||||
var dayTile = _dayTiles[i];
|
||||
|
||||
// Increment to next day
|
||||
currentDate.setTime(currentDate.getTime() + 90000000);
|
||||
[currentDate _resetToMidnight];
|
||||
|
||||
var isPresentMonth = (now.getMonth() == currentDate.getMonth()
|
||||
&& now.getFullYear() == currentDate.getFullYear());
|
||||
|
||||
[dayTile setDate:[currentDate copy]];
|
||||
[dayTile setStringValue:currentDate.getDate()];
|
||||
[dayTile setDisabled:/*![self isEnabled] ||*/ currentDate.getMonth() !== currentMonth.getMonth() || currentDate < [_datePicker minDate] || currentDate > [_datePicker maxDate]];
|
||||
[dayTile setHighlighted:isPresentMonth && currentDate.getDate() == now.getDate()];
|
||||
}
|
||||
|
||||
// Select the dates
|
||||
[self _selectDate:[_datePicker dateValue] timeInterval:[_datePicker timeInterval]];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Select methods
|
||||
|
||||
/*! Select one date or several date depending of the giving interval
|
||||
@param aStartDate
|
||||
@param anInterval;
|
||||
*/
|
||||
- (void)_selectDate:(CPDate)aStartDate timeInterval:(CPInteger)anInterval
|
||||
{
|
||||
var endDate = [[CPDate alloc] initWithTimeInterval:anInterval sinceDate:aStartDate],
|
||||
tilesCount = [_dayTiles count];
|
||||
|
||||
aStartDate = [aStartDate copy];
|
||||
|
||||
[aStartDate _resetToMidnight];
|
||||
[endDate _resetToMidnight];
|
||||
|
||||
var firstSelected = NO;
|
||||
|
||||
for (var i = 0; i < tilesCount; i++)
|
||||
{
|
||||
var tile = _dayTiles[i],
|
||||
tileDate = [[tile date] copy],
|
||||
selected = NO;
|
||||
|
||||
[tileDate _resetToMidnight];
|
||||
|
||||
if (aStartDate)
|
||||
selected = tileDate >= aStartDate && tileDate <= endDate;
|
||||
|
||||
// Select a tile
|
||||
[tile setSelected:selected];
|
||||
|
||||
// If we are disabled, we have to disable selected tiles so they will appear disabled
|
||||
[tile setDisabled:[tile isDisabled] || (selected && ![self isEnabled])];
|
||||
|
||||
if (selected)
|
||||
{
|
||||
if (!firstSelected)
|
||||
{
|
||||
firstSelected = YES;
|
||||
[tile setFirstSelected:YES];
|
||||
}
|
||||
else
|
||||
[tile setFirstSelected:NO];
|
||||
|
||||
[tile setLastSelected:NO];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (firstSelected)
|
||||
{
|
||||
firstSelected = NO;
|
||||
|
||||
// As there was a first selected and we are now on an unselected tile,
|
||||
// we are sure that i > 0
|
||||
[_dayTiles[i-1] setLastSelected:YES];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Layout methods
|
||||
|
||||
/*! Tile the view
|
||||
*/
|
||||
- (void)tile
|
||||
{
|
||||
var tileSize = [self tileSize],
|
||||
width = tileSize.width,
|
||||
height = tileSize.height,
|
||||
tilesCount = [_dayTiles count],
|
||||
borderWidth = [_datePicker valueForThemeAttribute:@"border-width"],
|
||||
margin = [_datePicker valueForThemeAttribute:@"tile-margin"],
|
||||
tileInset = [_datePicker valueForThemeAttribute:@"tile-inset"],
|
||||
thisWidth,
|
||||
thisX,
|
||||
dayInWeek,
|
||||
weekInMonth,
|
||||
tileFrame,
|
||||
tileIndex;
|
||||
|
||||
// Set the frame of the tiles
|
||||
for (tileIndex = 0; tileIndex < tilesCount; tileIndex++)
|
||||
{
|
||||
dayInWeek = tileIndex % 7;
|
||||
weekInMonth = (tileIndex - dayInWeek) / 7;
|
||||
tileFrame;
|
||||
|
||||
if (margin) // Beginning with Aristo3
|
||||
{
|
||||
thisX = ROUND(dayInWeek * (width + 2 * margin.width));
|
||||
thisWidth = ROUND((dayInWeek+1) * (width + 2 * margin.width)) - thisX;
|
||||
|
||||
tileFrame = CGRectMake(tileInset.left + thisX, tileInset.top + margin.height + weekInMonth * (height + 2 * margin.height), thisWidth + borderWidth, height + borderWidth);
|
||||
}
|
||||
else
|
||||
tileFrame = CGRectMake(dayInWeek * width, weekInMonth * height, width + borderWidth, height + borderWidth);
|
||||
|
||||
[_dayTiles[tileIndex] setFrame:tileFrame];
|
||||
[_dayTiles[tileIndex] setDayInWeek:dayInWeek];
|
||||
}
|
||||
|
||||
[self reloadData];
|
||||
}
|
||||
|
||||
/*! Layout the subviews
|
||||
*/
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[super layoutSubviews];
|
||||
|
||||
[self tile];
|
||||
[_dayTiles makeObjectsPerformSelector:@selector(setNeedsLayout)];
|
||||
}
|
||||
|
||||
/*! Draw the component. This draws the border of the tile.
|
||||
The selected tile are drawed in the drawRect method of the tile. But the unselected tile here.
|
||||
It avoids some problems with tiles over other tiles (otherwise the color of the tile border would be different).
|
||||
Rememeber that the first pixel of a tile are over the last pixel of the last tile (because the border)
|
||||
*/
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
[super drawRect:aRect];
|
||||
|
||||
if ([_datePicker isCSSBased])
|
||||
{
|
||||
// We just have to draw the separator (if any)
|
||||
// No separator color means no separator
|
||||
var separatorColor = [_datePicker valueForThemeAttribute:@"separator-color"],
|
||||
separatorHeight = [_datePicker valueForThemeAttribute:@"separator-height"],
|
||||
separatorMarginWidth = [_datePicker valueForThemeAttribute:@"separator-margin-width"];
|
||||
|
||||
if (separatorColor)
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
bounds = [self bounds];
|
||||
|
||||
CGContextBeginPath(context);
|
||||
CGContextSetStrokeColor(context, separatorColor);
|
||||
CGContextSetLineWidth(context, separatorHeight);
|
||||
CGContextMoveToPoint(context, separatorMarginWidth, 0.5);
|
||||
CGContextAddLineToPoint(context, bounds.size.width - separatorMarginWidth, 0.5);
|
||||
CGContextStrokePath(context);
|
||||
CGContextClosePath(context);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
width = [self tileSize].width,
|
||||
height = [self tileSize].height,
|
||||
isBorderPair = ([_datePicker valueForThemeAttribute:@"border-width"] % 2) == 0;
|
||||
|
||||
CGContextBeginPath(context);
|
||||
CGContextSetStrokeColor(context, [_datePicker valueForThemeAttribute:@"border-color" inState:[_datePicker themeState]]);
|
||||
CGContextSetLineWidth(context, [_datePicker valueForThemeAttribute:@"border-width"]);
|
||||
|
||||
if ([_datePicker isBordered])
|
||||
{
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
var y = i * height;
|
||||
|
||||
// Very usefull to avoid to have a line of two pixels instead one
|
||||
if (!isBorderPair)
|
||||
y += 0.5;
|
||||
|
||||
CGContextMoveToPoint(context, 0, y);
|
||||
CGContextAddLineToPoint(context, [self bounds].size.width, y);
|
||||
}
|
||||
|
||||
for (var i = 0; i < 7; i++)
|
||||
{
|
||||
var x = i * width;
|
||||
|
||||
// Very usefull to avoid to have a line of two pixels instead one
|
||||
if (!isBorderPair)
|
||||
x += 0.5;
|
||||
|
||||
CGContextMoveToPoint(context, x, 0);
|
||||
CGContextAddLineToPoint(context, x, [self bounds].size.height);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var y = 0;
|
||||
|
||||
// Very usefull to avoid to have a line of two pixels instead one
|
||||
if (!isBorderPair)
|
||||
y += 0.5;
|
||||
|
||||
CGContextMoveToPoint(context, 0, y);
|
||||
CGContextAddLineToPoint(context, [self bounds].size.width, y);
|
||||
}
|
||||
|
||||
CGContextStrokePath(context);
|
||||
CGContextClosePath(context);
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Mouse event
|
||||
|
||||
/*! Mouse down event
|
||||
*/
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEnabled])
|
||||
return;
|
||||
|
||||
var dayTile = [_dayTiles objectAtIndex:[self indexOfTileForEvent:anEvent]],
|
||||
dateTile = [[dayTile date] copy],
|
||||
dateValue = [_datePicker dateValue];
|
||||
|
||||
_clickDate = [dateTile copy];
|
||||
_dragDate = nil;
|
||||
_indexDayTile = -1;
|
||||
_eventDragged = nil;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = YES;
|
||||
#endif
|
||||
|
||||
// Check if we have to change or not the month of the component
|
||||
if ([dayTile date].getMonth() == _date.getMonth())
|
||||
{
|
||||
if ([_datePicker datePickerMode] == CPRangeDateMode && [anEvent modifierFlags] & CPShiftKeyMask)
|
||||
{
|
||||
var dateValueAtMidnight = [[_datePicker dateValue] copy];
|
||||
|
||||
[dateValueAtMidnight _resetToMidnight];
|
||||
|
||||
if (dateTile < dateValueAtMidnight)
|
||||
{
|
||||
var interval;
|
||||
|
||||
if (dateTile == dateValueAtMidnight)
|
||||
interval = [_datePicker timeInterval];
|
||||
else
|
||||
interval = ([dateValueAtMidnight timeIntervalSinceDate:dateTile] + [_datePicker timeInterval]);
|
||||
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:dateTile] timeInterval:interval];
|
||||
}
|
||||
else if ([[dayTile date] isEqualToDate:dateValueAtMidnight])
|
||||
{
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:dateTile] timeInterval:0];
|
||||
}
|
||||
else
|
||||
{
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:[dateValueAtMidnight copy]] timeInterval:([dateTile timeIntervalSinceDate:dateValueAtMidnight])];
|
||||
}
|
||||
|
||||
// Be sure to display the good month
|
||||
[_delegate setDateValue:dateTile];
|
||||
}
|
||||
else
|
||||
{
|
||||
var minDate = [[_datePicker minDate] copy],
|
||||
maxDate = [[_datePicker maxDate] copy];
|
||||
|
||||
[minDate _resetToMidnight];
|
||||
[maxDate _resetToLastSeconds];
|
||||
|
||||
if (dateTile >= minDate && dateTile <= maxDate)
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:dateTile] timeInterval:0];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Check the year and the month. The year is usefull when changing from Jan to Dec.
|
||||
if (_date.getMonth() - [dayTile date].getMonth() == 1 || _date.getFullYear() - [dayTile date].getFullYear() == 1)
|
||||
[_delegate _displayPreviousMonth];
|
||||
else
|
||||
[_delegate _displayNextMonth];
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = NO;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*! Mouse dragged event
|
||||
*/
|
||||
- (void)mouseDragged:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEnabled] || !CGRectContainsPoint([self bounds],[self convertPoint:[anEvent locationInWindow] fromView:nil]))
|
||||
return;
|
||||
|
||||
var dayTile = [_dayTiles objectAtIndex:[self indexOfTileForEvent:anEvent]],
|
||||
dateTile = [[dayTile date] copy],
|
||||
dateValue = [_datePicker dateValue];
|
||||
|
||||
_dragDate = [dateTile copy];
|
||||
_indexDayTile = [self indexOfTileForEvent:anEvent];
|
||||
_eventDragged = anEvent;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = YES;
|
||||
#endif
|
||||
|
||||
if ([_datePicker datePickerMode] == CPSingleDateMode)
|
||||
{
|
||||
// Check if we have to change or not the month of the component
|
||||
if ([dayTile date].getMonth() == _date.getMonth())
|
||||
{
|
||||
[_timerMonth invalidate];
|
||||
_isMonthJustChanged = NO;
|
||||
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:dateTile] timeInterval:0];
|
||||
}
|
||||
else if (!_isMonthJustChanged)
|
||||
{
|
||||
[_timerMonth invalidate];
|
||||
_isMonthJustChanged = NO;
|
||||
|
||||
// Check the year and the month. The year is usefull when changing from Jan to Dec.
|
||||
if (_date.getMonth() - [dayTile date].getMonth() == 1 || _date.getFullYear() - [dayTile date].getFullYear() == 1)
|
||||
[_delegate _displayPreviousMonth];
|
||||
else
|
||||
[_delegate _displayNextMonth];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (dateTile.getMonth() == _date.getMonth() || !_isMonthJustChanged)
|
||||
{
|
||||
[_timerMonth invalidate];
|
||||
_isMonthJustChanged = NO;
|
||||
|
||||
var dateValueAtMidnight = [[_datePicker dateValue] copy];
|
||||
|
||||
[dateValueAtMidnight _resetToMidnight];
|
||||
|
||||
if (dateTile < _clickDate)
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:dateTile] timeInterval:[_clickDate timeIntervalSinceDate:dateTile]];
|
||||
else if ([[dayTile date] isEqualToDate:_clickDate])
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:dateTile] timeInterval:0];
|
||||
else
|
||||
[_datePicker _setDateValue:[self _hoursMinutesSecondsFromDatePickerForDate:_clickDate] timeInterval:[dateTile timeIntervalSinceDate:dateValueAtMidnight]];
|
||||
}
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
_datePicker._invokedByUserEvent = NO;
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)mouseUp:(CPEvent)anEvent
|
||||
{
|
||||
[_timerMonth invalidate];
|
||||
_dragDate = nil;
|
||||
_clickDate = nil;
|
||||
_isMonthJustChanged = NO;
|
||||
_indexDayTile = -1;
|
||||
_eventDragged = nil;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Timer
|
||||
|
||||
- (void)_timerNextMonthEvent:(CPEvent)anEvent
|
||||
{
|
||||
if (_isMonthJustChanged)
|
||||
{
|
||||
_dragDate.setMonth(_date.getMonth() + 1);
|
||||
[_delegate _displayNextMonth];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_timerPreviousMonthEvent:(CPEvent)anEvent
|
||||
{
|
||||
if (_isMonthJustChanged)
|
||||
{
|
||||
_dragDate.setMonth(_date.getMonth() - 1);
|
||||
[_delegate _displayPreviousMonth];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Date methods
|
||||
|
||||
- (CPDate)_hoursMinutesSecondsFromDatePickerForDate:(CPDate)aDate
|
||||
{
|
||||
var dateValue = [_datePicker dateValue];
|
||||
|
||||
aDate.setHours(dateValue.getHours());
|
||||
aDate.setMinutes(dateValue.getMinutes());
|
||||
aDate.setSeconds(dateValue.getSeconds());
|
||||
|
||||
return aDate;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,502 +0,0 @@
|
||||
/* _CPDatePickerTextField.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexandre Wilhelm
|
||||
* Copyright 2012 <alexandre.wilhelmfr@gmail.com>
|
||||
*
|
||||
* 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 "CPControl.j"
|
||||
@import "CPFont.j"
|
||||
@import "CPTextField.j"
|
||||
@import "CPStepper.j"
|
||||
|
||||
@import <Foundation/CPArray.j>
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPDate.j>
|
||||
@import <Foundation/CPDateFormatter.j>
|
||||
@import <Foundation/CPLocale.j>
|
||||
|
||||
@class CPDatePicker
|
||||
@class _CPDatePickerElementView
|
||||
|
||||
@import "_CPDatePickerElementView.j"
|
||||
|
||||
@global CPSingleDateMode
|
||||
@global CPRangeDateMode
|
||||
|
||||
@global CPTextFieldAndStepperDatePickerStyle
|
||||
@global CPTextFieldDatePickerStyle
|
||||
|
||||
@global CPHourMinuteDatePickerElementFlag
|
||||
@global CPHourMinuteSecondDatePickerElementFlag
|
||||
@global CPTimeZoneDatePickerElementFlag
|
||||
@global CPYearMonthDatePickerElementFlag
|
||||
@global CPYearMonthDayDatePickerElementFlag
|
||||
@global CPEraDatePickerElementFlag
|
||||
|
||||
var CPZeroKeyCode = 48,
|
||||
CPNineKeyCode = 57,
|
||||
CPMajAKeyCode = 65,
|
||||
CPMajPKeyCode = 80,
|
||||
CPAKeyCode = 97,
|
||||
CPPKeyCode = 112;
|
||||
|
||||
// This class is used to represente the datePicker with the CPTextFieldAndStepperDatePickerStyle/CPTextFieldDatePickerStyle mode
|
||||
@implementation _CPDatePickerTextField : CPControl
|
||||
{
|
||||
_CPDatePickerElementTextField _firstTextField @accessors(property=firstTextField);
|
||||
_CPDatePickerElementTextField _lastTextField @accessors(property=lastTextField);
|
||||
|
||||
_CPDatePickerElementTextField _currentTextField;
|
||||
_CPDatePickerElementView _datePickerElementView;
|
||||
CPDatePicker _datePicker;
|
||||
CPStepper _stepper;
|
||||
CPInteger _datePickerElements @accessors(getter=datePickerElements);
|
||||
}
|
||||
|
||||
|
||||
#pragma mark Init
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame withDatePicker:(CPDatePicker)aDatePicker
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_datePicker = aDatePicker;
|
||||
[self _init];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_init
|
||||
{
|
||||
_datePickerElements = [_datePicker datePickerElements];
|
||||
|
||||
_datePickerElementView = [[_CPDatePickerElementView alloc] initWithFrame:CGRectMakeZero() withDatePicker:_datePicker];
|
||||
[self addSubview:_datePickerElementView];
|
||||
|
||||
_stepper = [CPStepper stepper];
|
||||
[_stepper setTarget:self];
|
||||
[_stepper setAction:@selector(_clickStepper:)];
|
||||
[self addSubview:_stepper];
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
if ([_datePicker currentValueForThemeAttribute:@"uses-focus-ring"])
|
||||
{
|
||||
// As with overflow:hidden, views are clipping their content, in order
|
||||
// to show a focus ring (which is external to a view), we need to let
|
||||
// content extend outside the view.
|
||||
_datePicker._DOMElement.style.overflow = "visible";
|
||||
_DOMElement.style.overflow = "visible";
|
||||
_datePickerElementView._DOMElement.style.overflow = "visible";
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Override responder methods
|
||||
|
||||
- (BOOL)becomeFirstResponder
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)acceptsFirstResponder
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)resignFirstResponder
|
||||
{
|
||||
// End the timer of editing
|
||||
[_currentTextField _endEditing];
|
||||
|
||||
// Don't forget to unbind, otherwise several steppers will increase or decrease
|
||||
[_currentTextField unbind:@"objectValue"];
|
||||
[_currentTextField makeDeselectable];
|
||||
_currentTextField = nil
|
||||
|
||||
// This is usefull when clicking on the stepper when the datePicker is not selected
|
||||
[_stepper setObjectValue:0];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)canBecomeKeyView
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Setter Getter methods
|
||||
|
||||
/*! Set the value of the control
|
||||
@param aDateValue
|
||||
*/
|
||||
- (void)setDateValue:(CPDate)aDateValue
|
||||
{
|
||||
var dateValue = [aDateValue copy];
|
||||
[dateValue _dateWithTimeZone:[_datePicker timeZone]];
|
||||
[_datePickerElementView setDateValue:dateValue];
|
||||
|
||||
// Be sure to update the stepper value. We don't use -setObjectValue to avoid a binding update.
|
||||
if (_currentTextField)
|
||||
_stepper._value = [_currentTextField intValue];
|
||||
}
|
||||
|
||||
/*! Set the widget enabled or not
|
||||
@param aBoolean
|
||||
*/
|
||||
- (void)setEnabled:(BOOL)aBoolean
|
||||
{
|
||||
[super setEnabled:aBoolean];
|
||||
[_stepper setEnabled:aBoolean];
|
||||
[_datePickerElementView setEnabled:aBoolean];
|
||||
}
|
||||
|
||||
- (void)setTextColor:(CPColor)aColor
|
||||
{
|
||||
[super setTextColor:aColor];
|
||||
[_datePickerElementView setTextColor:aColor];
|
||||
}
|
||||
|
||||
- (void)setTextFont:(CPFont)aFont
|
||||
{
|
||||
[self setFont:aFont];
|
||||
[_datePickerElementView setTextFont:aFont];
|
||||
}
|
||||
|
||||
- (void)setDatePickerElements:(CPInteger)aDatePickerElements
|
||||
{
|
||||
if (_datePickerElements === aDatePickerElements)
|
||||
return;
|
||||
|
||||
_datePickerElements = aDatePickerElements;
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Notification methods
|
||||
|
||||
/*! This is called to when the user just changed the selected textField
|
||||
@param aNotification
|
||||
*/
|
||||
- (void)_datePickerElementTextFieldBecomeFirstResponder:(CPNotification)aNotification
|
||||
{
|
||||
if ([[aNotification userInfo] objectForKey:@"textField"] == _currentTextField)
|
||||
return;
|
||||
|
||||
[self _selectTextField:[[aNotification userInfo] objectForKey:@"textField"]];
|
||||
|
||||
// This is tricky, its to avoid to have the cursor
|
||||
if ([[self window] firstResponder] != _datePicker)
|
||||
[[self window] makeFirstResponder:_datePicker];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark SelectTextField action
|
||||
|
||||
- (void)_selectTextFieldWithFlags:(unsigned)flags
|
||||
{
|
||||
[_datePickerElementView _updateResponderTextField];
|
||||
|
||||
// We select the firstTextField when the datePicker becomes firstResponder if _currentTextField is null. It can be null just when using tab
|
||||
if (!_currentTextField)
|
||||
{
|
||||
if (flags & CPShiftKeyMask)
|
||||
[self _selectTextField:_lastTextField];
|
||||
else
|
||||
[self _selectTextField:_firstTextField];
|
||||
}
|
||||
}
|
||||
|
||||
/*! Select a textField
|
||||
@param aDatePickerElementTextField the textField
|
||||
*/
|
||||
- (void)_selectTextField:(_CPDatePickerElementTextField)aDatePickerElementTextField
|
||||
{
|
||||
if (_currentTextField == aDatePickerElementTextField)
|
||||
return;
|
||||
|
||||
// End the timer of editing
|
||||
[_currentTextField _endEditing];
|
||||
|
||||
// Don't forget to unbind, otherwise several steppers will increase or decrease
|
||||
[_currentTextField unbind:@"objectValue"];
|
||||
[_currentTextField makeDeselectable];
|
||||
|
||||
_currentTextField = aDatePickerElementTextField;
|
||||
[_currentTextField makeSelectable];
|
||||
|
||||
// We cannot assign a value with the textField AM/PM
|
||||
if ([_currentTextField dateType] != CPAMPMDateType)
|
||||
{
|
||||
// We update the value of the stepper dependind on the textField
|
||||
[_stepper setObjectValue:[_currentTextField intValue]];
|
||||
[_stepper setMaxValue:[_currentTextField maxNumber]];
|
||||
[_stepper setMinValue:[_currentTextField minNumber]];
|
||||
|
||||
// We bind the stepper with textField
|
||||
[_currentTextField bind:@"objectValue" toObject:_stepper withKeyPath:@"objectValue" options:nil];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Events
|
||||
|
||||
/*! Called when the user click on the stepper
|
||||
*/
|
||||
- (void)_clickStepper:(id)sender
|
||||
{
|
||||
// Success when clicking on the stepper if the datePicker is not selected
|
||||
if ([[self window] firstResponder] != _datePicker || !_currentTextField)
|
||||
{
|
||||
var isUp = NO;
|
||||
|
||||
if ([sender objectValue] == 1)
|
||||
isUp = YES;
|
||||
|
||||
[self _selectTextField:_firstTextField];
|
||||
[[self window] makeFirstResponder:_datePicker];
|
||||
|
||||
// Update the dateValue with the binding.
|
||||
if (isUp)
|
||||
[_stepper setDoubleValue:[_currentTextField intValue] + 1];
|
||||
else
|
||||
[_stepper setDoubleValue:[_currentTextField intValue] - 1];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ([_currentTextField dateType] != CPAMPMDateType)
|
||||
{
|
||||
// Make sure to get the good value, especially when we reach the maxDate or minDate
|
||||
[sender setDoubleValue:[_currentTextField intValue]];
|
||||
}
|
||||
else
|
||||
{
|
||||
// AM/PM behavior
|
||||
if ([[_currentTextField stringValue] isEqualToString:@"PM"])
|
||||
[_currentTextField setStringValue:@"AM"];
|
||||
else
|
||||
[_currentTextField setStringValue:@"PM"];
|
||||
|
||||
[[CPNotificationCenter defaultCenter] postNotificationName:CPDatePickerElementTextFieldAMPMChangedNotification object:_currentTextField userInfo:nil];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
PerformKeyEquivalent event
|
||||
We need to override that to handle the tab key
|
||||
*/
|
||||
- (BOOL)performKeyEquivalent:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEnabled] || !_currentTextField || [[self window] firstResponder] != _datePicker)
|
||||
return NO;
|
||||
|
||||
if ([anEvent charactersIgnoringModifiers] === CPTabCharacter)
|
||||
{
|
||||
if ([anEvent modifierFlags] & CPShiftKeyMask)
|
||||
[self insertBacktab:self];
|
||||
else
|
||||
[self insertTab:self];
|
||||
|
||||
return YES;
|
||||
}
|
||||
else if ([anEvent charactersIgnoringModifiers] === CPBackTabCharacter)
|
||||
{
|
||||
[self insertBacktab:self];
|
||||
return YES;
|
||||
}
|
||||
|
||||
return [super performKeyEquivalent:anEvent];
|
||||
}
|
||||
|
||||
- (void)insertTab:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
if (_currentTextField == _lastTextField)
|
||||
[[self window] selectNextKeyView:self];
|
||||
else
|
||||
[self moveRight:sender];
|
||||
}
|
||||
|
||||
- (void)moveRight:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
[self _selectTextField:[_currentTextField nextTextField]];
|
||||
}
|
||||
|
||||
- (void)insertBacktab:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
if (_currentTextField == _firstTextField)
|
||||
[[self window] selectPreviousKeyView:self];
|
||||
else
|
||||
[self moveLeft:sender];
|
||||
}
|
||||
|
||||
- (void)moveLeft:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
[self _selectTextField:[_currentTextField previousTextField]];
|
||||
}
|
||||
|
||||
- (void)moveDown:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
[_currentTextField _invalidTimer];
|
||||
[_stepper setDoubleValue:[_currentTextField intValue]];
|
||||
[_stepper performClickDown:self];
|
||||
}
|
||||
|
||||
- (void)moveUp:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
[_currentTextField _invalidTimer];
|
||||
[_stepper setDoubleValue:[_currentTextField intValue]];
|
||||
[_stepper performClickUp:self];
|
||||
}
|
||||
|
||||
- (void)insertNewline:(id)sender
|
||||
{
|
||||
if (!_currentTextField)
|
||||
return;
|
||||
|
||||
[_currentTextField _endEditing];
|
||||
}
|
||||
|
||||
/*! KeyDown event
|
||||
We just care care about the event A/P and every numbers
|
||||
*/
|
||||
- (void)keyDown:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEnabled])
|
||||
return;
|
||||
|
||||
[self interpretKeyEvents:[anEvent]];
|
||||
|
||||
if ([_datePicker _isAmericanFormat] && [_currentTextField dateType] == CPAMPMDateType && ([anEvent keyCode] == CPAKeyCode || [anEvent keyCode] == CPPKeyCode || [anEvent keyCode] == CPMajAKeyCode || [anEvent keyCode] == CPMajPKeyCode))
|
||||
{
|
||||
if ([anEvent keyCode] == CPAKeyCode || [anEvent keyCode] == CPMajAKeyCode)
|
||||
[_currentTextField setStringValue:@"AM"];
|
||||
else
|
||||
[_currentTextField setStringValue:@"PM"];
|
||||
|
||||
[[CPNotificationCenter defaultCenter] postNotificationName:CPDatePickerElementTextFieldAMPMChangedNotification object:_currentTextField userInfo:nil];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
[_currentTextField setValueForKeyEvent:anEvent];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Layout methods
|
||||
|
||||
/*! Layout the subviews
|
||||
*/
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[_datePicker _sizeToControlSize];
|
||||
[self setFrameSize:[_datePicker frameSize]];
|
||||
|
||||
[super layoutSubviews];
|
||||
|
||||
var frameSize,
|
||||
bezelInset = [_datePicker valueForThemeAttribute:@"bezel-inset" inState:[_datePicker themeState]];
|
||||
|
||||
// Check the mode to display or not the stepper
|
||||
if ([_datePicker datePickerStyle] == CPTextFieldAndStepperDatePickerStyle)
|
||||
{
|
||||
[_stepper setHidden:NO];
|
||||
[_stepper setControlSize:[_datePicker controlSize]];
|
||||
|
||||
frameSize = CGSizeMake(CGRectGetWidth([_datePicker frame]) - CGRectGetWidth([_stepper frame]) - [_datePicker currentValueForThemeAttribute:@"stepper-margin"], CGRectGetHeight([_datePicker frame]));
|
||||
|
||||
frameSize.width -= bezelInset.left;
|
||||
frameSize.height -= bezelInset.top + bezelInset.bottom;
|
||||
|
||||
[_datePickerElementView setFrameSize:frameSize];
|
||||
[_datePickerElementView setFrameOrigin:CGPointMake(bezelInset.left, bezelInset.top)];
|
||||
|
||||
[_stepper setFrameOrigin:CGPointMake(CGRectGetMaxX([_datePickerElementView frame]) + [_datePicker currentValueForThemeAttribute:@"stepper-margin"], bezelInset.top + CGRectGetHeight([_datePickerElementView frame]) / 2 - CGRectGetHeight([_stepper frame]) / 2)];
|
||||
}
|
||||
else if ([_datePicker datePickerStyle] == CPTextFieldDatePickerStyle)
|
||||
{
|
||||
frameSize = CGSizeMake(CGRectGetWidth([_datePicker frame]), CGRectGetHeight([_datePicker frame]));
|
||||
|
||||
frameSize.width -= bezelInset.left + bezelInset.right;
|
||||
frameSize.height -= bezelInset.top + bezelInset.bottom;
|
||||
|
||||
[_datePickerElementView setFrameSize:frameSize];
|
||||
[_datePickerElementView setFrameOrigin:CGPointMake(bezelInset.left, bezelInset.top)];
|
||||
[_stepper setHidden:YES];
|
||||
}
|
||||
|
||||
// FIXME: should be done in a self setControlSize
|
||||
[_datePickerElementView setControlSize:[_datePicker controlSize]];
|
||||
|
||||
[_datePickerElementView setNeedsLayout];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Override observers
|
||||
|
||||
- (void)_removeObservers
|
||||
{
|
||||
if (!_isObserving)
|
||||
return;
|
||||
|
||||
[super _removeObservers];
|
||||
|
||||
[[CPNotificationCenter defaultCenter] removeObserver:self name:CPDatePickerElementTextFieldBecomeFirstResponder object:self];
|
||||
}
|
||||
|
||||
- (void)_addObservers
|
||||
{
|
||||
if (_isObserving)
|
||||
return;
|
||||
|
||||
[super _addObservers];
|
||||
|
||||
[[CPNotificationCenter defaultCenter] addObserver:self selector:@selector(_datePickerElementTextFieldBecomeFirstResponder:) name:CPDatePickerElementTextFieldBecomeFirstResponder object:self];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,168 +0,0 @@
|
||||
/*
|
||||
* CPDictionaryController.j
|
||||
* AppKit
|
||||
*
|
||||
* Adapted from Cocotron, by Johannes Fortmann
|
||||
*
|
||||
* Created by Blair Duncan
|
||||
* Copyright 2013, SGL Studio, BBDO Toronto All rights reserved.
|
||||
*
|
||||
* 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 "CPArrayController.j"
|
||||
|
||||
@implementation CPDictionaryController : CPArrayController
|
||||
{
|
||||
CPDictionary _contentDictionary;
|
||||
|
||||
CPArray _includedKeys @accessors(property=includedKeys);
|
||||
CPArray _excludedKeys @accessors(property=excludedKeys);
|
||||
|
||||
CPString _initialKey @accessors(property=initialKey);
|
||||
id _initialValue @accessors(property=initialValue);
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_initialKey = @"key";
|
||||
_initialValue = @"value";
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)newObject
|
||||
{
|
||||
var keys = [_contentDictionary allKeys],
|
||||
newKey = _initialKey,
|
||||
count = 0;
|
||||
|
||||
if ([keys containsObject:newKey])
|
||||
while ([keys containsObject:newKey])
|
||||
newKey = [CPString stringWithFormat:@"%@%i", _initialKey, ++count];
|
||||
|
||||
return [self _newObjectWithKey:newKey value:_initialValue];
|
||||
}
|
||||
|
||||
- (id)_newObjectWithKey:(CPString)aKey value:(id)aValue
|
||||
{
|
||||
var aNewObject = [_CPDictionaryControllerKeyValuePair new];
|
||||
|
||||
aNewObject._dictionary = _contentDictionary;
|
||||
aNewObject._controller = self;
|
||||
aNewObject._key = aKey;
|
||||
|
||||
if (aValue != nil)
|
||||
[aNewObject setValue:aValue];
|
||||
|
||||
return aNewObject;
|
||||
}
|
||||
|
||||
- (CPDictionary)contentDictionary
|
||||
{
|
||||
return _contentDictionary;
|
||||
}
|
||||
|
||||
- (void)setContentDictionary:(CPDictionary)aDictionary
|
||||
{
|
||||
if (aDictionary == _contentDictionary)
|
||||
return;
|
||||
|
||||
if ([aDictionary isKindOfClass:[CPDictionary class]])
|
||||
_contentDictionary = aDictionary;
|
||||
else
|
||||
_contentDictionary = nil;
|
||||
|
||||
var array = [CPArray array],
|
||||
allKeys = [_contentDictionary allKeys];
|
||||
|
||||
[allKeys addObjectsFromArray:_includedKeys];
|
||||
|
||||
var iter = [[CPSet setWithArray:allKeys] objectEnumerator],
|
||||
obj;
|
||||
|
||||
while ((obj = [iter nextObject]) != nil)
|
||||
if (![_excludedKeys containsObject:obj])
|
||||
[array addObject:[self _newObjectWithKey:obj value:nil]];
|
||||
|
||||
[super setContent:array];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
||||
|
||||
var CPIncludedKeys = @"CPIncludedKeys",
|
||||
CPExcludedKeys = @"CPExcludedKeys";
|
||||
|
||||
@implementation CPDictionaryController (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_includedKeys = [aCoder decodeObjectForKey:CPIncludedKeys];
|
||||
_excludedKeys = [aCoder decodeObjectForKey:CPExcludedKeys];
|
||||
_initialKey = @"key";
|
||||
_initialValue = @"value";
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
[aCoder encodeObject:_includedKeys forKey:CPIncludedKeys];
|
||||
[aCoder encodeObject:_excludedKeys forKey:CPExcludedKeys];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
|
||||
|
||||
@implementation _CPDictionaryControllerKeyValuePair : CPObject
|
||||
{
|
||||
CPString _key @accessors(property=key);
|
||||
CPDictionary _dictionary @accessors(property=dictionary);
|
||||
CPDictionaryController _controller @accessors(property=controller);
|
||||
}
|
||||
|
||||
- (id)value
|
||||
{
|
||||
return [_dictionary objectForKey:_key];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue
|
||||
{
|
||||
[_dictionary setObject:aValue forKey:_key];
|
||||
}
|
||||
|
||||
- (BOOL)isExplicitlyIncluded
|
||||
{
|
||||
return [[_controller _includedKeys] containsObject:_key];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
+96
-96
@@ -23,16 +23,11 @@
|
||||
@import <Foundation/CPString.j>
|
||||
@import <Foundation/CPArray.j>
|
||||
|
||||
@import "CPAlert.j"
|
||||
@import "CPResponder.j"
|
||||
@import "CPSavePanel.j"
|
||||
@import "CPViewController.j"
|
||||
@import "CPWindowController.j"
|
||||
|
||||
@class CPDocumentController
|
||||
|
||||
@global CPApp
|
||||
|
||||
|
||||
/*
|
||||
@global
|
||||
@@ -87,12 +82,12 @@ CPDocumentDidFailToSaveNotification = @"CPDocumentDidFailToSaveNotification";
|
||||
|
||||
var CPDocumentUntitledCount = 0;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPDocument
|
||||
|
||||
CPDocument is used to represent a document/file in a Cappuccino application.
|
||||
In a document-based application, generally multiple documents are open simultaneously
|
||||
In a document-based application, generally multiple documents are open simutaneously
|
||||
(multiple text documents, slide presentations, spreadsheets, etc.), and multiple
|
||||
CPDocuments should be used to represent this.
|
||||
*/
|
||||
@@ -125,18 +120,18 @@ var CPDocumentUntitledCount = 0;
|
||||
- (id)init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_windowControllers = [];
|
||||
_viewControllersForWindowControllers = @{};
|
||||
_viewControllersForWindowControllers = [CPDictionary dictionary];
|
||||
|
||||
_hasUndoManager = YES;
|
||||
_changeCount = 0;
|
||||
|
||||
[self setNextResponder:CPApp];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -146,13 +141,13 @@ var CPDocumentUntitledCount = 0;
|
||||
@param anError not used
|
||||
@return the initialized document
|
||||
*/
|
||||
- (id)initWithType:(CPString)aType error:(/*{*/CPError/*}*/)anError
|
||||
- (id)initWithType:(CPString)aType error:({CPError})anError
|
||||
{
|
||||
self = [self init];
|
||||
|
||||
|
||||
if (self)
|
||||
[self setFileType:aType];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -170,7 +165,7 @@ var CPDocumentUntitledCount = 0;
|
||||
- (id)initWithContentsOfURL:(CPURL)anAbsoluteURL ofType:(CPString)aType delegate:(id)aDelegate didReadSelector:(SEL)aDidReadSelector contextInfo:(id)aContextInfo
|
||||
{
|
||||
self = [self init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self setFileURL:anAbsoluteURL];
|
||||
@@ -178,7 +173,7 @@ var CPDocumentUntitledCount = 0;
|
||||
|
||||
[self readFromURL:anAbsoluteURL ofType:aType delegate:aDelegate didReadSelector:aDidReadSelector contextInfo:aContextInfo];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -195,7 +190,7 @@ var CPDocumentUntitledCount = 0;
|
||||
- (id)initForURL:(CPURL)anAbsoluteURL withContentsOfURL:(CPURL)absoluteContentsURL ofType:(CPString)aType delegate:(id)aDelegate didReadSelector:(SEL)aDidReadSelector contextInfo:(id)aContextInfo
|
||||
{
|
||||
self = [self init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self setFileURL:anAbsoluteURL];
|
||||
@@ -203,7 +198,7 @@ var CPDocumentUntitledCount = 0;
|
||||
|
||||
[self readFromURL:absoluteContentsURL ofType:aType delegate:aDelegate didReadSelector:aDidReadSelector contextInfo:aContextInfo];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -212,10 +207,10 @@ var CPDocumentUntitledCount = 0;
|
||||
throws an exception.
|
||||
@param aType the format of the data
|
||||
@param anError not used
|
||||
@throws CPUnsupportedMethodException if this method hasn't been overridden by the subclass
|
||||
@throws CPUnsupportedMethodException if this method hasn't been overriden by the subclass
|
||||
@return the document data
|
||||
*/
|
||||
- (CPData)dataOfType:(CPString)aType error:(/*{*/CPError/*}*/)anError
|
||||
- (CPData)dataOfType:(CPString)aType error:({CPError})anError
|
||||
{
|
||||
[CPException raise:CPUnsupportedMethodException
|
||||
reason:"dataOfType:error: must be overridden by the document subclass."];
|
||||
@@ -244,6 +239,11 @@ var CPDocumentUntitledCount = 0;
|
||||
{
|
||||
}
|
||||
|
||||
- (CPWindowController)firstEligibleExistingWindowController
|
||||
{
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Creating and managing window controllers
|
||||
/*!
|
||||
Creates the window controller for this document.
|
||||
@@ -256,7 +256,6 @@ var CPDocumentUntitledCount = 0;
|
||||
- (void)makeViewAndWindowControllers
|
||||
{
|
||||
var viewCibName = [self viewCibName],
|
||||
windowCibName = [self windowCibName],
|
||||
viewController = nil,
|
||||
windowController = nil;
|
||||
|
||||
@@ -264,21 +263,31 @@ var CPDocumentUntitledCount = 0;
|
||||
if ([viewCibName length])
|
||||
viewController = [[CPViewController alloc] initWithCibName:viewCibName bundle:nil owner:self];
|
||||
|
||||
// From a cib if we have one.
|
||||
if ([windowCibName length])
|
||||
windowController = [[CPWindowController alloc] initWithWindowCibName:windowCibName owner:self];
|
||||
// If we have a view controller, check if we have a free window for it.
|
||||
if (viewController)
|
||||
windowController = [self firstEligibleExistingWindowController];
|
||||
|
||||
// If not you get a standard window capable of displaying multiple documents and view
|
||||
else if (viewController)
|
||||
// If not, create one.
|
||||
if (!windowController)
|
||||
{
|
||||
var view = [viewController view],
|
||||
viewFrame = [view frame];
|
||||
var windowCibName = [self windowCibName];
|
||||
|
||||
viewFrame.origin = CGPointMake(50, 50);
|
||||
// From a cib if we have one.
|
||||
if ([windowCibName length])
|
||||
windowController = [[CPWindowController alloc] initWithWindowCibName:windowCibName owner:self];
|
||||
|
||||
var theWindow = [[CPWindow alloc] initWithContentRect:viewFrame styleMask:CPTitledWindowMask | CPClosableWindowMask | CPMiniaturizableWindowMask | CPResizableWindowMask];
|
||||
// If not you get a standard window capable of displaying multiple documents and view
|
||||
else if (viewController)
|
||||
{
|
||||
var view = [viewController view],
|
||||
viewFrame = [view frame];
|
||||
|
||||
viewFrame.origin = CGPointMake(50, 50);
|
||||
|
||||
windowController = [[CPWindowController alloc] initWithWindow:theWindow];
|
||||
var theWindow = [[CPWindow alloc] initWithContentRect:viewFrame styleMask:CPTitledWindowMask | CPClosableWindowMask | CPMiniaturizableWindowMask | CPResizableWindowMask];
|
||||
|
||||
windowController = [[CPWindowController alloc] initWithWindow:theWindow];
|
||||
}
|
||||
}
|
||||
|
||||
if (windowController && viewController)
|
||||
@@ -372,14 +381,14 @@ var CPDocumentUntitledCount = 0;
|
||||
{
|
||||
if (_fileURL)
|
||||
return [_fileURL lastPathComponent];
|
||||
|
||||
|
||||
if (!_untitledDocumentIndex)
|
||||
_untitledDocumentIndex = ++CPDocumentUntitledCount;
|
||||
|
||||
if (_untitledDocumentIndex == 1)
|
||||
return @"Untitled";
|
||||
|
||||
if (_untitledDocumentIndex == 1)
|
||||
return @"Untitled";
|
||||
|
||||
return @"Untitled " + _untitledDocumentIndex;
|
||||
return @"Untitled " + _untitledDocumentIndex;
|
||||
}
|
||||
|
||||
- (CPString)viewCibName
|
||||
@@ -448,7 +457,7 @@ var CPDocumentUntitledCount = 0;
|
||||
return;
|
||||
|
||||
_fileURL = aFileURL;
|
||||
|
||||
|
||||
[_windowControllers makeObjectsPerformSelector:@selector(synchronizeWindowTitleWithDocumentName)];
|
||||
}
|
||||
|
||||
@@ -479,10 +488,10 @@ var CPDocumentUntitledCount = 0;
|
||||
|
||||
[_writeRequest setValue:@"close" forHTTPHeaderField:@"Connection"];
|
||||
|
||||
if (aSaveOperation === CPSaveOperation)
|
||||
if (aSaveOperation == CPSaveOperation)
|
||||
[_writeRequest setValue:@"true" forHTTPHeaderField:@"x-cappuccino-overwrite"];
|
||||
|
||||
if (aSaveOperation !== CPSaveToOperation)
|
||||
if (aSaveOperation != CPSaveToOperation)
|
||||
[self updateChangeCount:CPChangeCleared];
|
||||
|
||||
// FIXME: Oh man is this every looking for trouble, we need to handle login at the Cappuccino level, with HTTP Errors.
|
||||
@@ -500,24 +509,22 @@ var CPDocumentUntitledCount = 0;
|
||||
// If we got this far and it wasn't an HTTP request, then everything is fine.
|
||||
if (![aResponse isKindOfClass:[CPHTTPURLResponse class]])
|
||||
return;
|
||||
|
||||
|
||||
var statusCode = [aResponse statusCode];
|
||||
|
||||
|
||||
// Nothing to do if everything is hunky dory.
|
||||
if (statusCode === 200)
|
||||
return;
|
||||
|
||||
|
||||
var session = aConnection.session;
|
||||
|
||||
|
||||
if (aConnection == _readConnection)
|
||||
{
|
||||
[aConnection cancel];
|
||||
|
||||
|
||||
alert("There was an error retrieving the document.");
|
||||
|
||||
var theDelegate = session.delegate;
|
||||
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, session.didReadSelector, self, NO, session.contextInfo);
|
||||
|
||||
objj_msgSend(session.delegate, session.didReadSelector, self, NO, session.contextInfo);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -525,26 +532,24 @@ var CPDocumentUntitledCount = 0;
|
||||
if (statusCode == 409)
|
||||
{
|
||||
[aConnection cancel];
|
||||
|
||||
|
||||
if (confirm("There already exists a file with that name, would you like to overwrite it?"))
|
||||
{
|
||||
[_writeRequest setValue:@"true" forHTTPHeaderField:@"x-cappuccino-overwrite"];
|
||||
|
||||
|
||||
[aConnection start];
|
||||
}
|
||||
else
|
||||
else
|
||||
{
|
||||
if (session.saveOperation != CPSaveToOperation)
|
||||
{
|
||||
_changeCount += session.changeCount;
|
||||
[_windowControllers makeObjectsPerformSelector:@selector(setDocumentEdited:) withObject:[self isDocumentEdited]];
|
||||
}
|
||||
|
||||
|
||||
_writeRequest = nil;
|
||||
|
||||
var theDelegate = session.delegate;
|
||||
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, session.didSaveSelector, self, NO, session.contextInfo);
|
||||
|
||||
objj_msgSend(session.delegate, session.didSaveSelector, self, NO, session.contextInfo);
|
||||
[self _sendDocumentSavedNotification:NO];
|
||||
}
|
||||
}
|
||||
@@ -557,24 +562,23 @@ var CPDocumentUntitledCount = 0;
|
||||
*/
|
||||
- (void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)aData
|
||||
{
|
||||
var session = aConnection.session,
|
||||
theDelegate = session.delegate;
|
||||
|
||||
var session = aConnection.session;
|
||||
|
||||
// READ
|
||||
if (aConnection == _readConnection)
|
||||
{
|
||||
[self readFromData:[CPData dataWithRawString:aData] ofType:session.fileType error:nil];
|
||||
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, session.didReadSelector, self, YES, session.contextInfo);
|
||||
objj_msgSend(session.delegate, session.didReadSelector, self, YES, session.contextInfo);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (session.saveOperation != CPSaveToOperation)
|
||||
[self setFileURL:session.absoluteURL];
|
||||
|
||||
|
||||
_writeRequest = nil;
|
||||
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, session.didSaveSelector, self, YES, session.contextInfo);
|
||||
|
||||
objj_msgSend(session.delegate, session.didSaveSelector, self, YES, session.contextInfo);
|
||||
[self _sendDocumentSavedNotification:YES];
|
||||
}
|
||||
}
|
||||
@@ -585,25 +589,24 @@ var CPDocumentUntitledCount = 0;
|
||||
*/
|
||||
- (void)connection:(CPURLConnection)aConnection didFailWithError:(CPError)anError
|
||||
{
|
||||
var session = aConnection.session,
|
||||
theDelegate = session.delegate;
|
||||
|
||||
var session = aConnection.session;
|
||||
|
||||
if (_readConnection == aConnection)
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, session.didReadSelector, self, NO, session.contextInfo);
|
||||
|
||||
objj_msgSend(session.delegate, session.didReadSelector, self, NO, session.contextInfo);
|
||||
|
||||
else
|
||||
{
|
||||
{
|
||||
if (session.saveOperation != CPSaveToOperation)
|
||||
{
|
||||
_changeCount += session.changeCount;
|
||||
[_windowControllers makeObjectsPerformSelector:@selector(setDocumentEdited:) withObject:[self isDocumentEdited]];
|
||||
}
|
||||
}
|
||||
|
||||
_writeRequest = nil;
|
||||
|
||||
alert("There was an error saving the document.");
|
||||
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, session.didSaveSelector, self, NO, session.contextInfo);
|
||||
objj_msgSend(session.delegate, session.didSaveSelector, self, NO, session.contextInfo);
|
||||
[self _sendDocumentSavedNotification:NO];
|
||||
}
|
||||
}
|
||||
@@ -640,9 +643,9 @@ var CPDocumentUntitledCount = 0;
|
||||
else if (aChangeType == CPChangeCleared)
|
||||
_changeCount = 0;
|
||||
/*else if (aChangeType == CPCHangeReadOtherContents)
|
||||
|
||||
else if (aChangeType == CPChangeAutosaved)*/
|
||||
|
||||
|
||||
else if (aChangeType == CPChangeAutosaved)*/
|
||||
|
||||
[_windowControllers makeObjectsPerformSelector:@selector(setDocumentEdited:) withObject:[self isDocumentEdited]];
|
||||
}
|
||||
|
||||
@@ -682,9 +685,9 @@ var CPDocumentUntitledCount = 0;
|
||||
{
|
||||
if (_hasUndoManager == aFlag)
|
||||
return;
|
||||
|
||||
|
||||
_hasUndoManager = aFlag;
|
||||
|
||||
|
||||
if (!_hasUndoManager)
|
||||
[self setUndoManager:nil];
|
||||
}
|
||||
@@ -693,7 +696,7 @@ var CPDocumentUntitledCount = 0;
|
||||
- (void)_undoManagerWillCloseGroup:(CPNotification)aNotification
|
||||
{
|
||||
var undoManager = [aNotification object];
|
||||
|
||||
|
||||
if ([undoManager isUndoing] || [undoManager isRedoing])
|
||||
return;
|
||||
|
||||
@@ -720,13 +723,13 @@ var CPDocumentUntitledCount = 0;
|
||||
- (void)setUndoManager:(CPUndoManager)anUndoManager
|
||||
{
|
||||
var defaultCenter = [CPNotificationCenter defaultCenter];
|
||||
|
||||
|
||||
if (_undoManager)
|
||||
{
|
||||
[defaultCenter removeObserver:self
|
||||
name:CPUndoManagerDidUndoChangeNotification
|
||||
object:_undoManager];
|
||||
|
||||
|
||||
[defaultCenter removeObserver:self
|
||||
name:CPUndoManagerDidRedoChangeNotification
|
||||
object:_undoManager];
|
||||
@@ -735,17 +738,17 @@ var CPDocumentUntitledCount = 0;
|
||||
name:CPUndoManagerWillCloseUndoGroupNotification
|
||||
object:_undoManager];
|
||||
}
|
||||
|
||||
|
||||
_undoManager = anUndoManager;
|
||||
|
||||
|
||||
if (_undoManager)
|
||||
{
|
||||
|
||||
|
||||
[defaultCenter addObserver:self
|
||||
selector:@selector(_undoManagerDidUndoChange:)
|
||||
name:CPUndoManagerDidUndoChangeNotification
|
||||
object:_undoManager];
|
||||
|
||||
|
||||
[defaultCenter addObserver:self
|
||||
selector:@selector(_undoManagerDidRedoChange:)
|
||||
name:CPUndoManagerDidRedoChangeNotification
|
||||
@@ -771,7 +774,7 @@ var CPDocumentUntitledCount = 0;
|
||||
|
||||
return _undoManager;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Implemented as a delegate of a CPWindow
|
||||
@ignore
|
||||
@@ -800,7 +803,7 @@ var CPDocumentUntitledCount = 0;
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPDocumentWillSaveNotification
|
||||
object:self];
|
||||
|
||||
|
||||
[self saveToURL:_fileURL ofType:[self fileType] forSaveOperation:CPSaveOperation delegate:delegate didSaveSelector:didSaveSelector contextInfo:contextInfo];
|
||||
}
|
||||
else
|
||||
@@ -858,30 +861,27 @@ var CPDocumentUntitledCount = 0;
|
||||
[[CPDocumentController sharedDocumentController] removeDocument:self];
|
||||
}
|
||||
|
||||
- (void)shouldCloseWindowController:(CPWindowController)controller delegate:(id)delegate shouldCloseSelector:(SEL)selector contextInfo:(Object)info
|
||||
- (void)shouldCloseWindowController:(CPWindowController)controller delegate:(id)delegate shouldCloseSelector:(SEL)selector contextInfo:(Object)info
|
||||
{
|
||||
if ([controller shouldCloseDocument] || ([_windowControllers count] < 2 && [_windowControllers indexOfObject:controller] !== CPNotFound))
|
||||
[self canCloseDocumentWithDelegate:self shouldCloseSelector:@selector(_document:shouldClose:context:) contextInfo:{delegate:delegate, selector:selector, context:info}];
|
||||
|
||||
else if ([delegate respondsToSelector:selector])
|
||||
delegate.isa.objj_msgSend3(delegate, selector, self, YES, info);
|
||||
objj_msgSend(delegate, selector, self, YES, info);
|
||||
}
|
||||
|
||||
- (void)_document:(CPDocument)aDocument shouldClose:(BOOL)shouldClose context:(Object)context
|
||||
{
|
||||
var theDelegate = context.delegate;
|
||||
|
||||
if (aDocument === self && shouldClose)
|
||||
[self close];
|
||||
|
||||
if (theDelegate != null)
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, context.selector, aDocument, shouldClose, context.context);
|
||||
objj_msgSend(context.delegate, context.selector, aDocument, shouldClose, context.context);
|
||||
}
|
||||
|
||||
- (void)canCloseDocumentWithDelegate:(id)aDelegate shouldCloseSelector:(SEL)aSelector contextInfo:(Object)context
|
||||
- (void)canCloseDocumentWithDelegate:(id)aDelegate shouldCloseSelector:(SEL)aSelector contextInfo:(Object)context
|
||||
{
|
||||
if (![self isDocumentEdited])
|
||||
return [aDelegate respondsToSelector:aSelector] && aDelegate.isa.objj_msgSend3(aDelegate, aSelector, self, YES, context);
|
||||
return [aDelegate respondsToSelector:aSelector] && objj_msgSend(aDelegate, aSelector, self, YES, context);
|
||||
|
||||
_canCloseAlert = [[CPAlert alloc] init];
|
||||
|
||||
@@ -910,8 +910,8 @@ var CPDocumentUntitledCount = 0;
|
||||
|
||||
if (returnCode === 0)
|
||||
[self saveDocumentWithDelegate:delegate didSaveSelector:selector contextInfo:context];
|
||||
else if (delegate != null)
|
||||
delegate.isa.objj_msgSend3(delegate, selector, self, returnCode === 2, context);
|
||||
else
|
||||
objj_msgSend(delegate, selector, self, returnCode === 2, context);
|
||||
|
||||
_canCloseAlert = nil;
|
||||
}
|
||||
@@ -921,9 +921,9 @@ var CPDocumentUntitledCount = 0;
|
||||
var _CPReadSessionMake = function(aType, aDelegate, aDidReadSelector, aContextInfo)
|
||||
{
|
||||
return { fileType:aType, delegate:aDelegate, didReadSelector:aDidReadSelector, contextInfo:aContextInfo };
|
||||
};
|
||||
}
|
||||
|
||||
var _CPSaveSessionMake = function(anAbsoluteURL, aSaveOperation, aChangeCount, aDelegate, aDidSaveSelector, aContextInfo, aConnection)
|
||||
{
|
||||
return { absoluteURL:anAbsoluteURL, saveOperation:aSaveOperation, changeCount:aChangeCount, delegate:aDelegate, didSaveSelector:aDidSaveSelector, contextInfo:aContextInfo, connection:aConnection };
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,16 +24,12 @@
|
||||
@import <Foundation/CPBundle.j>
|
||||
|
||||
@import "CPDocument.j"
|
||||
@import "CPOpenPanel.j"
|
||||
@import "CPMenuItem.j"
|
||||
@import "CPWindowController.j"
|
||||
|
||||
@global CPApp
|
||||
@import "CPOpenPanel.j";
|
||||
|
||||
|
||||
var CPSharedDocumentController = nil;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPDocumentController
|
||||
This class is responsible for managing an application's open documents.
|
||||
@@ -45,7 +41,7 @@ var CPSharedDocumentController = nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the singleton instance of the application's document controller. If it has not
|
||||
Returns the singleton instance of the application's document controller. If it has not
|
||||
been created yet, it will be created then returned.
|
||||
@return a CPDocumentController
|
||||
*/
|
||||
@@ -53,7 +49,7 @@ var CPSharedDocumentController = nil;
|
||||
{
|
||||
if (!CPSharedDocumentController)
|
||||
[[self alloc] init];
|
||||
|
||||
|
||||
return CPSharedDocumentController;
|
||||
}
|
||||
|
||||
@@ -63,11 +59,11 @@ var CPSharedDocumentController = nil;
|
||||
- (id)init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_documents = [[CPArray alloc] init];
|
||||
|
||||
|
||||
if (!CPSharedDocumentController)
|
||||
CPSharedDocumentController = self;
|
||||
|
||||
@@ -89,16 +85,16 @@ var CPSharedDocumentController = nil;
|
||||
{
|
||||
var index = 0,
|
||||
count = [_documents count];
|
||||
|
||||
for (; index < count; ++index)
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var theDocument = _documents[index];
|
||||
|
||||
if ([[theDocument fileURL] isEqual:aURL])
|
||||
return theDocument;
|
||||
|
||||
if ([[theDocument fileURL] isEqual:aURL])
|
||||
return theDocument;
|
||||
}
|
||||
|
||||
return nil;
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -106,13 +102,13 @@ var CPSharedDocumentController = nil;
|
||||
@param aType the type of the new document
|
||||
@param shouldDisplay whether to display the document on screen
|
||||
*/
|
||||
- (CPDocument)openUntitledDocumentOfType:(CPString)aType display:(BOOL)shouldDisplay
|
||||
- (void)openUntitledDocumentOfType:(CPString)aType display:(BOOL)shouldDisplay
|
||||
{
|
||||
var theDocument = [self makeUntitledDocumentOfType:aType error:nil];
|
||||
|
||||
|
||||
if (theDocument)
|
||||
[self addDocument:theDocument];
|
||||
|
||||
|
||||
if (shouldDisplay)
|
||||
{
|
||||
[theDocument makeWindowControllers];
|
||||
@@ -128,7 +124,7 @@ var CPSharedDocumentController = nil;
|
||||
@param anError not used
|
||||
@return the created document
|
||||
*/
|
||||
- (CPDocument)makeUntitledDocumentOfType:(CPString)aType error:(/*{*/CPError/*}*/)anError
|
||||
- (CPDocument)makeUntitledDocumentOfType:(CPString)aType error:({CPError})anError
|
||||
{
|
||||
return [[[self documentClassForType:aType] alloc] initWithType:aType error:anError];
|
||||
}
|
||||
@@ -148,7 +144,7 @@ var CPSharedDocumentController = nil;
|
||||
{
|
||||
var type = [self typeForContentsOfURL:anAbsoluteURL error:anError];
|
||||
|
||||
result = [self makeDocumentWithContentsOfURL:anAbsoluteURL ofType:type delegate:self didReadSelector:@selector(document:didRead:contextInfo:) contextInfo:@{ @"shouldDisplay": shouldDisplay }];
|
||||
result = [self makeDocumentWithContentsOfURL:anAbsoluteURL ofType:type delegate:self didReadSelector:@selector(document:didRead:contextInfo:) contextInfo:[CPDictionary dictionaryWithObject:shouldDisplay forKey:@"shouldDisplay"]];
|
||||
|
||||
[self addDocument:result];
|
||||
|
||||
@@ -181,7 +177,7 @@ var CPSharedDocumentController = nil;
|
||||
@param aType the document type
|
||||
@param aDelegate the delegate to notify
|
||||
@param aSelector the selector to notify with
|
||||
@param aContextInfo the context information passed to the delegate
|
||||
@param aContextInfo the context infomration passed to the delegate
|
||||
*/
|
||||
- (CPDocument)makeDocumentWithContentsOfURL:(CPURL)anAbsoluteURL ofType:(CPString)aType delegate:(id)aDelegate didReadSelector:(SEL)aSelector contextInfo:(id)aContextInfo
|
||||
{
|
||||
@@ -214,7 +210,7 @@ var CPSharedDocumentController = nil;
|
||||
return;
|
||||
|
||||
[aDocument makeWindowControllers];
|
||||
|
||||
|
||||
if ([aContextInfo objectForKey:@"shouldDisplay"])
|
||||
[aDocument showWindows];
|
||||
}
|
||||
@@ -228,7 +224,7 @@ var CPSharedDocumentController = nil;
|
||||
[self openUntitledDocumentOfType:[[_documentTypes objectAtIndex:0] objectForKey:@"CPBundleTypeName"] display:YES];
|
||||
}
|
||||
|
||||
- (void)openDocument:(id)aSender
|
||||
-(void)openDocument:(id)aSender
|
||||
{
|
||||
var openPanel = [CPOpenPanel openPanel];
|
||||
|
||||
@@ -253,14 +249,6 @@ var CPSharedDocumentController = nil;
|
||||
return _documents;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the CPDocument object associated with the main window.
|
||||
*/
|
||||
- (CPDocument)currentDocument
|
||||
{
|
||||
return [[[CPApp mainWindow] windowController] document];
|
||||
}
|
||||
|
||||
/*!
|
||||
Adds \c aDocument under the control of the receiver.
|
||||
@param aDocument the document to add
|
||||
@@ -279,33 +267,6 @@ var CPSharedDocumentController = nil;
|
||||
[_documents removeObjectIdenticalTo:aDocument];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the document object whose window controller
|
||||
owns a specified window.
|
||||
*/
|
||||
- (CPDocument)documentForWindow:(CPWindow)aWindow
|
||||
{
|
||||
return [[aWindow windowController] document];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a Boolean value that indicates whether the receiver
|
||||
has any documents with unsaved changes.
|
||||
*/
|
||||
- (BOOL)hasEditedDocuments
|
||||
{
|
||||
var iter = [_documents objectEnumerator],
|
||||
obj;
|
||||
|
||||
while ((obj = [iter nextObject]) != nil)
|
||||
{
|
||||
if ([obj isDocumentEdited])
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (CPString)defaultType
|
||||
{
|
||||
return [_documentTypes[0] objectForKey:@"CPBundleTypeName"];
|
||||
@@ -315,17 +276,17 @@ var CPSharedDocumentController = nil;
|
||||
{
|
||||
var index = 0,
|
||||
count = _documentTypes.length,
|
||||
|
||||
|
||||
extension = [[anAbsoluteURL pathExtension] lowercaseString],
|
||||
starType = nil;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var documentType = _documentTypes[index],
|
||||
extensions = [documentType objectForKey:@"CFBundleTypeExtensions"],
|
||||
extensionIndex = 0,
|
||||
extensionCount = extensions.length;
|
||||
|
||||
|
||||
for (; extensionIndex < extensionCount; ++extensionIndex)
|
||||
{
|
||||
var thisExtension = [extensions[extensionIndex] lowercaseString];
|
||||
@@ -351,11 +312,11 @@ var CPSharedDocumentController = nil;
|
||||
for (;i < count; ++i)
|
||||
{
|
||||
var documentType = _documentTypes[i];
|
||||
|
||||
|
||||
if ([documentType objectForKey:@"CPBundleTypeName"] == aType)
|
||||
return documentType;
|
||||
}
|
||||
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@@ -375,13 +336,13 @@ var CPSharedDocumentController = nil;
|
||||
|
||||
@implementation CPDocumentController (Closing)
|
||||
|
||||
- (void)closeAllDocumentsWithDelegate:(id)aDelegate didCloseAllSelector:(SEL)didCloseSelector contextInfo:(Object)info
|
||||
- (void)closeAllDocumentsWithDelegate:(id)aDelegate didCloseAllSelector:(SEL)didCloseSelector contextInfo:(Object)info
|
||||
{
|
||||
var context = {
|
||||
delegate: aDelegate,
|
||||
selector: didCloseSelector,
|
||||
context: info
|
||||
};
|
||||
delegate: aDelegate,
|
||||
selector: didCloseSelector,
|
||||
context: info
|
||||
};
|
||||
|
||||
[self _closeDocumentsStartingWith:nil shouldClose:YES context:context];
|
||||
}
|
||||
@@ -402,10 +363,8 @@ var CPSharedDocumentController = nil;
|
||||
}
|
||||
}
|
||||
|
||||
var theDelegate = context.delegate;
|
||||
|
||||
if ([theDelegate respondsToSelector:context.selector])
|
||||
theDelegate.isa.objj_msgSend3(theDelegate, context.selector, self, [[self documents] count] === 0, context.context);
|
||||
if ([context.delegate respondsToSelector:context.selector])
|
||||
objj_msgSend(context.delegate, context.selector, self, [[self documents] count] === 0, context.context);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -431,14 +390,13 @@ var CPSharedDocumentController = nil;
|
||||
|
||||
- (void)noteNewRecentDocument:(CPDocument)aDocument
|
||||
{
|
||||
[self noteNewRecentDocumentURL:[aDocument fileURL]];
|
||||
[self noteNewRecentDocumentURL:[[aDocument fileURL] absoluteString]];
|
||||
}
|
||||
|
||||
- (void)noteNewRecentDocumentURL:(CPURL)aURL
|
||||
- (void)noteNewRecentDocumentURL:(CPString)aURL
|
||||
{
|
||||
var urlAsString = [aURL isKindOfClass:CPString] ? aURL : [aURL absoluteString];
|
||||
if (typeof window["cpNoteNewRecentDocumentPath"] === 'function')
|
||||
window.cpNoteNewRecentDocumentPath(urlAsString);
|
||||
window.cpNoteNewRecentDocumentPath(aURL);
|
||||
|
||||
[self _updateRecentDocumentsMenu];
|
||||
}
|
||||
|
||||
+98
-137
@@ -20,27 +20,52 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPDragServer_Constants.j"
|
||||
@import "CPEvent.j"
|
||||
@import "CPImageView.j"
|
||||
@import "CPPasteboard.j"
|
||||
@import "CPView.j"
|
||||
@import "CPWindow_Constants.j"
|
||||
@import <AppKit/CPView.j>
|
||||
@import <AppKit/CPEvent.j>
|
||||
@import <AppKit/CPPasteboard.j>
|
||||
@import <AppKit/CPImageView.j>
|
||||
|
||||
@class CPWindow // This file is imported by CPWindow.j
|
||||
@class _CPDOMDataTransferPasteboard
|
||||
#import "CoreGraphics/CGGeometry.h"
|
||||
#import "Platform/Platform.h"
|
||||
|
||||
@global CPApp
|
||||
|
||||
CPDragOperationNone = 0,
|
||||
CPDragOperationCopy = 1 << 1,
|
||||
CPDragOperationLink = 1 << 1,
|
||||
CPDragOperationGeneric = 1 << 2,
|
||||
CPDragOperationPrivate = 1 << 3,
|
||||
CPDragOperationMove = 1 << 4,
|
||||
CPDragOperationDelete = 1 << 5,
|
||||
CPDragOperationEvery = -1;
|
||||
|
||||
#define DRAGGING_WINDOW(anObject) ([anObject isKindOfClass:[CPWindow class]] ? anObject : [anObject window])
|
||||
|
||||
var CPDragServerPreviousEvent = nil,
|
||||
CPDragServerPeriodicUpdateInterval = 0.05;
|
||||
var CPDragServerPreviousEvent = nil,
|
||||
CPDragServerAutoscrollInterval = nil;
|
||||
/*
|
||||
var CPDragServerAutoscroll = function()
|
||||
{
|
||||
[CPDragServerSource autoscroll:CPDragServerPreviousEvent];
|
||||
}
|
||||
|
||||
var CPSharedDragServer = nil;
|
||||
if (CPDragServerAutoscrollInterval === nil)
|
||||
{
|
||||
if ([CPDragServerSource respondsToSelector:@selector(autoscroll:)])
|
||||
CPDragServerAutoscrollInterval = setInterval(CPDragServerAutoscroll, 100);
|
||||
}
|
||||
|
||||
var CPDragServerSource = nil,
|
||||
CPDragServerDraggingInfo = nil;
|
||||
CPDragServerPreviousEvent = anEvent;
|
||||
|
||||
if (CPDragServerAutoscrollInterval !== nil)
|
||||
clearInterval(CPDragServerAutoscrollInterval);
|
||||
|
||||
CPDragServerAutoscrollInterval = nil;
|
||||
*/
|
||||
|
||||
var CPSharedDragServer = nil;
|
||||
|
||||
var CPDragServerSource = nil;
|
||||
var CPDragServerDraggingInfo = nil;
|
||||
|
||||
/*
|
||||
CPDraggingInfo is a container of information about a specific dragging session.
|
||||
@@ -67,7 +92,7 @@ var CPDragServerSource = nil,
|
||||
- (unsigned)draggingSourceOperationMask
|
||||
*/
|
||||
|
||||
- (CGPoint)draggingLocation
|
||||
- (CPPoint)draggingLocation
|
||||
{
|
||||
return [[CPDragServer sharedDragServer] draggingLocation];
|
||||
}
|
||||
@@ -102,7 +127,7 @@ var CPDragServerSource = nil,
|
||||
@end
|
||||
|
||||
var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
CPDraggingSource_draggedImage_endedAt_operation_ = 1 << 1,
|
||||
CPDraggingSource_draggedImage_endAt_operation_ = 1 << 1,
|
||||
CPDraggingSource_draggedView_movedTo_ = 1 << 2,
|
||||
CPDraggingSource_draggedView_endedAt_operation_ = 1 << 3;
|
||||
|
||||
@@ -125,13 +150,10 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
|
||||
CGPoint _draggingLocation;
|
||||
id _draggingDestination;
|
||||
BOOL _draggingDestinationWantsPeriodicUpdates;
|
||||
|
||||
CGPoint _startDragLocation;
|
||||
BOOL _shouldSlideBack;
|
||||
unsigned _dragOperation;
|
||||
|
||||
CPTimer _draggingUpdateTimer;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -163,7 +185,7 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
|
||||
if (self)
|
||||
{
|
||||
_draggedWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessWindowMask];
|
||||
_draggedWindow = [[CPWindow alloc] initWithContentRect:_CGRectMakeZero() styleMask:CPBorderlessWindowMask];
|
||||
|
||||
[_draggedWindow setLevel:CPDraggingWindowLevel];
|
||||
}
|
||||
@@ -201,12 +223,7 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
- (void)draggingSourceUpdatedWithGlobalLocation:(CGPoint)aGlobalLocation
|
||||
{
|
||||
if (![CPPlatform supportsDragAndDrop])
|
||||
{
|
||||
var frame = [_draggedWindow frame];
|
||||
frame.origin.x = aGlobalLocation.x - _draggingOffset.width;
|
||||
frame.origin.y = aGlobalLocation.y - _draggingOffset.height;
|
||||
[_draggedWindow _setFrame:frame display:YES animate:NO constrainWidth:NO constrainHeight:NO];
|
||||
}
|
||||
[_draggedWindow setFrameOrigin:_CGPointMake(aGlobalLocation.x - _draggingOffset.width, aGlobalLocation.y - _draggingOffset.height)];
|
||||
|
||||
if (_implementedDraggingSourceMethods & CPDraggingSource_draggedImage_movedTo_)
|
||||
[_draggingSource draggedImage:[_draggedView image] movedTo:aGlobalLocation];
|
||||
@@ -217,111 +234,40 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
|
||||
- (CPDragOperation)draggingUpdatedInPlatformWindow:(CPPlatformWindow)aPlatformWindow location:(CGPoint)aLocation
|
||||
{
|
||||
[_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.
|
||||
draggingDestination = [aPlatformWindow _dragHitTest:aLocation pasteboard:[CPDragServerDraggingInfo draggingPasteboard]];
|
||||
var 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:)])
|
||||
if (_draggingDestination && [_draggingDestination respondsToSelector:@selector(draggingExited:)])
|
||||
[_draggingDestination draggingExited:CPDragServerDraggingInfo];
|
||||
|
||||
_draggingDestination = draggingDestination;
|
||||
|
||||
if ([_draggingDestination respondsToSelector:@selector(wantsPeriodicDraggingUpdates)])
|
||||
_draggingDestinationWantsPeriodicUpdates = [_draggingDestination wantsPeriodicDraggingUpdates];
|
||||
else
|
||||
_draggingDestinationWantsPeriodicUpdates = YES;
|
||||
|
||||
if ([_draggingDestination respondsToSelector:@selector(draggingEntered:)])
|
||||
if (_draggingDestination && [_draggingDestination respondsToSelector:@selector(draggingEntered:)])
|
||||
dragOperation = [_draggingDestination draggingEntered:CPDragServerDraggingInfo];
|
||||
}
|
||||
else if ([_draggingDestination respondsToSelector:@selector(draggingUpdated:)])
|
||||
else if (_draggingDestination && [_draggingDestination respondsToSelector:@selector(draggingUpdated:)])
|
||||
dragOperation = [_draggingDestination draggingUpdated:CPDragServerDraggingInfo];
|
||||
|
||||
if (!_draggingDestination)
|
||||
dragOperation = CPDragOperationNone;
|
||||
else
|
||||
{
|
||||
if (_draggingDestinationWantsPeriodicUpdates)
|
||||
_draggingUpdateTimer = [CPTimer scheduledTimerWithTimeInterval:CPDragServerPeriodicUpdateInterval
|
||||
target:self
|
||||
selector:@selector(_sendPeriodicDraggingUpdate:)
|
||||
userInfo:@{ "platformWindow":aPlatformWindow, "location":aLocation }
|
||||
repeats:NO];
|
||||
|
||||
var scrollView = [_draggingDestination isKindOfClass:[CPView class]] ? [_draggingDestination enclosingScrollView] : nil;
|
||||
if (scrollView)
|
||||
{
|
||||
var contentView = [scrollView contentView],
|
||||
bounds = [contentView bounds],
|
||||
insetBounds = CGRectInset(bounds, 30, 30),
|
||||
eventLocation = [contentView convertPoint:_draggingLocation fromView:nil],
|
||||
deltaX = 0,
|
||||
deltaY = 0;
|
||||
|
||||
if (!CGRectContainsPoint(insetBounds, eventLocation))
|
||||
{
|
||||
if ([scrollView hasVerticalScroller])
|
||||
{
|
||||
if (eventLocation.y < CGRectGetMinY(insetBounds))
|
||||
deltaY = CGRectGetMinY(insetBounds) - eventLocation.y;
|
||||
else if (eventLocation.y > CGRectGetMaxY(insetBounds))
|
||||
deltaY = CGRectGetMaxY(insetBounds) - eventLocation.y;
|
||||
if (deltaY < -insetBounds.size.height)
|
||||
deltaY = -insetBounds.size.height;
|
||||
if (deltaY > insetBounds.size.height)
|
||||
deltaY = insetBounds.size.height;
|
||||
}
|
||||
|
||||
if ([scrollView hasHorizontalScroller])
|
||||
{
|
||||
if (eventLocation.x < CGRectGetMinX(insetBounds))
|
||||
deltaX = CGRectGetMinX(insetBounds) - eventLocation.x;
|
||||
else if (eventLocation.x > CGRectGetMaxX(insetBounds))
|
||||
deltaX = CGRectGetMaxX(insetBounds) - eventLocation.x;
|
||||
if (deltaX < -insetBounds.size.width)
|
||||
deltaX = -insetBounds.size.width;
|
||||
if (deltaX > insetBounds.size.width)
|
||||
deltaX = insetBounds.size.width;
|
||||
}
|
||||
|
||||
var scrollPoint = CGPointMake(bounds.origin.x - deltaX, bounds.origin.y - deltaY);
|
||||
|
||||
[contentView scrollToPoint:scrollPoint];
|
||||
[[scrollView _headerView] scrollPoint:scrollPoint];
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dragOperation;
|
||||
}
|
||||
|
||||
- (void)_sendPeriodicDraggingUpdate:(CPTimer)aTimer
|
||||
{
|
||||
var userInfo = [aTimer userInfo];
|
||||
_dragOperation = [self draggingUpdatedInPlatformWindow:[userInfo objectForKey:@"platformWindow"]
|
||||
location:[userInfo objectForKey:@"location"]];
|
||||
}
|
||||
|
||||
- (void)draggingEndedInPlatformWindow:(CPPlatformWindow)aPlatformWindow globalLocation:(CGPoint)aLocation operation:(CPDragOperation)anOperation
|
||||
{
|
||||
[_draggingUpdateTimer invalidate];
|
||||
_draggingUpdateTimer = nil;
|
||||
|
||||
[_draggedView removeFromSuperview];
|
||||
|
||||
if (![CPPlatform supportsDragAndDrop])
|
||||
[_draggedWindow orderOut:self];
|
||||
|
||||
if (_implementedDraggingSourceMethods & CPDraggingSource_draggedImage_endedAt_operation_)
|
||||
if (_implementedDraggingSourceMethods & CPDraggingSource_draggedImage_endAt_operation_)
|
||||
[_draggingSource draggedImage:[_draggedView image] endedAt:aLocation operation:anOperation];
|
||||
else if (_implementedDraggingSourceMethods & CPDraggingSource_draggedView_endedAt_operation_)
|
||||
[_draggingSource draggedView:_draggedView endedAt:aLocation operation:anOperation];
|
||||
@@ -331,8 +277,8 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
|
||||
- (void)performDragOperationInPlatformWindow:(CPPlatformWindow)aPlatformWindow
|
||||
{
|
||||
if (_draggingDestination &&
|
||||
(![_draggingDestination respondsToSelector:@selector(prepareForDragOperation:)] || [_draggingDestination prepareForDragOperation:CPDragServerDraggingInfo]) &&
|
||||
if (_draggingDestination &&
|
||||
(![_draggingDestination respondsToSelector:@selector(prepareForDragOperation:)] || [_draggingDestination prepareForDragOperation:CPDragServerDraggingInfo]) &&
|
||||
(![_draggingDestination respondsToSelector:@selector(performDragOperation:)] || [_draggingDestination performDragOperation:CPDragServerDraggingInfo]) &&
|
||||
[_draggingDestination respondsToSelector:@selector(concludeDragOperation:)])
|
||||
[_draggingDestination concludeDragOperation:CPDragServerDraggingInfo];
|
||||
@@ -370,26 +316,22 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
if (mouseDownWindow)
|
||||
mouseDownEventLocation = [mouseDownWindow convertBaseToGlobal:mouseDownEventLocation];
|
||||
|
||||
_draggingOffset = CGSizeMake(mouseDownEventLocation.x - viewLocation.x, mouseDownEventLocation.y - viewLocation.y);
|
||||
_draggingOffset = _CGSizeMake(mouseDownEventLocation.x - viewLocation.x, mouseDownEventLocation.y - viewLocation.y);
|
||||
}
|
||||
else
|
||||
_draggingOffset = CGSizeMakeZero();
|
||||
_draggingOffset = _CGSizeMakeZero();
|
||||
|
||||
if ([CPPlatform isBrowser])
|
||||
[_draggedWindow setPlatformWindow:[aWindow platformWindow]];
|
||||
|
||||
[aView setFrameOrigin:CGPointMakeZero()];
|
||||
[aView setFrameOrigin:_CGPointMakeZero()];
|
||||
|
||||
var mouseLocation = [CPEvent mouseLocation],
|
||||
viewSize = [aView frameSize],
|
||||
startDragLocationX = mouseLocation.x - _draggingOffset.width,
|
||||
startDragLocationY = mouseLocation.y - _draggingOffset.height,
|
||||
draggedWindowFrame = CGRectMake(startDragLocationX, startDragLocationY, viewSize.width, viewSize.height);
|
||||
var mouseLocation = [CPEvent mouseLocation];
|
||||
|
||||
// Place it where the mouse pointer is.
|
||||
_startDragLocation = CGPointMake(startDragLocationX, startDragLocationY);
|
||||
|
||||
[_draggedWindow _setFrame:draggedWindowFrame display:YES animate:NO constrainWidth:NO constrainHeight:NO];
|
||||
_startDragLocation = _CGPointMake(mouseLocation.x - _draggingOffset.width, mouseLocation.y - _draggingOffset.height);
|
||||
[_draggedWindow setFrameOrigin:_startDragLocation];
|
||||
[_draggedWindow setFrameSize:[aView frame].size];
|
||||
|
||||
[[_draggedWindow contentView] addSubview:aView];
|
||||
|
||||
@@ -400,8 +342,8 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
if ([_draggingSource respondsToSelector:@selector(draggedImage:movedTo:)])
|
||||
_implementedDraggingSourceMethods |= CPDraggingSource_draggedImage_movedTo_;
|
||||
|
||||
if ([_draggingSource respondsToSelector:@selector(draggedImage:endedAt:operation:)])
|
||||
_implementedDraggingSourceMethods |= CPDraggingSource_draggedImage_endedAt_operation_;
|
||||
if ([_draggingSource respondsToSelector:@selector(draggedImage:endAt:operation:)])
|
||||
_implementedDraggingSourceMethods |= CPDraggingSource_draggedImage_endAt_operation_;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -438,7 +380,7 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
var imageSize = [anImage size];
|
||||
|
||||
if (!_imageView)
|
||||
_imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, imageSize.width, imageSize.height)];
|
||||
_imageView = [[CPImageView alloc] initWithFrame:_CGRectMake(0.0, 0.0, imageSize.width, imageSize.height)];
|
||||
|
||||
[_imageView setImage:anImage];
|
||||
|
||||
@@ -462,27 +404,46 @@ var CPDraggingSource_draggedImage_movedTo_ = 1 << 0,
|
||||
// Stop tracking events.
|
||||
return;
|
||||
}
|
||||
else if (type === CPKeyDown)
|
||||
{
|
||||
var characters = [anEvent characters];
|
||||
|
||||
if (characters === CPEscapeFunctionKey)
|
||||
{
|
||||
_dragOperation = CPDragOperationNone;
|
||||
[self draggingEndedInPlatformWindow:platformWindow globalLocation:CGPointMakeZero() operation:_dragOperation];
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
[self draggingSourceUpdatedWithGlobalLocation:platformWindowLocation];
|
||||
_dragOperation = [self draggingUpdatedInPlatformWindow:platformWindow location:platformWindowLocation];
|
||||
}
|
||||
[self draggingSourceUpdatedWithGlobalLocation:platformWindowLocation];
|
||||
_dragOperation = [self draggingUpdatedInPlatformWindow:platformWindow location:platformWindowLocation];
|
||||
|
||||
// If we're not a mouse up, then we're going to want to grab the next event.
|
||||
[CPApp setTarget:self selector:@selector(trackDragging:)
|
||||
forNextEventMatchingMask:CPMouseMovedMask | CPLeftMouseDraggedMask | CPLeftMouseUpMask | CPKeyDownMask
|
||||
untilDate:nil inMode:0 dequeue:YES];
|
||||
forNextEventMatchingMask:CPMouseMovedMask | CPLeftMouseDraggedMask | CPLeftMouseUpMask
|
||||
untilDate:nil inMode:0 dequeue:NO];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPWindow (CPDraggingAdditions)
|
||||
|
||||
/* @ignore */
|
||||
- (id)_dragHitTest:(CGPoint)aPoint pasteboard:(CPPasteboard)aPasteboard
|
||||
{
|
||||
// If none of our views or ourselves has registered for drag events...
|
||||
if (!_inclusiveRegisteredDraggedTypes)
|
||||
return nil;
|
||||
|
||||
// We don't need to do this because the only place this gets called
|
||||
// -_dragHitTest: in CPPlatformWindow does this already. Perhaps to
|
||||
// be safe?
|
||||
// if (![self containsPoint:aPoint])
|
||||
// return nil;
|
||||
|
||||
var adjustedPoint = [self convertPlatformWindowToBase:aPoint],
|
||||
hitView = [_windowView hitTest:adjustedPoint];
|
||||
|
||||
while (hitView && ![aPasteboard availableTypeFromArray:[hitView registeredDraggedTypes]])
|
||||
hitView = [hitView superview];
|
||||
|
||||
if (hitView)
|
||||
return hitView;
|
||||
|
||||
if ([aPasteboard availableTypeFromArray:[self registeredDraggedTypes]])
|
||||
return self;
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* CPDragServer_Constants.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@typedef CPDragOperation
|
||||
CPDragOperationNone = 0;
|
||||
CPDragOperationCopy = 1 << 1;
|
||||
CPDragOperationLink = 1 << 1;
|
||||
CPDragOperationGeneric = 1 << 2;
|
||||
CPDragOperationPrivate = 1 << 3;
|
||||
CPDragOperationMove = 1 << 4;
|
||||
CPDragOperationDelete = 1 << 5;
|
||||
CPDragOperationEvery = -1;
|
||||
+127
-297
@@ -20,35 +20,93 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPEvent_Constants.j"
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPObjJRuntime.j>
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
@import "CPCompatibility.j"
|
||||
@import "CGGeometry.j"
|
||||
@import "CPTrackingArea.j"
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
@class CPTextField
|
||||
@class CPWindow
|
||||
@class CPGraphicsContext
|
||||
|
||||
@global CPApp
|
||||
@global CPNewlineCharacter
|
||||
@global CPCarriageReturnCharacter
|
||||
@global CPEnterCharacter
|
||||
CPLeftMouseDown = 1;
|
||||
CPLeftMouseUp = 2;
|
||||
CPRightMouseDown = 3;
|
||||
CPRightMouseUp = 4;
|
||||
CPMouseMoved = 5;
|
||||
CPLeftMouseDragged = 6;
|
||||
CPRightMouseDragged = 7;
|
||||
CPMouseEntered = 8;
|
||||
CPMouseExited = 9;
|
||||
CPKeyDown = 10;
|
||||
CPKeyUp = 11;
|
||||
CPFlagsChanged = 12;
|
||||
CPAppKitDefined = 13;
|
||||
CPSystemDefined = 14;
|
||||
CPApplicationDefined = 15;
|
||||
CPPeriodic = 16;
|
||||
CPCursorUpdate = 17;
|
||||
CPScrollWheel = 22;
|
||||
CPOtherMouseDown = 25;
|
||||
CPOtherMouseUp = 26;
|
||||
CPOtherMouseDragged = 27;
|
||||
|
||||
@typedef DOMEvent
|
||||
@typedef CPEventType
|
||||
// iPhone Event Types
|
||||
CPTouchStart = 28;
|
||||
CPTouchMove = 29;
|
||||
CPTouchEnd = 30;
|
||||
CPTouchCancel = 31;
|
||||
|
||||
|
||||
CPAlphaShiftKeyMask = 1 << 16;
|
||||
CPShiftKeyMask = 1 << 17;
|
||||
CPControlKeyMask = 1 << 18;
|
||||
CPAlternateKeyMask = 1 << 19;
|
||||
CPCommandKeyMask = 1 << 20;
|
||||
CPNumericPadKeyMask = 1 << 21;
|
||||
CPHelpKeyMask = 1 << 22;
|
||||
CPFunctionKeyMask = 1 << 23;
|
||||
CPDeviceIndependentModifierFlagsMask = 0xffff0000;
|
||||
|
||||
CPLeftMouseDownMask = 1 << CPLeftMouseDown;
|
||||
CPLeftMouseUpMask = 1 << CPLeftMouseUp;
|
||||
CPRightMouseDownMask = 1 << CPRightMouseDown;
|
||||
CPRightMouseUpMask = 1 << CPRightMouseUp;
|
||||
CPOtherMouseDownMask = 1 << CPOtherMouseDown;
|
||||
CPOtherMouseUpMask = 1 << CPOtherMouseUp;
|
||||
CPMouseMovedMask = 1 << CPMouseMoved;
|
||||
CPLeftMouseDraggedMask = 1 << CPLeftMouseDragged;
|
||||
CPRightMouseDraggedMask = 1 << CPRightMouseDragged;
|
||||
CPOtherMouseDragged = 1 << CPOtherMouseDragged;
|
||||
CPMouseEnteredMask = 1 << CPMouseEntered;
|
||||
CPMouseExitedMask = 1 << CPMouseExited;
|
||||
CPCursorUpdateMask = 1 << CPCursorUpdate;
|
||||
CPKeyDownMask = 1 << CPKeyDown;
|
||||
CPKeyUpMask = 1 << CPKeyUp;
|
||||
CPFlagsChangedMask = 1 << CPFlagsChanged;
|
||||
CPAppKitDefinedMask = 1 << CPAppKitDefined;
|
||||
CPSystemDefinedMask = 1 << CPSystemDefined;
|
||||
CPApplicationDefinedMask = 1 << CPApplicationDefined;
|
||||
CPPeriodicMask = 1 << CPPeriodic;
|
||||
CPScrollWheelMask = 1 << CPScrollWheel;
|
||||
CPAnyEventMask = 0xffffffff;
|
||||
|
||||
CPDOMEventDoubleClick = "dblclick",
|
||||
CPDOMEventMouseDown = "mousedown",
|
||||
CPDOMEventMouseUp = "mouseup",
|
||||
CPDOMEventMouseMoved = "mousemove",
|
||||
CPDOMEventMouseDragged = "mousedrag",
|
||||
CPDOMEventKeyUp = "keyup",
|
||||
CPDOMEventKeyDown = "keydown",
|
||||
CPDOMEventKeyPress = "keypress";
|
||||
CPDOMEventCopy = "copy";
|
||||
CPDOMEventPaste = "paste";
|
||||
CPDOMEventScrollWheel = "mousewheel";
|
||||
CPDOMEventTouchStart = "touchstart";
|
||||
CPDOMEventTouchMove = "touchmove";
|
||||
CPDOMEventTouchEnd = "touchend";
|
||||
CPDOMEventTouchCancel = "touchcancel";
|
||||
|
||||
var _CPEventPeriodicEventPeriod = 0,
|
||||
_CPEventPeriodicEventTimer = nil,
|
||||
_CPEventUpperCaseRegex = new RegExp("[A-Z]"),
|
||||
_CPEventStartupMilliseconds = new Date().getTime();
|
||||
_CPEventPeriodicEventTimer = nil;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPEvent
|
||||
CPEvent encapsulates the details of a Cappuccino keyboard or mouse event.
|
||||
@@ -56,7 +114,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
@implementation CPEvent : CPObject
|
||||
{
|
||||
CPEventType _type;
|
||||
CGPoint _location;
|
||||
CPPoint _location;
|
||||
unsigned _modifierFlags;
|
||||
CPTimeInterval _timestamp;
|
||||
CPGraphicsContext _context;
|
||||
@@ -66,40 +124,18 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
CPWindow _window;
|
||||
Number _windowNumber;
|
||||
CPString _characters;
|
||||
CPString _charactersIgnoringModifiers;
|
||||
CPString _charactersIgnoringModifiers
|
||||
BOOL _isARepeat;
|
||||
unsigned _keyCode;
|
||||
DOMEvent _DOMEvent;
|
||||
int _data1;
|
||||
int _data2;
|
||||
short _subtype;
|
||||
|
||||
|
||||
float _deltaX;
|
||||
float _deltaY;
|
||||
float _deltaZ;
|
||||
float _scrollingDeltaX;
|
||||
float _scrollingDeltaY;
|
||||
BOOL _hasPreciseScrollingDeltas;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
BOOL _suppressCappuccinoCut;
|
||||
BOOL _suppressCappuccinoPaste;
|
||||
#endif
|
||||
|
||||
CPTrackingArea _trackingArea;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the current time in fractional seconds since startup.
|
||||
*/
|
||||
+ (CPTimeInterval)currentTimestamp
|
||||
{
|
||||
return (new Date().getTime() - _CPEventStartupMilliseconds) / 1000;
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a new keyboard event.
|
||||
|
||||
@param anEventType the event type. Must be one of CPKeyDown, CPKeyUp or CPFlagsChanged
|
||||
@param aPoint the location of the cursor in the window specified by \c aWindowNumber
|
||||
@param modifierFlags a bitwise combination of the modifiers specified in the CPEvent globals
|
||||
@@ -119,13 +155,12 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
characters:(CPString)characters charactersIgnoringModifiers:(CPString)unmodCharacters isARepeat:(BOOL)repeatKey keyCode:(unsigned short)code
|
||||
{
|
||||
return [[self alloc] _initKeyEventWithType:anEventType location:aPoint modifierFlags:modifierFlags
|
||||
timestamp:aTimestamp windowNumber:aWindowNumber context:aGraphicsContext
|
||||
timestamp:aTimestamp windowNumber:aWindowNumber context:aGraphicsContext
|
||||
characters:characters charactersIgnoringModifiers:unmodCharacters isARepeat:repeatKey keyCode:code];
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a new mouse event.
|
||||
|
||||
Creates a new mouse event
|
||||
@param anEventType the event type
|
||||
@param aPoint the location of the cursor in the window specified by \c aWindowNumber
|
||||
@param modifierFlags a bitwise combination of the modifiers specified in the CPEvent globals
|
||||
@@ -138,7 +173,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
@throws CPInternalInconsistencyException if an invalid event type is provided
|
||||
@return the new mouse event
|
||||
*/
|
||||
+ (id)mouseEventWithType:(CPEventType)anEventType location:(CGPoint)aPoint modifierFlags:(unsigned)modifierFlags
|
||||
+ (id)mouseEventWithType:(CPEventType)anEventType location:(CGPoint)aPoint modifierFlags:(unsigned)modifierFlags
|
||||
timestamp:(CPTimeInterval)aTimestamp windowNumber:(int)aWindowNumber context:(CPGraphicsContext)aGraphicsContext
|
||||
eventNumber:(int)anEventNumber clickCount:(int)aClickCount pressure:(float)aPressure
|
||||
{
|
||||
@@ -147,29 +182,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a new mouse tracking event.
|
||||
|
||||
@param anEventType the event type
|
||||
@param aPoint the location of the cursor in the window specified by \c aWindowNumber
|
||||
@param modifierFlags a bitwise combination of the modifiers specified in the CPEvent globals
|
||||
@param aTimestamp the time the event occurred
|
||||
@param aWindowNumber the number of the CPWindow where the event occurred
|
||||
@param aGraphicsContext the graphics context where the event occurred
|
||||
@param anEventNumber a number for this event
|
||||
@param aTrackingArea the tracking area that triggered the event
|
||||
@throws CPInternalInconsistencyException if an invalid event type is provided
|
||||
@return the new mouse event
|
||||
*/
|
||||
+ (id)enterExitEventWithType:(CPEventType)anEventType location:(CGPoint)aPoint modifierFlags:(unsigned)modifierFlags
|
||||
timestamp:(CPTimeInterval)aTimestamp windowNumber:(int)aWindowNumber context:(CPGraphicsContext)aGraphicsContext
|
||||
eventNumber:(int)anEventNumber trackingArea:(CPTrackingArea)aTrackingArea
|
||||
{
|
||||
return [[self alloc] _initEnterExitEventWithType:anEventType location:aPoint modifierFlags:modifierFlags timestamp:aTimestamp windowNumber:aWindowNumber context:aGraphicsContext eventNumber:anEventNumber trackingArea:aTrackingArea];
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a new custom event.
|
||||
|
||||
Creates a new custom event
|
||||
@param anEventType the event type. Must be one of CPAppKitDefined, CPSystemDefined, CPApplicationDefined or CPPeriodic
|
||||
@param aLocation the location of the cursor in the window specified by \c aWindowNumber
|
||||
@param modifierFlags a bitwise combination of the modifiers specified in the CPEvent globals
|
||||
@@ -190,31 +203,17 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
timestamp:aTimestamp windowNumber:aWindowNumber context:aGraphicsContext subtype:aSubtype data1:aData1 data2:aData2];
|
||||
}
|
||||
|
||||
- (id)_initWithType:(CPEventType)anEventType
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_type = anEventType;
|
||||
|
||||
// Make sure these are 0 rather than nil.
|
||||
_deltaX = 0;
|
||||
_scrollingDeltaX = 0;
|
||||
_deltaY = 0;
|
||||
_scrollingDeltaY = 0;
|
||||
_deltaZ = 0;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (id)_initMouseEventWithType:(CPEventType)anEventType location:(CGPoint)aPoint modifierFlags:(unsigned)modifierFlags
|
||||
- (id)_initMouseEventWithType:(CPEventType)anEventType location:(CPPoint)aPoint modifierFlags:(unsigned)modifierFlags
|
||||
timestamp:(CPTimeInterval)aTimestamp windowNumber:(int)aWindowNumber context:(CPGraphicsContext)aGraphicsContext
|
||||
eventNumber:(int)anEventNumber clickCount:(int)aClickCount pressure:(float)aPressure
|
||||
{
|
||||
if (self = [self _initWithType:anEventType])
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_location = CGPointCreateCopy(aPoint);
|
||||
_type = anEventType;
|
||||
_location = CPPointCreateCopy(aPoint);
|
||||
_modifierFlags = modifierFlags;
|
||||
_timestamp = aTimestamp;
|
||||
_context = aGraphicsContext;
|
||||
@@ -223,40 +222,21 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
_pressure = aPressure;
|
||||
_window = [CPApp windowWithWindowNumber:aWindowNumber];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (id)_initEnterExitEventWithType:(CPEventType)anEventType location:(CGPoint)aPoint modifierFlags:(unsigned)modifierFlags
|
||||
timestamp:(CPTimeInterval)aTimestamp windowNumber:(int)aWindowNumber context:(CPGraphicsContext)aGraphicsContext
|
||||
eventNumber:(int)anEventNumber trackingArea:(CPTrackingArea)aTrackingArea
|
||||
{
|
||||
if ((anEventType != CPMouseEntered) && (anEventType != CPMouseExited) && (anEventType != CPCursorUpdate))
|
||||
[CPException raise:CPInternalInconsistencyException reason:"Invalid event type"];
|
||||
|
||||
if (self = [self _initWithType:anEventType])
|
||||
{
|
||||
_location = CGPointCreateCopy(aPoint);
|
||||
_modifierFlags = modifierFlags;
|
||||
_timestamp = aTimestamp;
|
||||
_context = aGraphicsContext;
|
||||
_eventNumber = anEventNumber;
|
||||
_trackingArea = aTrackingArea;
|
||||
_window = [CPApp windowWithWindowNumber:aWindowNumber];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (id)_initKeyEventWithType:(CPEventType)anEventType location:(CGPoint)aPoint modifierFlags:(unsigned int)modifierFlags
|
||||
- (id)_initKeyEventWithType:(CPEventType)anEventType location:(CPPoint)aPoint modifierFlags:(unsigned int)modifierFlags
|
||||
timestamp:(CPTimeInterval)aTimestamp windowNumber:(int)aWindowNumber context:(CPGraphicsContext)aGraphicsContext
|
||||
characters:(CPString)characters charactersIgnoringModifiers:(CPString)unmodCharacters isARepeat:(BOOL)isARepeat keyCode:(unsigned short)code
|
||||
{
|
||||
if (self = [self _initWithType:anEventType])
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_location = CGPointCreateCopy(aPoint);
|
||||
_type = anEventType;
|
||||
_location = CPPointCreateCopy(aPoint);
|
||||
_modifierFlags = modifierFlags;
|
||||
_timestamp = aTimestamp;
|
||||
_context = aGraphicsContext;
|
||||
@@ -266,7 +246,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
_keyCode = code;
|
||||
_windowNumber = aWindowNumber;
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -275,32 +255,34 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
timestamp:(CPTimeInterval)aTimestamp windowNumber:(int)aWindowNumber context:(CPGraphicsContext)aGraphicsContext
|
||||
subtype:(short)aSubtype data1:(int)aData1 data2:(int)aData2
|
||||
{
|
||||
if (self = [self _initWithType:anEventType])
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_location = CGPointCreateCopy(aPoint);
|
||||
_type = anEventType;
|
||||
_location = CPPointCreateCopy(aPoint);
|
||||
_modifierFlags = modifierFlags;
|
||||
_timestamp = aTimestamp;
|
||||
_context = aGraphicsContext;
|
||||
_subtype = aSubtype;
|
||||
_data1 = aData1;
|
||||
_data2 = aData2;
|
||||
_windowNumber = aWindowNumber;
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the location of the mouse (for mouse events).
|
||||
If the receiver is not a mouse event, it returns \c nil.
|
||||
If \c window returns \c nil, then the mouse coordinates will be based on the screen coordinates.
|
||||
If this is not a mouse event, it returns \c nil.
|
||||
If \c window returns \c nil, then
|
||||
the mouse coordinates will be based on the screen coordinates.
|
||||
Otherwise, the coordinates are relative to the window's coordinates.
|
||||
|
||||
@return the location of the mouse, or \c nil for non-mouse events.
|
||||
*/
|
||||
- (CGPoint)locationInWindow
|
||||
{
|
||||
return CGPointMakeCopy(_location);
|
||||
return _CGPointMakeCopy(_location);
|
||||
}
|
||||
|
||||
- (CGPoint)globalLocation
|
||||
@@ -315,7 +297,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns event information as a bit mask.
|
||||
Returns event information as a bit mask
|
||||
*/
|
||||
- (unsigned)modifierFlags
|
||||
{
|
||||
@@ -323,7 +305,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the time the event occurred in seconds since startup.
|
||||
Returns the time the event occurred
|
||||
*/
|
||||
- (CPTimeInterval)timestamp
|
||||
{
|
||||
@@ -339,15 +321,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the subtype of the event.
|
||||
*/
|
||||
- (CPEventType)subtype
|
||||
{
|
||||
return _subtype;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the event's associated window.
|
||||
Returns the event's associated window
|
||||
*/
|
||||
- (CPWindow)window
|
||||
{
|
||||
@@ -371,14 +345,11 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
*/
|
||||
- (int)buttonNumber
|
||||
{
|
||||
if (_type === CPRightMouseDown || _type === CPRightMouseUp || _type === CPRightMouseDragged)
|
||||
return 1;
|
||||
|
||||
return 0;
|
||||
return _buttonNumber;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the number of clicks that caused this event (mouse only).
|
||||
Returns the number of clicks that caused this event. (mouse only)
|
||||
*/
|
||||
- (int)clickCount
|
||||
{
|
||||
@@ -386,8 +357,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the characters associated with this event (keyboard only).
|
||||
|
||||
Returns the characters associated with this event (keyboard only)
|
||||
@throws CPInternalInconsistencyException if this method is called on a non-key event
|
||||
*/
|
||||
- (CPString)characters
|
||||
@@ -397,7 +367,6 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
|
||||
/*!
|
||||
Returns the character ignoring any modifiers (except shift).
|
||||
|
||||
@throws CPInternalInconsistencyException if this method is called on a non-key event
|
||||
*/
|
||||
- (CPString)charactersIgnoringModifiers
|
||||
@@ -407,7 +376,6 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
|
||||
/*!
|
||||
Returns \c YES if the keyboard event was caused by the key being held down.
|
||||
|
||||
@throws CPInternalInconsistencyException if this method is called on a non-key event
|
||||
*/
|
||||
- (BOOL)isARepeat
|
||||
@@ -417,7 +385,6 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
|
||||
/*!
|
||||
Returns the key's key code.
|
||||
|
||||
@throws CPInternalInconsistencyException if this method is called on a non-key event
|
||||
*/
|
||||
- (unsigned short)keyCode
|
||||
@@ -450,17 +417,7 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
return _DOMEvent;
|
||||
}
|
||||
|
||||
- (int)data1
|
||||
{
|
||||
return _data1;
|
||||
}
|
||||
|
||||
- (int)data2
|
||||
{
|
||||
return _data2;
|
||||
}
|
||||
|
||||
// Getting Scroll Wheel Event Information
|
||||
// Getting Scroll Wheel Event Infomration
|
||||
/*!
|
||||
Returns the change in the x-axis for a mouse event.
|
||||
*/
|
||||
@@ -485,173 +442,45 @@ var _CPEventPeriodicEventPeriod = 0,
|
||||
return _deltaZ;
|
||||
}
|
||||
|
||||
- (BOOL)hasPreciseScrollingDeltas
|
||||
{
|
||||
return !!_hasPreciseScrollingDeltas;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the change in points on the x-axis for a mouse movement, unless hasPreciseScrollingDeltas is NO,
|
||||
in which case the change is measured in number of "lines" or "rows" and needs to be multiplied as appropriate
|
||||
to get change in pixels.
|
||||
*/
|
||||
- (float)scrollingDeltaX
|
||||
{
|
||||
return _scrollingDeltaX;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the change in points on the y-axis for a mouse movement, unless hasPreciseScrollingDeltas is NO,
|
||||
in which case the change is measured in number of "lines" or "columns" and needs to be multiplied as appropriate
|
||||
to get change in pixels.
|
||||
*/
|
||||
- (float)scrollingDeltaY
|
||||
{
|
||||
return _scrollingDeltaY;
|
||||
}
|
||||
|
||||
- (BOOL)_triggersKeyEquivalent:(CPString)aKeyEquivalent withModifierMask:aKeyEquivalentModifierMask
|
||||
{
|
||||
if (!aKeyEquivalent)
|
||||
return NO;
|
||||
|
||||
if (_CPEventUpperCaseRegex.test(aKeyEquivalent))
|
||||
aKeyEquivalentModifierMask |= CPShiftKeyMask;
|
||||
|
||||
// Windows and Linux don't have command keys, so just switch it to ctrl.
|
||||
if (!CPBrowserIsOperatingSystem(CPMacOperatingSystem) && (aKeyEquivalentModifierMask & CPCommandKeyMask))
|
||||
{
|
||||
aKeyEquivalentModifierMask |= CPControlKeyMask;
|
||||
aKeyEquivalentModifierMask &= ~CPCommandKeyMask;
|
||||
}
|
||||
|
||||
if ((_modifierFlags & (CPShiftKeyMask | CPAlternateKeyMask | CPCommandKeyMask | CPControlKeyMask)) !== aKeyEquivalentModifierMask)
|
||||
return NO;
|
||||
|
||||
// Treat \r and \n as the same key equivalent. See issue #710.
|
||||
if (_characters === CPNewlineCharacter || _characters === CPCarriageReturnCharacter)
|
||||
return CPNewlineCharacter === aKeyEquivalent || CPCarriageReturnCharacter === aKeyEquivalent;
|
||||
|
||||
return [_characters caseInsensitiveCompare:aKeyEquivalent] === CPOrderedSame;
|
||||
}
|
||||
|
||||
- (BOOL)_couldBeKeyEquivalent
|
||||
{
|
||||
if (_type !== CPKeyDown)
|
||||
return NO;
|
||||
|
||||
var characterCount = _characters.length;
|
||||
|
||||
if (!characterCount)
|
||||
return NO;
|
||||
|
||||
if (_modifierFlags & (CPCommandKeyMask | CPControlKeyMask))
|
||||
return YES;
|
||||
|
||||
// Cocoa allows almost any key as a key equivalent unless the first responder is a
|
||||
// text field (presumably a subclass of NSText.)
|
||||
var firstResponderIsText = [[_window firstResponder] isKindOfClass:[CPTextField class]];
|
||||
|
||||
// Some keys are accepted as key equivalents even if the first responder is a text
|
||||
// field.
|
||||
for (var i = 0; i < characterCount; i++)
|
||||
{
|
||||
var c = _characters.charAt(i);
|
||||
|
||||
if ((c >= CPUpArrowFunctionKey && c <= CPModeSwitchFunctionKey) ||
|
||||
c === CPEnterCharacter ||
|
||||
c === CPNewlineCharacter ||
|
||||
c === CPCarriageReturnCharacter ||
|
||||
c === CPEscapeFunctionKey)
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
|
||||
return !firstResponderIsText;
|
||||
// FIXME: More cases? Space?
|
||||
return _type === CPKeyDown &&
|
||||
_modifierFlags & (CPCommandKeyMask | CPControlKeyMask) &&
|
||||
[_characters length] > 0;
|
||||
}
|
||||
|
||||
/*!
|
||||
Return YES if this event is a part of processing a browser controlled cut or paste event
|
||||
where the browser will go ahead and do the work of cutting or pasting within the input
|
||||
element after processing of this event. The implication is that it should not be done by
|
||||
the CPTextField (or whatever else is controlling the input) since this would result in
|
||||
nothing being cut (because the field already cut the text out), or a double paste
|
||||
(because the field pasted as well as the browser).
|
||||
*/
|
||||
- (BOOL)_platformIsEffectingCutOrPaste
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
return _suppressCappuccinoCut || _suppressCappuccinoPaste;
|
||||
#else
|
||||
return NO;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
Generates periodic events every \c aPeriod seconds.
|
||||
|
||||
@param aDelay the number of seconds before the first event
|
||||
@param aPeriod the length of time in seconds between successive events
|
||||
*/
|
||||
+ (void)startPeriodicEventsAfterDelay:(CPTimeInterval)aDelay withPeriod:(CPTimeInterval)aPeriod
|
||||
{
|
||||
_CPEventPeriodicEventPeriod = aPeriod;
|
||||
|
||||
|
||||
// FIXME: OH TIMERS!!!
|
||||
_CPEventPeriodicEventTimer = window.setTimeout(function() { _CPEventPeriodicEventTimer = window.setInterval(_CPEventFirePeriodEvent, aPeriod * 1000.0); }, aDelay * 1000.0);
|
||||
}
|
||||
|
||||
/*!
|
||||
Stops the periodic events from being generated.
|
||||
Stops the periodic events from being generated
|
||||
*/
|
||||
+ (void)stopPeriodicEvents
|
||||
{
|
||||
if (_CPEventPeriodicEventTimer == nil)
|
||||
if (_CPEventPeriodicEventTimer === nil)
|
||||
return;
|
||||
|
||||
|
||||
window.clearTimeout(_CPEventPeriodicEventTimer);
|
||||
|
||||
|
||||
_CPEventPeriodicEventTimer = nil;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
switch (_type)
|
||||
{
|
||||
case CPKeyDown:
|
||||
case CPKeyUp:
|
||||
case CPFlagsChanged:
|
||||
return [CPString stringWithFormat:@"CPEvent: type=%d loc=%@ time=%.1f flags=0x%X win=%@ winNum=%d ctxt=%@ chars=\"%@\" unmodchars=\"%@\" repeat=%d keyCode=%d", _type, CGStringFromPoint(_location), _timestamp, _modifierFlags, _window, _windowNumber, _context, _characters, _charactersIgnoringModifiers, _isARepeat, _keyCode];
|
||||
case CPLeftMouseDown:
|
||||
case CPLeftMouseUp:
|
||||
case CPRightMouseDown:
|
||||
case CPRightMouseUp:
|
||||
case CPMouseMoved:
|
||||
case CPLeftMouseDragged:
|
||||
case CPRightMouseDragged:
|
||||
case CPMouseEntered:
|
||||
case CPMouseExited:
|
||||
return [CPString stringWithFormat:@"CPEvent: type=%d loc=%@ time=%.1f flags=0x%X win=%@ winNum=%d ctxt=%@ evNum=%d click=%d buttonNumber=%d pressure=%f", _type, CGStringFromPoint(_location), _timestamp, _modifierFlags, _window, _windowNumber, _context, _eventNumber, _clickCount, [self buttonNumber], _pressure];
|
||||
default:
|
||||
return [CPString stringWithFormat:@"CPEvent: type=%d loc=%@ time=%.1f flags=0x%X win=%@ winNum=%d ctxt=%@ subtype=%d data1=%d data2=%d", _type, CGStringFromPoint(_location), _timestamp, _modifierFlags, _window, _windowNumber, _context, _subtype, _data1, _data2];
|
||||
}
|
||||
}
|
||||
|
||||
- (CPTrackingArea)trackingArea
|
||||
{
|
||||
if ((_type !== CPMouseEntered) && (_type !== CPMouseExited) && (_type !== CPCursorUpdate))
|
||||
[CPException raise:CPInternalInconsistencyException format:@"You can't call trackingArea for events of type %#x", _type];
|
||||
|
||||
return _trackingArea;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
function _CPEventFirePeriodEvent()
|
||||
{
|
||||
[CPApp sendEvent:[CPEvent otherEventWithType:CPPeriodic location:CGPointMakeZero() modifierFlags:0 timestamp:[CPEvent currentTimestamp] windowNumber:0 context:nil subtype:0 data1:0 data2:0]];
|
||||
[CPApp sendEvent:[CPEvent otherEventWithType:CPPeriodic location:_CGPointMakeZero() modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0]];
|
||||
}
|
||||
|
||||
var CPEventClass = [CPEvent class];
|
||||
@@ -673,3 +502,4 @@ function _CPEventFromNativeMouseEvent(aNativeEvent, anEventType, aPoint, modifie
|
||||
|
||||
return aNativeEvent;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
/*
|
||||
* CPEvent_Constants.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
CPLeftMouseDown = 1;
|
||||
CPLeftMouseUp = 2;
|
||||
CPRightMouseDown = 3;
|
||||
CPRightMouseUp = 4;
|
||||
CPMouseMoved = 5;
|
||||
CPLeftMouseDragged = 6;
|
||||
CPRightMouseDragged = 7;
|
||||
CPMouseEntered = 8;
|
||||
CPMouseExited = 9;
|
||||
CPKeyDown = 10;
|
||||
CPKeyUp = 11;
|
||||
CPFlagsChanged = 12;
|
||||
CPAppKitDefined = 13;
|
||||
CPSystemDefined = 14;
|
||||
CPApplicationDefined = 15;
|
||||
CPPeriodic = 16;
|
||||
CPCursorUpdate = 17;
|
||||
CPScrollWheel = 22;
|
||||
CPOtherMouseDown = 25;
|
||||
CPOtherMouseUp = 26;
|
||||
CPOtherMouseDragged = 27;
|
||||
|
||||
// iPhone Event Types
|
||||
CPTouchStart = 28;
|
||||
CPTouchMove = 29;
|
||||
CPTouchEnd = 30;
|
||||
CPTouchCancel = 31;
|
||||
|
||||
CPAlphaShiftKeyMask = 1 << 16;
|
||||
CPShiftKeyMask = 1 << 17;
|
||||
CPControlKeyMask = 1 << 18;
|
||||
CPAlternateKeyMask = 1 << 19;
|
||||
CPCommandKeyMask = 1 << 20;
|
||||
CPNumericPadKeyMask = 1 << 21;
|
||||
CPHelpKeyMask = 1 << 22;
|
||||
CPFunctionKeyMask = 1 << 23;
|
||||
CPDeviceIndependentModifierFlagsMask = 0xffff0000;
|
||||
|
||||
CPLeftMouseDownMask = 1 << CPLeftMouseDown;
|
||||
CPLeftMouseUpMask = 1 << CPLeftMouseUp;
|
||||
CPRightMouseDownMask = 1 << CPRightMouseDown;
|
||||
CPRightMouseUpMask = 1 << CPRightMouseUp;
|
||||
CPOtherMouseDownMask = 1 << CPOtherMouseDown;
|
||||
CPOtherMouseUpMask = 1 << CPOtherMouseUp;
|
||||
CPMouseMovedMask = 1 << CPMouseMoved;
|
||||
CPLeftMouseDraggedMask = 1 << CPLeftMouseDragged;
|
||||
CPRightMouseDraggedMask = 1 << CPRightMouseDragged;
|
||||
CPOtherMouseDragged = 1 << CPOtherMouseDragged;
|
||||
CPMouseEnteredMask = 1 << CPMouseEntered;
|
||||
CPMouseExitedMask = 1 << CPMouseExited;
|
||||
CPCursorUpdateMask = 1 << CPCursorUpdate;
|
||||
CPKeyDownMask = 1 << CPKeyDown;
|
||||
CPKeyUpMask = 1 << CPKeyUp;
|
||||
CPFlagsChangedMask = 1 << CPFlagsChanged;
|
||||
CPAppKitDefinedMask = 1 << CPAppKitDefined;
|
||||
CPSystemDefinedMask = 1 << CPSystemDefined;
|
||||
CPApplicationDefinedMask = 1 << CPApplicationDefined;
|
||||
CPPeriodicMask = 1 << CPPeriodic;
|
||||
CPScrollWheelMask = 1 << CPScrollWheel;
|
||||
CPAnyEventMask = 0xffffffff;
|
||||
|
||||
CPUpArrowFunctionKey = "\uF700";
|
||||
CPDownArrowFunctionKey = "\uF701";
|
||||
CPLeftArrowFunctionKey = "\uF702";
|
||||
CPRightArrowFunctionKey = "\uF703";
|
||||
CPF1FunctionKey = "\uF704";
|
||||
CPF2FunctionKey = "\uF705";
|
||||
CPF3FunctionKey = "\uF706";
|
||||
CPF4FunctionKey = "\uF707";
|
||||
CPF5FunctionKey = "\uF708";
|
||||
CPF6FunctionKey = "\uF709";
|
||||
CPF7FunctionKey = "\uF70A";
|
||||
CPF8FunctionKey = "\uF70B";
|
||||
CPF9FunctionKey = "\uF70C";
|
||||
CPF10FunctionKey = "\uF70D";
|
||||
CPF11FunctionKey = "\uF70E";
|
||||
CPF12FunctionKey = "\uF70F";
|
||||
CPF13FunctionKey = "\uF710";
|
||||
CPF14FunctionKey = "\uF711";
|
||||
CPF15FunctionKey = "\uF712";
|
||||
CPF16FunctionKey = "\uF713";
|
||||
CPF17FunctionKey = "\uF714";
|
||||
CPF18FunctionKey = "\uF715";
|
||||
CPF19FunctionKey = "\uF716";
|
||||
CPF20FunctionKey = "\uF717";
|
||||
CPF21FunctionKey = "\uF718";
|
||||
CPF22FunctionKey = "\uF719";
|
||||
CPF23FunctionKey = "\uF71A";
|
||||
CPF24FunctionKey = "\uF71B";
|
||||
CPF25FunctionKey = "\uF71C";
|
||||
CPF26FunctionKey = "\uF71D";
|
||||
CPF27FunctionKey = "\uF71E";
|
||||
CPF28FunctionKey = "\uF71F";
|
||||
CPF29FunctionKey = "\uF720";
|
||||
CPF30FunctionKey = "\uF721";
|
||||
CPF31FunctionKey = "\uF722";
|
||||
CPF32FunctionKey = "\uF723";
|
||||
CPF33FunctionKey = "\uF724";
|
||||
CPF34FunctionKey = "\uF725";
|
||||
CPF35FunctionKey = "\uF726";
|
||||
CPInsertFunctionKey = "\uF727";
|
||||
CPDeleteFunctionKey = "\uF728";
|
||||
CPHomeFunctionKey = "\uF729";
|
||||
CPBeginFunctionKey = "\uF72A";
|
||||
CPEndFunctionKey = "\uF72B";
|
||||
CPPageUpFunctionKey = "\uF72C";
|
||||
CPPageDownFunctionKey = "\uF72D";
|
||||
CPPrintScreenFunctionKey = "\uF72E";
|
||||
CPScrollLockFunctionKey = "\uF72F";
|
||||
CPPauseFunctionKey = "\uF730";
|
||||
CPSysReqFunctionKey = "\uF731";
|
||||
CPBreakFunctionKey = "\uF732";
|
||||
CPResetFunctionKey = "\uF733";
|
||||
CPStopFunctionKey = "\uF734";
|
||||
CPMenuFunctionKey = "\uF735";
|
||||
CPUserFunctionKey = "\uF736";
|
||||
CPSystemFunctionKey = "\uF737";
|
||||
CPPrintFunctionKey = "\uF738";
|
||||
CPClearLineFunctionKey = "\uF739";
|
||||
CPClearDisplayFunctionKey = "\uF73A";
|
||||
CPInsertLineFunctionKey = "\uF73B";
|
||||
CPDeleteLineFunctionKey = "\uF73C";
|
||||
CPInsertCharFunctionKey = "\uF73D";
|
||||
CPDeleteCharFunctionKey = "\uF73E";
|
||||
CPPrevFunctionKey = "\uF73F";
|
||||
CPNextFunctionKey = "\uF740";
|
||||
CPSelectFunctionKey = "\uF741";
|
||||
CPExecuteFunctionKey = "\uF742";
|
||||
CPUndoFunctionKey = "\uF743";
|
||||
CPRedoFunctionKey = "\uF744";
|
||||
CPFindFunctionKey = "\uF745";
|
||||
CPHelpFunctionKey = "\uF746";
|
||||
CPModeSwitchFunctionKey = "\uF747";
|
||||
CPEscapeFunctionKey = "\u001B";
|
||||
CPSpaceFunctionKey = "\u0020";
|
||||
|
||||
|
||||
CPDOMEventDoubleClick = "dblclick";
|
||||
CPDOMEventMouseDown = "mousedown";
|
||||
CPDOMEventMouseUp = "mouseup";
|
||||
CPDOMEventMouseMoved = "mousemove";
|
||||
CPDOMEventMouseDragged = "mousedrag";
|
||||
CPDOMEventKeyUp = "keyup";
|
||||
CPDOMEventKeyDown = "keydown";
|
||||
CPDOMEventKeyPress = "keypress";
|
||||
CPDOMEventCopy = "copy";
|
||||
CPDOMEventPaste = "paste";
|
||||
CPDOMEventScrollWheel = "mousewheel";
|
||||
CPDOMEventTouchStart = "touchstart";
|
||||
CPDOMEventTouchMove = "touchmove";
|
||||
CPDOMEventTouchEnd = "touchend";
|
||||
CPDOMEventTouchCancel = "touchcancel";
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* CPFlashMovie.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPFlashMovie
|
||||
|
||||
CPFlashMovie is used to represent a Flash movie in the Cappuccino framework.
|
||||
*/
|
||||
@implementation CPFlashMovie : CPObject
|
||||
{
|
||||
CPString _filename;
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a new Flash movie with the swf at \c aFileName.
|
||||
@param aFilename the swf to load
|
||||
@return the initialized CPFlashMovie
|
||||
*/
|
||||
+ (id)flashMovieWithFile:(CPString)aFilename
|
||||
{
|
||||
return [[self alloc] initWithFile:aFilename];
|
||||
}
|
||||
|
||||
/*!
|
||||
Initializes the Flash movie.
|
||||
@param aFilename the swf to load
|
||||
@return the initialized CPFlashMovie
|
||||
*/
|
||||
- (id)initWithFile:(CPString)aFilename
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
_filename = aFilename;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (CPString)filename
|
||||
{
|
||||
return _filename;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPFlashMovieFilenameKey = "CPFlashMovieFilenameKey";
|
||||
|
||||
@implementation CPFlashMovie (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
_filename = [aCoder decodeObjectForKey:CPFlashMovieFilenameKey];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[aCoder encodeObject:_filename forKey:CPFlashMovieFilenameKey];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,204 @@
|
||||
/*
|
||||
* CPFlashView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPFlashMovie.j"
|
||||
@import "CPView.j"
|
||||
|
||||
#include "Platform/Platform.h"
|
||||
|
||||
var IEFlashCLSID = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
*/
|
||||
@implementation CPFlashView : CPView
|
||||
{
|
||||
CPFlashMovie _flashMovie;
|
||||
|
||||
CPDictionary _params;
|
||||
CPDictionary _paramElements;
|
||||
#if PLATFORM(DOM)
|
||||
DOMElement _DOMParamElement;
|
||||
DOMElement _DOMObjectElement;
|
||||
DOMElement _DOMInnerObjectElement;
|
||||
#endif
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
if (self)
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
if (!CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
{
|
||||
_DOMObjectElement = document.createElement(@"object");
|
||||
_DOMObjectElement.width = @"100%";
|
||||
_DOMObjectElement.height = @"100%";
|
||||
_DOMObjectElement.style.top = @"0px";
|
||||
_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;
|
||||
}
|
||||
|
||||
- (void)setFlashMovie:(CPFlashMovie)aFlashMovie
|
||||
{
|
||||
if (_flashMovie == aFlashMovie)
|
||||
return;
|
||||
|
||||
_flashMovie = aFlashMovie;
|
||||
#if PLATFORM(DOM)
|
||||
if (!CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
{
|
||||
_DOMParamElement.value = [aFlashMovie filename];
|
||||
_DOMInnerObjectElement.data = [aFlashMovie filename];
|
||||
}
|
||||
else
|
||||
[self _rebuildIEObjects];
|
||||
#endif
|
||||
}
|
||||
|
||||
- (CPFlashMovie)flashMovie
|
||||
{
|
||||
return _flashMovie;
|
||||
}
|
||||
|
||||
- (void)setFlashVars:(CPDictionary)aDictionary
|
||||
{
|
||||
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];
|
||||
}
|
||||
|
||||
- (CPDictionary)flashVars
|
||||
{
|
||||
return [_params objectForKey:@"flashvars"];
|
||||
}
|
||||
|
||||
- (void)setParameters:(CPDictionary)aDictionary
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
if (_paramElements && !CPBrowserIsEngine(CPInternetExplorerBrowserEngine))
|
||||
{
|
||||
var elements = [_paramElements allValues],
|
||||
count = [elements count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
_DOMObjectElement.removeChild([elements objectAtIndex:i]);
|
||||
}
|
||||
#endif
|
||||
_params = aDictionary;
|
||||
#if PLATFORM(DOM)
|
||||
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];
|
||||
}
|
||||
}
|
||||
else
|
||||
[self _rebuildIEObjects];
|
||||
#endif
|
||||
}
|
||||
|
||||
- (CPDictionary)parameters
|
||||
{
|
||||
return _params;
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
- (void)_rebuildIEObjects
|
||||
{
|
||||
_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
|
||||
|
||||
- (void)mouseDragged:(CPEvent)anEvent
|
||||
{
|
||||
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
|
||||
}
|
||||
|
||||
- (void)mouseUp:(CPEvent)anEvent
|
||||
{
|
||||
[[[self window] platformWindow] _propagateCurrentDOMEvent:YES];
|
||||
}
|
||||
|
||||
@end
|
||||
+46
-530
@@ -20,448 +20,98 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPBundle.j>
|
||||
var _CPFonts = {},
|
||||
_CPFontSystemFontFace = @"Arial, sans-serif",
|
||||
_CPWrapRegExp = new RegExp("\\s*,\\s*", "g");
|
||||
|
||||
@import "CPView.j"
|
||||
@import "CPFontDescriptor.j"
|
||||
@import "_CPObject+Theme.j"
|
||||
@import "CPControl.j"
|
||||
|
||||
CPFontDefaultSystemFontFace = @"Arial, sans-serif";
|
||||
CPFontDefaultSystemFontSize = 12;
|
||||
#define _CPCreateCSSString(aName, aSize, isBold) (isBold ? @"bold " : @"") + ROUND(aSize) + @"px " + ((aName === _CPFontSystemFontFace) ? aName : (@"\"" + aName.replace(_CPWrapRegExp, '", "') + @"\", " + _CPFontSystemFontFace))
|
||||
#define _CPCachedFont(aName, aSize, isBold) _CPFonts[_CPCreateCSSString(aName, aSize, isBold)]
|
||||
|
||||
/*!
|
||||
To create a font of a size that will dynamically reflect the current
|
||||
system font size, use this for the size argument.
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPFont
|
||||
|
||||
The CPFont class allows control of the fonts used for displaying text anywhere on the screen. The primary method for getting a particular font is through one of the class methods that take a name and/or size as arguments, and return the appropriate CPFont.
|
||||
*/
|
||||
CPFontCurrentSystemSize = -1;
|
||||
|
||||
// For internal use only by this class and subclasses
|
||||
_CPFontSystemFacePlaceholder = "_CPFontSystemFacePlaceholder";
|
||||
|
||||
var _CPFontCache = {},
|
||||
_CPSystemFontCache = {},
|
||||
_CPFontSystemFontFace = CPFontDefaultSystemFontFace,
|
||||
_CPFontSystemFontSize = CPFontDefaultSystemFontSize,
|
||||
_CPFontSystemFontSizeSmall = CPFontDefaultSystemFontSize - 1,
|
||||
_CPFontSystemFontSizeMini = CPFontDefaultSystemFontSize - 2,
|
||||
_CPFontFallbackFaces = CPFontDefaultSystemFontFace.split(", "),
|
||||
_CPFontStripRegExp = new RegExp("(^\\s*[\"']?|[\"']?\\s*$)", "g"),
|
||||
_CPFontSystemFontFaceSpecified = NO;
|
||||
|
||||
|
||||
#define _CPRealFontSize(aSize) (aSize <= 0 ? _CPFontSystemFontSize : aSize)
|
||||
#define _CPFontNormalizedNames(aName) _CPFontNormalizedNameArray(aName).join(", ")
|
||||
#define _CPCachedFont(aName, aSize, isBold, isItalic) _CPFontCache[_CPFontCreateCSSString(_CPFontNormalizedNames(aName), aSize, isBold, isItalic)]
|
||||
#define _CPUserFont(aName, aSize, isBold, isItalic) _CPCachedFont(aName, aSize, isBold, isItalic) || [[CPFont alloc] _initWithName:aName size:aSize bold:isBold italic:isItalic system:NO]
|
||||
|
||||
#define _CPSystemFontCacheKey(aSize, isBold) (String(aSize) + (isBold ? "b" : ""))
|
||||
#define _CPCachedSystemFont(aSize, isBold) _CPSystemFontCache[_CPSystemFontCacheKey(aSize, isBold)]
|
||||
#define _CPSystemFont(aSize, isBold) (_CPCachedSystemFont(aSize, isBold) || [[CPFont alloc] _initWithName:_CPFontSystemFacePlaceholder size:aSize bold:isBold italic:NO system:YES])
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPFont
|
||||
|
||||
The CPFont class allows control of the fonts used for displaying text anywhere on the screen.
|
||||
The primary method for getting a particular font is through one of the class methods that take
|
||||
a name and/or size as arguments, and return the appropriate CPFont.
|
||||
|
||||
### System fonts
|
||||
When you create a font using \c -systemFontOfSize: or \c -boldSystemFontOfSize:, a proxy font is
|
||||
created that always refers to the current system font face and size. By default the system
|
||||
font face/size is Arial 12px, with a fallback to sans-serif 12px. You may configure this at
|
||||
runtime in two ways:
|
||||
|
||||
- By sending [CPFont setSystemFontFace:<face>] and/or [CPFont setSystemFontSize:<size>].
|
||||
Note that if you change the system font face or size during runtime, the next time
|
||||
any view using a system font is redrawn, it will show the new font.
|
||||
- By configuring Info.plist for your application or for AppKit. You can set the font face
|
||||
by adding a CPSystemFontFace string item to the Info.plist, and you can set the font size
|
||||
by adding a CPSystemFontSize integer item to the Info.plist.
|
||||
|
||||
Note that in either case, you can specify a comma-delimited list of fonts as the font face.
|
||||
Do not quote enclose font faces that contain spaces, that is done automatically when a CSS
|
||||
representation of a font is requested.
|
||||
|
||||
The browser will use the first available font in the list you supply. CPFont always ensures
|
||||
that Arial and sans-serif are in the CSS representation of a font as a fallback, so there is
|
||||
no need to add them to the end of your font list.
|
||||
|
||||
### nib2cib conversion
|
||||
Fonts are converted by nib2cib according to the following algorithm:
|
||||
|
||||
- If the font family is Lucida Grande, then a system font will be created.
|
||||
- If the font is Lucida Grande 13 (plain), the "default" font will be used at runtime.
|
||||
The default font is taken from the "font" theme attribute if one exists,
|
||||
otherwise from the current system font face and size.
|
||||
- Lucida Grande of any size other than 13 will retain its size.
|
||||
- Fonts using any family other than Lucida Grande will be used as is, including the size.
|
||||
|
||||
### Using custom web fonts
|
||||
The configurability of CPFont makes it easy to use a custom web font as the system font.
|
||||
For example, if you want to use the google font Asap as the system font, you would do the
|
||||
following:
|
||||
|
||||
- Add a <link> to the <head> of index-debug.html and index.html:
|
||||
@code
|
||||
<link href='http://fonts.googleapis.com/css?family=Asap:400,700' rel='stylesheet' type='text/css'>
|
||||
@endcode
|
||||
- Specify Asap as the system font in Info.plist by adding the following item:
|
||||
@code
|
||||
<key>CPSystemFontFace</key>
|
||||
<string>Asap</string>
|
||||
@endcode
|
||||
*/
|
||||
@implementation CPFont : CPObject <CPTheme>
|
||||
@implementation CPFont : CPObject
|
||||
{
|
||||
CPString _name;
|
||||
float _size;
|
||||
float _ascender;
|
||||
float _descender;
|
||||
float _lineHeight;
|
||||
BOOL _isBold @accessors(readonly, getter=isBold);
|
||||
BOOL _isItalic @accessors(readonly, getter=isItalic);
|
||||
BOOL _isSystem @accessors(readonly, getter=isSystem);
|
||||
|
||||
BOOL _isBold;
|
||||
|
||||
CPString _cssString;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return @"font";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"system-font-face": [CPNull null],
|
||||
@"system-font-style": [CPNull null],
|
||||
@"system-font-size-regular": [CPNull null],
|
||||
@"system-font-size-small": [CPNull null],
|
||||
@"system-font-size-mini": [CPNull null]
|
||||
};
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPFont class])
|
||||
return;
|
||||
|
||||
var systemFontFace = [[CPBundle mainBundle] objectForInfoDictionaryKey:@"CPSystemFontFace"];
|
||||
|
||||
if (!systemFontFace)
|
||||
systemFontFace = [[CPBundle bundleForClass:[CPView class]] objectForInfoDictionaryKey:@"CPSystemFontFace"];
|
||||
|
||||
if (systemFontFace)
|
||||
{
|
||||
_CPFontSystemFontFace = _CPFontNormalizedNames(systemFontFace);
|
||||
_CPFontSystemFontFaceSpecified = YES;
|
||||
}
|
||||
|
||||
var systemFontSize = [[CPBundle mainBundle] objectForInfoDictionaryKey:@"CPSystemFontSize"];
|
||||
|
||||
if (!systemFontSize)
|
||||
systemFontSize = [[CPBundle bundleForClass:[CPView class]] objectForInfoDictionaryKey:@"CPSystemFontSize"];
|
||||
|
||||
if (systemFontSize)
|
||||
{
|
||||
_CPFontSystemFontSize = systemFontSize;
|
||||
_CPFontSystemFontFaceSpecified = YES;
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)initializeSystemFontFromTheme:(CPTheme)aTheme
|
||||
{
|
||||
// If something was specified via +initialize (from an Info.plist file), don't do anything
|
||||
if (_CPFontSystemFontFaceSpecified)
|
||||
return;
|
||||
|
||||
// Reset all system font caches
|
||||
_CPSystemFontCache = {};
|
||||
|
||||
// Now, try to get information from the theme
|
||||
var systemFontFace = [aTheme valueForAttributeWithName:@"system-font-face" forClass:[CPFont class]];
|
||||
|
||||
if (systemFontFace)
|
||||
{
|
||||
[self _invalidateSystemFontCache];
|
||||
_CPFontSystemFontFace = _CPFontNormalizedNames(systemFontFace);
|
||||
}
|
||||
|
||||
var systemFontSize = [aTheme valueForAttributeWithName:@"system-font-size-regular" forClass:[CPFont class]];
|
||||
|
||||
if (systemFontSize)
|
||||
{
|
||||
[self _invalidateSystemFontCache];
|
||||
_CPFontSystemFontSize = systemFontSize;
|
||||
}
|
||||
|
||||
systemFontSize = [aTheme valueForAttributeWithName:@"system-font-size-small" forClass:[CPFont class]];
|
||||
|
||||
if (systemFontSize)
|
||||
{
|
||||
[self _invalidateSystemFontCache];
|
||||
_CPFontSystemFontSizeSmall = systemFontSize;
|
||||
}
|
||||
|
||||
systemFontSize = [aTheme valueForAttributeWithName:@"system-font-size-mini" forClass:[CPFont class]];
|
||||
|
||||
if (systemFontSize)
|
||||
{
|
||||
[self _invalidateSystemFontCache];
|
||||
_CPFontSystemFontSizeMini = systemFontSize;
|
||||
}
|
||||
|
||||
// Is there something to add to the global syle definition ?
|
||||
var systemFontStyle = [aTheme valueForAttributeWithName:@"system-font-style" forClass:[CPFont class]];
|
||||
|
||||
if (systemFontStyle)
|
||||
{
|
||||
// Yes, so install it in the DOM Style element
|
||||
document.getElementsByTagName("STYLE")[0].innerHTML += "\n" + [aTheme setCSSResourcesPathInString:systemFontStyle];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the default system font face, which may consist of several comma-separated family names.
|
||||
*/
|
||||
+ (CPString)systemFontFace
|
||||
{
|
||||
return _CPFontSystemFontFace;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the default system font face, which may consist of several comma-separated family names.
|
||||
*/
|
||||
+ (CPString)setSystemFontFace:(CPString)aFace
|
||||
{
|
||||
var normalizedFaces = _CPFontNormalizedNames(aFace);
|
||||
|
||||
if (normalizedFaces === _CPFontSystemFontFace)
|
||||
return;
|
||||
|
||||
[self _invalidateSystemFontCache];
|
||||
_CPFontSystemFontFace = aFace;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the default system font size.
|
||||
*/
|
||||
+ (float)systemFontSize
|
||||
{
|
||||
return _CPFontSystemFontSize;
|
||||
}
|
||||
|
||||
+ (CPFont)systemFontForControlSize:(CPControlSize)aSize
|
||||
{
|
||||
switch (aSize)
|
||||
{
|
||||
case CPSmallControlSize:
|
||||
return [self systemFontOfSize:_CPFontSystemFontSizeSmall];
|
||||
|
||||
case CPMiniControlSize:
|
||||
return [self systemFontOfSize:_CPFontSystemFontSizeMini];
|
||||
|
||||
case CPRegularControlSize:
|
||||
default:
|
||||
return [self systemFontOfSize:_CPFontSystemFontSize];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the default system font size.
|
||||
*/
|
||||
+ (float)setSystemFontSize:(float)size
|
||||
{
|
||||
if (size > 0 && size !== _CPFontSystemFontSize)
|
||||
{
|
||||
[self _invalidateSystemFontCache];
|
||||
_CPFontSystemFontSize = size;
|
||||
}
|
||||
}
|
||||
|
||||
+ (void)_invalidateSystemFontCache
|
||||
{
|
||||
var systemSize = String(_CPFontSystemFontSize),
|
||||
currentSize = String(CPFontCurrentSystemSize);
|
||||
|
||||
for (var key in _CPSystemFontCache)
|
||||
{
|
||||
if (_CPSystemFontCache.hasOwnProperty(key) &&
|
||||
(key.indexOf(systemSize) === 0 || key.indexOf(currentSize) === 0))
|
||||
{
|
||||
delete _CPSystemFontCache[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a font with the specified name and size.
|
||||
@param aName the name of the font
|
||||
@param aSize the size of the font (in px). 0 or negative will create a font
|
||||
in the current system font size.
|
||||
@param aSize the size of the font (in points)
|
||||
@return the requested font
|
||||
*/
|
||||
+ (CPFont)fontWithName:(CPString)aName size:(float)aSize
|
||||
{
|
||||
return _CPUserFont(aName, aSize <= 0 ? _CPFontSystemFontSize : aSize, NO, NO);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a font with the specified name, size and style.
|
||||
@param aName the name of the font
|
||||
@param aSize the size of the font (in px). 0 or negative will create a font
|
||||
in the current system font size.
|
||||
@param italic whether the font should be italicized
|
||||
@return the requested font
|
||||
*/
|
||||
+ (CPFont)fontWithName:(CPString)aName size:(float)aSize italic:(BOOL)italic
|
||||
{
|
||||
return _CPUserFont(aName, aSize <= 0 ? _CPFontSystemFontSize : aSize, NO, italic);
|
||||
return _CPCachedFont(aName, aSize, NO) || [[CPFont alloc] _initWithName:aName size:aSize bold:NO];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a bold font with the specified name and size.
|
||||
@param aName the name of the font
|
||||
@param aSize the size of the font (in px). 0 or negative will create a font
|
||||
in the current system font size.
|
||||
@param aSize the size of the font (in points)
|
||||
@return the requested bold font
|
||||
*/
|
||||
+ (CPFont)boldFontWithName:(CPString)aName size:(float)aSize
|
||||
{
|
||||
return _CPUserFont(aName, aSize <= 0 ? _CPFontSystemFontSize : aSize, YES, NO);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a bold font with the specified name, size and style.
|
||||
@param aName the name of the font
|
||||
@param aSize the size of the font (in px). 0 or negative will create a font
|
||||
in the current system font size.
|
||||
@param italic whether the font should be italicized
|
||||
@return the requested font
|
||||
*/
|
||||
+ (CPFont)boldFontWithName:(CPString)aName size:(float)aSize italic:(BOOL)italic
|
||||
{
|
||||
return _CPUserFont(aName, aSize <= 0 ? _CPFontSystemFontSize : aSize, YES, italic);
|
||||
}
|
||||
|
||||
/*!
|
||||
Internal font getter like fontWithName:size:italic: with a bold selector.
|
||||
*/
|
||||
+ (CPFont)_fontWithName:(CPString)aName size:(float)aSize bold:(BOOL)bold italic:(BOOL)italic
|
||||
{
|
||||
return _CPUserFont(aName, aSize <= 0 ? _CPFontSystemFontSize : aSize, bold, italic);
|
||||
return _CPCachedFont(aName, aSize, YES) || [[CPFont alloc] _initWithName:aName size:aSize bold:YES];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the system font scaled to the specified size
|
||||
@param aSize the size of the font (in px). 0 creates a static font
|
||||
in the current system font size. Negative creates a font
|
||||
that dynamically tracks the current system font size.
|
||||
@param aSize the size of the font (in points)
|
||||
@return the requested system font
|
||||
*/
|
||||
+ (CPFont)systemFontOfSize:(CGSize)aSize
|
||||
+ (CPFont)systemFontOfSize:(CPSize)aSize
|
||||
{
|
||||
return _CPSystemFont(aSize === 0 ? _CPFontSystemFontSize : aSize, NO);
|
||||
return _CPCachedFont(_CPFontSystemFontFace, aSize, NO) || [[CPFont alloc] _initWithName:_CPFontSystemFontFace size:aSize bold:NO];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the bold system font scaled to the specified size
|
||||
@param aSize the size of the font (in px). 0 creates a static font
|
||||
in the current system font size. Negative creates a font
|
||||
that dynamically tracks the current system font size.
|
||||
@param aSize the size of the font (in points)
|
||||
@return the requested bold system font
|
||||
*/
|
||||
+ (CPFont)boldSystemFontOfSize:(CGSize)aSize
|
||||
+ (CPFont)boldSystemFontOfSize:(CPSize)aSize
|
||||
{
|
||||
return _CPSystemFont(aSize === 0 ? _CPFontSystemFontSize : aSize, YES);
|
||||
return _CPCachedFont(_CPFontSystemFontFace, aSize, YES) || [[CPFont alloc] _initWithName:_CPFontSystemFontFace size:aSize bold:YES];
|
||||
}
|
||||
|
||||
- (id)_initWithName:(CPString)aName size:(float)aSize bold:(BOOL)isBold italic:(BOOL)isItalic system:(BOOL)isSystem
|
||||
{
|
||||
/* FIXME Font Descriptor
|
||||
@ignore
|
||||
*/
|
||||
- (id)_initWithName:(CPString)aName size:(float)aSize bold:(BOOL)isBold
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_name = aName;
|
||||
_size = aSize;
|
||||
_ascender = 0;
|
||||
_descender = 0;
|
||||
_lineHeight = 0;
|
||||
_isBold = isBold;
|
||||
_isItalic = isItalic;
|
||||
_isSystem = isSystem;
|
||||
|
||||
_theme = [CPTheme defaultTheme];
|
||||
_themeState = CPThemeStateNormal;
|
||||
[self _loadThemeAttributes];
|
||||
|
||||
if (isSystem)
|
||||
{
|
||||
_name = aName;
|
||||
_cssString = _CPFontCreateCSSString(_CPFontSystemFontFace, _size, _isBold, _isItalic);
|
||||
_CPSystemFontCache[_CPSystemFontCacheKey(_size, _isBold)] = self;
|
||||
}
|
||||
else
|
||||
{
|
||||
_name = _CPFontNormalizedNames(aName);
|
||||
_cssString = _CPFontCreateCSSString(_name, _size, _isBold, _isItalic);
|
||||
_CPFontCache[_cssString] = self;
|
||||
}
|
||||
|
||||
_cssString = _CPCreateCSSString(_name, _size, _isBold);
|
||||
|
||||
_CPFonts[_cssString] = self;
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the distance of the longest ascender's top y-coordinate from the baseline (in CSS px)
|
||||
*/
|
||||
- (float)ascender
|
||||
{
|
||||
var font = _isSystem ? _CPSystemFont(_size, _isBold) : self;
|
||||
|
||||
if (!font._ascender)
|
||||
[font _getMetrics];
|
||||
|
||||
return font._ascender;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the bottom y coordinate (in CSS px), offset from the baseline, of the receiver's longest descender.
|
||||
Thus, if the longest descender extends 2 px below the baseline, descender will return –2.
|
||||
*/
|
||||
- (float)descender
|
||||
{
|
||||
var font = _isSystem ? _CPSystemFont(_size, _isBold) : self;
|
||||
|
||||
if (!font._descender)
|
||||
[font _getMetrics];
|
||||
|
||||
return font._descender;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the default line height.
|
||||
|
||||
NOTE: This was moved from NSFont to NSLayoutManager in Cocoa, but since there is no CPLayoutManager, it has been kept here.
|
||||
*/
|
||||
- (float)defaultLineHeightForFont
|
||||
{
|
||||
var font = _isSystem ? _CPSystemFont(_size, _isBold) : self;
|
||||
|
||||
if (!font._lineHeight)
|
||||
[font _getMetrics];
|
||||
|
||||
return font._lineHeight;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the font size (in CSS px)
|
||||
Returns the font size (in points)
|
||||
*/
|
||||
- (float)size
|
||||
{
|
||||
return _CPRealFontSize(_size);
|
||||
return _size;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -469,9 +119,7 @@ following:
|
||||
*/
|
||||
- (CPString)cssString
|
||||
{
|
||||
var font = _isSystem ? _CPSystemFont(_size, _isBold) : self;
|
||||
|
||||
return font._cssString;
|
||||
return _cssString;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -479,101 +127,24 @@ following:
|
||||
*/
|
||||
- (CPString)familyName
|
||||
{
|
||||
if (_isSystem)
|
||||
return _CPFontSystemFontFace;
|
||||
|
||||
return _name;
|
||||
}
|
||||
|
||||
- (BOOL)isSystemSize
|
||||
{
|
||||
return _size <= 0;
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)anObject
|
||||
{
|
||||
return [anObject isKindOfClass:[CPFont class]] && [anObject cssString] === _cssString;
|
||||
return [anObject isKindOfClass:[CPFont class]] && [anObject cssString] === [self cssString];
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return [CPString stringWithFormat:@"%@ %@", [super description], [self cssString]];
|
||||
}
|
||||
|
||||
- (id)copy
|
||||
{
|
||||
return [[CPFont alloc] _initWithName:_name size:_size bold:_isBold italic:_isItalic system:_isSystem];
|
||||
}
|
||||
|
||||
- (void)_getMetrics
|
||||
{
|
||||
var metrics = [CPString metricsOfFont:self];
|
||||
|
||||
_ascender = [metrics objectForKey:@"ascender"];
|
||||
_descender = [metrics objectForKey:@"descender"];
|
||||
_lineHeight = [metrics objectForKey:@"lineHeight"];
|
||||
}
|
||||
|
||||
- (CPControlSize)controlSizeCorrespondingToFontSize
|
||||
{
|
||||
switch (_size)
|
||||
{
|
||||
case _CPFontSystemFontSizeSmall:
|
||||
return CPSmallControlSize;
|
||||
|
||||
case _CPFontSystemFontSizeMini:
|
||||
return CPMiniControlSize;
|
||||
|
||||
default:
|
||||
// If we can't find a corresponding size, return regular control size
|
||||
return CPRegularControlSize;
|
||||
}
|
||||
return [CPString stringWithFormat:@"%@ %@ %f pt.", [super description], [self familyName], [self size]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPFont(DescriptorAdditions)
|
||||
|
||||
- (id)_initWithFontDescriptor:(CPFontDescriptor)fontDescriptor
|
||||
{
|
||||
var aName = [fontDescriptor objectForKey: CPFontNameAttribute] ,
|
||||
aSize = [fontDescriptor pointSize],
|
||||
isBold = [fontDescriptor symbolicTraits] & CPFontBoldTrait,
|
||||
isItalic = [fontDescriptor symbolicTraits] & CPFontItalicTrait;
|
||||
|
||||
return [self _initWithName:aName size:aSize bold:isBold italic:isItalic system:NO];
|
||||
}
|
||||
|
||||
+ (CPFont)fontWithDescriptor:(CPFontDescriptor)fontDescriptor size:(float)aSize
|
||||
{
|
||||
var aName = [fontDescriptor objectForKey: CPFontNameAttribute],
|
||||
isBold = [fontDescriptor symbolicTraits] & CPFontBoldTrait,
|
||||
isItalic = [fontDescriptor symbolicTraits] & CPFontItalicTrait;
|
||||
|
||||
return [self _fontWithName:aName size:aSize || [fontDescriptor pointSize] bold:isBold italic:isItalic];
|
||||
}
|
||||
|
||||
- (CPFontDescriptor)fontDescriptor
|
||||
{
|
||||
var traits = 0;
|
||||
|
||||
if ([self isBold])
|
||||
traits |= CPFontBoldTrait;
|
||||
|
||||
if ([self isItalic])
|
||||
traits |= CPFontItalicTrait;
|
||||
|
||||
return [[CPFontDescriptor fontDescriptorWithName:_name size:_size] fontDescriptorWithSymbolicTraits:traits];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
var CPFontNameKey = @"CPFontNameKey",
|
||||
CPFontSizeKey = @"CPFontSizeKey",
|
||||
CPFontIsBoldKey = @"CPFontIsBoldKey",
|
||||
CPFontIsItalicKey = @"CPFontIsItalicKey",
|
||||
CPFontIsSystemKey = @"CPFontIsSystemKey";
|
||||
var CPFontNameKey = @"CPFontNameKey",
|
||||
CPFontSizeKey = @"CPFontSizeKey",
|
||||
CPFontIsBoldKey = @"CPFontIsBoldKey";
|
||||
|
||||
@implementation CPFont (CPCoding)
|
||||
|
||||
@@ -584,17 +155,9 @@ var CPFontNameKey = @"CPFontNameKey",
|
||||
*/
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
var fontName = [aCoder decodeObjectForKey:CPFontNameKey],
|
||||
size = [aCoder decodeFloatForKey:CPFontSizeKey],
|
||||
isBold = [aCoder decodeBoolForKey:CPFontIsBoldKey],
|
||||
isItalic = [aCoder decodeBoolForKey:CPFontIsItalicKey],
|
||||
isSystem = [aCoder decodeBoolForKey:CPFontIsSystemKey];
|
||||
|
||||
self = [self _initWithName:fontName size:size bold:isBold italic:isItalic system:isSystem];
|
||||
|
||||
[self _decodeThemeObjectsWithCoder:aCoder];
|
||||
|
||||
return self;
|
||||
return [self _initWithName:[aCoder decodeObjectForKey:CPFontNameKey]
|
||||
size:[aCoder decodeFloatForKey:CPFontSizeKey]
|
||||
bold:[aCoder decodeBoolForKey:CPFontIsBoldKey]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -606,53 +169,6 @@ var CPFontNameKey = @"CPFontNameKey",
|
||||
[aCoder encodeObject:_name forKey:CPFontNameKey];
|
||||
[aCoder encodeFloat:_size forKey:CPFontSizeKey];
|
||||
[aCoder encodeBool:_isBold forKey:CPFontIsBoldKey];
|
||||
[aCoder encodeBool:_isItalic forKey:CPFontIsItalicKey];
|
||||
[aCoder encodeBool:_isSystem forKey:CPFontIsSystemKey];
|
||||
|
||||
[self _encodeThemeObjectsWithCoder:aCoder];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
// aName must be normalized
|
||||
var _CPFontCreateCSSString = function(aName, aSize, isBold, isItalic)
|
||||
{
|
||||
var properties = (isItalic ? "italic " : "") + (isBold ? "bold " : "") + _CPRealFontSize(aSize) + "px ";
|
||||
|
||||
return properties + _CPFontConcatNameWithFallback(aName);
|
||||
};
|
||||
|
||||
var _CPFontConcatNameWithFallback = function(aName)
|
||||
{
|
||||
var names = _CPFontNormalizedNameArray(aName),
|
||||
fallbackFaces = _CPFontFallbackFaces.slice(0);
|
||||
|
||||
// Remove the fallback names used in the names passed in
|
||||
for (var i = 0; i < names.length; ++i)
|
||||
{
|
||||
for (var j = 0; j < fallbackFaces.length; ++j)
|
||||
{
|
||||
if (names[i].toLowerCase() === fallbackFaces[j].toLowerCase())
|
||||
{
|
||||
fallbackFaces.splice(j, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (names[i].indexOf(" ") > 0)
|
||||
names[i] = '"' + names[i] + '"';
|
||||
}
|
||||
|
||||
return names.concat(fallbackFaces).join(", ");
|
||||
};
|
||||
|
||||
var _CPFontNormalizedNameArray = function(aName)
|
||||
{
|
||||
var names = aName.split(",");
|
||||
|
||||
for (var i = 0; i < names.length; ++i)
|
||||
names[i] = names[i].replace(_CPFontStripRegExp, "");
|
||||
|
||||
return names;
|
||||
};
|
||||
|
||||
+62
-370
@@ -22,61 +22,18 @@
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "CPFont.j"
|
||||
@import "CPFontDescriptor.j"
|
||||
|
||||
@global CPApp
|
||||
@class CPFontPanel
|
||||
|
||||
CPItalicFontMask = 1 << 0;
|
||||
CPBoldFontMask = 1 << 1;
|
||||
CPUnboldFontMask = 1 << 2;
|
||||
CPNonStandardCharacterSetFontMask = 1 << 3;
|
||||
CPNarrowFontMask = 1 << 4;
|
||||
CPExpandedFontMask = 1 << 5;
|
||||
CPCondensedFontMask = 1 << 6;
|
||||
CPSmallCapsFontMask = 1 << 7;
|
||||
CPPosterFontMask = 1 << 8;
|
||||
CPCompressedFontMask = 1 << 9;
|
||||
CPFixedPitchFontMask = 1 << 10;
|
||||
CPUnitalicFontMask = 1 << 24;
|
||||
@import <AppKit/CPFont.j>
|
||||
|
||||
|
||||
var CPSharedFontManager = nil,
|
||||
CPFontManagerFactory = nil,
|
||||
CPFontPanelFactory = nil;
|
||||
|
||||
/*
|
||||
modifyFont: sender's tag
|
||||
*/
|
||||
CPNoFontChangeAction = 0;
|
||||
CPViaPanelFontAction = 1;
|
||||
CPAddTraitFontAction = 2;
|
||||
CPSizeUpFontAction = 3;
|
||||
CPSizeDownFontAction = 4;
|
||||
CPHeavierFontAction = 5;
|
||||
CPLighterFontAction = 6;
|
||||
CPRemoveTraitFontAction = 7;
|
||||
CPFontManagerFactory = Nil;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
*/
|
||||
@implementation CPFontManager : CPObject
|
||||
{
|
||||
CPArray _availableFonts;
|
||||
|
||||
id _target @accessors(property=target);
|
||||
SEL _action @accessors(property=action);
|
||||
|
||||
id _delegate @accessors(property=delegate);
|
||||
|
||||
CPFont _selectedFont;
|
||||
BOOL _multiple @accessors(getter=isMultiple, setter=setMultiple:);
|
||||
|
||||
CPDictionary _activeChange;
|
||||
|
||||
unsigned _fontAction;
|
||||
CPArray _availableFonts;
|
||||
}
|
||||
|
||||
// Getting the Shared Font Manager
|
||||
@@ -88,7 +45,7 @@ CPRemoveTraitFontAction = 7;
|
||||
{
|
||||
if (!CPSharedFontManager)
|
||||
CPSharedFontManager = [[CPFontManagerFactory alloc] init];
|
||||
|
||||
|
||||
return CPSharedFontManager;
|
||||
}
|
||||
|
||||
@@ -101,25 +58,6 @@ CPRemoveTraitFontAction = 7;
|
||||
{
|
||||
CPFontManagerFactory = aClass;
|
||||
}
|
||||
/*!
|
||||
Sets the class that will be used to create the application's
|
||||
Font panel.
|
||||
*/
|
||||
+ (void)setFontPanelFactory:(Class)aClass
|
||||
{
|
||||
CPFontPanelFactory = aClass;
|
||||
}
|
||||
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_action = @selector(changeFont:);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns an array of the available fonts
|
||||
@@ -127,10 +65,7 @@ CPRemoveTraitFontAction = 7;
|
||||
- (CPArray)availableFonts
|
||||
{
|
||||
if (!_availableFonts)
|
||||
{
|
||||
_availableFonts = [];
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
{
|
||||
_CPFontDetectSpan = document.createElement("span");
|
||||
_CPFontDetectSpan.fontSize = "24px";
|
||||
_CPFontDetectSpan.appendChild(document.createTextNode("mmmmmmmmmml"));
|
||||
@@ -139,19 +74,15 @@ CPRemoveTraitFontAction = 7;
|
||||
div.style.top = "-1000px";
|
||||
div.appendChild(_CPFontDetectSpan);
|
||||
document.getElementsByTagName("body")[0].appendChild(div);
|
||||
|
||||
_CPFontDetectReferenceFonts = _CPFontDetectPickTwoDifferentFonts(["monospace", "serif", "sans-serif", "cursive"]);
|
||||
|
||||
for (var i = 0; i < _CPFontDetectAllFonts.length; i++)
|
||||
{
|
||||
|
||||
_CPFontDetectReferenceFonts = _CPFontDetectPickTwoDifferentFonts(["monospace", "serif", "sans-serif", "cursive"]);
|
||||
|
||||
_availableFonts = [];
|
||||
for (var i = 0; i < _CPFontDetectAllFonts.length; i++) {
|
||||
var available = _CPFontDetectFontAvailable(_CPFontDetectAllFonts[i]);
|
||||
if (available)
|
||||
if (available)
|
||||
_availableFonts.push(_CPFontDetectAllFonts[i]);
|
||||
}
|
||||
#else
|
||||
// If there's no font detection, just assume all fonts are available.
|
||||
_availableFonts = _CPFontDetectAllFonts;
|
||||
#endif
|
||||
}
|
||||
return _availableFonts;
|
||||
}
|
||||
@@ -165,318 +96,79 @@ CPRemoveTraitFontAction = 7;
|
||||
return _CPFontDetectFontAvailable(aFontName);
|
||||
}
|
||||
|
||||
- (void)setSelectedFont:(CPFont)aFont isMultiple:(BOOL)aFlag
|
||||
{
|
||||
_selectedFont = aFont;
|
||||
_multiple = aFlag;
|
||||
|
||||
// TODO Notify CPFontPanel when it exists.
|
||||
}
|
||||
|
||||
- (CPFont)selectedFont
|
||||
{
|
||||
return _selectedFont;
|
||||
}
|
||||
|
||||
- (int)weightOfFont:(CPFont)aFont
|
||||
{
|
||||
// TODO Weight 5 is a normal of book weight and 9 and above is bold, but it would be nice to be more
|
||||
// precise than that.
|
||||
return [aFont isBold] ? 9 : 5;
|
||||
}
|
||||
|
||||
- (CPFontTraitMask)traitsOfFont:(CPFont)aFont
|
||||
{
|
||||
return ([aFont isBold] ? CPBoldFontMask : 0) | ([aFont isItalic] ? CPItalicFontMask : 0);
|
||||
}
|
||||
|
||||
- (CPFont)convertFont:(CPFont)aFont toFace:(CPString)aTypeface
|
||||
{
|
||||
if (!aFont)
|
||||
return nil;
|
||||
|
||||
var shouldBeBold = [aFont isBold],
|
||||
shouldBeItalic = [aFont isItalic],
|
||||
shouldBeSize = [aFont size];
|
||||
|
||||
aFont = [CPFont _fontWithName:aTypeface size:shouldBeSize bold:shouldBeBold italic:shouldBeItalic] || aFont;
|
||||
|
||||
return aFont;
|
||||
}
|
||||
|
||||
- (@action)addFontTrait:(id)sender
|
||||
{
|
||||
var tag = [sender tag];
|
||||
_activeChange = tag == nil ? @{} : @{ @"addTraits": tag };
|
||||
_fontAction = CPAddTraitFontAction;
|
||||
|
||||
[self sendAction];
|
||||
}
|
||||
|
||||
- (BOOL)sendAction
|
||||
{
|
||||
return [CPApp sendAction:_action to:_target from:self];
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
This method open the font panel, create it if necessary.
|
||||
@param sender The object that sent the message.
|
||||
*/
|
||||
- (CPFontPanel)fontPanel:(BOOL)createIt
|
||||
{
|
||||
var panel = nil,
|
||||
panelExists = [CPFontPanelFactory sharedFontPanelExists];
|
||||
|
||||
if ((panelExists) || (!panelExists && createIt))
|
||||
panel = [CPFontPanelFactory sharedFontPanel];
|
||||
|
||||
return panel;
|
||||
}
|
||||
|
||||
/*!
|
||||
Convert a font to have the specified Font traits. The font is unchanged expect for the specified Font traits.
|
||||
Using CPUnboldFontMask or CPUnitalicFontMask will respectively remove Bold and Italic traits.
|
||||
@param aFont The font to convert.
|
||||
@param fontTrait The new font traits mask.
|
||||
@result The converted font or \c aFont if the conversion failed.
|
||||
*/
|
||||
- (CPFont)convertFont:(CPFont)aFont toHaveTrait:(CPFontTraitMask)fontTrait
|
||||
{
|
||||
var attributes = [[[aFont fontDescriptor] fontAttributes] copy],
|
||||
symbolicTrait = [[aFont fontDescriptor] symbolicTraits];
|
||||
|
||||
if (fontTrait & CPBoldFontMask)
|
||||
symbolicTrait |= CPFontBoldTrait;
|
||||
|
||||
if (fontTrait & CPItalicFontMask)
|
||||
symbolicTrait |= CPFontItalicTrait;
|
||||
|
||||
if (fontTrait & CPUnboldFontMask) /* FIXME: this only change CPFontSymbolicTrait what about CPFontWeightTrait */
|
||||
symbolicTrait &= ~CPFontBoldTrait;
|
||||
|
||||
if (fontTrait & CPUnitalicFontMask)
|
||||
symbolicTrait &= ~CPFontItalicTrait;
|
||||
|
||||
if (fontTrait & CPExpandedFontMask)
|
||||
symbolicTrait |= CPFontExpandedTrait;
|
||||
|
||||
if (fontTrait & CPSmallCapsFontMask)
|
||||
symbolicTrait |= CPFontSmallCapsTrait;
|
||||
|
||||
if (![attributes containsKey:CPFontTraitsAttribute])
|
||||
[attributes setObject:[CPDictionary dictionaryWithObject:[CPNumber numberWithUnsignedInt:symbolicTrait]
|
||||
forKey:CPFontSymbolicTrait]
|
||||
forKey:CPFontTraitsAttribute];
|
||||
else
|
||||
[[attributes objectForKey:CPFontTraitsAttribute] setObject:[CPNumber numberWithUnsignedInt:symbolicTrait]
|
||||
forKey:CPFontSymbolicTrait];
|
||||
|
||||
return [[aFont class] fontWithDescriptor:[CPFontDescriptor fontDescriptorWithFontAttributes:attributes] size:0.0];
|
||||
}
|
||||
|
||||
/*!
|
||||
Convert a font to not have the specified Font traits. The font is unchanged expect for the specified Font traits.
|
||||
@param aFont The font to convert.
|
||||
@param fontTrait The font traits mask to remove.
|
||||
@result The converted font or \c aFont if the conversion failed.
|
||||
*/
|
||||
- (CPFont)convertFont:(CPFont)aFont toNotHaveTrait:(CPFontTraitMask)fontTrait
|
||||
{
|
||||
var attributes = [[[aFont fontDescriptor] fontAttributes] copy],
|
||||
symbolicTrait = [[aFont fontDescriptor] symbolicTraits];
|
||||
|
||||
if ((fontTrait & CPBoldFontMask) || (fontTrait & CPUnboldFontMask)) /* FIXME: see convertFont:toHaveTrait: about CPFontWeightTrait */
|
||||
symbolicTrait &= ~CPFontBoldTrait;
|
||||
|
||||
if ((fontTrait & CPItalicFontMask) || (fontTrait & CPUnitalicFontMask))
|
||||
symbolicTrait &= ~CPFontItalicTrait;
|
||||
|
||||
if (fontTrait & CPExpandedFontMask)
|
||||
symbolicTrait &= ~CPFontExpandedTrait;
|
||||
|
||||
if (fontTrait & CPSmallCapsFontMask)
|
||||
symbolicTrait &= ~CPFontSmallCapsTrait;
|
||||
|
||||
if (![attributes containsKey:CPFontTraitsAttribute])
|
||||
[attributes setObject:[CPDictionary dictionaryWithObject:[CPNumber numberWithUnsignedInt:symbolicTrait]
|
||||
forKey:CPFontSymbolicTrait]
|
||||
forKey:CPFontTraitsAttribute];
|
||||
else
|
||||
[[attributes objectForKey:CPFontTraitsAttribute] setObject:[CPNumber numberWithUnsignedInt:symbolicTrait]
|
||||
forKey:CPFontSymbolicTrait];
|
||||
|
||||
return [[aFont class] fontWithDescriptor:[CPFontDescriptor fontDescriptorWithFontAttributes:attributes] size:0.0];
|
||||
}
|
||||
|
||||
/*!
|
||||
Convert a font to have specified size. The font is unchanged expect for the specified size.
|
||||
@param aFont The font to convert.
|
||||
@param aSize The new font size.
|
||||
@result The converted font or \c aFont if the conversion failed.
|
||||
*/
|
||||
- (CPFont)convertFont:(CPFont)aFont toSize:(float)aSize
|
||||
{
|
||||
var descriptor = [aFont fontDescriptor];
|
||||
|
||||
return [[aFont class] fontWithDescriptor: descriptor size:aSize]
|
||||
}
|
||||
|
||||
- (void)orderFrontFontPanel:(id)sender
|
||||
{
|
||||
[[self fontPanel:YES] orderFront:sender];
|
||||
}
|
||||
|
||||
- (void)modifyFont:(id)sender
|
||||
{
|
||||
_fontAction = [sender tag];
|
||||
[self sendAction];
|
||||
|
||||
if (_selectedFont)
|
||||
[self setSelectedFont:[self convertFont:_selectedFont] isMultiple:NO];
|
||||
}
|
||||
|
||||
/*!
|
||||
This method causes the receiver to send its action message.
|
||||
@param sender The object that sent the message. (a Font panel)
|
||||
*/
|
||||
- (void)modifyFontViaPanel:(id)sender
|
||||
{
|
||||
_fontAction = CPViaPanelFontAction;
|
||||
if (_selectedFont)
|
||||
[self setSelectedFont:[self convertFont:_selectedFont] isMultiple:NO];
|
||||
|
||||
[self sendAction];
|
||||
}
|
||||
|
||||
/*!
|
||||
Convert a font according to current font changes, provided by the object that initiated the font change.
|
||||
@param aFont The font to convert.
|
||||
@result The converted font or \c aFont if the conversion failed.
|
||||
*/
|
||||
- (CPFont)convertFont:(CPFont)aFont
|
||||
{
|
||||
var newFont = nil;
|
||||
|
||||
switch (_fontAction)
|
||||
{
|
||||
case CPNoFontChangeAction:
|
||||
newFont = aFont;
|
||||
break;
|
||||
|
||||
case CPViaPanelFontAction:
|
||||
newFont = [[self fontPanel:NO] panelConvertFont:aFont];
|
||||
break;
|
||||
|
||||
case CPAddTraitFontAction:
|
||||
newFont = aFont;
|
||||
|
||||
if (!_activeChange)
|
||||
break;
|
||||
|
||||
var addTraits = [_activeChange valueForKey:@"addTraits"];
|
||||
|
||||
if (addTraits)
|
||||
newFont = [self convertFont:aFont toHaveTrait:addTraits];
|
||||
break;
|
||||
|
||||
case CPSizeUpFontAction:
|
||||
newFont = [self convertFont:aFont toSize:[aFont size] + 1.0]; /* any limit ? */
|
||||
break;
|
||||
|
||||
case CPSizeDownFontAction:
|
||||
if ([aFont size] > 1)
|
||||
newFont = [self convertFont:aFont toSize:[aFont size] - 1.0];
|
||||
/* else CPBeep() :-p */
|
||||
break;
|
||||
|
||||
default:
|
||||
CPLog.trace(@"-[" + [self className] + " " + _cmd + "] unsupported font action: " + _fontAction + " aFont unchanged");
|
||||
newFont = aFont;
|
||||
break;
|
||||
}
|
||||
|
||||
return newFont;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
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",
|
||||
/* "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",*/
|
||||
"Big Caslon", "Bitstream Vera Sans", "Bitstream Vera Sans Mono", "Bitstream Vera Serif",
|
||||
/* "Blackadder ITC", "Blackletter686 BT", "Bodoni MT", "Bodoni MT Black", "Bodoni MT Condensed", "Bodoni MT Poster Compressed", "Book Antiqua", "Bookman", "Bookman Old Style", "Bradley Hand ITC", "Braggadocio", "Britannic Bold", "Broadway", "Broadway BT",*/
|
||||
/* "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",*/
|
||||
"Big Caslon","Bitstream Vera Sans","Bitstream Vera Sans Mono","Bitstream Vera Serif",
|
||||
/* "Blackadder ITC","Blackletter686 BT","Bodoni MT","Bodoni MT Black","Bodoni MT Condensed","Bodoni MT Poster Compressed","Book Antiqua","Bookman","Bookman Old Style","Bradley Hand ITC","Braggadocio","Britannic Bold","Broadway","Broadway BT",*/
|
||||
"Brush Script MT",
|
||||
/* "BudHand", "CAMPBELL", "Calibri", "Californian FB", "Calisto MT", "Calligraph421 BT",*/
|
||||
/* "BudHand","CAMPBELL","Calibri","Californian FB","Calisto MT","Calligraph421 BT",*/
|
||||
"Cambria",
|
||||
/* "Candara", "Capitals",*/
|
||||
"Caslon", "Castellar", "Cataneo BT", "Centaur", "Century Gothic", "Century Schoolbook", "Century Schoolbook L",
|
||||
/* "Champignon", "Charcoal", "Charter", "Charter BT", "Chicago", "Chick", "Chiller", "ClearlyU", "Colonna MT",*/
|
||||
"Comic Sans", "Comic Sans MS", "Consolas", "Constantia", "Cooper Black", "Copperplate", "Copperplate Gothic Bold", "Copperplate Gothic Light", "Corbel", "Courier", "Courier New",
|
||||
/* "Croobie", "Curlz MT", "Desdemona", "Didot", "DomBold BT", "Edwardian Script ITC", "Engravers MT", "Eras Bold ITC", "Eras Demi ITC", "Eras Light ITC", "Eras Medium ITC", "Eurostile", "FIRSTHOME", "Fat", "Felix Titling", "Fine Hand", "Fixed", "Footlight MT Light", "Forte", "Franklin Gothic Book", "Franklin Gothic Demi", "Franklin Gothic Demi Cond", "Franklin Gothic Heavy", "Franklin Gothic Medium", "Franklin Gothic Medium Cond", "Freestyle Script", "French Script MT", "Freshbot", "Frosty",*/
|
||||
/* "Candara","Capitals",*/
|
||||
"Caslon","Castellar","Cataneo BT","Centaur","Century Gothic","Century Schoolbook","Century Schoolbook L",
|
||||
/* "Champignon","Charcoal","Charter","Charter BT","Chicago","Chick","Chiller","ClearlyU","Colonna MT",*/
|
||||
"Comic Sans", "Comic Sans MS","Consolas","Constantia","Cooper Black","Copperplate","Copperplate Gothic Bold","Copperplate Gothic Light","Corbel","Courier","Courier New",
|
||||
/* "Croobie","Curlz MT","Desdemona","Didot","DomBold BT","Edwardian Script ITC","Engravers MT","Eras Bold ITC","Eras Demi ITC","Eras Light ITC","Eras Medium ITC","Eurostile","FIRSTHOME","Fat","Felix Titling","Fine Hand","Fixed","Footlight MT Light","Forte","Franklin Gothic Book","Franklin Gothic Demi","Franklin Gothic Demi Cond","Franklin Gothic Heavy","Franklin Gothic Medium","Franklin Gothic Medium Cond","Freestyle Script","French Script MT","Freshbot","Frosty",*/
|
||||
"Futura",
|
||||
/* "GENUINE", "Gadget", "Garamond",*/
|
||||
"Geneva", "Georgia", "Georgia Ref", "Geeza Pro", "Gigi", "Gill Sans", "Gill Sans MT", "Gill Sans MT Condensed", "Gill Sans MT Ext Condensed Bold", "Gill Sans Ultra Bold", "Gill Sans Ultra Bold Condensed",
|
||||
/* "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", */
|
||||
/* "GENUINE","Gadget","Garamond",*/
|
||||
"Geneva","Georgia","Georgia Ref", "Geeza Pro", "Gigi","Gill Sans","Gill Sans MT","Gill Sans MT Condensed","Gill Sans MT Ext Condensed Bold","Gill Sans Ultra Bold","Gill Sans Ultra Bold Condensed",
|
||||
/* "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", */
|
||||
"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",
|
||||
/* "Niagara Engraved", "Niagara Solid", "Nimbus Mono L", "Nimbus Roman No9 L", "OCR A Extended", "OCRB", "Odessa LET", "Old English Text MT", "OldDreadfulNo7 BT", "One Stroke Script LET", "Onyx", "Optima", "Orange LET", "Palace Script MT", "Palatino", "Palatino Linotype", */
|
||||
/* "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",
|
||||
/* "Niagara Engraved","Niagara Solid","Nimbus Mono L","Nimbus Roman No9 L","OCR A Extended","OCRB","Odessa LET","Old English Text MT","OldDreadfulNo7 BT","One Stroke Script LET","Onyx","Optima","Orange LET","Palace Script MT","Palatino","Palatino Linotype", */
|
||||
"Papyrus",
|
||||
/* "ParkAvenue BT", "Pepita MT", "Perpetua", "Perpetua Titling MT", "Placard Condensed", "Playbill", "Poornut", "Pristina", "Pump Demi Bold LET", "Pussycat", "Quixley LET", "Rage Italic", "Rage Italic LET", "Ravie", "Rockwell", "Rockwell Condensed", "Rockwell Extra Bold", "Ruach LET", "Runic MT Condensed", "Sand", "Script MT Bold", "Scruff LET", "Segoe UI", "Showcard Gothic", "Skia", "Smudger LET", "Snap ITC", "Square721 BT", "Staccato222 BT", "Stencil", "Sylfaen", */
|
||||
"Tahoma", "Techno", "Tempus Sans ITC", "Terminal", "Textile", "Times", "Times New Roman", "Tiranti Solid LET", "Trebuchet MS",
|
||||
/* "Tw Cen MT", "Tw Cen MT Condensed", "Tw Cen MT Condensed Extra Bold", "URW Antiqua T", "URW Bookman L", "URW Chancery L", "URW Gothic L", "URW Palladio L", "Univers", "University Roman LET", "Utopia", */
|
||||
"Verdana", "Verdana Ref", /* "Victorian LET", "Viner Hand ITC", "Vivaldi", "Vladimir Script", "Vrinda", "Weltron Urban", "Westwood LET", "Wide Latin", "Zapf Chancery", */
|
||||
/* "ParkAvenue BT","Pepita MT","Perpetua","Perpetua Titling MT","Placard Condensed","Playbill","Poornut","Pristina","Pump Demi Bold LET","Pussycat","Quixley LET","Rage Italic","Rage Italic LET","Ravie","Rockwell","Rockwell Condensed","Rockwell Extra Bold","Ruach LET","Runic MT Condensed","Sand","Script MT Bold","Scruff LET","Segoe UI","Showcard Gothic","Skia","Smudger LET","Snap ITC","Square721 BT","Staccato222 BT","Stencil","Sylfaen", */
|
||||
"Tahoma","Techno","Tempus Sans ITC","Terminal","Textile","Times","Times New Roman","Tiranti Solid LET","Trebuchet MS",
|
||||
/* "Tw Cen MT","Tw Cen MT Condensed","Tw Cen MT Condensed Extra Bold","URW Antiqua T","URW Bookman L","URW Chancery L","URW Gothic L","URW Palladio L","Univers","University Roman LET","Utopia", */
|
||||
"Verdana","Verdana Ref", /* "Victorian LET","Viner Hand ITC","Vivaldi","Vladimir Script","Vrinda","Weltron Urban","Westwood LET","Wide Latin","Zapf Chancery", */
|
||||
"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,
|
||||
bHeight = _CPFontDetectSpan.offsetHeight;
|
||||
|
||||
return (a.w != bWidth || a.h != bHeight);
|
||||
};
|
||||
|
||||
_CPFontDetectSpan.style.fontFamily= '"' + fontB + '", "' + fontA + '"';
|
||||
var bWidth = _CPFontDetectSpan.offsetWidth;
|
||||
var 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,6 +1,6 @@
|
||||
/*
|
||||
* CPGeometry.j
|
||||
* Foundation
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
@@ -20,109 +20,34 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "_CGGeometry.j"
|
||||
@import "CGGeometry.j"
|
||||
|
||||
|
||||
@typedef CPRectEdge
|
||||
CPMinXEdge = 0;
|
||||
CPMinYEdge = 1;
|
||||
CPMaxXEdge = 2;
|
||||
CPMaxYEdge = 3;
|
||||
|
||||
/*!
|
||||
Makes a CGPoint object out of two numbers provided as arguments
|
||||
@group CGPoint
|
||||
@param x the x-coordinate of the CGPoint
|
||||
@param y the y-coordinate of the CGPoint
|
||||
@return CGPoint a CGPoint with an X and Y coordinate equal to the function arguments
|
||||
*/
|
||||
// FIXME: the rest!
|
||||
CPMakePoint = CGPointMake;
|
||||
|
||||
/*!
|
||||
Creates and returns a new CGSize object from the provided dimensions.
|
||||
@group CGSize
|
||||
@param width the width for the new CGSize
|
||||
@param height the height for the new CGSize
|
||||
@return CGSize the new CGSize
|
||||
*/
|
||||
CPMakeSize = CGSizeMake;
|
||||
|
||||
/*!
|
||||
Returns a CGRect made of the specified arguments
|
||||
@group CGRect
|
||||
@param x the x-coordinate of the rectangle's origin
|
||||
@param y the y-coordinate of the rectangle's origin
|
||||
@param width the width of the new rectangle
|
||||
@param height the height of the new rectangle
|
||||
@return CGRect the new rectangle
|
||||
*/
|
||||
CPMakeRect = CGRectMake;
|
||||
|
||||
/*!
|
||||
Creates a copy of a specified point and returns the copy
|
||||
@group CGPoint
|
||||
@param the point to be copied
|
||||
@return CGPoint the copy of the provided CGPoint
|
||||
@addtogroup appkit
|
||||
@{
|
||||
*/
|
||||
CPPointCreateCopy = CGPointMakeCopy;
|
||||
|
||||
/*!
|
||||
Tests whether the two CGPoints are equal to each other by comparing their
|
||||
\c x and \c y members.
|
||||
@group @CGPoint
|
||||
@param lhsPoint the first CGPoint to check
|
||||
@param rhsPoint the second CGPoint to check
|
||||
@return BOOL \c YES if the two points have the same x's, and the same y's.
|
||||
*/
|
||||
CPPointEqualToPoint = CGPointEqualToPoint;
|
||||
|
||||
/*!
|
||||
Tests whether the CGPoint is contained by the CGRect.
|
||||
@group CGPoint
|
||||
@param aPoint the CGPoint to check
|
||||
@param aRect the CGRect to check
|
||||
@return BOOL \c YES if the rect contains the point.
|
||||
*/
|
||||
CPPointInRect = function(aPoint, aRect)
|
||||
Creates a copy of a specified point and returns the copy
|
||||
@group CGPoint
|
||||
@param the point to be copied
|
||||
@return CGPoint the copy of the provided CGPoint
|
||||
*/
|
||||
function CPPointCreateCopy(aPoint)
|
||||
{
|
||||
return CGRectContainsPoint(aRect, aPoint)
|
||||
};
|
||||
|
||||
/*!
|
||||
Test whether the two CGRects have the same origin and size
|
||||
@group CGRect
|
||||
@param lhsRect the first CGRect to compare
|
||||
@param rhsRect the second CGRect to compare
|
||||
@return BOOL \c YES if the two rectangles have the same origin and size. \c NO, otherwise.
|
||||
*/
|
||||
CPRectEqualToRect = CGRectEqualToRect;
|
||||
|
||||
/*!
|
||||
Returns \c YES if the CGRect has no area.
|
||||
The test is performed by checking if the width and height are both zero.
|
||||
@group CGRect
|
||||
@param aRect the CGRect to test
|
||||
@return BOOL \c YES if the CGRect has no area, and \c NO, otherwise.
|
||||
*/
|
||||
CPRectIsEmpty = CGRectIsEmpty;
|
||||
|
||||
/*!
|
||||
Returns a \c BOOL indicating whether CGRect \c possibleOuter
|
||||
contains CGRect \c possibleInner.
|
||||
@group CGRect
|
||||
@param possibleOuter the CGRect to test if \c possibleInner is inside of
|
||||
@param possibleInner the CGRect to test if it fits inside \c possibleOuter.
|
||||
@return BOOL \c YES if \c possibleInner fits inside \c possibleOuter.
|
||||
*/
|
||||
CPRectContainsRect = CGRectContainsRect;
|
||||
|
||||
/*!
|
||||
Returns the intersection of the two provided rectangles as a new rectangle
|
||||
@group CGRect
|
||||
@param lhsRect the first rectangle used for calculation
|
||||
@param rhsRect the second rectangle used for calculation
|
||||
@return CGRect the intersection of the two rectangles
|
||||
*/
|
||||
CPRectIntersection = CGRectIntersection;
|
||||
return { x: aPoint.x, y: aPoint.y };
|
||||
}
|
||||
|
||||
/*!
|
||||
Makes a CGPoint object out of two numbers provided as arguments
|
||||
@@ -130,8 +55,11 @@ CPRectIntersection = CGRectIntersection;
|
||||
@param x the x-coordinate of the CGPoint
|
||||
@param y the y-coordinate of the CGPoint
|
||||
@return CGPoint a CGPoint with an X and Y coordinate equal to the function arguments
|
||||
*/
|
||||
CPPointMake = CGPointMake;
|
||||
*/
|
||||
function CPPointMake(x, y)
|
||||
{
|
||||
return { x: x, y: y };
|
||||
}
|
||||
|
||||
/*!
|
||||
Makes a CGRect with an origin and size equal to \c aRect less the \c dX/dY insets specified.
|
||||
@@ -140,7 +68,11 @@ CPPointMake = CGPointMake;
|
||||
@group CGRect
|
||||
@return CGRect a rectangle like \c aRect with an inset
|
||||
*/
|
||||
CPRectInset = CGRectInset;
|
||||
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);
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@@ -148,7 +80,31 @@ CPRectInset = CGRectInset;
|
||||
@return void
|
||||
@deprecated
|
||||
*/
|
||||
CPRectIntegral = CGRectIntegral;
|
||||
function CPRectIntegral(aRect)
|
||||
{
|
||||
// FIXME!!!
|
||||
alert("CPRectIntegral unimplemented");
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the intersection of the two provided rectangles as a new rectangle
|
||||
@group CGRect
|
||||
@param lhsRect the first rectangle used for calculation
|
||||
@param rhsRect the second rectangle used for calculation
|
||||
@return CGRect the intersection of the two rectangles
|
||||
*/
|
||||
function CPRectIntersection(lhsRect, rhsRect)
|
||||
{
|
||||
var intersection = CPRectMake(
|
||||
Math.max(CPRectGetMinX(lhsRect), CPRectGetMinX(rhsRect)),
|
||||
Math.max(CPRectGetMinY(lhsRect), CPRectGetMinY(rhsRect)),
|
||||
0, 0);
|
||||
|
||||
intersection.size.width = Math.min(CPRectGetMaxX(lhsRect), CPRectGetMaxX(rhsRect)) - CPRectGetMinX(intersection);
|
||||
intersection.size.height = Math.min(CPRectGetMaxY(lhsRect), CPRectGetMaxY(rhsRect)) - CPRectGetMinY(intersection);
|
||||
|
||||
return CPRectIsEmpty(intersection) ? CPRectMakeZero() : intersection;
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a copy of the provided rectangle
|
||||
@@ -156,7 +112,10 @@ CPRectIntegral = CGRectIntegral;
|
||||
@param aRect the CGRect that will be copied
|
||||
@return CGRect the rectangle copy
|
||||
*/
|
||||
CPRectCreateCopy = CGRectCreateCopy;
|
||||
function CPRectCreateCopy(aRect)
|
||||
{
|
||||
return { origin: CPPointCreateCopy(aRect.origin), size: CPSizeCreateCopy(aRect.size) };
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a CGRect made of the specified arguments
|
||||
@@ -167,7 +126,10 @@ CPRectCreateCopy = CGRectCreateCopy;
|
||||
@param height the height of the new rectangle
|
||||
@return CGRect the new rectangle
|
||||
*/
|
||||
CPRectMake = CGRectMake;
|
||||
function CPRectMake(x, y, width, height)
|
||||
{
|
||||
return { origin: CPPointMake(x, y), size: CPSizeMake(width, height) };
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a new rectangle with its origin offset by \c dX and \c dY.
|
||||
@@ -177,14 +139,36 @@ CPRectMake = CGRectMake;
|
||||
@param dY the amount added to the y-size of the new rectangle
|
||||
@return CGRect the new rectangle with modified size
|
||||
*/
|
||||
CPRectOffset = CGRectOffset;
|
||||
function CPRectOffset(aRect, dX, dY)
|
||||
{
|
||||
return CPRectMake(aRect.origin.x + dX, aRect.origin.y + dY, aRect.size.width, aRect.size.height);
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return CGRect
|
||||
*/
|
||||
CPRectStandardize = CGRectStandardize;
|
||||
function CPRectStandardize(aRect)
|
||||
{
|
||||
var width = CPRectGetWidth(aRect),
|
||||
height = CPRectGetHeight(aRect),
|
||||
standardized = CPRectCreateCopy(aRect);
|
||||
|
||||
if (width < 0.0)
|
||||
{
|
||||
standardized.origin.x += width;
|
||||
standardized.size.width = -width;
|
||||
}
|
||||
|
||||
if (height < 0.0)
|
||||
{
|
||||
standardized.origin.y += height;
|
||||
standardized.size.height = -height;
|
||||
}
|
||||
|
||||
return standardized;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the smallest rectangle that can contain the two argument \c CGRects.
|
||||
@@ -193,7 +177,15 @@ CPRectStandardize = CGRectStandardize;
|
||||
@param rhsRect the second CGRect to use for the union calculation
|
||||
@return CGRect the union rectangle
|
||||
*/
|
||||
CPRectUnion = CGRectUnion;
|
||||
function CPRectUnion(lhsRect, rhsRect)
|
||||
{
|
||||
var minX = Math.min(CPRectGetMinX(lhsRect), CPRectGetMinX(rhsRect)),
|
||||
minY = Math.min(CPRectGetMinY(lhsRect), CPRectGetMinY(rhsRect)),
|
||||
maxX = Math.max(CPRectGetMaxX(lhsRect), CPRectGetMaxX(rhsRect)),
|
||||
maxY = Math.max(CPRectGetMaxY(lhsRect), CPRectGetMaxY(rhsRect));
|
||||
|
||||
return CPRectMake(minX, minY, maxX - minX, maxY - minY);
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates and returns a copy of the provided CGSize
|
||||
@@ -201,7 +193,10 @@ CPRectUnion = CGRectUnion;
|
||||
@param aSize the CGSize to copy
|
||||
@return CGSize the copy of the CGSize
|
||||
*/
|
||||
CPSizeCreateCopy = CGSizeCreateCopy;
|
||||
function CPSizeCreateCopy(aSize)
|
||||
{
|
||||
return { width: aSize.width, height: aSize.height };
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates and returns a new CGSize object from the provided dimensions.
|
||||
@@ -210,7 +205,10 @@ CPSizeCreateCopy = CGSizeCreateCopy;
|
||||
@param height the height for the new CGSize
|
||||
@return CGSize the new CGSize
|
||||
*/
|
||||
CPSizeMake = CGSizeMake;
|
||||
function CPSizeMake(width, height)
|
||||
{
|
||||
return { width: width, height: height };
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the CGRect, \c aRect, contains
|
||||
@@ -220,63 +218,132 @@ CPSizeMake = CGSizeMake;
|
||||
@group CGRect
|
||||
@return BOOL \c YES if the rectangle contains the point, \c NO otherwise.
|
||||
*/
|
||||
CPRectContainsPoint = CGRectContainsPoint;
|
||||
function CPRectContainsPoint(aRect, aPoint)
|
||||
{
|
||||
return aPoint.x >= CPRectGetMinX(aRect) &&
|
||||
aPoint.y >= CPRectGetMinY(aRect) &&
|
||||
aPoint.x < CPRectGetMaxX(aRect) &&
|
||||
aPoint.y < CPRectGetMaxY(aRect);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a \c BOOL indicating whether CGRect \c possibleOuter
|
||||
contains CGRect \c possibleInner.
|
||||
@group CGRect
|
||||
@param possibleOuter the CGRect to test if \c possibleInner is inside of
|
||||
@param possibleInner the CGRect to test if it fits inside \c possibleOuter.
|
||||
@return BOOL \c YES if \c possibleInner fits inside \c possibleOuter.
|
||||
*/
|
||||
function CPRectContainsRect(possibleOuter, possibleInner)
|
||||
{
|
||||
return CGRectContainsRect(possibleOuter, possibleInner);
|
||||
}
|
||||
|
||||
/*!
|
||||
Tests whether the two CGPoints are equal to each other by comparing their
|
||||
\c x and \c y members.
|
||||
@group @CGPoint
|
||||
@param lhsPoint the first CGPoint to check
|
||||
@param rhsPoint the second CGPoint to check
|
||||
@return BOOL \c YES if the two points have the same x's, and the same y's.
|
||||
*/
|
||||
function CPPointEqualToPoint(lhsPoint, rhsPoint)
|
||||
{
|
||||
return lhsPoint.x == rhsPoint.x && lhsPoint.y == rhsPoint.y;
|
||||
}
|
||||
|
||||
/*!
|
||||
Test whether the two CGRects have the same origin and size
|
||||
@group CGRect
|
||||
@param lhsRect the first CGRect to compare
|
||||
@param rhsRect the second CGRect to compare
|
||||
@return BOOL \c YES if the two rectangles have the same origin and size. \c NO, otherwise.
|
||||
*/
|
||||
function CPRectEqualToRect(lhsRect, rhsRect)
|
||||
{
|
||||
return CPPointEqualToPoint(lhsRect.origin, rhsRect.origin) &&
|
||||
CPSizeEqualToSize(lhsRect.size, rhsRect.size);
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return int
|
||||
*/
|
||||
CPRectGetHeight = CGRectGetHeight;
|
||||
function CPRectGetHeight(aRect)
|
||||
{
|
||||
return aRect.size.height;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return int
|
||||
*/
|
||||
CPRectGetMaxX = CGRectGetMaxX;
|
||||
function CPRectGetMaxX(aRect)
|
||||
{
|
||||
return aRect.origin.x + aRect.size.width;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return int
|
||||
*/
|
||||
CPRectGetMaxY = CGRectGetMaxY;
|
||||
function CPRectGetMaxY(aRect)
|
||||
{
|
||||
return aRect.origin.y + aRect.size.height;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return float
|
||||
*/
|
||||
CPRectGetMidX = CGRectGetMidX;
|
||||
function CPRectGetMidX(aRect)
|
||||
{
|
||||
return aRect.origin.x + (aRect.size.width) / 2.0;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return float
|
||||
*/
|
||||
CPRectGetMidY = CGRectGetMidY;
|
||||
function CPRectGetMidY(aRect)
|
||||
{
|
||||
return aRect.origin.y + (aRect.size.height) / 2.0;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return int
|
||||
*/
|
||||
CPRectGetMinX = CGRectGetMinX;
|
||||
function CPRectGetMinX(aRect)
|
||||
{
|
||||
return aRect.origin.x;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return int
|
||||
*/
|
||||
CPRectGetMinY = CGRectGetMinY;
|
||||
function CPRectGetMinY(aRect)
|
||||
{
|
||||
return aRect.origin.y;
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGRect
|
||||
@param aRect a CGRect
|
||||
@return int
|
||||
*/
|
||||
CPRectGetWidth = CGRectGetWidth;
|
||||
function CPRectGetWidth(aRect)
|
||||
{
|
||||
return aRect.size.width;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the two rectangles intersect
|
||||
@@ -285,7 +352,22 @@ CPRectGetWidth = CGRectGetWidth;
|
||||
@param rhsRect the second CGRect
|
||||
@return BOOL \c YES if the two rectangles have any common spaces, and \c NO, otherwise.
|
||||
*/
|
||||
CPRectIntersectsRect = CGRectIntersectsRect;
|
||||
function CPRectIntersectsRect(lhsRect, rhsRect)
|
||||
{
|
||||
return !CPRectIsEmpty(CPRectIntersection(lhsRect, rhsRect));
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the CGRect has no area.
|
||||
The test is performed by checking if the width and height are both zero.
|
||||
@group CGRect
|
||||
@param aRect the CGRect to test
|
||||
@return BOOL \c YES if the CGRect has no area, and \c NO, otherwise.
|
||||
*/
|
||||
function CPRectIsEmpty(aRect)
|
||||
{
|
||||
return aRect.size.width <= 0.0 || aRect.size.height <= 0.0;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the CGRect has no area.
|
||||
@@ -293,18 +375,10 @@ CPRectIntersectsRect = CGRectIntersectsRect;
|
||||
@group CGRect
|
||||
@return BOOL \c YES if the CGRect has no area, and \c NO, otherwise.
|
||||
*/
|
||||
CPRectIsNull = CGRectIsNull;
|
||||
|
||||
/*!
|
||||
Creates two rectangles -- slice and rem -- from inRect, by dividing inRect
|
||||
with a line that's parallel to the side of inRect specified by edge.
|
||||
The size of slice is determined by amount, which specifies the distance from edge.
|
||||
|
||||
slice and rem must not be NULL.
|
||||
|
||||
@group CGRect
|
||||
*/
|
||||
CPDivideRect = CGRectDivide;
|
||||
function CPRectIsNull(aRect)
|
||||
{
|
||||
return aRect.size.width <= 0.0 || aRect.size.height <= 0.0;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the two CGSizes are identical.
|
||||
@@ -313,7 +387,10 @@ CPDivideRect = CGRectDivide;
|
||||
@param rhsSize the second CGSize to compare
|
||||
@return BOOL \c YES if the two sizes are identical. \c NO, otherwise.
|
||||
*/
|
||||
CPSizeEqualToSize = CGSizeEqualToSize;
|
||||
function CPSizeEqualToSize(lhsSize, rhsSize)
|
||||
{
|
||||
return lhsSize.width == rhsSize.width && lhsSize.height == rhsSize.height;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a human readable string of the provided CGPoint.
|
||||
@@ -321,7 +398,10 @@ CPSizeEqualToSize = CGSizeEqualToSize;
|
||||
@param aPoint the point to represent
|
||||
@return CGPoint a string representation of the CGPoint
|
||||
*/
|
||||
CPStringFromPoint = CGStringFromPoint;
|
||||
function CPStringFromPoint(aPoint)
|
||||
{
|
||||
return "{" + aPoint.x + ", " + aPoint.y + "}";
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a human readable string of the provided CGSize.
|
||||
@@ -329,7 +409,10 @@ CPStringFromPoint = CGStringFromPoint;
|
||||
@param aSize the size to represent
|
||||
@return CGSize a string representation of the CGSize
|
||||
*/
|
||||
CPStringFromSize = CGStringFromSize;
|
||||
function CPStringFromSize(aSize)
|
||||
{
|
||||
return "{" + aSize.width + ", " + aSize.height + "}";
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a human readable string of the provided CGRect.
|
||||
@@ -337,7 +420,10 @@ CPStringFromSize = CGStringFromSize;
|
||||
@param aRect the rectangle to represent
|
||||
@return CGString the string representation of the rectangle
|
||||
*/
|
||||
CPStringFromRect = CGStringFromRect;
|
||||
function CPStringFromRect(aRect)
|
||||
{
|
||||
return "{" + CPStringFromPoint(aRect.origin) + ", " + CPStringFromSize(aRect.size) + "}";
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a CGPoint from a string with a comma separated pair of integers.
|
||||
@@ -345,7 +431,12 @@ CPStringFromRect = CGStringFromRect;
|
||||
@param aString a string containing two comma separated integers
|
||||
@return CGPoint the point object created from the string
|
||||
*/
|
||||
CPPointFromString = CGPointFromString;
|
||||
function CPPointFromString(aString)
|
||||
{
|
||||
var comma = aString.indexOf(',');
|
||||
|
||||
return { x:parseFloat(aString.substr(1, comma - 1), 10), y:parseFloat(aString.substring(comma + 1, aString.length), 10) };
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a CGSize from a string containing a pair of comma separated integers.
|
||||
@@ -353,7 +444,12 @@ CPPointFromString = CGPointFromString;
|
||||
@param aString a string containing two comma separated integers
|
||||
@return CGSize the size object created from the string
|
||||
*/
|
||||
CPSizeFromString = CGSizeFromString;
|
||||
function CPSizeFromString(aString)
|
||||
{
|
||||
var comma = aString.indexOf(',');
|
||||
|
||||
return { width:parseFloat(aString.substr(1, comma - 1), 10), height:parseFloat(aString.substring(comma + 1, aString.length), 10) };
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a CGRect created from a string.
|
||||
@@ -361,32 +457,53 @@ CPSizeFromString = CGSizeFromString;
|
||||
@param aString a string in the form generated by \c CPStringFromRect
|
||||
@return CGRect the rectangle created from the string
|
||||
*/
|
||||
CPRectFromString = CGRectFromString;
|
||||
function CPRectFromString(aString)
|
||||
{
|
||||
var comma = aString.indexOf(',', aString.indexOf(',') + 1);
|
||||
|
||||
return { origin:CPPointFromString(aString.substr(1, comma - 1)), size:CPSizeFromString(aString.substring(comma + 2, aString.length)) };
|
||||
}
|
||||
|
||||
/*!
|
||||
@group CGPoint
|
||||
@param anEvent
|
||||
@return CGPoint
|
||||
*/
|
||||
CPPointFromEvent = CGPointFromEvent;
|
||||
function CPPointFromEvent(anEvent)
|
||||
{
|
||||
return CPPointMake(anEvent.clientX, anEvent.clientY, 0);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a zero sized CGSize.
|
||||
@group CGSize
|
||||
@return CGSize a size object with zeros for \c width and \c height
|
||||
*/
|
||||
CPSizeMakeZero = CGSizeMakeZero;
|
||||
function CPSizeMakeZero()
|
||||
{
|
||||
return CPSizeMake(0, 0);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a rectangle at origin \c (0,0) and size of \c (0,0).
|
||||
@group CGRect
|
||||
@return CGRect a zeroed out CGRect
|
||||
*/
|
||||
CPRectMakeZero = CGRectMakeZero;
|
||||
function CPRectMakeZero()
|
||||
{
|
||||
return CPRectMake(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a point located at \c (0, 0).
|
||||
@group CGPoint
|
||||
@return CGPoint a point located at \c (0, 0)
|
||||
*/
|
||||
CPPointMakeZero = CGPointMakeZero;
|
||||
function CPPointMakeZero()
|
||||
{
|
||||
return CPPointMake(0, 0, 0);
|
||||
}
|
||||
|
||||
/*!
|
||||
@}
|
||||
*/
|
||||
@@ -1,169 +0,0 @@
|
||||
/*
|
||||
* CPGradient.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexander Ljungberg.
|
||||
* Copyright 2012, SlevenBits Ltd.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
@import <Foundation/CPException.j>
|
||||
@import <Foundation/CPMutableArray.j>
|
||||
|
||||
@import "CGColor.j"
|
||||
@import "CGColorSpace.j"
|
||||
@import "CGGradient.j"
|
||||
@import "CPBezierPath.j"
|
||||
@import "CPGraphicsContext.j"
|
||||
|
||||
CPGradientDrawsBeforeStartingLocation = kCGGradientDrawsBeforeStartLocation;
|
||||
CPGradientDrawsAfterEndingLocation = kCGGradientDrawsAfterEndLocation;
|
||||
|
||||
/*!
|
||||
A class for drawing linear and radial gradients with a convenient API.
|
||||
*/
|
||||
@implementation CPGradient : CPObject
|
||||
{
|
||||
CGGradient _gradient;
|
||||
}
|
||||
|
||||
- (id)initWithStartingColor:(CPColor)startingColor endingColor:(CPColor)endingColor
|
||||
{
|
||||
return [self initWithColors:[startingColor, endingColor]];
|
||||
}
|
||||
|
||||
- (id)initWithColors:(CPArray)someColors
|
||||
{
|
||||
var count = [someColors count];
|
||||
|
||||
if (count < 2)
|
||||
[CPException raise:CPInvalidArgumentException reason:@"at least 2 colors required"];
|
||||
|
||||
var distance = 1.0 / (count - 1),
|
||||
locations = [CPMutableArray array],
|
||||
location = 0.0;
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
[locations addObject:location];
|
||||
location += distance;
|
||||
}
|
||||
|
||||
return [self initWithColors:someColors atLocations:locations colorSpace:nil];
|
||||
}
|
||||
|
||||
- (id)initWithColors:(CPArray)someColors atLocations:(CPArray)someLocations colorSpace:(CPColorSpace)aColorSpace
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
var colorSpace = [aColorSpace CGColorSpace] || CGColorSpaceCreateDeviceRGB,
|
||||
cgColors = [someColors arrayByApplyingBlock:function(color)
|
||||
{
|
||||
return CGColorCreate(colorSpace, [color components])
|
||||
}];
|
||||
|
||||
_gradient = CGGradientCreateWithColors(colorSpace, cgColors, someLocations);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)drawInRect:(CGRect)rect angle:(float)angle
|
||||
{
|
||||
var ctx = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
CGContextSaveGState(ctx);
|
||||
CGContextClipToRect(ctx, rect);
|
||||
CGContextAddRect(ctx, rect);
|
||||
|
||||
[self _drawInRect:rect atAngle:angle];
|
||||
|
||||
CGContextRestoreGState(ctx);
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore like draw in rect but apply no clipping.
|
||||
*/
|
||||
- (void)_drawInRect:(CGRect)rect atAngle:(float)angle
|
||||
{
|
||||
var ctx = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
|
||||
startPoint,
|
||||
endPoint;
|
||||
|
||||
// Modulo of negative values doesn't work as expected in JS.
|
||||
angle = ((angle % 360.0) + 360.0) % 360.0;
|
||||
|
||||
if (angle < 90.0)
|
||||
startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect));
|
||||
else if (angle < 180.0)
|
||||
startPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect));
|
||||
else if (angle < 270.0)
|
||||
startPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect));
|
||||
else
|
||||
startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect));
|
||||
|
||||
// A line segment comes out of the starting point at the given angle, with the first colour
|
||||
// at the starting point and the last at the end. To do what drawInRect: is supposed to do
|
||||
// we want the opposite corner of the starting corner to just reach the final colour stop.
|
||||
// So when the angle isn't a right angle, the segment has to extend beyond the edge of the
|
||||
// rectangle just far enough. This is hard to describe without a picture but if we place
|
||||
// another line through the opposite corner at -90 degrees, it'll help form some triangles
|
||||
// from which we can derive this formula:
|
||||
//
|
||||
// length = cos(angle) * (rectWidth + rectHeight * tan(angle))
|
||||
//
|
||||
// This simplifies down to (in the first quadrant) rectWidth * cos(a) + rectHeight * sin(a).
|
||||
|
||||
var radians = PI * angle / 180.0,
|
||||
length = ABS(CGRectGetWidth(rect) * COS(radians)) + ABS(CGRectGetHeight(rect) * SIN(radians));
|
||||
|
||||
endPoint = CGPointMake(startPoint.x + length * COS(radians),
|
||||
startPoint.y + length * SIN(radians));
|
||||
|
||||
[self drawFromPoint:startPoint toPoint:endPoint options:CPGradientDrawsBeforeStartingLocation | CPGradientDrawsAfterEndingLocation];
|
||||
}
|
||||
|
||||
- (void)drawInBezierPath:(CPBezierPath)aPath angle:(float)anAngle
|
||||
{
|
||||
[CPGraphicsContext saveGraphicsState];
|
||||
|
||||
var ctx = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
// Nail down the path which CGContextDrawLinearGradient will cause to be filled.
|
||||
// Note we don't do this by clipping to the path and then calling drawInRect:atAngle:
|
||||
// as this would cut off any antialias of the drawing, plus any active context shadow.
|
||||
CGContextBeginPath(ctx);
|
||||
CGContextAddPath(ctx, aPath._path);
|
||||
CGContextSetLineWidth(ctx, [aPath lineWidth]);
|
||||
CGContextClosePath(ctx);
|
||||
|
||||
[self _drawInRect:[aPath bounds] atAngle:anAngle];
|
||||
|
||||
[CPGraphicsContext restoreGraphicsState];
|
||||
}
|
||||
|
||||
- (void)drawFromPoint:(NSPoint)startingPoint toPoint:(NSPoint)endingPoint options:(NSGradientDrawingOptions)options
|
||||
{
|
||||
var ctx = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
// TODO kCGGradientDrawsBeforeStartLocation and kCGGradientDrawsAfterEndLocation are not actually supported
|
||||
// by CGContextDrawLinearGradient yet.
|
||||
CGContextDrawLinearGradient(ctx, _gradient, startingPoint, endingPoint, options);
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* CPGraphics.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2010, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPColor.j"
|
||||
@import "CPGraphicsContext.j"
|
||||
|
||||
CPCalibratedWhiteColorSpace = @"CalibratedWhiteColorSpace";
|
||||
CPCalibratedBlackColorSpace = @"CalibratedBlackColorSpace";
|
||||
CPCalibratedRGBColorSpace = @"CalibratedRGBColorSpace";
|
||||
CPDeviceWhiteColorSpace = @"DeviceWhiteColorSpace";
|
||||
CPDeviceBlackColorSpace = @"DeviceBlackColorSpace";
|
||||
CPDeviceRGBColorSpace = @"DeviceRGBColorSpace";
|
||||
CPDeviceCMYKColorSpace = @"DeviceCMYKColorSpace";
|
||||
CPNamedColorSpace = @"NamedColorSpace";
|
||||
CPPatternColorSpace = @"PatternColorSpace";
|
||||
CPCustomColorSpace = @"CustomColorSpace";
|
||||
|
||||
function CPDrawTiledRects(
|
||||
/* CGRect */ boundsRect,
|
||||
/* CGRect */ clipRect,
|
||||
/* CPRectEdge[] */ sides,
|
||||
/* float[] */ grays)
|
||||
{
|
||||
if (sides.length != grays.length)
|
||||
[CPException raise:CPInvalidArgumentException reason:@"sides (length: " + sides.length + ") and grays (length: " + grays.length + ") must have the same length."];
|
||||
|
||||
var colors = [grays arrayByApplyingBlock:function(gray)
|
||||
{
|
||||
return [CPColor colorWithCalibratedWhite:gray alpha:1.0];
|
||||
}];
|
||||
|
||||
return CPDrawColorTiledRects(boundsRect, clipRect, sides, colors);
|
||||
}
|
||||
|
||||
function CPDrawColorTiledRects(
|
||||
/* CGRect */ boundsRect,
|
||||
/* CGRect */ clipRect,
|
||||
/* CPRectEdge[] */ sides,
|
||||
/* CPColor[] */ colors)
|
||||
{
|
||||
if (sides.length != colors.length)
|
||||
[CPException raise:CPInvalidArgumentException reason:@"sides (length: " + sides.length + ") and colors (length: " + colors.length + ") must have the same length."];
|
||||
|
||||
var resultRect = CGRectMakeCopy(boundsRect),
|
||||
slice = CGRectMakeZero(),
|
||||
remainder = CGRectMakeZero(),
|
||||
context = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
CGContextSaveGState(context);
|
||||
CGContextSetLineWidth(context, 1.0);
|
||||
|
||||
for (var sideIndex = 0; sideIndex < sides.length; ++sideIndex)
|
||||
{
|
||||
var side = sides[sideIndex];
|
||||
|
||||
CGRectDivide(resultRect, slice, remainder, 1.0, side);
|
||||
resultRect = remainder;
|
||||
slice = CGRectIntersection(slice, clipRect);
|
||||
|
||||
// Cocoa docs say that only slices that are within the clipRect are actually drawn
|
||||
if (CGRectIsEmpty(slice))
|
||||
continue;
|
||||
|
||||
var minX,
|
||||
maxX,
|
||||
minY,
|
||||
maxY;
|
||||
|
||||
if (side == CPMinXEdge || side == CPMaxXEdge)
|
||||
{
|
||||
// Make sure we have at least 1 pixel to draw a line
|
||||
if (CGRectGetWidth(slice) < 1.0)
|
||||
continue;
|
||||
|
||||
minX = CGRectGetMinX(slice) + 0.5;
|
||||
maxX = minX;
|
||||
minY = CGRectGetMinY(slice);
|
||||
maxY = CGRectGetMaxY(slice);
|
||||
}
|
||||
else // CPMinYEdge || CPMaxYEdge
|
||||
{
|
||||
// Make sure we have at least 1 pixel to draw a line
|
||||
if (CGRectGetHeight(slice) < 1.0)
|
||||
continue;
|
||||
|
||||
minX = CGRectGetMinX(slice);
|
||||
maxX = CGRectGetMaxX(slice);
|
||||
minY = CGRectGetMinY(slice) + 0.5;
|
||||
maxY = minY;
|
||||
}
|
||||
|
||||
CGContextBeginPath(context);
|
||||
CGContextMoveToPoint(context, minX, minY);
|
||||
CGContextAddLineToPoint(context, maxX, maxY);
|
||||
CGContextSetStrokeColor(context, colors[sideIndex]);
|
||||
CGContextStrokePath(context);
|
||||
}
|
||||
|
||||
CGContextRestoreGState(context);
|
||||
|
||||
return resultRect;
|
||||
}
|
||||
@@ -20,13 +20,7 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
@import "CGContext.j"
|
||||
|
||||
|
||||
var CPGraphicsContextCurrent = nil,
|
||||
CPGraphicsContextThreadStack = nil;
|
||||
var CPGraphicsContextCurrent = nil;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@@ -34,7 +28,7 @@ var CPGraphicsContextCurrent = nil,
|
||||
*/
|
||||
@implementation CPGraphicsContext : CPObject
|
||||
{
|
||||
CGContext _graphicsPort;
|
||||
CPContext _graphicsPort;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -53,29 +47,6 @@ var CPGraphicsContextCurrent = nil,
|
||||
CPGraphicsContextCurrent = aGraphicsContext;
|
||||
}
|
||||
|
||||
+ (void)saveGraphicsState
|
||||
{
|
||||
if (!CPGraphicsContextCurrent)
|
||||
return;
|
||||
|
||||
if (!CPGraphicsContextThreadStack)
|
||||
CPGraphicsContextThreadStack = [CPMutableArray array];
|
||||
|
||||
[CPGraphicsContextThreadStack addObject:CPGraphicsContextCurrent];
|
||||
[CPGraphicsContextCurrent saveGraphicsState];
|
||||
}
|
||||
|
||||
+ (void)restoreGraphicsState
|
||||
{
|
||||
var lastContext = [CPGraphicsContextThreadStack lastObject];
|
||||
|
||||
if (lastContext)
|
||||
{
|
||||
[lastContext restoreGraphicsState];
|
||||
[CPGraphicsContextThreadStack removeLastObject];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates a graphics context with a provided port.
|
||||
@param aContext the context to initialize with
|
||||
@@ -92,13 +63,13 @@ var CPGraphicsContextCurrent = nil,
|
||||
@param aGraphicsPort the graphics port to initialize with
|
||||
@return the initialized context
|
||||
*/
|
||||
- (id)initWithGraphicsPort:(CGContext)aGraphicsPort
|
||||
- (id)initWithGraphicsPort:(CPContext)aGraphicsPort
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
_graphicsPort = aGraphicsPort;
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -110,27 +81,4 @@ var CPGraphicsContextCurrent = nil,
|
||||
return _graphicsPort;
|
||||
}
|
||||
|
||||
/*!
|
||||
(Not implemented. Always returns Cappuccino's default, `YES`.)
|
||||
|
||||
Return `isFlipped` of the receiver's focused view, unless no view is focused in which case the receiver's
|
||||
`flipped` flag, as set by `graphicsContextWithGraphicsPort:flipped:`, is returned.
|
||||
|
||||
Note: Cappuccino is flipped by default.
|
||||
*/
|
||||
- (BOOL)isFlipped
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)saveGraphicsState
|
||||
{
|
||||
CGContextSaveGState(_graphicsPort);
|
||||
}
|
||||
|
||||
- (void)restoreGraphicsState
|
||||
{
|
||||
CGContextRestoreGState(_graphicsPort);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+33
-599
@@ -25,27 +25,11 @@
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPRunLoop.j>
|
||||
@import <Foundation/CPString.j>
|
||||
@import <Foundation/CPData.j>
|
||||
@import <Foundation/CPKeyedArchiver.j>
|
||||
@import <Foundation/CPKeyedUnarchiver.j>
|
||||
|
||||
@import "CGGeometry.j"
|
||||
@import "CPCompatibility.j"
|
||||
@import "CPGeometry.j"
|
||||
|
||||
@class CPColor
|
||||
#include "Platform/Platform.h"
|
||||
|
||||
@protocol CPImageDelegate <CPObject>
|
||||
|
||||
@optional
|
||||
- (void)imageDidLoad:(CPImage)anImage;
|
||||
- (void)imageDidError:(CPImage)anImage;
|
||||
- (void)imageDidAbort:(CPImage)anImage;
|
||||
|
||||
@end
|
||||
|
||||
var CPImageDelegate_imageDidLoad_ = 1 << 1,
|
||||
CPImageDelegate_imageDidError_ = 1 << 2,
|
||||
CPImageDelegate_imageDidAbort_ = 1 << 3;
|
||||
|
||||
CPImageLoadStatusInitialized = 0;
|
||||
CPImageLoadStatusLoading = 1;
|
||||
@@ -62,48 +46,20 @@ CPImageNameColorPanel = @"CPImageNameColorPanel";
|
||||
CPImageNameColorPanelHighlighted = @"CPImageNameColorPanelHighlighted";
|
||||
|
||||
var imagesForNames = { },
|
||||
AppKitImageForNames = { },
|
||||
ImageDescriptionFormat = "%s {\n filename: \"%s\",\n size: { width:%f, height:%f }\n}";
|
||||
AppKitImageForNames = { };
|
||||
|
||||
AppKitImageForNames[CPImageNameColorPanel] = CGSizeMake(26.0, 29.0);
|
||||
AppKitImageForNames[CPImageNameColorPanelHighlighted] = CGSizeMake(26.0, 29.0);
|
||||
|
||||
/*!
|
||||
Returns a resource image with a relative path and size
|
||||
in a bundle.
|
||||
|
||||
@param filename A filename or relative path to a resource image.
|
||||
@param width Width of the image. May be omitted.
|
||||
@param height Height of the image. May be omitted if width is omitted.
|
||||
@param size Instead of passing width/height, a CGSize may be passed.
|
||||
@param bundle Bundle in which the image resource can be found.
|
||||
If omitted, defaults to the main bundle.
|
||||
@return CPImage
|
||||
*/
|
||||
function CPImageInBundle()
|
||||
function CPImageInBundle(aFilename, aSize, aBundle)
|
||||
{
|
||||
var filename = arguments[0],
|
||||
size = nil,
|
||||
bundle = nil;
|
||||
if (!aBundle)
|
||||
aBundle = [CPBundle mainBundle];
|
||||
|
||||
if (typeof(arguments[1]) === "number")
|
||||
{
|
||||
size = CGSizeMake(arguments[1], arguments[2]);
|
||||
bundle = arguments[3];
|
||||
}
|
||||
else if (typeof(arguments[1]) === "object")
|
||||
{
|
||||
size = arguments[1];
|
||||
bundle = arguments[2];
|
||||
}
|
||||
if (aSize)
|
||||
return [[CPImage alloc] initWithContentsOfFile:[aBundle pathForResource:aFilename] size:aSize];
|
||||
|
||||
if (!bundle)
|
||||
bundle = [CPBundle mainBundle];
|
||||
|
||||
if (size)
|
||||
return [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:filename] size:size];
|
||||
|
||||
return [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:filename]];
|
||||
return [[CPImage alloc] initWithContentsOfFile:[aBundle pathForResource:aFilename]];
|
||||
}
|
||||
|
||||
function CPAppKitImage(aFilename, aSize)
|
||||
@@ -111,7 +67,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
return CPImageInBundle(aFilename, aSize, [CPBundle bundleForClass:[CPView class]]);
|
||||
}
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPImage
|
||||
|
||||
@@ -119,7 +75,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
|
||||
@@ -134,15 +90,14 @@ function CPAppKitImage(aFilename, aSize)
|
||||
*/
|
||||
@implementation CPImage : CPObject
|
||||
{
|
||||
CGSize _size;
|
||||
CPString _filename;
|
||||
CPString _name;
|
||||
CGSize _size;
|
||||
CPString _filename;
|
||||
CPString _name;
|
||||
|
||||
id <CPImageDelegate> _delegate;
|
||||
unsigned _loadStatus;
|
||||
unsigned _implementedDelegateMethods;
|
||||
id _delegate;
|
||||
unsigned _loadStatus;
|
||||
|
||||
Image _image;
|
||||
Image _image;
|
||||
}
|
||||
|
||||
- (id)init
|
||||
@@ -152,24 +107,19 @@ function CPAppKitImage(aFilename, aSize)
|
||||
|
||||
/*!
|
||||
Initializes the image, by associating it with a filename. The image
|
||||
denoted in \c aFilename is not actually loaded. It will be loaded
|
||||
once needed.
|
||||
|
||||
denoted in \c aFilename is not actually loaded. It will
|
||||
be loaded once needed.
|
||||
@param aFilename the file containing the image
|
||||
@param aSize the image's size
|
||||
@return the initialized image
|
||||
*/
|
||||
- (id)initByReferencingFile:(CPString)aFilename size:(CGSize)aSize
|
||||
{
|
||||
// Quietly return nil like in Cocoa, rather than crashing later.
|
||||
if (aFilename == nil)
|
||||
return nil;
|
||||
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_size = CGSizeMakeCopy(aSize);
|
||||
_size = CPSizeCreateCopy(aSize);
|
||||
_filename = aFilename;
|
||||
_loadStatus = CPImageLoadStatusInitialized;
|
||||
}
|
||||
@@ -209,20 +159,6 @@ function CPAppKitImage(aFilename, aSize)
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Initializes the receiver with the specified data. The method loads the data into memory.
|
||||
@param someData the CPData object representing the image
|
||||
@return the initialized image
|
||||
*/
|
||||
- (id)initWithData:(CPData)someData
|
||||
{
|
||||
var base64 = [someData base64],
|
||||
type = [base64 hasPrefix:@"/9j/4AAQSkZJRgABAQEASABIAAD/"] ? @"jpg" : @"png",
|
||||
dataURL = "data:image/" + type + ";base64," + base64;
|
||||
|
||||
return [self initWithContentsOfFile:dataURL];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the path of the file associated with this image.
|
||||
*/
|
||||
@@ -231,37 +167,6 @@ function CPAppKitImage(aFilename, aSize)
|
||||
return _filename;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the data associated with this image.
|
||||
@discussion Returns nil if the reciever was not initialized with -initWithData: and the browser does not support the canvas feature;
|
||||
*/
|
||||
- (CPData)data
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
var dataURL;
|
||||
|
||||
if ([_filename hasPrefix:@"data:image"])
|
||||
dataURL = _filename;
|
||||
else if (CPFeatureIsCompatible(CPHTMLCanvasFeature))
|
||||
{
|
||||
var canvas = document.createElement("canvas"),
|
||||
ctx = canvas.getContext("2d");
|
||||
|
||||
canvas.width = _image.width;
|
||||
canvas.height = _image.height;
|
||||
|
||||
ctx.drawImage(_image, 0, 0);
|
||||
|
||||
dataURL = canvas.toDataURL("image/png");
|
||||
}
|
||||
else
|
||||
return nil;
|
||||
|
||||
var base64 = dataURL.replace(/^data:image\/png;base64,/, "");
|
||||
return [CPData dataWithBase64:base64];
|
||||
#endif
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the size of the image.
|
||||
@param the size of the image
|
||||
@@ -276,7 +181,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
*/
|
||||
- (CGSize)size
|
||||
{
|
||||
return CGSizeMakeCopy(_size);
|
||||
return _size;
|
||||
}
|
||||
|
||||
+ (id)imageNamed:(CPString)aName
|
||||
@@ -288,9 +193,6 @@ function CPAppKitImage(aFilename, aSize)
|
||||
|
||||
var imageOrSize = AppKitImageForNames[aName];
|
||||
|
||||
if (!imageOrSize)
|
||||
return nil;
|
||||
|
||||
if (!imageOrSize.isa)
|
||||
{
|
||||
imageOrSize = CPAppKitImage("CPImage/" + aName + ".png", imageOrSize);
|
||||
@@ -303,19 +205,17 @@ function CPAppKitImage(aFilename, aSize)
|
||||
return imageOrSize;
|
||||
}
|
||||
|
||||
- (BOOL)setName:(CPString)aName
|
||||
- (void)setName:(CPString)aName
|
||||
{
|
||||
if (_name === aName)
|
||||
return YES;
|
||||
return;
|
||||
|
||||
if (imagesForNames[aName])
|
||||
return NO;
|
||||
if (imagesForNames[aName] === self)
|
||||
imagesForNames[aName] = nil;
|
||||
|
||||
_name = aName;
|
||||
|
||||
imagesForNames[aName] = self;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (CPString)name
|
||||
@@ -323,34 +223,13 @@ function CPAppKitImage(aFilename, aSize)
|
||||
return _name;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the underlying Image element for a single image.
|
||||
*/
|
||||
- (Image)image
|
||||
{
|
||||
return _image;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the receiver's delegate.
|
||||
@param the delegate
|
||||
*/
|
||||
- (void)setDelegate:(id <CPImageDelegate>)aDelegate
|
||||
- (void)setDelegate:(id)aDelegate
|
||||
{
|
||||
if (_delegate === aDelegate)
|
||||
return;
|
||||
|
||||
_delegate = aDelegate;
|
||||
_implementedDelegateMethods = 0;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(imageDidLoad:)])
|
||||
_implementedDelegateMethods |= CPImageDelegate_imageDidLoad_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(imageDidError:)])
|
||||
_implementedDelegateMethods |= CPImageDelegate_imageDidError_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(imageDidAbort:)])
|
||||
_implementedDelegateMethods |= CPImageDelegate_imageDidAbort_;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -398,7 +277,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
|
||||
}
|
||||
[self _derefFromImage];
|
||||
};
|
||||
}
|
||||
|
||||
_image.onerror = function ()
|
||||
{
|
||||
@@ -410,7 +289,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
|
||||
}
|
||||
[self _derefFromImage];
|
||||
};
|
||||
}
|
||||
|
||||
_image.onabort = function ()
|
||||
{
|
||||
@@ -422,7 +301,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
|
||||
}
|
||||
[self _derefFromImage];
|
||||
};
|
||||
}
|
||||
|
||||
_image.src = _filename;
|
||||
|
||||
@@ -432,11 +311,6 @@ function CPAppKitImage(aFilename, aSize)
|
||||
#endif
|
||||
}
|
||||
|
||||
- (BOOL)isSingleImage
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)isThreePartImage
|
||||
{
|
||||
return NO;
|
||||
@@ -447,29 +321,6 @@ function CPAppKitImage(aFilename, aSize)
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)isMaterialIconImage
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
var filename = [self filename],
|
||||
size = [self size];
|
||||
|
||||
if (filename.indexOf("data:") === 0)
|
||||
{
|
||||
var index = filename.indexOf(",");
|
||||
|
||||
if (index > 0)
|
||||
filename = [CPString stringWithFormat:@"%s,%s...%s", filename.substr(0, index), filename.substr(index + 1, 10), filename.substr(filename.length - 10)];
|
||||
else
|
||||
filename = "data:<unknown type>";
|
||||
}
|
||||
|
||||
return [CPString stringWithFormat:ImageDescriptionFormat, [super description], filename, size.width, size.height];
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (void)_derefFromImage
|
||||
{
|
||||
@@ -491,7 +342,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
postNotificationName:CPImageDidLoadNotification
|
||||
object:self];
|
||||
|
||||
if (_implementedDelegateMethods & CPImageDelegate_imageDidLoad_)
|
||||
if ([_delegate respondsToSelector:@selector(imageDidLoad:)])
|
||||
[_delegate imageDidLoad:self];
|
||||
}
|
||||
|
||||
@@ -500,7 +351,7 @@ function CPAppKitImage(aFilename, aSize)
|
||||
{
|
||||
_loadStatus = CPImageLoadStatusReadError;
|
||||
|
||||
if (_implementedDelegateMethods & CPImageDelegate_imageDidError_)
|
||||
if ([_delegate respondsToSelector:@selector(imageDidError:)])
|
||||
[_delegate imageDidError:self];
|
||||
}
|
||||
|
||||
@@ -509,235 +360,12 @@ function CPAppKitImage(aFilename, aSize)
|
||||
{
|
||||
_loadStatus = CPImageLoadStatusCancelled;
|
||||
|
||||
if (_implementedDelegateMethods & CPImageDelegate_imageDidAbort_)
|
||||
if ([_delegate respondsToSelector:@selector(imageDidAbort:)])
|
||||
[_delegate imageDidAbort:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark CSS Theming
|
||||
|
||||
// The code below adds support for CSS theming with 100% compatibility with current theming system.
|
||||
// The idea is to extend CPImage (and CPColor) with CSS components and adapt low level UI components to
|
||||
// support this new kind of CPColor/CPImage. See CPImageView, CPView and _CPImageAndTextView.
|
||||
//
|
||||
// To create a CPImage that uses CSS, simply use the new class method :
|
||||
// + (CPImage)imageWithCSSDictionary:(CPDictionary)aDictionary beforeDictionary:(CPDictionary)beforeDictionary afterDictionary:(CPDictionary)afterDictionary size:(CGSize)aSize
|
||||
// where beforeDictionary & afterDictionary are related to ::before & ::after pseudo-elements.
|
||||
// If you don't need them, just use the simplified class method :
|
||||
// + (CPImage)imageWithCSSDictionary:(CPDictionary)aDictionary size:(CGSize)aSize
|
||||
//
|
||||
// Examples :
|
||||
// regularImageNormal = [CPImage imageWithCSSDictionary:@{
|
||||
// @"border-color": A3ColorActiveBorder,
|
||||
// @"border-style": @"solid",
|
||||
// @"border-width": @"1px",
|
||||
// @"border-radius": @"50%",
|
||||
// @"box-sizing": @"border-box",
|
||||
// @"background-color": A3ColorBackgroundWhite,
|
||||
// @"transition-duration": @"0.35s",
|
||||
// @"transition-property": @"all",
|
||||
// @"transition-timing-function": @"ease"
|
||||
// }
|
||||
// size:CGSizeMake(16,16)];
|
||||
//
|
||||
// imageSearch = [CPImage imageWithCSSDictionary:@{
|
||||
// @"background-image": @"url(%%packed.png)",
|
||||
// @"background-position": @"-16px -32px",
|
||||
// @"background-repeat": @"no-repeat",
|
||||
// @"background-size": @"100px 400px"
|
||||
// }
|
||||
// size:CGSizeMake(16,16)];
|
||||
//
|
||||
// Remark : Please note the special URL of the background image used in this example : url(%%packed.png)
|
||||
// During theme loading, "%%" will be replaced by the path to the theme blend resources folder.
|
||||
// Typically, a CSS theme will use some (rare) images all packed together in a single image resource (see packed.png in Aristo3 theme)
|
||||
//
|
||||
// Also, please note that if you don't use one of the CSS components, you can either set it to nil (best solution) or to an empty dictionary, like :
|
||||
// aCssImage = [CPImage imageWithCSSDictionary:@{} beforeDictionary:nil afterDictionary:@{ ... }];
|
||||
//
|
||||
// You can use -(BOOL)isCSSBased to determine how to cope with it in your code.
|
||||
// -(BOOL)hasCSSDictionary, -(BOOL)hasCSSBeforeDictionary and -(BOOL)hasCSSAfterDictionary are convience methods you can use.
|
||||
//
|
||||
// Remark : -(DOMElement)applyCSSImageForView is meant to be used by low level UI widgets (like CPImageView and _CPImageAndTextView) to implement CSS theme support.
|
||||
//
|
||||
// In some circumstances, you may have to clear a CSS image. You can do this easily by replacing your current image with the special dummy empty CSS image :
|
||||
// [CPImage dummyCSSImageOfSize:CGSizeMake(someWidth, someHeight)]
|
||||
|
||||
@implementation CPImage (CSSTheming)
|
||||
{
|
||||
CPDictionary _cssDictionary @accessors(property=cssDictionary);
|
||||
CPDictionary _cssBeforeDictionary @accessors(property=cssBeforeDictionary);
|
||||
CPDictionary _cssAfterDictionary @accessors(property=cssAfterDictionary);
|
||||
CGSize _displaySize;
|
||||
}
|
||||
|
||||
+ (CPImage)imageWithCSSDictionary:(CPDictionary)aDictionary size:(CGSize)aSize
|
||||
{
|
||||
return [[CPImage alloc] initWithCSSDictionary:aDictionary beforeDictionary:nil afterDictionary:nil size:aSize];
|
||||
}
|
||||
|
||||
+ (CPImage)imageWithCSSDictionary:(CPDictionary)aDictionary beforeDictionary:(CPDictionary)beforeDictionary afterDictionary:(CPDictionary)afterDictionary size:(CGSize)aSize
|
||||
{
|
||||
return [[CPImage alloc] initWithCSSDictionary:aDictionary beforeDictionary:beforeDictionary afterDictionary:afterDictionary size:aSize];
|
||||
}
|
||||
|
||||
+ (CPImage)dummyCSSImageOfSize:(CGSize)aSize
|
||||
{
|
||||
// This is used to clear a previous CSS image
|
||||
return [[CPImage alloc] initWithCSSDictionary:@{} beforeDictionary:nil afterDictionary:nil size:aSize];
|
||||
}
|
||||
|
||||
+ (CPImage)imageWithMaterialIconNamed:(CPString)iconName size:(CGSize)size
|
||||
{
|
||||
return [_CPMaterialIconImage imageWithIconNamed:iconName size:size];
|
||||
}
|
||||
|
||||
+ (CPImage)imageWithMaterialIconNamed:(CPString)iconName size:(CGSize)size color:(CPColor)color
|
||||
{
|
||||
return [_CPMaterialIconImage imageWithIconNamed:iconName size:size color:color];
|
||||
}
|
||||
|
||||
- (id)initWithCSSDictionary:(CPDictionary)aDictionary beforeDictionary:(CPDictionary)beforeDictionary afterDictionary:(CPDictionary)afterDictionary size:(CGSize)aSize
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_size = CGSizeMakeCopy(aSize);
|
||||
_filename = @"CSS image";
|
||||
_loadStatus = CPImageLoadStatusCompleted;
|
||||
_cssDictionary = aDictionary;
|
||||
_cssBeforeDictionary = beforeDictionary;
|
||||
_cssAfterDictionary = afterDictionary;
|
||||
_displaySize = CGSizeMakeCopy(aSize);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)isCSSBased
|
||||
{
|
||||
return !!(_cssDictionary || _cssBeforeDictionary || _cssAfterDictionary);
|
||||
}
|
||||
|
||||
- (BOOL)hasCSSDictionary
|
||||
{
|
||||
return ([_cssDictionary count] > 0);
|
||||
}
|
||||
|
||||
- (BOOL)hasCSSBeforeDictionary
|
||||
{
|
||||
return ([_cssBeforeDictionary count] > 0);
|
||||
}
|
||||
|
||||
- (BOOL)hasCSSAfterDictionary
|
||||
{
|
||||
return ([_cssAfterDictionary count] > 0);
|
||||
}
|
||||
|
||||
- (DOMElement)applyCSSImageForView:(CPView)aView onDOMElement:(DOMElement)aDOMElement styleNode:(DOMElement)aStyleNode previousState:(CPArrayRef)aPreviousStateRef
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
// First, restore previous CSS styling before applying the new one
|
||||
|
||||
var aPreviousState = @deref(aPreviousStateRef);
|
||||
|
||||
for (var i = 0, count = aPreviousState.length; i < count; i++)
|
||||
aDOMElement.style[aPreviousState[i][0]] = aPreviousState[i][1];
|
||||
|
||||
aPreviousState = @[];
|
||||
|
||||
// Then apply new CSS styling
|
||||
|
||||
[_cssDictionary enumerateKeysAndObjectsUsingBlock:function(aKey, anObject, stop)
|
||||
{
|
||||
[aPreviousState addObject:@[aKey, aDOMElement.style[aKey]]];
|
||||
aDOMElement.style[aKey] = anObject;
|
||||
}];
|
||||
|
||||
if (_cssBeforeDictionary || _cssAfterDictionary)
|
||||
{
|
||||
// We need to create a unique class name
|
||||
|
||||
var styleClassName = @".CP" + [aView UID],
|
||||
styleContent = @"";
|
||||
|
||||
if (_cssBeforeDictionary)
|
||||
{
|
||||
styleContent += styleClassName + @"::before { ";
|
||||
|
||||
[_cssBeforeDictionary enumerateKeysAndObjectsUsingBlock:function(aKey, anObject, stop)
|
||||
{
|
||||
styleContent += aKey + ": " + anObject + "; ";
|
||||
}];
|
||||
|
||||
styleContent += "} ";
|
||||
}
|
||||
|
||||
if (_cssAfterDictionary)
|
||||
{
|
||||
styleContent += styleClassName + @"::after { ";
|
||||
|
||||
[_cssAfterDictionary enumerateKeysAndObjectsUsingBlock:function(aKey, anObject, stop)
|
||||
{
|
||||
styleContent += aKey + ": " + anObject + "; ";
|
||||
}];
|
||||
|
||||
styleContent += "} ";
|
||||
}
|
||||
|
||||
var styleDescription = document.createTextNode(styleContent);
|
||||
|
||||
if (!aStyleNode)
|
||||
{
|
||||
aStyleNode = document.createElement("style");
|
||||
|
||||
aView._DOMElement.insertBefore(aStyleNode, aView._DOMElement.firstChild);
|
||||
|
||||
aStyleNode.appendChild(styleDescription);
|
||||
}
|
||||
else
|
||||
{
|
||||
aStyleNode.replaceChild(styleDescription, aStyleNode.firstChild);
|
||||
}
|
||||
|
||||
aDOMElement.className = @"CP"+[aView UID];
|
||||
}
|
||||
else
|
||||
{
|
||||
// no before/after so remove aStyleNode if existing
|
||||
|
||||
if (aStyleNode)
|
||||
{
|
||||
aView._DOMElement.removeChild(aStyleNode);
|
||||
aStyleNode = nil;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Return actualised values
|
||||
|
||||
@deref(aPreviousStateRef) = aPreviousState;
|
||||
|
||||
return aStyleNode;
|
||||
#endif
|
||||
}
|
||||
|
||||
- (BOOL)_shouldBeResized
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPImageCSSDictionaryKey = @"CPImageCSSDictionaryKey",
|
||||
CPImageCSSBeforeDictionaryKey = @"CPImageCSSBeforeDictionaryKey",
|
||||
CPImageCSSAfterDictionaryKey = @"CPImageCSSAfterDictionaryKey";
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation CPImage (CPCoding)
|
||||
|
||||
/*!
|
||||
@@ -747,10 +375,7 @@ var CPImageCSSDictionaryKey = @"CPImageCSSDictionaryKey",
|
||||
*/
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
if ([aCoder containsValueForKey:CPImageCSSDictionaryKey])
|
||||
return [self initWithCSSDictionary:[aCoder decodeObjectForKey:CPImageCSSDictionaryKey] beforeDictionary:[aCoder decodeObjectForKey:CPImageCSSBeforeDictionaryKey] afterDictionary:[aCoder decodeObjectForKey:CPImageCSSAfterDictionaryKey] size:[aCoder decodeSizeForKey:@"CPSize"]];
|
||||
else
|
||||
return [self initWithContentsOfFile:[aCoder decodeObjectForKey:@"CPFilename"] size:[aCoder decodeSizeForKey:@"CPSize"]];
|
||||
return [self initWithContentsOfFile:[aCoder decodeObjectForKey:@"CPFilename"] size:[aCoder decodeSizeForKey:@"CPSize"]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -761,180 +386,10 @@ var CPImageCSSDictionaryKey = @"CPImageCSSDictionaryKey",
|
||||
{
|
||||
[aCoder encodeObject:_filename forKey:@"CPFilename"];
|
||||
[aCoder encodeSize:_size forKey:@"CPSize"];
|
||||
|
||||
// CSS Styling
|
||||
if ([self isCSSBased])
|
||||
{
|
||||
[aCoder encodeObject:_cssDictionary forKey:CPImageCSSDictionaryKey];
|
||||
[aCoder encodeObject:_cssBeforeDictionary forKey:CPImageCSSBeforeDictionaryKey];
|
||||
[aCoder encodeObject:_cssAfterDictionary forKey:CPImageCSSAfterDictionaryKey];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMaterialIconImage : CPImage
|
||||
{
|
||||
CPMutableDictionary _cachedColorVersions;
|
||||
CPColor _cachedInvertedColor;
|
||||
}
|
||||
|
||||
+ (_CPMaterialIconImage)imageWithIconNamed:(CPString)iconName size:(CGSize)size
|
||||
{
|
||||
return [[_CPMaterialIconImage alloc] initWithIconName:iconName size:size];
|
||||
}
|
||||
|
||||
+ (_CPMaterialIconImage)imageWithIconNamed:(CPString)iconName size:(CGSize)size color:(CPColor)color
|
||||
{
|
||||
return [[_CPMaterialIconImage alloc] initWithIconName:iconName size:size color:color];
|
||||
}
|
||||
|
||||
+ (_CPMaterialIconImage)imageWithIconNamed:(CPString)iconName size:(CGSize)size color:(CPColor)color additionalCSSDictionary:(CPDictionary)additionalCSSDictionary
|
||||
{
|
||||
return [[_CPMaterialIconImage alloc] initWithIconName:iconName size:size color:color additionalCSSDictionary:additionalCSSDictionary];
|
||||
}
|
||||
|
||||
- (CPDictionary)_baseMaterialIconCSSDictionaryForIconName:(CPString)iconName size:(CGSize)size
|
||||
{
|
||||
return @{
|
||||
@"width": size.width + @"px",
|
||||
@"height": size.height + @"px",
|
||||
@"top": @"0px",
|
||||
@"left": @"0px",
|
||||
@"content": @"'" + iconName + @"'",
|
||||
|
||||
@"position": @"absolute",
|
||||
@"z-index": @"300",
|
||||
|
||||
@"font-family": @"'Material Icons'",
|
||||
@"font-weight": @"normal",
|
||||
@"font-style": @"normal",
|
||||
@"font-size": MIN(size.width, size.height) + @"px",
|
||||
@"display": @"inline-block",
|
||||
@"line-height": @"1",
|
||||
@"text-transform": @"none",
|
||||
@"letter-spacing": @"normal",
|
||||
@"word-wrap": @"normal",
|
||||
@"white-space": @"nowrap",
|
||||
@"direction": @"ltr",
|
||||
@"-webkit-font-smoothing": @"antialiased",
|
||||
@"text-rendering": @"optimizeLegibility",
|
||||
@"-moz-osx-font-smoothing": @"grayscale",
|
||||
@"font-feature-settings": @"'liga'"
|
||||
};
|
||||
}
|
||||
|
||||
- (_CPMaterialIconImage)initWithIconName:(CPString)iconName size:(CGSize)size
|
||||
{
|
||||
return [super initWithCSSDictionary:@{}
|
||||
beforeDictionary:@{}
|
||||
afterDictionary:[self _baseMaterialIconCSSDictionaryForIconName:iconName size:size]
|
||||
size:size];
|
||||
}
|
||||
|
||||
- (_CPMaterialIconImage)initWithIconName:(CPString)iconName size:(CGSize)size color:(CPColor)color
|
||||
{
|
||||
var materialIconCSSDictionary = [self _baseMaterialIconCSSDictionaryForIconName:iconName size:size];
|
||||
|
||||
[materialIconCSSDictionary setObject:[color cssString] forKey:@"color"];
|
||||
|
||||
return [super initWithCSSDictionary:@{}
|
||||
beforeDictionary:@{}
|
||||
afterDictionary:materialIconCSSDictionary
|
||||
size:size];
|
||||
}
|
||||
|
||||
- (void)addRotationEffectWithAngle:(float)angle
|
||||
{
|
||||
[self addCSSDictionary:@{
|
||||
@"transform": @"rotate("+angle+"deg)",
|
||||
@"transition": @"transform 0.35s ease"
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)addCSSDictionary:(CPDictionary)additionalCSSDictionary
|
||||
{
|
||||
[_cssAfterDictionary addEntriesFromDictionary:additionalCSSDictionary];
|
||||
}
|
||||
|
||||
- (void)setSize:(CGSize)aSize
|
||||
{
|
||||
[self _setDisplaySize:aSize];
|
||||
[super setSize:aSize];
|
||||
}
|
||||
|
||||
- (void)_setDisplaySize:(CGSize)aSize
|
||||
{
|
||||
if (CGSizeEqualToSize(_displaySize, aSize))
|
||||
return;
|
||||
|
||||
_displaySize = CGSizeMakeCopy(aSize);
|
||||
|
||||
[_cssAfterDictionary setObject:(aSize.width + @"px") forKey:@"width"];
|
||||
[_cssAfterDictionary setObject:(aSize.height + @"px") forKey:@"height"];
|
||||
[_cssAfterDictionary setObject:(MIN(aSize.width, aSize.height) + @"px") forKey:@"font-size"];
|
||||
}
|
||||
|
||||
- (BOOL)_shouldBeResized
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)isMaterialIconImage
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (_CPMaterialIconImage)invertedImage
|
||||
{
|
||||
if (!_cachedInvertedColor)
|
||||
{
|
||||
var sourceCSSColor = [_cssAfterDictionary objectForKey:@"color"] || @"rgba(0,0,0,1)",
|
||||
sourceColor = [CPColor colorWithCSSString:sourceCSSColor];
|
||||
|
||||
_cachedInvertedColor = [CPColor colorWithRed:(1-[sourceColor redComponent])
|
||||
green:(1-[sourceColor greenComponent])
|
||||
blue:(1-[sourceColor blueComponent])
|
||||
alpha:[sourceColor alphaComponent]];
|
||||
}
|
||||
|
||||
return [self imageVersionWithColor:_cachedInvertedColor];
|
||||
}
|
||||
|
||||
- (_CPMaterialIconImage)imageVersionWithColor:(CPColor)aColor
|
||||
{
|
||||
// We can't just set the color in the cssAfterDictionary as this would not be noticed as a new image,
|
||||
// so -setImage won't do anything, so no visual refresh won't occur.
|
||||
// The trick here is to keep in cache a clone of this image for each needed color.
|
||||
var colorCSSString = [aColor cssString];
|
||||
|
||||
if (!_cachedColorVersions)
|
||||
_cachedColorVersions = @{};
|
||||
|
||||
var cachedColorVersion = [_cachedColorVersions objectForKey:colorCSSString];
|
||||
|
||||
if (!cachedColorVersion)
|
||||
{
|
||||
cachedColorVersion = [self duplicate];
|
||||
[cachedColorVersion _setCSSColor:colorCSSString];
|
||||
|
||||
[_cachedColorVersions setObject:cachedColorVersion forKey:colorCSSString];
|
||||
}
|
||||
|
||||
return cachedColorVersion;
|
||||
}
|
||||
|
||||
- (void)_setCSSColor:(CPString)aCSSColor
|
||||
{
|
||||
[_cssAfterDictionary setObject:aCSSColor forKey:@"color"];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation CPThreePartImage : CPObject
|
||||
{
|
||||
CPArray _imageSlices;
|
||||
@@ -969,11 +424,6 @@ var CPImageCSSDictionaryKey = @"CPImageCSSDictionaryKey",
|
||||
return _isVertical;
|
||||
}
|
||||
|
||||
- (BOOL)isSingleImage
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)isThreePartImage
|
||||
{
|
||||
return YES;
|
||||
@@ -1038,11 +488,6 @@ var CPThreePartImageImageSlicesKey = @"CPThreePartImageImageSlicesKey",
|
||||
return _imageSlices;
|
||||
}
|
||||
|
||||
- (BOOL)isSingleImage
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)isThreePartImage
|
||||
{
|
||||
return NO;
|
||||
@@ -1075,14 +520,3 @@ var CPNinePartImageImageSlicesKey = @"CPNinePartImageImageSlicesKey";
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation CPImage (Duplication)
|
||||
|
||||
- (CPImage)duplicate
|
||||
{
|
||||
return [CPKeyedUnarchiver unarchiveObjectWithData:[CPKeyedArchiver archivedDataWithRootObject:self]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+129
-311
@@ -26,23 +26,25 @@
|
||||
@import "CPImage.j"
|
||||
@import "CPShadowView.j"
|
||||
|
||||
@global CPImagesPboardType
|
||||
@global appkit_tag_dom_elements
|
||||
#include "Platform/Platform.h"
|
||||
#include "Platform/DOM/CPDOMDisplayServer.h"
|
||||
|
||||
@typedef CPImageAlignment
|
||||
CPImageAlignCenter = 0;
|
||||
CPImageAlignTop = 1;
|
||||
CPImageAlignTopLeft = 2;
|
||||
CPImageAlignTopRight = 3;
|
||||
CPImageAlignLeft = 4;
|
||||
CPImageAlignBottom = 5;
|
||||
CPImageAlignBottomLeft = 6;
|
||||
CPImageAlignBottomRight = 7;
|
||||
CPImageAlignRight = 8;
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
var CPImageViewEmptyPlaceholderImage = nil;
|
||||
CPScaleProportionally = 0;
|
||||
CPScaleToFit = 1;
|
||||
CPScaleNone = 2;
|
||||
|
||||
/*!
|
||||
var CPImageViewShadowBackgroundColor = nil;
|
||||
|
||||
var LEFT_SHADOW_INSET = 3.0,
|
||||
RIGHT_SHADOW_INSET = 3.0,
|
||||
TOP_SHADOW_INSET = 3.0,
|
||||
BOTTOM_SHADOW_INSET = 5.0,
|
||||
VERTICAL_SHADOW_INSET = TOP_SHADOW_INSET + BOTTOM_SHADOW_INSET,
|
||||
HORIZONTAL_SHADOW_INSET = LEFT_SHADOW_INSET + RIGHT_SHADOW_INSET;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPImageView
|
||||
|
||||
@@ -50,95 +52,41 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
*/
|
||||
@implementation CPImageView : CPControl
|
||||
{
|
||||
DOMElement _DOMImageElement;
|
||||
DOMElement _DOMImageElement;
|
||||
|
||||
BOOL _hasShadow;
|
||||
CPView _shadowView;
|
||||
|
||||
BOOL _hasShadow;
|
||||
CPView _shadowView;
|
||||
BOOL _isEditable;
|
||||
|
||||
BOOL _isEditable;
|
||||
|
||||
CGRect _imageRect;
|
||||
CPImageAlignment _imageAlignment;
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPImageView class])
|
||||
return;
|
||||
|
||||
var bundle = [CPBundle bundleForClass:[CPView class]];
|
||||
|
||||
CPImageViewEmptyPlaceholderImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"empty.png"]];
|
||||
}
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding === CPValueBinding || aBinding === CPValueURLBinding || aBinding === CPValuePathBinding || aBinding === CPDataBinding)
|
||||
return [CPImageViewValueBinder class];
|
||||
else if ([aBinding hasPrefix:CPEditableBinding])
|
||||
return [CPMultipleValueAndBinding class];
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
CGRect _imageRect;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
[self _createDOMImageElement];
|
||||
#endif
|
||||
}
|
||||
_DOMImageElement = document.createElement("img");
|
||||
_DOMImageElement.style.position = "absolute";
|
||||
_DOMImageElement.style.left = "0px";
|
||||
_DOMImageElement.style.top = "0px";
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_createDOMImageElement
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
var image = [self objectValue],
|
||||
isCSSBasedImage = [image isCSSBased],
|
||||
isIMGImageElement = _DOMImageElement && (_DOMImageElement.nodeName == "IMG");
|
||||
|
||||
// First, check if we need to destroy a current DOM image element. This is the case if :
|
||||
// - we have one but not the right one (that is a DIV but needing an IMG, and vice versa)
|
||||
|
||||
if (_DOMImageElement)
|
||||
{
|
||||
if ((isIMGImageElement && isCSSBasedImage) || (!isIMGImageElement && !isCSSBasedImage))
|
||||
if ([CPPlatform supportsDragAndDrop])
|
||||
{
|
||||
// OK, destroy it
|
||||
|
||||
_DOMElement.removeChild(_DOMImageElement);
|
||||
|
||||
_DOMImageElement = nil;
|
||||
|
||||
// CSS styling cleaning
|
||||
_cssStylePreviousState = @[];
|
||||
_cssStyleNode = nil;
|
||||
_DOMImageElement.setAttribute("draggable", "true");
|
||||
_DOMImageElement.style["-khtml-user-drag"] = "element";
|
||||
}
|
||||
else
|
||||
return;
|
||||
}
|
||||
|
||||
_DOMImageElement = document.createElement(isCSSBasedImage ? "div" : "img");
|
||||
_DOMImageElement.style.position = "absolute";
|
||||
_DOMImageElement.style.left = "0px";
|
||||
_DOMImageElement.style.top = "0px";
|
||||
|
||||
if ([CPPlatform supportsDragAndDrop])
|
||||
{
|
||||
_DOMImageElement.setAttribute("draggable", "true");
|
||||
_DOMImageElement.style["-khtml-user-drag"] = "element";
|
||||
}
|
||||
|
||||
_DOMImageElement.style.visibility = "hidden";
|
||||
AppKitTagDOMElement(self, _DOMImageElement);
|
||||
|
||||
CPDOMDisplayServerAppendChild(_DOMElement, _DOMImageElement);
|
||||
CPDOMDisplayServerAppendChild(_DOMElement, _DOMImageElement);
|
||||
|
||||
_DOMImageElement.style.visibility = "hidden";
|
||||
#endif
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -158,37 +106,29 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
- (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)
|
||||
[self _createDOMImageElement];
|
||||
|
||||
if ([newImage isCSSBased])
|
||||
_cssStyleNode = [newImage applyCSSImageForView:self
|
||||
onDOMElement:_DOMImageElement
|
||||
styleNode:_cssStyleNode
|
||||
previousState:@ref(_cssStylePreviousState)];
|
||||
else
|
||||
_DOMImageElement.src = newImage ? [newImage filename] : [CPImageViewEmptyPlaceholderImage filename];
|
||||
_DOMImageElement.src = newImage ? [newImage 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;
|
||||
@@ -206,9 +146,8 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
|
||||
- (void)imageDidLoad:(CPNotification)aNotification
|
||||
{
|
||||
[[CPNotificationCenter defaultCenter] removeObserver:self name:CPImageDidLoadNotification object:[self objectValue]];
|
||||
[self hideOrDisplayContents];
|
||||
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
@@ -230,52 +169,28 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
{
|
||||
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];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the type of image alignment that should be used to
|
||||
render the image.
|
||||
@param anImageAlignment the type of scaling to use
|
||||
*/
|
||||
- (void)setImageAlignment:(CPImageAlignment)anImageAlignment
|
||||
{
|
||||
if (_imageAlignment == anImageAlignment)
|
||||
return;
|
||||
|
||||
_imageAlignment = anImageAlignment;
|
||||
|
||||
if (![self image])
|
||||
return;
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (unsigned)imageAlignment
|
||||
{
|
||||
return _imageAlignment;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the type of image scaling that should be used to
|
||||
render the image.
|
||||
@@ -284,19 +199,19 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
- (void)setImageScaling:(CPImageScaling)anImageScaling
|
||||
{
|
||||
[super setImageScaling:anImageScaling];
|
||||
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
if ([self currentValueForThemeAttribute:@"image-scaling"] === CPImageScaleAxesIndependently)
|
||||
if ([self currentValueForThemeAttribute:@"image-scaling"] === CPScaleToFit)
|
||||
{
|
||||
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, 0.0, 0.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (CPUInteger)imageScaling
|
||||
- (unsigned)imageScaling
|
||||
{
|
||||
return [self currentValueForThemeAttribute:@"image-scaling"];
|
||||
}
|
||||
@@ -343,123 +258,78 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
imageScaling = [self currentValueForThemeAttribute:@"image-scaling"],
|
||||
x = 0.0,
|
||||
y = 0.0,
|
||||
insetWidth = (_hasShadow ? [_shadowView horizontalInset] : 0.0),
|
||||
insetHeight = (_hasShadow ? [_shadowView verticalInset] : 0.0),
|
||||
boundsWidth = CGRectGetWidth(bounds),
|
||||
boundsHeight = CGRectGetHeight(bounds),
|
||||
insetWidth = (_hasShadow ? HORIZONTAL_SHADOW_INSET : 0.0),
|
||||
insetHeight = (_hasShadow ? VERTICAL_SHADOW_INSET : 0.0),
|
||||
boundsWidth = _CGRectGetWidth(bounds),
|
||||
boundsHeight = _CGRectGetHeight(bounds),
|
||||
width = boundsWidth - insetWidth,
|
||||
height = boundsHeight - insetHeight;
|
||||
|
||||
if (imageScaling === CPImageScaleAxesIndependently)
|
||||
if (imageScaling === CPScaleToFit)
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
_DOMImageElement.width = ROUND(width);
|
||||
_DOMImageElement.height = ROUND(height);
|
||||
#endif
|
||||
#if PLATFORM(DOM)
|
||||
_DOMImageElement.width = ROUND(width);
|
||||
_DOMImageElement.height = ROUND(height);
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
var size = [image size];
|
||||
|
||||
|
||||
if (size.width == -1 && size.height == -1)
|
||||
return;
|
||||
|
||||
switch (imageScaling)
|
||||
if (imageScaling === CPScaleProportionally)
|
||||
{
|
||||
case CPImageScaleProportionallyDown:
|
||||
if (width >= size.width && height >= size.height)
|
||||
{
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
break;
|
||||
}
|
||||
|
||||
// intentionally fall through to the next case
|
||||
|
||||
case CPImageScaleProportionallyUpOrDown:
|
||||
// The max size it can be is size.width x size.height, so only
|
||||
// only proportion otherwise.
|
||||
if (width >= size.width && height >= size.height)
|
||||
{
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
}
|
||||
else
|
||||
{
|
||||
var imageRatio = size.width / size.height,
|
||||
viewRatio = width / height;
|
||||
|
||||
|
||||
if (viewRatio > imageRatio)
|
||||
width = height * imageRatio;
|
||||
else
|
||||
height = width / imageRatio;
|
||||
break;
|
||||
}
|
||||
|
||||
case CPImageScaleAxesIndependently:
|
||||
case CPImageScaleNone:
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
break;
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
#if PLATFORM(DOM)
|
||||
_DOMImageElement.width = ROUND(width);
|
||||
_DOMImageElement.height = ROUND(height);
|
||||
#endif
|
||||
|
||||
var x,
|
||||
y;
|
||||
|
||||
switch (_imageAlignment)
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
case CPImageAlignLeft:
|
||||
case CPImageAlignTopLeft:
|
||||
case CPImageAlignBottomLeft:
|
||||
x = 0.0;
|
||||
break;
|
||||
|
||||
case CPImageAlignRight:
|
||||
case CPImageAlignTopRight:
|
||||
case CPImageAlignBottomRight:
|
||||
x = boundsWidth - width;
|
||||
break;
|
||||
|
||||
default:
|
||||
x = (boundsWidth - width) / 2.0;
|
||||
break;
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
}
|
||||
|
||||
if (imageScaling == CPScaleNone)
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
_DOMImageElement.width = ROUND(size.width);
|
||||
_DOMImageElement.height = ROUND(size.height);
|
||||
#endif
|
||||
}
|
||||
|
||||
switch (_imageAlignment)
|
||||
{
|
||||
case CPImageAlignTop:
|
||||
case CPImageAlignTopLeft:
|
||||
case CPImageAlignTopRight:
|
||||
y = 0.0;
|
||||
break;
|
||||
|
||||
case CPImageAlignBottom:
|
||||
case CPImageAlignBottomLeft:
|
||||
case CPImageAlignBottomRight:
|
||||
y = boundsHeight - height;
|
||||
break;
|
||||
|
||||
default:
|
||||
y = (boundsHeight - height) / 2.0;
|
||||
break;
|
||||
}
|
||||
var x = (boundsWidth - width) / 2.0,
|
||||
y = (boundsHeight - height) / 2.0;
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
CPDOMDisplayServerSetStyleLeftTop(_DOMImageElement, NULL, x, y);
|
||||
#endif
|
||||
}
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
if ([image isCSSBased] && [image _shouldBeResized])
|
||||
{
|
||||
[image _setDisplaySize:CGSizeMake(ROUND(width), ROUND(height))];
|
||||
|
||||
_cssStyleNode = [image applyCSSImageForView:self
|
||||
onDOMElement:_DOMImageElement
|
||||
styleNode:_cssStyleNode
|
||||
previousState:@ref(_cssStylePreviousState)];
|
||||
}
|
||||
#endif
|
||||
|
||||
_imageRect = CGRectMake(x, y, width, height);
|
||||
|
||||
_imageRect = _CGRectMake(x, y, width, height);
|
||||
|
||||
if (_hasShadow)
|
||||
[_shadowView setFrame:CGRectMake(x - [_shadowView leftInset], y - [_shadowView topInset], width + insetWidth, height + insetHeight)];
|
||||
[_shadowView setFrame:_CGRectMake(x - LEFT_SHADOW_INSET, y - TOP_SHADOW_INSET, width + insetWidth, height + insetHeight)];
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
@@ -495,7 +365,7 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
return _isEditable;
|
||||
}
|
||||
|
||||
- (BOOL)performDragOperation:(CPDraggingInfo)aSender
|
||||
- (void)performDragOperation:(CPDraggingInfo)aSender
|
||||
{
|
||||
var images = [CPKeyedUnarchiver unarchiveObjectWithData:[[aSender draggingPasteboard] dataForType:CPImagesPboardType]];
|
||||
|
||||
@@ -504,64 +374,14 @@ var CPImageViewEmptyPlaceholderImage = nil;
|
||||
[self setImage:images[0]];
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPImageViewValueBinder : CPBinder
|
||||
{
|
||||
}
|
||||
|
||||
- (void)_updatePlaceholdersWithOptions:(CPDictionary)options
|
||||
{
|
||||
[self _setPlaceholder:nil forMarker:CPMultipleValuesMarker isDefault:YES];
|
||||
[self _setPlaceholder:nil forMarker:CPNoSelectionMarker isDefault:YES];
|
||||
[self _setPlaceholder:nil forMarker:CPNotApplicableMarker isDefault:YES];
|
||||
[self _setPlaceholder:nil forMarker:CPNullMarker isDefault:YES];
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source setImage:nil];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
var image;
|
||||
|
||||
if (aValue == nil)
|
||||
image = nil;
|
||||
else if (aBinding === CPDataBinding)
|
||||
image = [[CPImage alloc] initWithData:aValue];
|
||||
else if (aBinding === CPValueURLBinding || aBinding === CPValuePathBinding)
|
||||
image = [CPImage cachedImageWithContentsOfFile:aValue];
|
||||
else if (aBinding === CPValueBinding)
|
||||
image = aValue;
|
||||
|
||||
[_source setImage:image];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
var image = [_source image];
|
||||
|
||||
if (aBinding === CPDataBinding)
|
||||
return [image data];
|
||||
else if (aBinding === CPValueURLBinding || aBinding === CPValuePathBinding)
|
||||
return [image filename];
|
||||
else if (aBinding === CPValueBinding)
|
||||
return image;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPImageViewImageKey = @"CPImageViewImageKey",
|
||||
CPImageViewImageScalingKey = @"CPImageViewImageScalingKey",
|
||||
CPImageViewImageAlignmentKey = @"CPImageViewImageAlignmentKey",
|
||||
CPImageViewHasShadowKey = @"CPImageViewHasShadowKey",
|
||||
CPImageViewIsEditableKey = @"CPImageViewIsEditableKey";
|
||||
var CPImageViewImageKey = @"CPImageViewImageKey",
|
||||
CPImageViewImageScalingKey = @"CPImageViewImageScalingKey",
|
||||
CPImageViewHasShadowKey = @"CPImageViewHasShadowKey",
|
||||
CPImageViewIsEditableKey = @"CPImageViewIsEditableKey";
|
||||
|
||||
@implementation CPImageView (CPCoding)
|
||||
|
||||
@@ -572,24 +392,36 @@ var CPImageViewImageKey = @"CPImageViewImageKey",
|
||||
*/
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
#if PLATFORM(DOM)
|
||||
_DOMImageElement = document.createElement("img");
|
||||
_DOMImageElement.style.position = "absolute";
|
||||
_DOMImageElement.style.left = "0px";
|
||||
_DOMImageElement.style.top = "0px";
|
||||
_DOMImageElement.style.visibility = "hidden";
|
||||
if ([CPPlatform supportsDragAndDrop])
|
||||
{
|
||||
_DOMImageElement.setAttribute("draggable", "true");
|
||||
_DOMImageElement.style["-khtml-user-drag"] = "element";
|
||||
}
|
||||
#endif
|
||||
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
if (self)
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
[self _createDOMImageElement];
|
||||
_DOMElement.appendChild(_DOMImageElement);
|
||||
#endif
|
||||
|
||||
[self setHasShadow:[aCoder decodeBoolForKey:CPImageViewHasShadowKey]];
|
||||
[self setImageAlignment:[aCoder decodeIntForKey:CPImageViewImageAlignmentKey]];
|
||||
|
||||
if ([aCoder decodeBoolForKey:CPImageViewIsEditableKey])
|
||||
|
||||
if ([aCoder decodeBoolForKey:CPImageViewIsEditableKey] || NO)
|
||||
[self setEditable:YES];
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -600,39 +432,25 @@ 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)
|
||||
[_shadowView removeFromSuperview];
|
||||
|
||||
{
|
||||
var actualSubviews = _subviews;
|
||||
|
||||
_subviews = [_subviews copy];
|
||||
[_subviews removeObjectIdenticalTo:_shadowView];
|
||||
}
|
||||
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
|
||||
if (_shadowView)
|
||||
[self addSubview:_shadowView];
|
||||
|
||||
_subviews = actualSubviews;
|
||||
|
||||
[aCoder encodeBool:_hasShadow forKey:CPImageViewHasShadowKey];
|
||||
[aCoder encodeInt:_imageAlignment forKey:CPImageViewImageAlignmentKey];
|
||||
|
||||
if (_isEditable)
|
||||
[aCoder encodeBool:_isEditable forKey:CPImageViewIsEditableKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPImage (CachedImage)
|
||||
|
||||
+ (CPImage)cachedImageWithContentsOfFile:(CPString)aFile
|
||||
{
|
||||
var cached_name = [CPString stringWithFormat:@"%@_%d", [self class], [aFile hash]],
|
||||
image = [CPImage imageNamed:cached_name];
|
||||
|
||||
if (!image)
|
||||
{
|
||||
image = [[CPImage alloc] initWithContentsOfFile:aFile];
|
||||
[image setName:cached_name];
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,265 +0,0 @@
|
||||
/*
|
||||
* CPKeyBinding.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Nicholas Small.
|
||||
* Copyright 2010, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPArray.j>
|
||||
|
||||
@import "CPEvent_Constants.j"
|
||||
@import "CPText.j"
|
||||
|
||||
CPStandardKeyBindings = {
|
||||
@"@.": @"cancelOperation:",
|
||||
|
||||
@"@a": @"selectAll:",
|
||||
@"^a": @"moveToBeginningOfParagraph:",
|
||||
@"^$a": @"moveToBeginningOfParagraphAndModifySelection:",
|
||||
@"^b": @"moveBackward:",
|
||||
@"^$b": @"moveBackwardAndModifySelection:",
|
||||
@"^~b": @"moveWordBackward:",
|
||||
@"^~$b": @"moveWordBackwardAndModifySelection:",
|
||||
@"^d": @"deleteForward:",
|
||||
@"^e": @"moveToEndOfParagraph:",
|
||||
@"^$e": @"moveToEndOfParagraphAndModifySelection:",
|
||||
@"^f": @"moveForward:",
|
||||
@"^$f": @"moveForwardAndModifySelection:",
|
||||
@"^~f": @"moveWordForward:",
|
||||
@"^~$f": @"moveWordForwardAndModifySelection:",
|
||||
@"^h": @"deleteBackward:",
|
||||
@"^k": @"deleteToEndOfParagraph:",
|
||||
@"^l": @"centerSelectionInVisibleArea:",
|
||||
@"^n": @"moveDown:",
|
||||
@"^$n": @"moveDownAndModifySelection:",
|
||||
@"^o": [@"insertNewlineIgnoringFieldEditor:", @"moveBackward:"],
|
||||
@"^p": @"moveUp:",
|
||||
@"^$p": @"moveUpAndModifySelection:",
|
||||
@"^t": @"transpose:",
|
||||
@"^v": @"pageDown:",
|
||||
@"^$v": @"pageDownAndModifySelection:",
|
||||
@"^y": @"yank:"
|
||||
};
|
||||
|
||||
CPStandardKeyBindings[CPNewlineCharacter] = @"insertNewline:";
|
||||
CPStandardKeyBindings[CPCarriageReturnCharacter] = @"insertNewline:";
|
||||
CPStandardKeyBindings[CPEnterCharacter] = @"insertNewline:";
|
||||
CPStandardKeyBindings[@"~" + CPNewlineCharacter] = @"insertNewlineIgnoringFieldEditor:";
|
||||
CPStandardKeyBindings[@"~" + CPCarriageReturnCharacter] = @"insertNewlineIgnoringFieldEditor:";
|
||||
CPStandardKeyBindings[@"~" + CPEnterCharacter] = @"insertNewlineIgnoringFieldEditor:";
|
||||
CPStandardKeyBindings[@"^" + CPNewlineCharacter] = @"insertLineBreak:";
|
||||
CPStandardKeyBindings[@"^" + CPCarriageReturnCharacter] = @"insertLineBreak:";
|
||||
CPStandardKeyBindings[@"^" + CPEnterCharacter] = @"insertLineBreak:";
|
||||
|
||||
CPStandardKeyBindings[CPBackspaceCharacter] = @"deleteBackward:";
|
||||
CPStandardKeyBindings[@"~" + CPBackspaceCharacter] = @"deleteWordBackward:";
|
||||
CPStandardKeyBindings[CPDeleteCharacter] = @"deleteBackward:";
|
||||
CPStandardKeyBindings[@"@" + CPDeleteCharacter] = @"deleteToBeginningOfLine:";
|
||||
CPStandardKeyBindings[@"~" + CPDeleteCharacter] = @"deleteWordBackward:";
|
||||
CPStandardKeyBindings[@"^" + CPDeleteCharacter] = @"deleteBackwardByDecomposingPreviousCharacter:";
|
||||
CPStandardKeyBindings[@"^~" + CPDeleteCharacter] = @"deleteWordBackward:";
|
||||
|
||||
CPStandardKeyBindings[CPDeleteFunctionKey] = @"deleteForward:";
|
||||
CPStandardKeyBindings[@"~" + CPDeleteFunctionKey] = @"deleteWordForward:";
|
||||
|
||||
CPStandardKeyBindings[CPTabCharacter] = @"insertTab:";
|
||||
CPStandardKeyBindings[@"~" + CPTabCharacter] = @"insertTabIgnoringFieldEditor:";
|
||||
CPStandardKeyBindings[@"^" + CPTabCharacter] = @"selectNextKeyView:";
|
||||
CPStandardKeyBindings[CPBackTabCharacter] = @"insertBacktab:";
|
||||
CPStandardKeyBindings[@"^" + CPBackTabCharacter] = @"selectPreviousKeyView:";
|
||||
|
||||
CPStandardKeyBindings[CPEscapeFunctionKey] = @"cancelOperation:";
|
||||
CPStandardKeyBindings[@"~" + CPEscapeFunctionKey] = @"complete:";
|
||||
CPStandardKeyBindings[CPF5FunctionKey] = @"complete:";
|
||||
|
||||
CPStandardKeyBindings[CPLeftArrowFunctionKey] = @"moveLeft:";
|
||||
CPStandardKeyBindings[@"~" + CPLeftArrowFunctionKey] = @"moveWordLeft:";
|
||||
CPStandardKeyBindings[@"^" + CPLeftArrowFunctionKey] = @"moveToLeftEndOfLine:";
|
||||
CPStandardKeyBindings[@"@" + CPLeftArrowFunctionKey] = @"moveToLeftEndOfLine:";
|
||||
CPStandardKeyBindings[@"$" + CPLeftArrowFunctionKey] = @"moveLeftAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$~" + CPLeftArrowFunctionKey] = @"moveWordLeftAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$^" + CPLeftArrowFunctionKey] = @"moveToLeftEndOfLineAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$@" + CPLeftArrowFunctionKey] = @"moveToLeftEndOfLineAndModifySelection:";
|
||||
CPStandardKeyBindings[@"@^" + CPLeftArrowFunctionKey] = @"makeBaseWritingDirectionRightToLeft:";
|
||||
CPStandardKeyBindings[@"@^~" + CPLeftArrowFunctionKey] = @"makeTextWritingDirectionRightToLeft:";
|
||||
|
||||
CPStandardKeyBindings[CPRightArrowFunctionKey] = @"moveRight:";
|
||||
CPStandardKeyBindings[@"~" + CPRightArrowFunctionKey] = @"moveWordRight:";
|
||||
CPStandardKeyBindings[@"^" + CPRightArrowFunctionKey] = @"moveToRightEndOfLine:";
|
||||
CPStandardKeyBindings[@"@" + CPRightArrowFunctionKey] = @"moveToRightEndOfLine:";
|
||||
CPStandardKeyBindings[@"$" + CPRightArrowFunctionKey] = @"moveRightAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$~" + CPRightArrowFunctionKey] = @"moveWordRightAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$^" + CPRightArrowFunctionKey] = @"moveToRightEndOfLineAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$@" + CPRightArrowFunctionKey] = @"moveToRightEndOfLineAndModifySelection:";
|
||||
CPStandardKeyBindings[@"@^" + CPRightArrowFunctionKey] = @"makeBaseWritingDirectionLeftToRight:";
|
||||
CPStandardKeyBindings[@"@^~" + CPRightArrowFunctionKey] = @"makeTextWritingDirectionLeftToRight:";
|
||||
|
||||
CPStandardKeyBindings[CPUpArrowFunctionKey] = @"moveUp:";
|
||||
CPStandardKeyBindings[@"~" + CPUpArrowFunctionKey] = [@"moveBackward:", @"moveToBeginningOfParagraph:"];
|
||||
CPStandardKeyBindings[@"^" + CPUpArrowFunctionKey] = @"scrollPageUp:";
|
||||
CPStandardKeyBindings[@"@" + CPUpArrowFunctionKey] = @"moveToBeginningOfDocument:";
|
||||
CPStandardKeyBindings[@"$" + CPUpArrowFunctionKey] = @"moveUpAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$~" + CPUpArrowFunctionKey] = @"moveParagraphBackwardAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$@" + CPUpArrowFunctionKey] = @"moveToBeginningOfDocumentAndModifySelection:";
|
||||
|
||||
CPStandardKeyBindings[CPDownArrowFunctionKey] = @"moveDown:";
|
||||
CPStandardKeyBindings[@"~" + CPDownArrowFunctionKey] = [@"moveForward:", @"moveToEndOfParagraph:"];
|
||||
CPStandardKeyBindings[@"^" + CPDownArrowFunctionKey] = @"scrollPageDown:";
|
||||
CPStandardKeyBindings[@"@" + CPDownArrowFunctionKey] = @"moveToEndOfDocument:";
|
||||
CPStandardKeyBindings[@"$" + CPDownArrowFunctionKey] = @"moveDownAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$~" + CPDownArrowFunctionKey] = @"moveParagraphForwardAndModifySelection:";
|
||||
CPStandardKeyBindings[@"$@" + CPDownArrowFunctionKey] = @"moveToEndOfDocumentAndModifySelection:";
|
||||
CPStandardKeyBindings[@"@^" + CPDownArrowFunctionKey] = @"makeBaseWritingDirectionNatural:";
|
||||
CPStandardKeyBindings[@"@^~" + CPDownArrowFunctionKey] = @"makeTextWritingDirectionNatural:";
|
||||
|
||||
CPStandardKeyBindings[CPHomeFunctionKey] = @"scrollToBeginningOfDocument:";
|
||||
CPStandardKeyBindings[@"$" + CPHomeFunctionKey] = @"moveToBeginningOfDocumentAndModifySelection:";
|
||||
CPStandardKeyBindings[CPEndFunctionKey] = @"scrollToEndOfDocument:";
|
||||
CPStandardKeyBindings[@"$" + CPEndFunctionKey] = @"moveToEndOfDocumentAndModifySelection:";
|
||||
|
||||
CPStandardKeyBindings[CPPageUpFunctionKey] = @"scrollPageUp:";
|
||||
CPStandardKeyBindings[@"~" + CPPageUpFunctionKey] = @"pageUp:";
|
||||
CPStandardKeyBindings[@"$" + CPPageUpFunctionKey] = @"pageUpAndModifySelection:";
|
||||
CPStandardKeyBindings[CPPageDownFunctionKey] = @"scrollPageDown:";
|
||||
CPStandardKeyBindings[@"~" + CPPageDownFunctionKey] = @"pageDown:";
|
||||
CPStandardKeyBindings[@"$" + CPPageDownFunctionKey] = @"pageDownAndModifySelection:";
|
||||
|
||||
var CPKeyBindingCache = {};
|
||||
|
||||
@implementation CPKeyBinding : CPObject
|
||||
{
|
||||
CPString _key;
|
||||
unsigned _modifierFlags;
|
||||
|
||||
CPArray _selectors;
|
||||
|
||||
CPString _cacheName;
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPKeyBinding class])
|
||||
return;
|
||||
|
||||
[self createKeyBindingsFromJSObject:CPStandardKeyBindings];
|
||||
}
|
||||
|
||||
+ (void)createKeyBindingsFromJSObject:(JSObject)anObject
|
||||
{
|
||||
var binding;
|
||||
for (binding in anObject)
|
||||
[self cacheKeyBinding:[[CPKeyBinding alloc] initWithPhysicalKeyString:binding selectors:anObject[binding]]];
|
||||
}
|
||||
|
||||
+ (void)cacheKeyBinding:(CPKeyBinding)aBinding
|
||||
{
|
||||
if (!aBinding)
|
||||
return;
|
||||
|
||||
CPKeyBindingCache[[aBinding _cacheName]] = aBinding;
|
||||
}
|
||||
|
||||
+ (CPKeyBinding)keyBindingForKey:(CPString)aKey modifierFlags:(unsigned)aFlag
|
||||
{
|
||||
var tempBinding = [[self alloc] initWithKey:aKey modifierFlags:aFlag selectors:nil];
|
||||
return CPKeyBindingCache[[tempBinding _cacheName]];
|
||||
}
|
||||
|
||||
+ (CPArray)selectorsForKey:(CPString)aKey modifierFlags:(unsigned)aFlag
|
||||
{
|
||||
return [[self keyBindingForKey:aKey modifierFlags:aFlag] selectors];
|
||||
}
|
||||
|
||||
- (id)initWithPhysicalKeyString:(CPString)binding selectors:(CPArray)selectors
|
||||
{
|
||||
var components = binding.split(@""),
|
||||
modifierFlags = ([components containsObject:@"$"] ? CPShiftKeyMask : 0) |
|
||||
([components containsObject:@"^"] ? CPControlKeyMask : 0) |
|
||||
([components containsObject:@"~"] ? CPAlternateKeyMask : 0) |
|
||||
([components containsObject:@"@"] ? CPCommandKeyMask : 0);
|
||||
|
||||
if (![selectors isKindOfClass:CPArray])
|
||||
selectors = [selectors];
|
||||
|
||||
return [self initWithKey:[components lastObject] modifierFlags:modifierFlags selectors:selectors];
|
||||
}
|
||||
|
||||
- (id)initWithKey:(CPString)aKey modifierFlags:(unsigned)aFlag selectors:(CPArray)selectors
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_key = aKey;
|
||||
_modifierFlags = aFlag;
|
||||
|
||||
_selectors = selectors;
|
||||
|
||||
// We normalize our key binding string in order to properly cache it.
|
||||
// We want to ensure the modifiers are always in the same order.
|
||||
var cacheName = [];
|
||||
|
||||
if (_modifierFlags & CPCommandKeyMask)
|
||||
cacheName.push(@"@");
|
||||
if (_modifierFlags & CPControlKeyMask)
|
||||
cacheName.push(@"^");
|
||||
if (_modifierFlags & CPAlternateKeyMask)
|
||||
cacheName.push(@"~");
|
||||
if (_modifierFlags & CPShiftKeyMask)
|
||||
cacheName.push(@"$");
|
||||
|
||||
cacheName.push(_key);
|
||||
|
||||
_cacheName = cacheName.join(@"");
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (CPString)key
|
||||
{
|
||||
return _key;
|
||||
}
|
||||
|
||||
- (unsigned)modifierFlags
|
||||
{
|
||||
return _modifierFlags;
|
||||
}
|
||||
|
||||
- (CPArray)selectors
|
||||
{
|
||||
return _selectors;
|
||||
}
|
||||
|
||||
- (CPString)_cacheName
|
||||
{
|
||||
return _cacheName;
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(CPKeyBinding)rhs
|
||||
{
|
||||
return _key === [rhs key] && _modifierFlags === [rhs modifierFlags];
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return [CPString stringWithFormat:@"<KeyBinding string: '%@' modifierFlags: 0x%lx selectors: %@>", _key, _modifierFlags, _selectors];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,959 +0,0 @@
|
||||
/*
|
||||
* CPKeyValueBinding.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Ross Boucher 1/13/09
|
||||
* Copyright 280 North, Inc.
|
||||
*
|
||||
* Adapted from GNUStep
|
||||
* Released under the LGPL.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
@import <Foundation/CPArray.j>
|
||||
@import <Foundation/CPDictionary.j>
|
||||
@import <Foundation/CPInvocation.j>
|
||||
@import <Foundation/CPValueTransformer.j>
|
||||
@import <Foundation/CPKeyValueObserving.j>
|
||||
|
||||
@class CPButton
|
||||
|
||||
var exposedBindingsMap = @{},
|
||||
bindingsMap = @{};
|
||||
|
||||
@typedef CPBindingOperationKind
|
||||
var CPBindingOperationAnd = 0,
|
||||
CPBindingOperationOr = 1;
|
||||
|
||||
@implementation CPBinder : CPObject
|
||||
{
|
||||
CPDictionary _info;
|
||||
id _source @accessors(getter=source);
|
||||
|
||||
JSObject _suppressedNotifications;
|
||||
JSObject _placeholderForMarker;
|
||||
}
|
||||
|
||||
+ (void)exposeBinding:(CPString)aBinding forClass:(Class)aClass
|
||||
{
|
||||
var bindings = [exposedBindingsMap objectForKey:[aClass UID]];
|
||||
|
||||
if (!bindings)
|
||||
{
|
||||
bindings = [];
|
||||
[exposedBindingsMap setObject:bindings forKey:[aClass UID]];
|
||||
}
|
||||
|
||||
bindings.push(aBinding);
|
||||
}
|
||||
|
||||
+ (CPArray)exposedBindingsForClass:(Class)aClass
|
||||
{
|
||||
return [[exposedBindingsMap objectForKey:[aClass UID]] copy];
|
||||
}
|
||||
|
||||
+ (CPBinder)getBinding:(CPString)aBinding forObject:(id)anObject
|
||||
{
|
||||
return [[bindingsMap objectForKey:[anObject UID]] objectForKey:aBinding];
|
||||
}
|
||||
|
||||
+ (void)_reverseSetValueFromExclusiveBinderForObject:(id)anObject
|
||||
{
|
||||
var bindersByBindingName = [bindingsMap objectForKey:[anObject UID]];
|
||||
|
||||
[bindersByBindingName enumerateKeysAndObjectsUsingBlock:function(binding, binder, stop)
|
||||
{
|
||||
if ([binder isKindOfClass:[self class]])
|
||||
{
|
||||
[binder reverseSetValueFor:binding];
|
||||
stop(YES);
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
+ (CPDictionary)infoForBinding:(CPString)aBinding forObject:(id)anObject
|
||||
{
|
||||
var theBinding = [self getBinding:aBinding forObject:anObject];
|
||||
|
||||
if (theBinding)
|
||||
return theBinding._info;
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
+ (CPDictionary)allBindingsForObject:(id)anObject
|
||||
{
|
||||
return [bindingsMap objectForKey:[anObject UID]];
|
||||
}
|
||||
|
||||
+ (void)unbind:(CPString)aBinding forObject:(id)anObject
|
||||
{
|
||||
var bindings = [bindingsMap objectForKey:[anObject UID]];
|
||||
|
||||
if (!bindings)
|
||||
return;
|
||||
|
||||
var theBinding = [bindings objectForKey:aBinding];
|
||||
|
||||
if (!theBinding)
|
||||
return;
|
||||
|
||||
var info = theBinding._info,
|
||||
observedObject = [info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey];
|
||||
|
||||
[observedObject removeObserver:theBinding forKeyPath:keyPath];
|
||||
[bindings removeObjectForKey:aBinding];
|
||||
}
|
||||
|
||||
+ (void)unbindAllForObject:(id)anObject
|
||||
{
|
||||
var bindings = [bindingsMap objectForKey:[anObject UID]];
|
||||
|
||||
if (!bindings)
|
||||
return;
|
||||
|
||||
var allKeys = [bindings allKeys],
|
||||
count = allKeys.length;
|
||||
|
||||
while (count--)
|
||||
[anObject unbind:allKeys[count]];
|
||||
|
||||
[bindingsMap removeObjectForKey:[anObject UID]];
|
||||
}
|
||||
|
||||
- (id)initWithBinding:(CPString)aBinding name:(CPString)aName to:(id)aDestination keyPath:(CPString)aKeyPath options:(CPDictionary)options from:(id)aSource
|
||||
{
|
||||
// We use [self init] here because subclasses override init. We can't override this method
|
||||
// because their initialization has to occur before this method in this class is executed.
|
||||
self = [self init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_source = aSource;
|
||||
_info = @{
|
||||
CPObservedObjectKey: aDestination,
|
||||
CPObservedKeyPathKey: aKeyPath,
|
||||
};
|
||||
_suppressedNotifications = {};
|
||||
_placeholderForMarker = {};
|
||||
|
||||
if (options)
|
||||
[_info setObject:options forKey:CPOptionsKey];
|
||||
|
||||
[self _updatePlaceholdersWithOptions:options forBinding:aName];
|
||||
|
||||
[aDestination addObserver:self forKeyPath:aKeyPath options:0 context:aBinding];
|
||||
|
||||
var bindings = [bindingsMap objectForKey:[_source UID]];
|
||||
|
||||
if (!bindings)
|
||||
{
|
||||
bindings = @{};
|
||||
[bindingsMap setObject:bindings forKey:[_source UID]];
|
||||
}
|
||||
|
||||
[bindings setObject:self forKey:aName];
|
||||
[self setValueFor:aBinding];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (BOOL)isBindingAllowed:(CPString)aBinding forObject:(id)anObject
|
||||
{
|
||||
if ([[anObject class] isBindingExclusive:aBinding])
|
||||
{
|
||||
var bindingsForObject = [bindingsMap objectForKey:[anObject UID]],
|
||||
allBindings = [bindingsForObject allKeys],
|
||||
count = [allBindings count];
|
||||
|
||||
while (count--)
|
||||
{
|
||||
if ([[anObject class] isBindingExclusive:allBindings[count]])
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)raiseIfNotApplicable:(id)aValue forKeyPath:(CPString)keyPath options:(CPDictionary)options
|
||||
{
|
||||
if (aValue === CPNotApplicableMarker && [options objectForKey:CPRaisesForNotApplicableKeysBindingOption])
|
||||
{
|
||||
[CPException raise:CPGenericException
|
||||
reason:@"Cannot transform non-applicable key on: " + _source + " key path: " + keyPath + " value: " + aValue];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setValueFor:(CPString)theBinding
|
||||
{
|
||||
var destination = [_info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [_info objectForKey:CPObservedKeyPathKey],
|
||||
options = [_info objectForKey:CPOptionsKey],
|
||||
newValue = [destination valueForKeyPath:keyPath];
|
||||
|
||||
if (CPIsControllerMarker(newValue))
|
||||
{
|
||||
[self raiseIfNotApplicable:newValue forKeyPath:keyPath options:options];
|
||||
|
||||
var value = [self _placeholderForMarker:newValue];
|
||||
[self setPlaceholderValue:value withMarker:newValue forBinding:theBinding];
|
||||
}
|
||||
else
|
||||
{
|
||||
var value = [self transformValue:newValue withOptions:options];
|
||||
[self setValue:value forBinding:theBinding];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source setValue:aValue forKey:aBinding];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source setValue:aValue forKey:aBinding];
|
||||
}
|
||||
|
||||
- (void)reverseSetValueFor:(CPString)aBinding
|
||||
{
|
||||
var destination = [_info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [_info objectForKey:CPObservedKeyPathKey],
|
||||
options = [_info objectForKey:CPOptionsKey],
|
||||
newValue = [self valueForBinding:aBinding];
|
||||
|
||||
newValue = [self reverseTransformValue:newValue withOptions:options];
|
||||
|
||||
[self suppressSpecificNotificationFromObject:destination keyPath:keyPath];
|
||||
[destination setValue:newValue forKeyPath:keyPath];
|
||||
[self unsuppressSpecificNotificationFromObject:destination keyPath:keyPath];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
return [_source valueForKeyPath:aBinding];
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)changes context:(id)context
|
||||
{
|
||||
if (!changes)
|
||||
return;
|
||||
|
||||
var objectSuppressions = _suppressedNotifications[[anObject UID]];
|
||||
|
||||
if (objectSuppressions && objectSuppressions[aKeyPath])
|
||||
return;
|
||||
|
||||
[self setValueFor:context];
|
||||
}
|
||||
|
||||
- (id)transformValue:(id)aValue withOptions:(CPDictionary)options
|
||||
{
|
||||
var valueTransformerName = [options objectForKey:CPValueTransformerNameBindingOption],
|
||||
valueTransformer;
|
||||
|
||||
if (valueTransformerName)
|
||||
{
|
||||
valueTransformer = [CPValueTransformer valueTransformerForName:valueTransformerName];
|
||||
|
||||
if (!valueTransformer)
|
||||
{
|
||||
var valueTransformerClass = CPClassFromString(valueTransformerName);
|
||||
|
||||
if (valueTransformerClass)
|
||||
{
|
||||
valueTransformer = [[valueTransformerClass alloc] init];
|
||||
[valueTransformerClass setValueTransformer:valueTransformer forName:valueTransformerName];
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
valueTransformer = [options objectForKey:CPValueTransformerBindingOption];
|
||||
|
||||
if (valueTransformer)
|
||||
aValue = [valueTransformer transformedValue:aValue];
|
||||
|
||||
// If the value is nil AND the source doesn't respond to setPlaceholderString: then
|
||||
// we set the value to the placeholder. Otherwise, we do not want to short cut the process
|
||||
// of setting the placeholder that is based on the fact that the value is nil.
|
||||
if ((aValue == nil || aValue === [CPNull null])
|
||||
&& ![_source respondsToSelector:@selector(setPlaceholderString:)])
|
||||
aValue = [options objectForKey:CPNullPlaceholderBindingOption] || nil;
|
||||
|
||||
return aValue;
|
||||
}
|
||||
|
||||
- (id)reverseTransformValue:(id)aValue withOptions:(CPDictionary)options
|
||||
{
|
||||
var valueTransformerName = [options objectForKey:CPValueTransformerNameBindingOption],
|
||||
valueTransformer;
|
||||
|
||||
if (valueTransformerName)
|
||||
valueTransformer = [CPValueTransformer valueTransformerForName:valueTransformerName];
|
||||
else
|
||||
valueTransformer = [options objectForKey:CPValueTransformerBindingOption];
|
||||
|
||||
if (valueTransformer && [[valueTransformer class] allowsReverseTransformation])
|
||||
aValue = [valueTransformer reverseTransformedValue:aValue];
|
||||
|
||||
return aValue;
|
||||
}
|
||||
|
||||
- (BOOL)continuouslyUpdatesValue
|
||||
{
|
||||
var options = [_info objectForKey:CPOptionsKey];
|
||||
return [[options objectForKey:CPContinuouslyUpdatesValueBindingOption] boolValue];
|
||||
}
|
||||
|
||||
- (BOOL)handlesContentAsCompoundValue
|
||||
{
|
||||
var options = [_info objectForKey:CPOptionsKey];
|
||||
return [[options objectForKey:CPHandlesContentAsCompoundValueBindingOption] boolValue];
|
||||
}
|
||||
|
||||
/*!
|
||||
Use this to avoid reacting to the notifications coming out of a reverseTransformedValue:.
|
||||
*/
|
||||
- (void)suppressSpecificNotificationFromObject:(id)anObject keyPath:(CPString)aKeyPath
|
||||
{
|
||||
if (!anObject)
|
||||
return;
|
||||
|
||||
var uid = [anObject UID],
|
||||
objectSuppressions = _suppressedNotifications[uid];
|
||||
|
||||
if (!objectSuppressions)
|
||||
_suppressedNotifications[uid] = objectSuppressions = {};
|
||||
|
||||
objectSuppressions[aKeyPath] = YES;
|
||||
}
|
||||
|
||||
/*!
|
||||
Use this to cancel suppressSpecificNotificationFromObject:keyPath:.
|
||||
*/
|
||||
- (void)unsuppressSpecificNotificationFromObject:(id)anObject keyPath:(CPString)aKeyPath
|
||||
{
|
||||
if (!anObject)
|
||||
return;
|
||||
|
||||
var uid = [anObject UID],
|
||||
objectSuppressions = _suppressedNotifications[uid];
|
||||
|
||||
if (!objectSuppressions)
|
||||
return;
|
||||
|
||||
delete objectSuppressions[aKeyPath];
|
||||
}
|
||||
|
||||
- (void)_updatePlaceholdersWithOptions:(CPDictionary)options
|
||||
{
|
||||
var count = [CPBinderPlaceholderMarkers count];
|
||||
|
||||
while (count--)
|
||||
{
|
||||
var marker = CPBinderPlaceholderMarkers[count],
|
||||
optionName = CPBinderPlaceholderOptions[count],
|
||||
isExplicit = [options containsKey:optionName],
|
||||
placeholder = isExplicit ? [options objectForKey:optionName] : nil;
|
||||
|
||||
[self _setPlaceholder:placeholder forMarker:marker isDefault:!isExplicit];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_updatePlaceholdersWithOptions:(CPDictionary)options forBinding:(CPString)aBinding
|
||||
{
|
||||
[self _updatePlaceholdersWithOptions:options];
|
||||
}
|
||||
|
||||
- (JSObject)_placeholderForMarker:(id)aMarker
|
||||
{
|
||||
var placeholder = _placeholderForMarker[[aMarker UID]];
|
||||
|
||||
if (placeholder)
|
||||
return placeholder.value;
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)_setPlaceholder:(id)aPlaceholder forMarker:(id)aMarker isDefault:(BOOL)isDefault
|
||||
{
|
||||
if (isDefault)
|
||||
{
|
||||
var existingPlaceholder = _placeholderForMarker[[aMarker UID]];
|
||||
|
||||
// Don't overwrite an explicitly set placeholder with a default.
|
||||
if (existingPlaceholder && !existingPlaceholder.isDefault)
|
||||
return;
|
||||
}
|
||||
|
||||
_placeholderForMarker[[aMarker UID]] = { 'isDefault': isDefault, 'value': aPlaceholder };
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPObject (KeyValueBindingCreation)
|
||||
|
||||
+ (void)exposeBinding:(CPString)aBinding
|
||||
{
|
||||
[CPBinder exposeBinding:aBinding forClass:[self class]];
|
||||
}
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
return [CPBinder class];
|
||||
}
|
||||
|
||||
+ (BOOL)isBindingExclusive:(CPString)aBinding
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (CPArray)exposedBindings
|
||||
{
|
||||
var exposedBindings = [],
|
||||
theClass = [self class];
|
||||
|
||||
while (theClass)
|
||||
{
|
||||
var temp = [CPBinder exposedBindingsForClass:theClass];
|
||||
|
||||
if (temp)
|
||||
[exposedBindings addObjectsFromArray:temp];
|
||||
|
||||
theClass = [theClass superclass];
|
||||
}
|
||||
|
||||
return exposedBindings;
|
||||
}
|
||||
|
||||
- (Class)valueClassForBinding:(CPString)binding
|
||||
{
|
||||
return [CPString class];
|
||||
}
|
||||
|
||||
- (void)bind:(CPString)aBinding toObject:(id)anObject withKeyPath:(CPString)aKeyPath options:(CPDictionary)options
|
||||
{
|
||||
if (!anObject || !aKeyPath)
|
||||
return CPLog.error("Invalid object or path on " + self + " for " + aBinding);
|
||||
|
||||
if (![CPBinder isBindingAllowed:aBinding forObject:self])
|
||||
{
|
||||
CPLog.warn([self description] + " : cannot bind " + aBinding + " because another binding with the same functionality is already in use.");
|
||||
return;
|
||||
}
|
||||
//if (![[self exposedBindings] containsObject:aBinding])
|
||||
// CPLog.warn("No binding exposed on " + self + " for " + aBinding);
|
||||
|
||||
var binderClass = [[self class] _binderClassForBinding:aBinding];
|
||||
|
||||
[self unbind:aBinding];
|
||||
[[binderClass alloc] initWithBinding:[self _replacementKeyPathForBinding:aBinding] name:aBinding to:anObject keyPath:aKeyPath options:options from:self];
|
||||
}
|
||||
|
||||
- (CPDictionary)infoForBinding:(CPString)aBinding
|
||||
{
|
||||
return [CPBinder infoForBinding:aBinding forObject:self];
|
||||
}
|
||||
|
||||
- (void)unbind:(CPString)aBinding
|
||||
{
|
||||
var binderClass = [[self class] _binderClassForBinding:aBinding];
|
||||
[binderClass unbind:aBinding forObject:self];
|
||||
}
|
||||
|
||||
- (CPString)_replacementKeyPathForBinding:(CPString)binding
|
||||
{
|
||||
return binding;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Provides stub implementations that simply calls super for the "objectValue" binding.
|
||||
This class should not be necessary but assures backwards compliance with our old way of doing bindings.
|
||||
|
||||
IMPORTANT!
|
||||
Every class with a value binding should implement a subclass to handle its specific value binding logic.
|
||||
*/
|
||||
@implementation _CPValueBinder : CPBinder
|
||||
|
||||
- (void)setValueFor:(CPString)theBinding
|
||||
{
|
||||
[super setValueFor:@"objectValue"];
|
||||
}
|
||||
|
||||
- (void)reverseSetValueFor:(CPString)theBinding
|
||||
{
|
||||
[super reverseSetValueFor:@"objectValue"];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPMultipleValueBooleanBinding : CPBinder
|
||||
{
|
||||
CPBindingOperationKind _operation;
|
||||
}
|
||||
|
||||
- (void)setValueFor:(CPString)aBinding
|
||||
{
|
||||
var bindings = [bindingsMap valueForKey:[_source UID]];
|
||||
|
||||
if (!bindings)
|
||||
return;
|
||||
|
||||
var baseBinding = aBinding.replace(/\d$/, "");
|
||||
|
||||
[_source setValue:[self resolveMultipleValuesForBinding:baseBinding bindings:bindings booleanOperation:_operation] forKey:baseBinding];
|
||||
}
|
||||
|
||||
- (void)reverseSetValueFor:(CPString)theBinding
|
||||
{
|
||||
// read-only
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)changes context:(id)context
|
||||
{
|
||||
[self setValueFor:context];
|
||||
}
|
||||
|
||||
- (BOOL)resolveMultipleValuesForBinding:(CPString)aBinding bindings:(CPDictionary)bindings booleanOperation:(CPBindingOperationKind)operation
|
||||
{
|
||||
var bindingName = aBinding,
|
||||
theBinding,
|
||||
count = 2;
|
||||
|
||||
while (theBinding = [bindings objectForKey:bindingName])
|
||||
{
|
||||
var info = theBinding._info,
|
||||
object = [info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey],
|
||||
options = [info objectForKey:CPOptionsKey],
|
||||
value = [object valueForKeyPath:keyPath];
|
||||
|
||||
if (CPIsControllerMarker(value))
|
||||
{
|
||||
[self raiseIfNotApplicable:value forKeyPath:keyPath options:options];
|
||||
value = [theBinding _placeholderForMarker:value];
|
||||
}
|
||||
else
|
||||
value = [theBinding transformValue:value withOptions:options];
|
||||
|
||||
if (operation === CPBindingOperationOr)
|
||||
{
|
||||
// Any true condition means true for OR
|
||||
if (value)
|
||||
return YES;
|
||||
}
|
||||
|
||||
// Any false condition means false for AND
|
||||
else if (!value)
|
||||
return NO;
|
||||
|
||||
bindingName = aBinding + (count++);
|
||||
}
|
||||
|
||||
// If we get here, all OR conditions were false or all AND conditions were true
|
||||
return operation === CPBindingOperationOr ? NO : YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPMultipleValueAndBinding : _CPMultipleValueBooleanBinding
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
_operation = CPBindingOperationAnd;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPMultipleValueOrBinding : _CPMultipleValueBooleanBinding
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
_operation = CPBindingOperationOr;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPMultipleValueActionBinding : CPBinder
|
||||
{
|
||||
CPString _argumentBinding;
|
||||
CPString _targetBinding;
|
||||
}
|
||||
|
||||
- (void)setValueFor:(CPString)theBinding
|
||||
{
|
||||
// Called when the binding is first created
|
||||
[self checkForNullBinding:theBinding initializing:YES];
|
||||
}
|
||||
|
||||
- (void)reverseSetValueFor:(CPString)theBinding
|
||||
{
|
||||
// no-op
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)changes context:(id)context
|
||||
{
|
||||
// context is the binding name
|
||||
[self checkForNullBinding:context initializing:NO];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
|
||||
When the value of a multiple-value argument binding changes,
|
||||
if the binding is marked not to allow null arguments, we have to check
|
||||
if the binding's value is nil and disable the button if it is.
|
||||
Otherwise the button is enabled.
|
||||
*/
|
||||
- (void)checkForNullBinding:(CPString)theBinding initializing:(BOOL)isInitializing
|
||||
{
|
||||
// Only done for buttons
|
||||
if (![_source isKindOfClass:CPButton])
|
||||
return;
|
||||
|
||||
// We start with the button enabled for the first argument during init,
|
||||
// and subsequent checks can disable it.
|
||||
if (isInitializing && theBinding === CPArgumentBinding)
|
||||
[_source setEnabled:YES];
|
||||
|
||||
var bindings = [bindingsMap valueForKey:[_source UID]],
|
||||
binding = [bindings objectForKey:theBinding],
|
||||
info = binding._info,
|
||||
options = [info objectForKey:CPOptionsKey];
|
||||
|
||||
if (![options valueForKey:CPAllowsNullArgumentBindingOption])
|
||||
{
|
||||
var object = [info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey],
|
||||
value = [object valueForKeyPath:keyPath];
|
||||
|
||||
if (value == nil)
|
||||
{
|
||||
[_source setEnabled:NO];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If a binding value changed and did not fail the null test, enable the button
|
||||
if (!isInitializing)
|
||||
[_source setEnabled:YES];
|
||||
}
|
||||
|
||||
- (void)invokeAction
|
||||
{
|
||||
var bindings = [bindingsMap valueForKey:[_source UID]],
|
||||
theBinding = [bindings objectForKey:CPTargetBinding],
|
||||
|
||||
info = theBinding._info,
|
||||
object = [info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey],
|
||||
options = [info objectForKey:CPOptionsKey],
|
||||
|
||||
target = [object valueForKeyPath:keyPath],
|
||||
selector = [options objectForKey:CPSelectorNameBindingOption];
|
||||
|
||||
if (!target || !selector)
|
||||
return;
|
||||
|
||||
var invocation = [CPInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]],
|
||||
bindingName = CPArgumentBinding,
|
||||
count = 1;
|
||||
|
||||
while (theBinding = [bindings objectForKey:bindingName])
|
||||
{
|
||||
info = theBinding._info;
|
||||
object = [info objectForKey:CPObservedObjectKey];
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey];
|
||||
|
||||
[invocation setArgument:[object valueForKeyPath:keyPath] atIndex:++count];
|
||||
|
||||
bindingName = CPArgumentBinding + count;
|
||||
}
|
||||
|
||||
[invocation setSelector:selector];
|
||||
[invocation invokeWithTarget:target];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPActionBinding : _CPMultipleValueActionBinding
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_argumentBinding = CPArgumentBinding;
|
||||
_targetBinding = CPTargetBinding;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPDoubleClickActionBinding : _CPMultipleValueActionBinding
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_argumentBinding = CPArgumentBinding;
|
||||
_targetBinding = CPTargetBinding;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
/*!
|
||||
Abstract superclass for CPValueWithPatternBinding and CPTitleWithPatternBinding.
|
||||
*/
|
||||
@implementation _CPPatternBinding : CPBinder
|
||||
{
|
||||
CPString _bindingKey;
|
||||
CPString _patternPlaceholder;
|
||||
}
|
||||
|
||||
- (void)setValueFor:(CPString)aBinding
|
||||
{
|
||||
var bindings = [bindingsMap valueForKey:[_source UID]];
|
||||
|
||||
if (!bindings)
|
||||
return;
|
||||
|
||||
// Strip off any trailing number from the binding name
|
||||
var baseBinding = aBinding.replace(/\d$/, ""),
|
||||
result = [self resolveMultipleValuesForBindings:bindings];
|
||||
|
||||
if (result.isPlaceholder)
|
||||
[self setPlaceholderValue:result.value withMarker:result.marker forBinding:baseBinding];
|
||||
else
|
||||
[self setValue:result.value forBinding:baseBinding];
|
||||
}
|
||||
|
||||
- (void)reverseSetValueFor:(CPString)theBinding
|
||||
{
|
||||
// read-only
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)changes context:(id)context
|
||||
{
|
||||
[self setValueFor:context];
|
||||
}
|
||||
|
||||
- (JSObject)resolveMultipleValuesForBindings:(CPDictionary)bindings
|
||||
{
|
||||
var theBinding,
|
||||
result = { value:@"", isPlaceholder:NO, marker:nil };
|
||||
|
||||
for (var count = 1; theBinding = [bindings objectForKey:_bindingKey + count]; ++count)
|
||||
{
|
||||
var info = theBinding._info,
|
||||
object = [info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey],
|
||||
options = [info objectForKey:CPOptionsKey],
|
||||
value = [object valueForKeyPath:keyPath];
|
||||
|
||||
if (count === 1)
|
||||
result.value = [options objectForKey:CPDisplayPatternBindingOption];
|
||||
|
||||
if (CPIsControllerMarker(value))
|
||||
{
|
||||
[self raiseIfNotApplicable:value forKeyPath:keyPath options:options];
|
||||
|
||||
result.isPlaceholder = YES;
|
||||
result.marker = value;
|
||||
|
||||
value = [theBinding _placeholderForMarker:value];
|
||||
}
|
||||
else
|
||||
value = [theBinding transformValue:value withOptions:options];
|
||||
|
||||
if (value == nil)
|
||||
value = @"";
|
||||
|
||||
result.value = result.value.replace("%{" + _patternPlaceholder + count + "}@", [value description]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
/*!
|
||||
Users of this class must override setValue:forKey: and if the
|
||||
key is CPDisplayPatternValueBinding, set the appropriate value
|
||||
for the control class. For example, CPTextField uses setObjectValue.
|
||||
*/
|
||||
@implementation CPValueWithPatternBinding : _CPPatternBinding
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_bindingKey = CPDisplayPatternValueBinding;
|
||||
_patternPlaceholder = @"value";
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
/*!
|
||||
Users of this class must override setValue:forKey: and if the
|
||||
key is CPDisplayPatternTitleBinding, set the appropriate value
|
||||
for the control class. For example, CPBox uses setTitle.
|
||||
*/
|
||||
@implementation CPTitleWithPatternBinding : _CPPatternBinding
|
||||
|
||||
- (id)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_bindingKey = CPDisplayPatternTitleBinding;
|
||||
_patternPlaceholder = @"title";
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPStateMarker : CPObject
|
||||
{
|
||||
CPString _name;
|
||||
}
|
||||
|
||||
- (id)initWithName:(CPString)aName
|
||||
{
|
||||
if (self = [super init])
|
||||
_name = aName;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return "<" + _name + ">";
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
// Keys in options dictionary
|
||||
|
||||
// Keys in dictionary returned by infoForBinding
|
||||
CPObservedObjectKey = @"CPObservedObjectKey";
|
||||
CPObservedKeyPathKey = @"CPObservedKeyPathKey";
|
||||
CPOptionsKey = @"CPOptionsKey";
|
||||
|
||||
// special markers
|
||||
CPNoSelectionMarker = [[_CPStateMarker alloc] initWithName:@"NO SELECTION MARKER"];
|
||||
CPMultipleValuesMarker = [[_CPStateMarker alloc] initWithName:@"MULTIPLE VALUES MARKER"];
|
||||
CPNotApplicableMarker = [[_CPStateMarker alloc] initWithName:@"NOT APPLICABLE MARKER"];
|
||||
CPNullMarker = [[_CPStateMarker alloc] initWithName:@"NULL MARKER"];
|
||||
|
||||
// Binding name constants
|
||||
CPAlignmentBinding = @"alignment";
|
||||
CPArgumentBinding = @"argument";
|
||||
CPContentArrayBinding = @"contentArray";
|
||||
CPContentBinding = @"content";
|
||||
CPContentObjectBinding = @"contentObject";
|
||||
CPContentObjectsBinding = @"contentObjects";
|
||||
CPContentValuesBinding = @"contentValues";
|
||||
CPDisplayPatternTitleBinding = @"displayPatternTitle";
|
||||
CPDisplayPatternValueBinding = @"displayPatternValue";
|
||||
CPDoubleClickArgumentBinding = @"doubleClickArgument";
|
||||
CPDoubleClickTargetBinding = @"doubleClickTarget";
|
||||
CPEditableBinding = @"editable";
|
||||
CPEnabledBinding = @"enabled";
|
||||
CPFontBinding = @"font";
|
||||
CPFontNameBinding = @"fontName";
|
||||
CPFontBoldBinding = @"fontBold";
|
||||
CPHiddenBinding = @"hidden";
|
||||
CPFilterPredicateBinding = @"filterPredicate";
|
||||
CPMaxValueBinding = @"maxValue";
|
||||
CPMinValueBinding = @"minValue";
|
||||
CPPredicateBinding = @"predicate";
|
||||
CPSelectedIndexBinding = @"selectedIndex";
|
||||
CPSelectedLabelBinding = @"selectedLabel";
|
||||
CPSelectedObjectBinding = @"selectedObject";
|
||||
CPSelectedObjectsBinding = @"selectedObjects";
|
||||
CPSelectedTagBinding = @"selectedTag";
|
||||
CPSelectedValueBinding = @"selectedValue";
|
||||
CPSelectedValuesBinding = @"selectedValues";
|
||||
CPSelectionIndexesBinding = @"selectionIndexes";
|
||||
CPTargetBinding = @"target";
|
||||
CPTextColorBinding = @"textColor";
|
||||
CPTitleBinding = @"title";
|
||||
CPToolTipBinding = @"toolTip";
|
||||
CPValueBinding = @"value";
|
||||
CPAttributedStringBinding = @"attributedString";
|
||||
CPValueURLBinding = @"valueURL";
|
||||
CPValuePathBinding = @"valuePath";
|
||||
CPDataBinding = @"data";
|
||||
|
||||
// Binding options constants
|
||||
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)
|
||||
{
|
||||
return anObject === CPMultipleValuesMarker || anObject === CPNoSelectionMarker || anObject === CPNotApplicableMarker || anObject === CPNullMarker;
|
||||
};
|
||||
|
||||
var CPBinderPlaceholderMarkers = [CPMultipleValuesMarker, CPNoSelectionMarker, CPNotApplicableMarker, CPNullMarker],
|
||||
CPBinderPlaceholderOptions = [CPMultipleValuesPlaceholderBindingOption, CPNoSelectionPlaceholderBindingOption, CPNotApplicablePlaceholderBindingOption, CPNullPlaceholderBindingOption];
|
||||
|
||||
@@ -1,375 +0,0 @@
|
||||
/*
|
||||
* CPLevelIndicator.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Alexander Ljungberg.
|
||||
* Copyright 2011, WireLoad Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "CPWindow_Constants.j"
|
||||
@import "CPSlider.j"
|
||||
|
||||
@global CPApp
|
||||
|
||||
@typedef CPLevelIndicatorStyle
|
||||
CPRelevancyLevelIndicatorStyle = 0;
|
||||
CPContinuousCapacityLevelIndicatorStyle = 1;
|
||||
CPDiscreteCapacityLevelIndicatorStyle = 2;
|
||||
CPRatingLevelIndicatorStyle = 3;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPLevelIndicator
|
||||
|
||||
CPLevelIndicator is a control which indicates a value visually on a scale.
|
||||
*/
|
||||
@implementation CPLevelIndicator : CPControl
|
||||
{
|
||||
CPLevelIndicator _levelIndicatorStyle @accessors(property=levelIndicatorStyle);
|
||||
double _minValue @accessors(property=minValue);
|
||||
double _maxValue @accessors(property=maxValue);
|
||||
double _warningValue @accessors(property=warningValue);
|
||||
double _criticalValue @accessors(property=criticalValue);
|
||||
CPTickMarkPosition _tickMarkPosition @accessors(property=tickMarkPosition);
|
||||
int _numberOfTickMarks @accessors(property=numberOfTickMarks);
|
||||
int _numberOfMajorTickMarks @accessors(property=numberOfMajorTickMarks);
|
||||
|
||||
BOOL _isEditable;
|
||||
|
||||
BOOL _isTracking;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return "level-indicator";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"bezel-color": [CPNull null],
|
||||
@"color-empty": [CPNull null],
|
||||
@"color-normal": [CPNull null],
|
||||
@"color-warning": [CPNull null],
|
||||
@"color-critical": [CPNull null],
|
||||
@"spacing": 1.0,
|
||||
};
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_levelIndicatorStyle = CPDiscreteCapacityLevelIndicatorStyle;
|
||||
_maxValue = 2;
|
||||
_warningValue = 2;
|
||||
_criticalValue = 2;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
var bezelView = [self layoutEphemeralSubviewNamed:"bezel"
|
||||
positioned:CPWindowBelow
|
||||
relativeToEphemeralSubviewNamed:nil];
|
||||
// TODO Make themable.
|
||||
[bezelView setBackgroundColor:[self valueForThemeAttribute:@"bezel-color"]];
|
||||
|
||||
var segmentCount = _maxValue - _minValue;
|
||||
|
||||
if (segmentCount <= 0)
|
||||
return;
|
||||
|
||||
var filledColor = [self valueForThemeAttribute:@"color-normal"],
|
||||
value = [self doubleValue];
|
||||
|
||||
if (_warningValue < _criticalValue)
|
||||
{
|
||||
if (value >= _criticalValue)
|
||||
filledColor = [self valueForThemeAttribute:@"color-critical"];
|
||||
else if (value >= _warningValue)
|
||||
filledColor = [self valueForThemeAttribute:@"color-warning"];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (value <= _criticalValue)
|
||||
filledColor = [self valueForThemeAttribute:@"color-critical"];
|
||||
else if (value <= _warningValue)
|
||||
filledColor = [self valueForThemeAttribute:@"color-warning"];
|
||||
}
|
||||
|
||||
|
||||
for (var i = 0; i < segmentCount; i++)
|
||||
{
|
||||
var segmentView = [self layoutEphemeralSubviewNamed:"segment-bezel-" + i
|
||||
positioned:CPWindowAbove
|
||||
relativeToEphemeralSubviewNamed:bezelView];
|
||||
|
||||
[segmentView setBackgroundColor:(_minValue + i) < value ? filledColor : [self valueForThemeAttribute:@"color-empty"]];
|
||||
}
|
||||
}
|
||||
|
||||
- (CPView)createEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
return [[CPView alloc] initWithFrame:CGRectMakeZero()];
|
||||
}
|
||||
|
||||
- (CGRect)rectForEphemeralSubviewNamed:(CPString)aViewName
|
||||
{
|
||||
// TODO Put into theme attributes.
|
||||
var bezelHeight = 18,
|
||||
segmentHeight = 17,
|
||||
bounds = CGRectCreateCopy([self bounds]);
|
||||
|
||||
if (aViewName == "bezel")
|
||||
{
|
||||
bounds.origin.y = (CGRectGetHeight(bounds) - bezelHeight) / 2.0;
|
||||
bounds.size.height = bezelHeight;
|
||||
return bounds;
|
||||
}
|
||||
else if (aViewName.indexOf("segment-bezel") === 0)
|
||||
{
|
||||
var segment = parseInt(aViewName.substring("segment-bezel-".length), 10),
|
||||
segmentCount = _maxValue - _minValue;
|
||||
|
||||
if (segment >= segmentCount)
|
||||
return CGRectMakeZero();
|
||||
|
||||
var basicSegmentWidth = bounds.size.width / segmentCount,
|
||||
segmentFrame = CGRectCreateCopy([self bounds]),
|
||||
spacing = [self valueForThemeAttribute:@"spacing"];
|
||||
|
||||
segmentFrame.origin.y = (CGRectGetHeight(bounds) - bezelHeight) / 2.0;
|
||||
segmentFrame.origin.x = FLOOR(segment * basicSegmentWidth);
|
||||
segmentFrame.size.width = (segment == segmentCount - 1) ? bounds.size.width - segmentFrame.origin.x : FLOOR(((segment + 1) * basicSegmentWidth)) - FLOOR((segment * basicSegmentWidth)) - spacing;
|
||||
segmentFrame.size.height = segmentHeight;
|
||||
|
||||
return segmentFrame;
|
||||
}
|
||||
|
||||
return CGRectMakeZero();
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets whether or not the receiver level indicator can be edited.
|
||||
*/
|
||||
- (void)setEditable:(BOOL)shouldBeEditable
|
||||
{
|
||||
if (_isEditable === shouldBeEditable)
|
||||
return;
|
||||
|
||||
_isEditable = shouldBeEditable;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns \c YES if the textfield is currently editable by the user.
|
||||
*/
|
||||
- (BOOL)isEditable
|
||||
{
|
||||
return _isEditable;
|
||||
}
|
||||
|
||||
- (CPView)hitTest:(CGPoint)aPoint
|
||||
{
|
||||
// Don't swallow clicks when displayed in a table.
|
||||
if (![self isEditable])
|
||||
return nil;
|
||||
|
||||
return [super hitTest:aPoint];
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEditable] || ![self isEnabled])
|
||||
return;
|
||||
|
||||
[self _trackMouse:anEvent];
|
||||
}
|
||||
|
||||
- (void)_trackMouse:(CPEvent)anEvent
|
||||
{
|
||||
var type = [anEvent type];
|
||||
|
||||
if (type == CPLeftMouseDown || type == CPLeftMouseDragged)
|
||||
{
|
||||
var segmentCount = _maxValue - _minValue;
|
||||
|
||||
if (segmentCount <= 0)
|
||||
return;
|
||||
|
||||
var location = [self convertPoint:[anEvent locationInWindow] fromView:nil],
|
||||
bounds = [self bounds],
|
||||
oldValue = [self doubleValue],
|
||||
newValue = oldValue;
|
||||
|
||||
// Moving the mouse outside of the widget to the left sets it
|
||||
// to its minimum, and moving outside on the right sets it to
|
||||
// its maximum.
|
||||
if (type == CPLeftMouseDragged && location.x < 0)
|
||||
{
|
||||
newValue = _minValue;
|
||||
}
|
||||
else if (type == CPLeftMouseDragged && location.x > bounds.size.width)
|
||||
{
|
||||
newValue = _maxValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < segmentCount; i++)
|
||||
{
|
||||
var rect = [self rectForEphemeralSubviewNamed:"segment-bezel-" + i];
|
||||
|
||||
// Once we're tracking the mouse, we only care about horizontal mouse movement.
|
||||
if (location.x >= CGRectGetMinX(rect) && location.x < CGRectGetMaxX(rect))
|
||||
{
|
||||
newValue = (_minValue + i + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newValue != oldValue)
|
||||
[self setDoubleValue:newValue];
|
||||
|
||||
// Track the mouse to support click and slide value editing.
|
||||
_isTracking = YES;
|
||||
[CPApp setTarget:self selector:@selector(_trackMouse:) forNextEventMatchingMask:CPLeftMouseDraggedMask | CPLeftMouseUpMask untilDate:nil inMode:nil dequeue:YES];
|
||||
|
||||
if ([self isContinuous])
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
}
|
||||
else if (_isTracking)
|
||||
{
|
||||
_isTracking = NO;
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
- (CPLevelIndicatorStyle)style;
|
||||
- (void)setLevelIndicatorStyle:(CPLevelIndicatorStyle)style;
|
||||
*/
|
||||
|
||||
- (void)setMinValue:(double)minValue
|
||||
{
|
||||
if (_minValue === minValue)
|
||||
return;
|
||||
_minValue = minValue;
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setMaxValue:(double)maxValue
|
||||
{
|
||||
if (_maxValue === maxValue)
|
||||
return;
|
||||
_maxValue = maxValue;
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setWarningValue:(double)warningValue
|
||||
{
|
||||
if (_warningValue === warningValue)
|
||||
return;
|
||||
_warningValue = warningValue;
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setCriticalValue:(double)criticalValue
|
||||
{
|
||||
if (_criticalValue === criticalValue)
|
||||
return;
|
||||
_criticalValue = criticalValue;
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*
|
||||
- (CPTickMarkPosition)tickMarkPosition;
|
||||
- (void)setTickMarkPosition:(CPTickMarkPosition)position;
|
||||
|
||||
- (int)numberOfTickMarks;
|
||||
- (void)setNumberOfTickMarks:(int)count;
|
||||
|
||||
- (int)numberOfMajorTickMarks;
|
||||
- (void)setNumberOfMajorTickMarks:(int)count;
|
||||
|
||||
- (double)tickMarkValueAtIndex:(int)index;
|
||||
- (CGRect)rectOfTickMarkAtIndex:(int)index;
|
||||
*/
|
||||
|
||||
@end
|
||||
|
||||
var CPLevelIndicatorStyleKey = "CPLevelIndicatorStyleKey",
|
||||
CPLevelIndicatorMinValueKey = "CPLevelIndicatorMinValueKey",
|
||||
CPLevelIndicatorMaxValueKey = "CPLevelIndicatorMaxValueKey",
|
||||
CPLevelIndicatorWarningValueKey = "CPLevelIndicatorWarningValueKey",
|
||||
CPLevelIndicatorCriticalValueKey = "CPLevelIndicatorCriticalValueKey",
|
||||
CPLevelIndicatorTickMarkPositionKey = "CPLevelIndicatorTickMarkPositionKey",
|
||||
CPLevelIndicatorNumberOfTickMarksKey = "CPLevelIndicatorNumberOfTickMarksKey",
|
||||
CPLevelIndicatorNumberOfMajorTickMarksKey = "CPLevelIndicatorNumberOfMajorTickMarksKey",
|
||||
CPLevelIndicatorIsEditableKey = "CPLevelIndicatorIsEditableKey";
|
||||
|
||||
@implementation CPLevelIndicator (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_levelIndicatorStyle = [aCoder decodeIntForKey:CPLevelIndicatorStyleKey];
|
||||
_minValue = [aCoder decodeDoubleForKey:CPLevelIndicatorMinValueKey];
|
||||
_maxValue = [aCoder decodeDoubleForKey:CPLevelIndicatorMaxValueKey];
|
||||
_warningValue = [aCoder decodeDoubleForKey:CPLevelIndicatorWarningValueKey];
|
||||
_criticalValue = [aCoder decodeDoubleForKey:CPLevelIndicatorCriticalValueKey];
|
||||
_tickMarkPosition = [aCoder decodeIntForKey:CPLevelIndicatorTickMarkPositionKey];
|
||||
_numberOfTickMarks = [aCoder decodeIntForKey:CPLevelIndicatorNumberOfTickMarksKey];
|
||||
_numberOfMajorTickMarks = [aCoder decodeIntForKey:CPLevelIndicatorNumberOfMajorTickMarksKey];
|
||||
|
||||
_isEditable = [aCoder decodeBoolForKey:CPLevelIndicatorIsEditableKey];
|
||||
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
[aCoder encodeInt:_levelIndicatorStyle forKey:CPLevelIndicatorStyleKey];
|
||||
[aCoder encodeDouble:_minValue forKey:CPLevelIndicatorMinValueKey];
|
||||
[aCoder encodeDouble:_maxValue forKey:CPLevelIndicatorMaxValueKey];
|
||||
[aCoder encodeDouble:_warningValue forKey:CPLevelIndicatorWarningValueKey];
|
||||
[aCoder encodeDouble:_criticalValue forKey:CPLevelIndicatorCriticalValueKey];
|
||||
[aCoder encodeInt:_tickMarkPosition forKey:CPLevelIndicatorTickMarkPositionKey];
|
||||
[aCoder encodeInt:_numberOfTickMarks forKey:CPLevelIndicatorNumberOfTickMarksKey];
|
||||
[aCoder encodeInt:_numberOfMajorTickMarks forKey:CPLevelIndicatorNumberOfMajorTickMarksKey];
|
||||
[aCoder encodeBool:_isEditable forKey:CPLevelIndicatorIsEditableKey];
|
||||
}
|
||||
|
||||
@end
|
||||
+151
-382
@@ -25,21 +25,15 @@
|
||||
@import <Foundation/CPNotificationCenter.j>
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
@import "CPKeyValueBinding.j"
|
||||
@import "_CPMenuManager.j"
|
||||
@import "CPApplication.j"
|
||||
@import "CPClipView.j"
|
||||
@import "CPMenuItem.j"
|
||||
@import "CPPanel.j"
|
||||
|
||||
@global CPApp
|
||||
#include "../CoreGraphics/CGGeometry.h"
|
||||
#include "../Platform/Platform.h"
|
||||
|
||||
@protocol CPMenuDelegate <CPObject>
|
||||
|
||||
@optional
|
||||
- (void)menuWillOpen:(CPMenu)aMenu;
|
||||
- (void)menuDidClose:(CPMenu)aMenu;
|
||||
|
||||
@end
|
||||
|
||||
var CPMenuDelegate_menuWillOpen_ = 1 << 1,
|
||||
CPMenuDelegate_menuDidClose_ = 1 << 2;
|
||||
|
||||
CPMenuDidAddItemNotification = @"CPMenuDidAddItemNotification";
|
||||
CPMenuDidChangeItemNotification = @"CPMenuDidChangeItemNotification";
|
||||
@@ -47,51 +41,49 @@ CPMenuDidRemoveItemNotification = @"CPMenuDidRemoveItemNotification";
|
||||
|
||||
CPMenuDidEndTrackingNotification = @"CPMenuDidEndTrackingNotification";
|
||||
|
||||
var MENUBAR_HEIGHT = 28.0;
|
||||
|
||||
var _CPMenuBarVisible = NO,
|
||||
_CPMenuBarTitle = @"",
|
||||
_CPMenuBarIconImage = nil,
|
||||
_CPMenuBarIconImageAlphaValue = 1.0,
|
||||
_CPMenuBarAttributes = nil,
|
||||
_CPMenuBarSharedWindow = nil;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPMenu
|
||||
|
||||
Menus provide the user with a list of actions and/or submenus. Submenus themselves are full fledged menus
|
||||
and so a hierarchical structure appears.
|
||||
Menus provide the user with a list of actions and/or submenus. Submenus themselves are full fledged menus
|
||||
and so a heirarchical structure appears.
|
||||
*/
|
||||
@implementation CPMenu : CPObject
|
||||
{
|
||||
CPMenu _supermenu;
|
||||
CPMenu _supermenu;
|
||||
|
||||
CPString _title;
|
||||
CPString _name;
|
||||
CPString _title;
|
||||
CPString _name;
|
||||
|
||||
CPFont _font;
|
||||
CPFont _font;
|
||||
|
||||
float _minimumWidth;
|
||||
float _minimumWidth;
|
||||
|
||||
CPMutableArray _items;
|
||||
CPMutableArray _items;
|
||||
|
||||
BOOL _autoenablesItems;
|
||||
BOOL _showsStateColumn;
|
||||
|
||||
BOOL _autoenablesItems;
|
||||
BOOL _showsStateColumn;
|
||||
|
||||
id <CPMenuDelegate> _delegate;
|
||||
unsigned _implementedDelegateMethods;
|
||||
|
||||
int _highlightedIndex;
|
||||
_CPMenuWindow _menuWindow;
|
||||
|
||||
CPEvent _lastCloseEvent;
|
||||
id _delegate;
|
||||
|
||||
CPMenuItem _highlightedIndex;
|
||||
_CPMenuWindow _menuWindow;
|
||||
}
|
||||
|
||||
// Managing the Menu Bar
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPMenu class])
|
||||
return;
|
||||
|
||||
[[self class] setMenuBarAttributes:@{}];
|
||||
[[self class] setMenuBarAttributes:[CPDictionary dictionary]];
|
||||
}
|
||||
|
||||
+ (BOOL)menuBarVisible
|
||||
@@ -103,7 +95,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
if (_CPMenuBarVisible === menuBarShouldBeVisible)
|
||||
return;
|
||||
|
||||
|
||||
_CPMenuBarVisible = menuBarShouldBeVisible;
|
||||
|
||||
if ([CPPlatform supportsNativeMainMenu])
|
||||
@@ -113,13 +105,13 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
if (!_CPMenuBarSharedWindow)
|
||||
_CPMenuBarSharedWindow = [[_CPMenuBarWindow alloc] init];
|
||||
|
||||
|
||||
[_CPMenuBarSharedWindow setMenu:[CPApp mainMenu]];
|
||||
|
||||
|
||||
[_CPMenuBarSharedWindow setTitle:_CPMenuBarTitle];
|
||||
[_CPMenuBarSharedWindow setIconImage:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-icon-image" forClass:_CPMenuView]];
|
||||
[_CPMenuBarSharedWindow setIconImageAlphaValue:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-icon-image-alpha-value" forClass:_CPMenuView]];
|
||||
|
||||
[_CPMenuBarSharedWindow setIconImage:_CPMenuBarIconImage];
|
||||
[_CPMenuBarSharedWindow setIconImageAlphaValue:_CPMenuBarIconImageAlphaValue];
|
||||
|
||||
[_CPMenuBarSharedWindow setColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarBackgroundColor"]];
|
||||
[_CPMenuBarSharedWindow setTextColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarTextColor"]];
|
||||
[_CPMenuBarSharedWindow setTitleColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarTitleColor"]];
|
||||
@@ -128,12 +120,12 @@ var _CPMenuBarVisible = NO,
|
||||
[_CPMenuBarSharedWindow setHighlightColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarHighlightColor"]];
|
||||
[_CPMenuBarSharedWindow setHighlightTextColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarHighlightTextColor"]];
|
||||
[_CPMenuBarSharedWindow setHighlightTextShadowColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarHighlightTextShadowColor"]];
|
||||
|
||||
|
||||
[_CPMenuBarSharedWindow orderFront:self];
|
||||
}
|
||||
else
|
||||
[_CPMenuBarSharedWindow orderOut:self];
|
||||
|
||||
|
||||
// FIXME: There must be a better way to do this.
|
||||
#if PLATFORM(DOM)
|
||||
[[CPPlatformWindow primaryPlatformWindow] resizeEvent:nil];
|
||||
@@ -162,21 +154,14 @@ var _CPMenuBarVisible = NO,
|
||||
return _CPMenuBarImage;
|
||||
}
|
||||
|
||||
+ (void)_setOrRemoveMenuBarAttribute:(id)aValue forKey:(id)aKey
|
||||
{
|
||||
if (aValue == nil)
|
||||
[_CPMenuBarAttributes removeObjectForKey:aKey];
|
||||
else
|
||||
[_CPMenuBarAttributes setObject:aValue forKey:aKey];
|
||||
}
|
||||
|
||||
+ (void)setMenuBarAttributes:(CPDictionary)attributes
|
||||
{
|
||||
if (_CPMenuBarAttributes == attributes)
|
||||
return;
|
||||
|
||||
|
||||
_CPMenuBarAttributes = [attributes copy];
|
||||
|
||||
|
||||
var textColor = [attributes objectForKey:@"CPMenuBarTextColor"],
|
||||
titleColor = [attributes objectForKey:@"CPMenuBarTitleColor"],
|
||||
textShadowColor = [attributes objectForKey:@"CPMenuBarTextShadowColor"],
|
||||
@@ -184,40 +169,40 @@ var _CPMenuBarVisible = NO,
|
||||
highlightColor = [attributes objectForKey:@"CPMenuBarHighlightColor"],
|
||||
highlightTextColor = [attributes objectForKey:@"CPMenuBarHighlightTextColor"],
|
||||
highlightTextShadowColor = [attributes objectForKey:@"CPMenuBarHighlightTextShadowColor"];
|
||||
|
||||
|
||||
if (!textColor && titleColor)
|
||||
[_CPMenuBarAttributes setObject:titleColor forKey:@"CPMenuBarTextColor"];
|
||||
|
||||
|
||||
else if (textColor && !titleColor)
|
||||
[_CPMenuBarAttributes setObject:textColor forKey:@"CPMenuBarTitleColor"];
|
||||
|
||||
|
||||
else if (!textColor && !titleColor)
|
||||
{
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-text-color" forClass:_CPMenuView] forKey:@"CPMenuBarTextColor"];
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-title-color" forClass:_CPMenuView] forKey:@"CPMenuBarTitleColor"];
|
||||
[_CPMenuBarAttributes setObject:[CPColor colorWithRed:0.051 green:0.2 blue:0.275 alpha:1.0] forKey:@"CPMenuBarTextColor"];
|
||||
[_CPMenuBarAttributes setObject:[CPColor colorWithRed:0.051 green:0.2 blue:0.275 alpha:1.0] forKey:@"CPMenuBarTitleColor"];
|
||||
}
|
||||
|
||||
|
||||
if (!textShadowColor && titleShadowColor)
|
||||
[_CPMenuBarAttributes setObject:titleShadowColor forKey:@"CPMenuBarTextShadowColor"];
|
||||
|
||||
|
||||
else if (textShadowColor && !titleShadowColor)
|
||||
[_CPMenuBarAttributes setObject:textShadowColor forKey:@"CPMenuBarTitleShadowColor"];
|
||||
|
||||
|
||||
else if (!textShadowColor && !titleShadowColor)
|
||||
{
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-text-shadow-color" forClass:_CPMenuView] forKey:@"CPMenuBarTextShadowColor"];
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-title-shadow-color" forClass:_CPMenuView] forKey:@"CPMenuBarTitleShadowColor"];
|
||||
[_CPMenuBarAttributes setObject:[CPColor whiteColor] forKey:@"CPMenuBarTextShadowColor"];
|
||||
[_CPMenuBarAttributes setObject:[CPColor whiteColor] forKey:@"CPMenuBarTitleShadowColor"];
|
||||
}
|
||||
|
||||
|
||||
if (!highlightColor)
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-highlight-color" forClass:_CPMenuView] forKey:@"CPMenuBarHighlightColor"];
|
||||
|
||||
[_CPMenuBarAttributes setObject:[CPColor colorWithCalibratedRed:94.0/255.0 green:130.0/255.0 blue:186.0/255.0 alpha:1.0] forKey:@"CPMenuBarHighlightColor"];
|
||||
|
||||
if (!highlightTextColor)
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-highlight-text-color" forClass:_CPMenuView] forKey:@"CPMenuBarHighlightTextColor"];
|
||||
|
||||
[_CPMenuBarAttributes setObject:[CPColor whiteColor] forKey:@"CPMenuBarHighlightTextColor"];
|
||||
|
||||
if (!highlightTextShadowColor)
|
||||
[self _setOrRemoveMenuBarAttribute:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-highlight-text-shadow-color" forClass:_CPMenuView] forKey:@"CPMenuBarHighlightTextShadowColor"];
|
||||
|
||||
[_CPMenuBarAttributes setObject:[CPColor blackColor] forKey:@"CPMenuBarHighlightTextShadowColor"];
|
||||
|
||||
if (_CPMenuBarSharedWindow)
|
||||
{
|
||||
[_CPMenuBarSharedWindow setColor:[_CPMenuBarAttributes objectForKey:@"CPMenuBarBackgroundColor"]];
|
||||
@@ -245,14 +230,14 @@ var _CPMenuBarVisible = NO,
|
||||
- (float)menuBarHeight
|
||||
{
|
||||
if (self === [CPApp mainMenu])
|
||||
return [CPMenu menuBarHeight];
|
||||
|
||||
return MENUBAR_HEIGHT;
|
||||
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
+ (float)menuBarHeight
|
||||
{
|
||||
return [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-height" forClass:_CPMenuView];
|
||||
return MENUBAR_HEIGHT;
|
||||
}
|
||||
|
||||
// Creating a CPMenu Object
|
||||
@@ -264,18 +249,18 @@ var _CPMenuBarVisible = NO,
|
||||
- (id)initWithTitle:(CPString)aTitle
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_title = aTitle;
|
||||
_items = [];
|
||||
|
||||
|
||||
_autoenablesItems = YES;
|
||||
_showsStateColumn = YES;
|
||||
|
||||
[self setMinimumWidth:0];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -290,9 +275,24 @@ var _CPMenuBarVisible = NO,
|
||||
@param aMenuItem the item to insert
|
||||
@param anIndex the index in the menu to insert the item.
|
||||
*/
|
||||
- (void)insertItem:(CPMenuItem)aMenuItem atIndex:(CPUInteger)anIndex
|
||||
- (void)insertItem:(CPMenuItem)aMenuItem atIndex:(unsigned)anIndex
|
||||
{
|
||||
[self insertObject:aMenuItem inItemsAtIndex:anIndex];
|
||||
var menu = [aMenuItem menu];
|
||||
|
||||
if (menu)
|
||||
if (menu !== self)
|
||||
[CPException raise:CPInternalInconsistencyException reason:@"Attempted to insert item into menu that was already in another menu."];
|
||||
else
|
||||
return;
|
||||
|
||||
[aMenuItem setMenu:self];
|
||||
[_items insertObject:aMenuItem atIndex:anIndex];
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPMenuDidAddItemNotification
|
||||
object:self
|
||||
userInfo:[CPDictionary dictionaryWithObject:anIndex forKey:@"CPMenuItemIndex"]];
|
||||
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -303,10 +303,10 @@ var _CPMenuBarVisible = NO,
|
||||
@param anIndex the index location in the menu for the new item
|
||||
@return the new menu item
|
||||
*/
|
||||
- (CPMenuItem)insertItemWithTitle:(CPString)aTitle action:(SEL)anAction keyEquivalent:(CPString)aKeyEquivalent atIndex:(CPUInteger)anIndex
|
||||
- (CPMenuItem)insertItemWithTitle:(CPString)aTitle action:(SEL)anAction keyEquivalent:(CPString)aKeyEquivalent atIndex:(unsigned)anIndex
|
||||
{
|
||||
var item = [[CPMenuItem alloc] initWithTitle:aTitle action:anAction keyEquivalent:aKeyEquivalent];
|
||||
|
||||
|
||||
[self insertItem:item atIndex:anIndex];
|
||||
|
||||
return item;
|
||||
@@ -347,32 +347,18 @@ var _CPMenuBarVisible = NO,
|
||||
Removes the item at the specified index from the menu
|
||||
@param anIndex the index of the item to remove
|
||||
*/
|
||||
- (void)removeItemAtIndex:(CPUInteger)anIndex
|
||||
- (void)removeItemAtIndex:(unsigned)anIndex
|
||||
{
|
||||
[self removeObjectFromItemsAtIndex:anIndex];
|
||||
}
|
||||
|
||||
/*!
|
||||
Removes all the menu items in the receiver.
|
||||
This method is more efficient than removing menu items individually.
|
||||
|
||||
Unlike the other remove methods, this method does not post CPMenuDidChangeItemNotification notifications.
|
||||
*/
|
||||
- (void)removeAllItems
|
||||
{
|
||||
var count = [_items count];
|
||||
|
||||
// Remove the connection to this menu in case
|
||||
// someone else has a reference to the menu item.
|
||||
while (count--)
|
||||
[_items[count] setMenu:nil];
|
||||
|
||||
[self _highlightItemAtIndex:CPNotFound];
|
||||
|
||||
// Because we are changing _items directly, be sure to notify KVO
|
||||
[self willChangeValueForKey:@"items"];
|
||||
_items = [CPMutableArray array];
|
||||
[self didChangeValueForKey:@"items"];
|
||||
if (anIndex < 0 || anIndex >= _items.length)
|
||||
return;
|
||||
|
||||
[_items[anIndex] setMenu:nil];
|
||||
[_items removeObjectAtIndex:anIndex];
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPMenuDidRemoveItemNotification
|
||||
object:self
|
||||
userInfo:[CPDictionary dictionaryWithObject:anIndex forKey:@"CPMenuItemIndex"]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -381,20 +367,13 @@ var _CPMenuBarVisible = NO,
|
||||
*/
|
||||
- (void)itemChanged:(CPMenuItem)aMenuItem
|
||||
{
|
||||
/*
|
||||
During cib unarchiving, menu items will have a reference to their menu,
|
||||
but of course the items are still being unarchived and the menu's _items
|
||||
have not yet been instantiated. In that case we will not do anything here.
|
||||
*/
|
||||
if ([aMenuItem menu] !== self || !_items)
|
||||
if ([aMenuItem menu] != self)
|
||||
return;
|
||||
|
||||
[aMenuItem setValue:[aMenuItem valueForKey:@"changeCount"] + 1 forKey:@"changeCount"];
|
||||
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPMenuDidChangeItemNotification
|
||||
object:self
|
||||
userInfo:@{ @"CPMenuItemIndex": [_items indexOfObjectIdenticalTo:aMenuItem] }];
|
||||
userInfo:[CPDictionary dictionaryWithObject:[_items indexOfObjectIdenticalTo:aMenuItem] forKey:@"CPMenuItemIndex"]];
|
||||
}
|
||||
|
||||
// Finding Menu Items
|
||||
@@ -406,10 +385,10 @@ var _CPMenuBarVisible = NO,
|
||||
- (CPMenuItem)itemWithTag:(int)aTag
|
||||
{
|
||||
var index = [self indexOfItemWithTag:aTag];
|
||||
|
||||
|
||||
if (index == CPNotFound)
|
||||
return nil;
|
||||
|
||||
|
||||
return _items[index];
|
||||
}
|
||||
|
||||
@@ -421,10 +400,10 @@ var _CPMenuBarVisible = NO,
|
||||
- (CPMenuItem)itemWithTitle:(CPString)aTitle
|
||||
{
|
||||
var index = [self indexOfItemWithTitle:aTitle];
|
||||
|
||||
|
||||
if (index == CPNotFound)
|
||||
return nil;
|
||||
|
||||
|
||||
return _items[index];
|
||||
}
|
||||
|
||||
@@ -463,7 +442,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
if ([aMenuItem menu] !== self)
|
||||
return CPNotFound;
|
||||
|
||||
|
||||
return [_items indexOfObjectIdenticalTo:aMenuItem];
|
||||
}
|
||||
|
||||
@@ -476,7 +455,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
var index = 0,
|
||||
count = _items.length;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
if ([_items[index] title] === aTitle)
|
||||
return index;
|
||||
@@ -493,7 +472,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
var index = 0,
|
||||
count = _items.length;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
if ([_items[index] tag] == aTag)
|
||||
return index;
|
||||
@@ -511,11 +490,11 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
var index = 0,
|
||||
count = _items.length;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var item = _items[index];
|
||||
|
||||
|
||||
if ([item target] == aTarget && (!anAction || [item action] == anAction))
|
||||
return index;
|
||||
}
|
||||
@@ -532,7 +511,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
var index = 0,
|
||||
count = _items.length;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
if ([[_items[index] representedObject] isEqual:anObject])
|
||||
return index;
|
||||
@@ -549,7 +528,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
var index = 0,
|
||||
count = _items.length;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
if ([_items[index] submenu] == aMenu)
|
||||
return index;
|
||||
@@ -567,7 +546,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
[aMenuItem setTarget:aMenuItem];
|
||||
[aMenuItem setAction:@selector(submenuAction:)];
|
||||
|
||||
|
||||
[aMenuItem setSubmenu:aMenu];
|
||||
}
|
||||
|
||||
@@ -579,6 +558,7 @@ var _CPMenuBarVisible = NO,
|
||||
*/
|
||||
- (void)submenuAction:(id)aSender
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -626,73 +606,11 @@ var _CPMenuBarVisible = NO,
|
||||
}
|
||||
|
||||
/*!
|
||||
Enables or disables the receiver’s menu items.
|
||||
If the item has no target, an action binding is checked. If the target does not implement
|
||||
the menu item's action method or the binding's selector, the item is disabled.
|
||||
If the target responds to selector validateMenuItem: or validateUserInterfaceItem: (in that order) the return value is used.
|
||||
Not implemented.
|
||||
*/
|
||||
- (void)update
|
||||
{
|
||||
if (!_autoenablesItems)
|
||||
return;
|
||||
|
||||
var items = [self itemArray];
|
||||
|
||||
for (var i = 0; i < [items count]; i++)
|
||||
{
|
||||
var item = [items objectAtIndex:i];
|
||||
|
||||
if ([item hasSubmenu])
|
||||
continue;
|
||||
|
||||
// If there are enabled bindings for the item, they override anything else
|
||||
var binder = [CPBinder getBinding:CPEnabledBinding forObject:item];
|
||||
|
||||
if (binder)
|
||||
{
|
||||
[binder setValueFor:CPEnabledBinding];
|
||||
[[_menuWindow _menuView] tile];
|
||||
return;
|
||||
}
|
||||
|
||||
var validator = [CPApp targetForAction:[item action] to:[item target] from:item],
|
||||
shouldBeEnabled = YES;
|
||||
|
||||
if (!validator)
|
||||
{
|
||||
// If targetForAction: returns nil, it could be that there is no action.
|
||||
// If there is an action and nil is returned, no valid target could be found.
|
||||
if ([item action] || [item target])
|
||||
shouldBeEnabled = NO;
|
||||
else
|
||||
{
|
||||
// Check to see if there is a target binding with an invalid selector
|
||||
var info = [CPBinder infoForBinding:CPTargetBinding forObject:item];
|
||||
|
||||
if (info)
|
||||
{
|
||||
var object = [info objectForKey:CPObservedObjectKey],
|
||||
keyPath = [info objectForKey:CPObservedKeyPathKey],
|
||||
options = [info objectForKey:CPOptionsKey],
|
||||
target = [object valueForKeyPath:keyPath],
|
||||
selector = [options valueForKey:CPSelectorNameBindingOption];
|
||||
|
||||
if (target && selector && ![target respondsToSelector:CPSelectorFromString(selector)])
|
||||
shouldBeEnabled = NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (![validator respondsToSelector:[item action]])
|
||||
shouldBeEnabled = NO;
|
||||
else if ([validator respondsToSelector:@selector(validateMenuItem:)])
|
||||
shouldBeEnabled = [validator validateMenuItem:item];
|
||||
else if ([validator respondsToSelector:@selector(validateUserInterfaceItem:)])
|
||||
shouldBeEnabled = [validator validateUserInterfaceItem:item];
|
||||
|
||||
[item setEnabled:shouldBeEnabled];
|
||||
}
|
||||
|
||||
[[_menuWindow _menuView] tile];
|
||||
}
|
||||
|
||||
// Managing the Title
|
||||
@@ -734,13 +652,7 @@ var _CPMenuBarVisible = NO,
|
||||
// highlightedItem is always enabled. Do there exist edge cases: disabling on closing a menu,
|
||||
// etc.? Requires further investigation and tests.
|
||||
if (highlightedItem && [highlightedItem isEnabled])
|
||||
{
|
||||
// Perform any action binding
|
||||
var binding = [CPBinder getBinding:CPTargetBinding forObject:highlightedItem];
|
||||
[binding invokeAction];
|
||||
|
||||
[CPApp sendAction:[highlightedItem action] to:[highlightedItem target] from:highlightedItem];
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
@@ -771,7 +683,7 @@ var _CPMenuBarVisible = NO,
|
||||
itemIndex = [self indexOfItem:anItem];
|
||||
|
||||
if (itemIndex === CPNotFound)
|
||||
throw "In call to popUpMenuPositioningItem:atLocation:inView:callback:, menu item " +
|
||||
throw "In call to popUpMenuPositioningItem:atLocation:inView:callback:, menu item " +
|
||||
anItem + " is not present in menu " + self;
|
||||
}
|
||||
|
||||
@@ -780,7 +692,10 @@ var _CPMenuBarVisible = NO,
|
||||
if (aView && !theWindow)
|
||||
throw "In call to popUpMenuPositioningItem:atLocation:inView:callback:, view is not in any window.";
|
||||
|
||||
[self _menuWillOpen];
|
||||
var delegate = [self delegate];
|
||||
|
||||
if ([delegate respondsToSelector:@selector(menuWillOpen:)])
|
||||
[delegate menuWillOpen:aMenu];
|
||||
|
||||
// Convert location to global coordinates if not already in them.
|
||||
if (aView)
|
||||
@@ -832,9 +747,6 @@ var _CPMenuBarVisible = NO,
|
||||
}
|
||||
|
||||
// Show it.
|
||||
if ([CPPlatform isBrowser])
|
||||
[menuWindow setPlatformWindow:[[aView window] platformWindow]];
|
||||
|
||||
[menuWindow orderFront:self];
|
||||
|
||||
// Track it.
|
||||
@@ -868,13 +780,13 @@ var _CPMenuBarVisible = NO,
|
||||
|
||||
+ (void)popUpContextMenu:(CPMenu)aMenu withEvent:(CPEvent)anEvent forView:(CPView)aView withFont:(CPFont)aFont
|
||||
{
|
||||
// This is needed when we are making several rights click
|
||||
[[_CPMenuManager sharedMenuManager] cancelActiveMenu];
|
||||
|
||||
[aMenu _menuWillOpen];
|
||||
|
||||
var delegate = [aMenu delegate];
|
||||
|
||||
if ([delegate respondsToSelector:@selector(menuWillOpen:)])
|
||||
[delegate menuWillOpen:aMenu];
|
||||
|
||||
if (!aFont)
|
||||
aFont = [CPFont systemFontOfSize:[CPFont systemFontSize]];
|
||||
aFont = [CPFont systemFontOfSize:12.0];
|
||||
|
||||
var theWindow = [aView window],
|
||||
menuWindow = [_CPMenuWindow menuWindowWithMenu:aMenu font:aFont];
|
||||
@@ -904,9 +816,6 @@ var _CPMenuBarVisible = NO,
|
||||
[menuWindow setFrameOrigin:CGRectIntersection(unconstrainedFrame, constraintRect).origin];
|
||||
}
|
||||
|
||||
if ([CPPlatform isBrowser])
|
||||
[menuWindow setPlatformWindow:[[aView window] platformWindow]];
|
||||
|
||||
[menuWindow orderFront:self];
|
||||
|
||||
[[_CPMenuManager sharedMenuManager]
|
||||
@@ -941,32 +850,14 @@ var _CPMenuBarVisible = NO,
|
||||
*/
|
||||
- (CPMenuItem)highlightedItem
|
||||
{
|
||||
if (_highlightedIndex < 0)
|
||||
return nil;
|
||||
|
||||
var highlightedItem = _items[_highlightedIndex];
|
||||
|
||||
if ([highlightedItem isSeparatorItem])
|
||||
return nil;
|
||||
|
||||
return highlightedItem;
|
||||
return _highlightedIndex >= 0 ? _items[_highlightedIndex] : nil;
|
||||
}
|
||||
|
||||
// Managing the Delegate
|
||||
|
||||
- (void)setDelegate:(id <CPMenuDelegate>)aDelegate
|
||||
- (void)setDelegate:(id)aDelegate
|
||||
{
|
||||
if (_delegate === aDelegate)
|
||||
return;
|
||||
|
||||
_delegate = aDelegate;
|
||||
_implementedDelegateMethods = 0;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(menuWillOpen:)])
|
||||
_implementedDelegateMethods |= CPMenuDelegate_menuWillOpen_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(menuDidClose:)])
|
||||
_implementedDelegateMethods |= CPMenuDelegate_menuDidClose_;
|
||||
}
|
||||
|
||||
- (id)delegate
|
||||
@@ -974,23 +865,9 @@ var _CPMenuBarVisible = NO,
|
||||
return _delegate;
|
||||
}
|
||||
|
||||
- (void)_menuWillOpen
|
||||
{
|
||||
[self _sendDelegateMenuWillOpen];
|
||||
}
|
||||
|
||||
- (void)_menuDidClose
|
||||
{
|
||||
// Remember which event caused this menu to close, if any. CPPopUpButton uses this to detect
|
||||
// when a click on the button itself caused the menu to close.
|
||||
_lastCloseEvent = [CPApp currentEvent];
|
||||
|
||||
[self _sendDelegateMenuDidClose];
|
||||
}
|
||||
|
||||
// Handling Tracking
|
||||
/*!
|
||||
Cancels tracking.
|
||||
Cancels tracking.
|
||||
*/
|
||||
- (void)cancelTracking
|
||||
{
|
||||
@@ -1001,7 +878,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
[CPApp sendEvent:[CPEvent
|
||||
otherEventWithType:CPAppKitDefined
|
||||
location:CGPointMakeZero()
|
||||
location:_CGPointMakeZero()
|
||||
modifierFlags:0
|
||||
timestamp:0
|
||||
windowNumber:0
|
||||
@@ -1050,11 +927,22 @@ var _CPMenuBarVisible = NO,
|
||||
characters = [anEvent charactersIgnoringModifiers],
|
||||
modifierFlags = [anEvent modifierFlags];
|
||||
|
||||
for (; index < count; ++index)
|
||||
for(; index < count; ++index)
|
||||
{
|
||||
var item = _items[index];
|
||||
var item = _items[index],
|
||||
modifierMask = [item keyEquivalentModifierMask];
|
||||
|
||||
if ([anEvent _triggersKeyEquivalent:[item keyEquivalent] withModifierMask:[item keyEquivalentModifierMask]])
|
||||
if ([item keyEquivalent] === [[item keyEquivalent] uppercaseString])
|
||||
modifierMask |= CPShiftKeyMask;
|
||||
|
||||
if (CPBrowserIsOperatingSystem(CPWindowsOperatingSystem) && (modifierMask & CPCommandKeyMask))
|
||||
{
|
||||
modifierMask |= CPControlKeyMask;
|
||||
modifierMask &= ~CPCommandKeyMask;
|
||||
}
|
||||
|
||||
if ((modifierFlags & (CPShiftKeyMask | CPAlternateKeyMask | CPCommandKeyMask | CPControlKeyMask)) == modifierMask &&
|
||||
[characters caseInsensitiveCompare:[item keyEquivalent]] == CPOrderedSame)
|
||||
{
|
||||
if ([item isEnabled])
|
||||
[self performActionForItemAtIndex:index];
|
||||
@@ -1062,7 +950,7 @@ var _CPMenuBarVisible = NO,
|
||||
{
|
||||
//beep?
|
||||
}
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -1078,14 +966,22 @@ var _CPMenuBarVisible = NO,
|
||||
Sends the action of the menu item at the specified index.
|
||||
@param anIndex the index of the item
|
||||
*/
|
||||
- (void)performActionForItemAtIndex:(CPUInteger)anIndex
|
||||
- (void)performActionForItemAtIndex:(unsigned)anIndex
|
||||
{
|
||||
var item = _items[anIndex];
|
||||
|
||||
|
||||
[CPApp sendAction:[item action] to:[item target] from:item];
|
||||
}
|
||||
|
||||
//
|
||||
/*
|
||||
@ignore
|
||||
*/
|
||||
- (BOOL)_itemIsHighlighted:(CPMenuItem)aMenuItem
|
||||
{
|
||||
return _items[_highlightedIndex] == aMenuItem;
|
||||
}
|
||||
|
||||
/*
|
||||
@ignore
|
||||
*/
|
||||
@@ -1101,9 +997,6 @@ var _CPMenuBarVisible = NO,
|
||||
|
||||
if (_highlightedIndex !== CPNotFound)
|
||||
[[_items[_highlightedIndex] _menuItemView] highlight:YES];
|
||||
|
||||
if (_highlightedIndex !== CPNotFound && _menuWindow)
|
||||
[_menuWindow._menuView scrollRectToVisible:[[_items[_highlightedIndex] _menuItemView] frame]];
|
||||
}
|
||||
|
||||
- (void)_setMenuName:(CPString)aName
|
||||
@@ -1131,7 +1024,7 @@ var _CPMenuBarVisible = NO,
|
||||
}
|
||||
}
|
||||
|
||||
- (CPMenu)_menuWithName:(CPString)aName
|
||||
- (void)_menuWithName:(CPString)aName
|
||||
{
|
||||
if (aName === _name)
|
||||
return self;
|
||||
@@ -1150,98 +1043,10 @@ var _CPMenuBarVisible = NO,
|
||||
@end
|
||||
|
||||
|
||||
@implementation CPMenu (CPMenuDelegate)
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate menuWillOpen
|
||||
*/
|
||||
- (void)_sendDelegateMenuWillOpen
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPMenuDelegate_menuWillOpen_))
|
||||
return;
|
||||
|
||||
[_delegate menuWillOpen:self];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
Call delegate menuDidClose
|
||||
*/
|
||||
- (void)_sendDelegateMenuDidClose
|
||||
{
|
||||
if (!(_implementedDelegateMethods & CPMenuDelegate_menuDidClose_))
|
||||
return;
|
||||
|
||||
[_delegate menuDidClose:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation CPMenu (CPKeyValueCoding)
|
||||
|
||||
- (CPUInteger)countOfItems
|
||||
{
|
||||
return [_items count];
|
||||
}
|
||||
|
||||
- (CPMenuItem)objectInItemsAtIndex:(CPUInteger)anIndex
|
||||
{
|
||||
return [_items objectAtIndex:anIndex];
|
||||
}
|
||||
|
||||
- (CPArray)itemsAtIndexes:(CPIndexSet)indexes
|
||||
{
|
||||
return [_items objectsAtIndexes:indexes];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPMenu (CPKeyValueObserving)
|
||||
|
||||
- (void)insertObject:(CPMenuItem)aMenuItem inItemsAtIndex:(CPUInteger)anIndex
|
||||
{
|
||||
var menu = [aMenuItem menu];
|
||||
|
||||
if (menu)
|
||||
if (menu !== self)
|
||||
[CPException raise:CPInternalInconsistencyException reason:@"Attempted to insert item into menu that was already in another menu."];
|
||||
else
|
||||
return;
|
||||
|
||||
[aMenuItem setMenu:self];
|
||||
[self _highlightItemAtIndex:CPNotFound];
|
||||
[_items insertObject:aMenuItem atIndex:anIndex];
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPMenuDidAddItemNotification
|
||||
object:self
|
||||
userInfo:@{ @"CPMenuItemIndex": anIndex }];
|
||||
}
|
||||
|
||||
- (void)removeObjectFromItemsAtIndex:(CPUInteger)anIndex
|
||||
{
|
||||
if (anIndex < 0 || anIndex >= [_items count])
|
||||
return;
|
||||
|
||||
[[_items objectAtIndex:anIndex] setMenu:nil];
|
||||
[self _highlightItemAtIndex:CPNotFound];
|
||||
[_items removeObjectAtIndex:anIndex];
|
||||
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPMenuDidRemoveItemNotification
|
||||
object:self
|
||||
userInfo:@{ @"CPMenuItemIndex": anIndex }];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPMenuTitleKey = @"CPMenuTitleKey",
|
||||
CPMenuNameKey = @"CPMenuNameKey",
|
||||
CPMenuItemsKey = @"CPMenuItemsKey",
|
||||
CPMenuShowsStateColumnKey = @"CPMenuShowsStateColumnKey",
|
||||
CPMenuAutoEnablesItemsKey = @"CPMenuAutoEnablesItemsKey";
|
||||
CPMenuShowsStateColumnKey = @"CPMenuShowsStateColumnKey";
|
||||
|
||||
@implementation CPMenu (CPCoding)
|
||||
|
||||
@@ -1253,7 +1058,7 @@ var CPMenuTitleKey = @"CPMenuTitleKey",
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_title = [aCoder decodeObjectForKey:CPMenuTitleKey];
|
||||
@@ -1263,11 +1068,9 @@ var CPMenuTitleKey = @"CPMenuTitleKey",
|
||||
|
||||
_showsStateColumn = ![aCoder containsValueForKey:CPMenuShowsStateColumnKey] || [aCoder decodeBoolForKey:CPMenuShowsStateColumnKey];
|
||||
|
||||
_autoenablesItems = ![aCoder containsValueForKey:CPMenuAutoEnablesItemsKey] || [aCoder decodeBoolForKey:CPMenuAutoEnablesItemsKey];
|
||||
|
||||
[self setMinimumWidth:0];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -1286,40 +1089,6 @@ var CPMenuTitleKey = @"CPMenuTitleKey",
|
||||
|
||||
if (!_showsStateColumn)
|
||||
[aCoder encodeBool:_showsStateColumn forKey:CPMenuShowsStateColumnKey];
|
||||
|
||||
if (!_autoenablesItems)
|
||||
[aCoder encodeBool:_autoenablesItems forKey:CPMenuAutoEnablesItemsKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation CPMenu (CSSTheming)
|
||||
|
||||
+ (void)setNamedValue:(CPString)aName forKey:(CPString)aKey inAttributes:(CPDictionary)aDictionary forTheme:(CPTheme)aTheme
|
||||
{
|
||||
var value = [aTheme valueForAttributeWithName:aName forClass:_CPMenuView];
|
||||
|
||||
if (value)
|
||||
[aDictionary setObject:value forKey:aKey];
|
||||
else
|
||||
[aDictionary removeObjectForKey:aKey];
|
||||
}
|
||||
|
||||
+ (void)updateMenuBarAttributesWithTheme:(CPTheme)aTheme
|
||||
{
|
||||
var newAttributes = @{};
|
||||
|
||||
[CPMenu setNamedValue:@"menu-bar-text-color" forKey:@"CPMenuBarTextColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
[CPMenu setNamedValue:@"menu-bar-title-color" forKey:@"CPMenuBarTitleColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
[CPMenu setNamedValue:@"menu-bar-text-shadow-color" forKey:@"CPMenuBarTextShadowColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
[CPMenu setNamedValue:@"menu-bar-title-shadow-color" forKey:@"CPMenuBarTitleShadowColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
[CPMenu setNamedValue:@"menu-bar-highlight-color" forKey:@"CPMenuBarHighlightColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
[CPMenu setNamedValue:@"menu-bar-highlight-text-color" forKey:@"CPMenuBarHighlightTextColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
[CPMenu setNamedValue:@"menu-bar-highlight-text-shadow-color" forKey:@"CPMenuBarHighlightTextShadowColor" inAttributes:newAttributes forTheme:aTheme];
|
||||
|
||||
[CPMenu setMenuBarAttributes:newAttributes];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+194
-120
@@ -1,60 +1,53 @@
|
||||
/*
|
||||
* _CPMenuBarWindow.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPPanel.j"
|
||||
@import "_CPMenuManager.j"
|
||||
#include "../CoreGraphics/CGGeometry.h"
|
||||
#include "../Platform/Platform.h"
|
||||
|
||||
@class _CPMenuView
|
||||
@class CPMenu
|
||||
@class CPMenuItem
|
||||
@import "_CPMenuWindow.j"
|
||||
|
||||
@global CPMenuDidAddItemNotification
|
||||
@global CPMenuDidChangeItemNotification
|
||||
@global CPMenuDidRemoveItemNotification
|
||||
|
||||
var MENUBAR_HEIGHT = 28.0,
|
||||
MENUBAR_MARGIN = 10.0,
|
||||
MENUBAR_LEFT_MARGIN = 10.0,
|
||||
MENUBAR_RIGHT_MARGIN = 10.0;
|
||||
|
||||
var _CPMenuBarWindowBackgroundColor = nil,
|
||||
_CPMenuBarWindowFont = nil;
|
||||
|
||||
@implementation _CPMenuBarWindow : CPPanel
|
||||
{
|
||||
CPMenu _menu;
|
||||
CPView _highlightView;
|
||||
CPArray _menuItemViews;
|
||||
|
||||
|
||||
CPMenuItem _trackingMenuItem;
|
||||
|
||||
|
||||
CPImageView _iconImageView;
|
||||
CPTextField _titleField;
|
||||
|
||||
|
||||
CPColor _textColor;
|
||||
CPColor _titleColor;
|
||||
|
||||
|
||||
CPColor _textShadowColor;
|
||||
CPColor _titleShadowColor;
|
||||
|
||||
|
||||
CPColor _highlightColor;
|
||||
CPColor _highlightTextColor;
|
||||
CPColor _highlightTextShadowColor;
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self != [_CPMenuBarWindow class])
|
||||
return;
|
||||
|
||||
var bundle = [CPBundle bundleForClass:self];
|
||||
|
||||
_CPMenuBarWindowFont = [CPFont boldSystemFontOfSize:12.0];
|
||||
}
|
||||
|
||||
+ (CPFont)font
|
||||
{
|
||||
return [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-font" forClass:_CPMenuView];
|
||||
return _CPMenuBarWindowFont;
|
||||
}
|
||||
|
||||
- (id)init
|
||||
@@ -62,37 +55,35 @@
|
||||
// This only shows up in browser land, so don't bother calculating metrics in desktop.
|
||||
var contentRect = [[CPPlatformWindow primaryPlatformWindow] contentBounds];
|
||||
|
||||
contentRect.size.height = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-height" forClass:_CPMenuView];
|
||||
contentRect.size.height = MENUBAR_HEIGHT;
|
||||
|
||||
self = [super initWithContentRect:contentRect styleMask:CPBorderlessWindowMask];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_constrainsToUsableScreen = NO;
|
||||
|
||||
[self setLevel:CPMainMenuWindowLevel];
|
||||
[self setAutoresizingMask:CPWindowWidthSizable];
|
||||
|
||||
|
||||
var contentView = [self contentView];
|
||||
|
||||
|
||||
[contentView setAutoresizesSubviews:NO];
|
||||
|
||||
|
||||
[self setBecomesKeyOnlyIfNeeded:YES];
|
||||
|
||||
|
||||
//
|
||||
_iconImageView = [[CPImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 16.0, 16.0)];
|
||||
|
||||
|
||||
[contentView addSubview:_iconImageView];
|
||||
|
||||
|
||||
_titleField = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[_titleField setFont:[CPFont boldSystemFontOfSize:[CPFont systemFontSize] + 1]];
|
||||
[_titleField setFont:[CPFont boldSystemFontOfSize:13.0]];
|
||||
[_titleField setAlignment:CPCenterTextAlignment];
|
||||
[_titleField setTextShadowOffset:CGSizeMake(0, 1)];
|
||||
|
||||
|
||||
[contentView addSubview:_titleField];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -111,7 +102,7 @@
|
||||
|
||||
[_titleField setStringValue:aTitle];
|
||||
[_titleField sizeToFit];
|
||||
|
||||
|
||||
[self tile];
|
||||
}
|
||||
|
||||
@@ -130,32 +121,34 @@
|
||||
|
||||
- (void)setColor:(CPColor)aColor
|
||||
{
|
||||
var targetView = [[CPTheme defaultTheme] valueForAttributeWithName:@"css-based" forClass:CPView] ? [[self contentView] superview] : [self contentView];
|
||||
|
||||
if (!aColor)
|
||||
[targetView setBackgroundColor:[[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-background-color" forClass:_CPMenuView]];
|
||||
{
|
||||
if (!_CPMenuBarWindowBackgroundColor)
|
||||
_CPMenuBarWindowBackgroundColor = [CPColor colorWithPatternImage:[[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:[_CPMenuBarWindow class]] pathForResource:@"_CPMenuBarWindow/_CPMenuBarWindowBackground.png"] size:CGSizeMake(1.0, 28.0)]];
|
||||
|
||||
[[self contentView] setBackgroundColor:_CPMenuBarWindowBackgroundColor];
|
||||
}
|
||||
else
|
||||
[targetView setBackgroundColor:aColor];
|
||||
[[self contentView] setBackgroundColor:aColor];
|
||||
}
|
||||
|
||||
- (void)setTextColor:(CPColor)aColor
|
||||
{
|
||||
if (_textColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_textColor = aColor;
|
||||
|
||||
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setTextColor:) withObject:_textColor];
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setParentMenuTextColor:) withObject:_textColor];
|
||||
}
|
||||
|
||||
- (void)setTitleColor:(CPColor)aColor
|
||||
{
|
||||
if (_titleColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_titleColor = aColor;
|
||||
|
||||
|
||||
[_titleField setTextColor:aColor ? aColor : [CPColor blackColor]];
|
||||
}
|
||||
|
||||
@@ -163,20 +156,19 @@
|
||||
{
|
||||
if (_textShadowColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_textShadowColor = aColor;
|
||||
|
||||
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setTextShadowColor:) withObject:_textShadowColor];
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setParentMenuTextShadowColor:) withObject:_textShadowColor];
|
||||
}
|
||||
|
||||
- (void)setTitleShadowColor:(CPColor)aColor
|
||||
{
|
||||
if (_titleShadowColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_titleShadowColor = aColor;
|
||||
|
||||
|
||||
[_titleField setTextShadowColor:aColor ? aColor : [CPColor whiteColor]];
|
||||
}
|
||||
|
||||
@@ -184,39 +176,37 @@
|
||||
{
|
||||
if (_highlightColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_highlightColor = aColor;
|
||||
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setParentMenuHighlightColor:) withObject:_highlightColor];
|
||||
}
|
||||
|
||||
- (void)setHighlightTextColor:(CPColor)aColor
|
||||
{
|
||||
if (_highlightTextColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_highlightTextColor = aColor;
|
||||
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setParentMenuHighlightTextColor:) withObject:_highlightTextColor];
|
||||
// [_menuItemViews makeObjectsPerformSelector:@selector(setActivateColor:) withObject:_highlightTextColor];
|
||||
}
|
||||
|
||||
- (void)setHighlightTextShadowColor:(CPColor)aColor
|
||||
{
|
||||
if (_highlightTextShadowColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_highlightTextShadowColor = aColor;
|
||||
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(setParentMenuHighlightTextShadowColor:) withObject:_highlightTextShadowColor];
|
||||
|
||||
// [_menuItemViews makeObjectsPerformSelector:@selector(setActivateShadowColor:) withObject:_highlightTextShadowColor];
|
||||
}
|
||||
|
||||
- (void)setMenu:(CPMenu)aMenu
|
||||
{
|
||||
if (_menu == aMenu)
|
||||
return;
|
||||
|
||||
|
||||
var defaultCenter = [CPNotificationCenter defaultCenter];
|
||||
|
||||
|
||||
if (_menu)
|
||||
{
|
||||
[defaultCenter
|
||||
@@ -233,16 +223,16 @@
|
||||
removeObserver:self
|
||||
name:CPMenuDidRemoveItemNotification
|
||||
object:_menu];
|
||||
|
||||
|
||||
var items = [_menu itemArray],
|
||||
count = items.length;
|
||||
|
||||
|
||||
while (count--)
|
||||
[[items[count] _menuItemView] removeFromSuperview];
|
||||
}
|
||||
|
||||
_menu = aMenu;
|
||||
|
||||
|
||||
if (_menu)
|
||||
{
|
||||
[defaultCenter
|
||||
@@ -250,51 +240,41 @@
|
||||
selector:@selector(menuDidAddItem:)
|
||||
name:CPMenuDidAddItemNotification
|
||||
object:_menu];
|
||||
|
||||
|
||||
[defaultCenter
|
||||
addObserver:self
|
||||
selector:@selector(menuDidChangeItem:)
|
||||
name:CPMenuDidChangeItemNotification
|
||||
object:_menu];
|
||||
|
||||
|
||||
[defaultCenter
|
||||
addObserver:self
|
||||
selector:@selector(menuDidRemoveItem:)
|
||||
name:CPMenuDidRemoveItemNotification
|
||||
object:_menu];
|
||||
}
|
||||
|
||||
|
||||
_menuItemViews = [];
|
||||
|
||||
|
||||
var contentView = [self contentView],
|
||||
items = [_menu itemArray],
|
||||
count = items.length;
|
||||
|
||||
for (var index = 0; index < count; ++index)
|
||||
|
||||
for (index = 0; index < count; ++index)
|
||||
{
|
||||
var item = items[index],
|
||||
menuItemView = [item _menuItemView];
|
||||
|
||||
|
||||
_menuItemViews.push(menuItemView);
|
||||
|
||||
[menuItemView setTextColor:_textColor];
|
||||
[menuItemView setHidden:[item isHidden]];
|
||||
|
||||
// If first menu item has tag -1 and if there is a special theme value menu-bar-window-first-item-font,
|
||||
// set the corresponding font. This is used to set bold on the first item of the menubar (à la Cocoa)
|
||||
if ((index == 0) && ([item tag] == -1))
|
||||
{
|
||||
var firstItemFont = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-first-item-font" forClass:_CPMenuView];
|
||||
|
||||
if (firstItemFont)
|
||||
[item setFont:firstItemFont];
|
||||
}
|
||||
|
||||
|
||||
[menuItemView synchronizeWithMenuItem];
|
||||
|
||||
|
||||
[contentView addSubview:menuItemView];
|
||||
}
|
||||
|
||||
|
||||
[self tile];
|
||||
}
|
||||
|
||||
@@ -305,7 +285,7 @@
|
||||
|
||||
[menuItemView setHidden:[menuItem isHidden]];
|
||||
[menuItemView synchronizeWithMenuItem];
|
||||
|
||||
|
||||
[self tile];
|
||||
}
|
||||
|
||||
@@ -321,9 +301,9 @@
|
||||
[menuItemView setHidden:[menuItem isHidden]];
|
||||
|
||||
[menuItemView synchronizeWithMenuItem];
|
||||
|
||||
|
||||
[[self contentView] addSubview:menuItemView];
|
||||
|
||||
|
||||
[self tile];
|
||||
}
|
||||
|
||||
@@ -335,15 +315,10 @@
|
||||
[_menuItemViews removeObjectAtIndex:index];
|
||||
|
||||
[menuItemView removeFromSuperview];
|
||||
|
||||
|
||||
[self tile];
|
||||
}
|
||||
|
||||
- (BOOL)acceptsFirstMouse:(CPEvent)anEvent
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
var constraintRect = CGRectInset([[self platformWindow] visibleFrame], 5.0, 0.0);
|
||||
@@ -363,7 +338,7 @@
|
||||
|
||||
- (CPFont)font
|
||||
{
|
||||
return [CPFont systemFontOfSize:[CPFont systemFontSize]];
|
||||
[CPFont systemFontOfSize:12.0];
|
||||
}
|
||||
|
||||
- (void)tile
|
||||
@@ -371,46 +346,46 @@
|
||||
var items = [_menu itemArray],
|
||||
index = 0,
|
||||
count = items.length,
|
||||
|
||||
x = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-left-margin" forClass:_CPMenuView],
|
||||
|
||||
x = MENUBAR_LEFT_MARGIN,
|
||||
y = 0.0,
|
||||
isLeftAligned = YES;
|
||||
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var item = items[index];
|
||||
|
||||
|
||||
if ([item isSeparatorItem])
|
||||
{
|
||||
x = CGRectGetWidth([self frame]) - [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-right-margin" forClass:_CPMenuView];
|
||||
x = CGRectGetWidth([self frame]) - MENUBAR_RIGHT_MARGIN;
|
||||
isLeftAligned = NO;
|
||||
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
if ([item isHidden])
|
||||
continue;
|
||||
|
||||
var menuItemView = [item _menuItemView],
|
||||
frame = [menuItemView frame];
|
||||
|
||||
|
||||
if (isLeftAligned)
|
||||
{
|
||||
[menuItemView setFrame:CGRectMake(x, 0.0, CGRectGetWidth(frame), [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-height" forClass:_CPMenuView])];
|
||||
[menuItemView setFrame:CGRectMake(x, 0.0, CGRectGetWidth(frame), MENUBAR_HEIGHT)];
|
||||
|
||||
x += CGRectGetWidth([menuItemView frame]);
|
||||
}
|
||||
else
|
||||
{
|
||||
[menuItemView setFrame:CGRectMake(x - CGRectGetWidth(frame), 0.0, CGRectGetWidth(frame), [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-height" forClass:_CPMenuView])];
|
||||
|
||||
[menuItemView setFrame:CGRectMake(x - CGRectGetWidth(frame), 0.0, CGRectGetWidth(frame), MENUBAR_HEIGHT)];
|
||||
|
||||
x = CGRectGetMinX([menuItemView frame]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var bounds = [[self contentView] bounds],
|
||||
titleFrame = [_titleField frame];
|
||||
|
||||
|
||||
if ([_iconImageView isHidden])
|
||||
[_titleField setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(titleFrame)) / 2.0, (CGRectGetHeight(bounds) - CGRectGetHeight(titleFrame)) / 2.0)];
|
||||
else
|
||||
@@ -418,7 +393,7 @@
|
||||
var iconFrame = [_iconImageView frame],
|
||||
iconWidth = CGRectGetWidth(iconFrame),
|
||||
totalWidth = iconWidth + CGRectGetWidth(titleFrame);
|
||||
|
||||
|
||||
[_iconImageView setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - totalWidth) / 2.0, (CGRectGetHeight(bounds) - CGRectGetHeight(iconFrame)) / 2.0)];
|
||||
[_titleField setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - totalWidth) / 2.0 + iconWidth, (CGRectGetHeight(bounds) - CGRectGetHeight(titleFrame)) / 2.0)];
|
||||
}
|
||||
@@ -430,7 +405,7 @@
|
||||
|
||||
[super setFrame:aRect display:shouldDisplay animate:shouldAnimate];
|
||||
|
||||
if (!CGSizeEqualToSize(size, aRect.size))
|
||||
if (!_CGSizeEqualToSize(size, aRect.size))
|
||||
[self tile];
|
||||
}
|
||||
|
||||
@@ -480,3 +455,102 @@
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPMenuBarView : _CPMenuView
|
||||
{
|
||||
}
|
||||
|
||||
- (CGRect)rectForItemAtIndex:(int)anIndex
|
||||
{
|
||||
return [_menuItemViews[anIndex === CPNotFound ? 0 : anIndex] frame];
|
||||
}
|
||||
|
||||
- (int)itemIndexAtPoint:(CGPoint)aPoint
|
||||
{
|
||||
var bounds = [self bounds];
|
||||
|
||||
if (!CGRectContainsPoint(bounds, aPoint))
|
||||
return CPNotFound;
|
||||
|
||||
var x = aPoint.x,
|
||||
low = 0,
|
||||
high = _visibleMenuItemInfos.length - 1;
|
||||
|
||||
while (low <= high)
|
||||
{
|
||||
var middle = FLOOR(low + (high - low) / 2),
|
||||
info = _visibleMenuItemInfos[middle],
|
||||
frame = [info.view frame];
|
||||
|
||||
if (x < CGRectGetMinX(frame))
|
||||
high = middle - 1;
|
||||
|
||||
else if (x > CGRectGetMaxX(frame))
|
||||
low = middle + 1;
|
||||
|
||||
else
|
||||
return info.index;
|
||||
}
|
||||
|
||||
return CPNotFound;
|
||||
}
|
||||
|
||||
- (void)tile
|
||||
{
|
||||
var items = [_menu itemArray],
|
||||
index = 0,
|
||||
count = items.length,
|
||||
|
||||
x = MENUBAR_LEFT_MARGIN,
|
||||
y = 0.0,
|
||||
isLeftAligned = YES;
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var item = items[index];
|
||||
|
||||
if ([item isSeparatorItem])
|
||||
{
|
||||
x = CGRectGetWidth([self frame]) - MENUBAR_RIGHT_MARGIN;
|
||||
isLeftAligned = NO;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ([item isHidden])
|
||||
continue;
|
||||
|
||||
var menuItemView = [item _menuItemView],
|
||||
frame = [menuItemView frame];
|
||||
|
||||
if (isLeftAligned)
|
||||
{
|
||||
[menuItemView setFrameOrigin:CGPointMake(x, (MENUBAR_HEIGHT - 1.0 - CGRectGetHeight(frame)) / 2.0)];
|
||||
|
||||
x += CGRectGetWidth([menuItemView frame]) + MENUBAR_MARGIN;
|
||||
}
|
||||
else
|
||||
{
|
||||
[menuItemView setFrameOrigin:CGPointMake(x - CGRectGetWidth(frame), (MENUBAR_HEIGHT - 1.0 - CGRectGetHeight(frame)) / 2.0)];
|
||||
|
||||
x = CGRectGetMinX([menuItemView frame]) - MENUBAR_MARGIN;
|
||||
}
|
||||
}
|
||||
|
||||
var bounds = [[self contentView] bounds],
|
||||
titleFrame = [_titleField frame];
|
||||
|
||||
if ([_iconImageView isHidden])
|
||||
[_titleField setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(titleFrame)) / 2.0, (CGRectGetHeight(bounds) - CGRectGetHeight(titleFrame)) / 2.0)];
|
||||
else
|
||||
{
|
||||
var iconFrame = [_iconImageView frame],
|
||||
iconWidth = CGRectGetWidth(iconFrame),
|
||||
totalWidth = iconWidth + CGRectGetWidth(titleFrame);
|
||||
|
||||
[_iconImageView setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - totalWidth) / 2.0, (CGRectGetHeight(bounds) - CGRectGetHeight(iconFrame)) / 2.0)];
|
||||
[_titleField setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - totalWidth) / 2.0 + iconWidth, (CGRectGetHeight(bounds) - CGRectGetHeight(titleFrame)) / 2.0)];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+69
-490
@@ -1,54 +1,20 @@
|
||||
/*
|
||||
* _CPMenuManager.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include "../CoreGraphics/CGGeometry.h"
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPNotificationCenter.j>
|
||||
|
||||
@import "CPEvent.j"
|
||||
@import "CPKeyBinding.j"
|
||||
|
||||
@class CPWindow
|
||||
@class _CPMenuWindow
|
||||
@class _CPMenuView
|
||||
@class CPMenuItem
|
||||
|
||||
|
||||
@global CPApp
|
||||
@global CPMenuDidEndTrackingNotification
|
||||
@global _CPMenuWindowMenuBarBackgroundStyle
|
||||
@global _CPMenuWindowPopUpBackgroundStyle
|
||||
|
||||
_CPMenuManagerScrollingStateUp = -1;
|
||||
_CPMenuManagerScrollingStateDown = 1;
|
||||
_CPMenuManagerScrollingStateUp = -1,
|
||||
_CPMenuManagerScrollingStateDown = 1,
|
||||
_CPMenuManagerScrollingStateNone = 0;
|
||||
|
||||
var STICKY_TIME_INTERVAL = 0.4,
|
||||
SharedMenuManager = nil;
|
||||
var STICKY_TIME_INTERVAL = 500;
|
||||
|
||||
var SharedMenuManager = nil;
|
||||
|
||||
@implementation _CPMenuManager: CPObject
|
||||
{
|
||||
CPTimeInterval _startTime;
|
||||
CPEvent _openEvent;
|
||||
BOOL _mouseWasDragged;
|
||||
int _scrollingState;
|
||||
CGPoint _lastGlobalLocation;
|
||||
|
||||
@@ -58,13 +24,6 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
CPMutableArray _menuContainerStack;
|
||||
|
||||
Function _trackingCallback;
|
||||
|
||||
CPString _keyBuffer;
|
||||
|
||||
CPMenuItem _previousActiveItem;
|
||||
int _showTimerID;
|
||||
|
||||
int _menuBarButtonItemIndex;
|
||||
}
|
||||
|
||||
+ (_CPMenuManager)sharedMenuManager
|
||||
@@ -80,7 +39,7 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
if (SharedMenuManager)
|
||||
return SharedMenuManager;
|
||||
|
||||
return [super init];
|
||||
return [super init];
|
||||
}
|
||||
|
||||
- (id)trackingMenuContainer
|
||||
@@ -100,13 +59,9 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
{
|
||||
var menu = [aMenuContainer menu];
|
||||
|
||||
if ([menu numberOfItems] <= 0)
|
||||
return;
|
||||
|
||||
CPApp._activeMenu = menu;
|
||||
|
||||
_startTime = [anEvent timestamp];
|
||||
_openEvent = anEvent;
|
||||
_startTime = [anEvent timestamp];//new Date();
|
||||
_scrollingState = _CPMenuManagerScrollingStateNone;
|
||||
|
||||
_constraintRect = aRect;
|
||||
@@ -115,32 +70,25 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
|
||||
if (menu === [CPApp mainMenu])
|
||||
{
|
||||
var globalLocation = [anEvent globalLocation],
|
||||
var globalLocation = [anEvent globalLocation];
|
||||
|
||||
// Find which menu window the mouse is currently on top of
|
||||
menuLocation = [aMenuContainer convertGlobalToBase:globalLocation],
|
||||
// Find which menu window the mouse is currently on top of
|
||||
var menuLocation = [aMenuContainer convertGlobalToBase:globalLocation];
|
||||
|
||||
// Find out the item the mouse is currently on top of
|
||||
activeItemIndex = [aMenuContainer itemIndexAtPoint:menuLocation],
|
||||
// Find out the item the mouse is currently on top of
|
||||
var activeItemIndex = [aMenuContainer itemIndexAtPoint:menuLocation],
|
||||
activeItem = activeItemIndex !== CPNotFound ? [menu itemAtIndex:activeItemIndex] : nil;
|
||||
|
||||
_menuBarButtonItemIndex = activeItemIndex;
|
||||
// _menuBarButtonMenuContainer = aMenuContainer;
|
||||
_menuBarButtonMenuContainer = aMenuContainer;
|
||||
|
||||
if ([activeItem _isMenuBarButton])
|
||||
return [self trackMenuBarButtonEvent:anEvent];
|
||||
}
|
||||
|
||||
_mouseWasDragged = NO;
|
||||
|
||||
[self trackEvent:anEvent];
|
||||
}
|
||||
|
||||
- (void)_trackAgain
|
||||
{
|
||||
[CPApp setTarget:self selector:@selector(trackEvent:) forNextEventMatchingMask:CPKeyDownMask | CPPeriodicMask | CPMouseMovedMask | CPLeftMouseDraggedMask | CPLeftMouseDownMask | CPLeftMouseUpMask | CPRightMouseUpMask | CPAppKitDefinedMask | CPScrollWheelMask untilDate:nil inMode:nil dequeue:YES];
|
||||
}
|
||||
|
||||
- (void)trackEvent:(CPEvent)anEvent
|
||||
{
|
||||
var type = [anEvent type],
|
||||
@@ -148,84 +96,27 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
|
||||
// Close Menu Event.
|
||||
if (type === CPAppKitDefined)
|
||||
return [self completeTracking];
|
||||
return [self completeTracking]
|
||||
|
||||
if (type === CPKeyDown)
|
||||
{
|
||||
var menu = trackingMenu,
|
||||
submenu = [[menu highlightedItem] submenu];
|
||||
|
||||
// get the current active menu
|
||||
while (submenu && [submenu._menuWindow isVisible])
|
||||
{
|
||||
menu = submenu;
|
||||
submenu = [[menu highlightedItem] submenu];
|
||||
}
|
||||
|
||||
if ([menu numberOfItems])
|
||||
[self interpretKeyEvent:anEvent forMenu:menu];
|
||||
|
||||
[self _trackAgain];
|
||||
return;
|
||||
}
|
||||
[CPApp setTarget:self selector:@selector(trackEvent:) forNextEventMatchingMask:CPPeriodicMask | CPMouseMovedMask | CPLeftMouseDraggedMask | CPLeftMouseUpMask | CPAppKitDefinedMask untilDate:nil inMode:nil dequeue:YES];
|
||||
|
||||
// Periodic events don't have a valid location.
|
||||
var globalLocation = type === CPPeriodic ? _lastGlobalLocation : [anEvent globalLocation];
|
||||
|
||||
if (!globalLocation)
|
||||
{
|
||||
[self _trackAgain];
|
||||
return;
|
||||
}
|
||||
// Remember this for the next periodic event.
|
||||
_lastGlobalLocation = globalLocation;
|
||||
|
||||
// Find which menu window the mouse is currently on top of
|
||||
var activeMenuContainer = [self menuContainerForPoint:globalLocation],
|
||||
activeMenu = [activeMenuContainer menu],
|
||||
menuLocation = [activeMenuContainer convertGlobalToBase:globalLocation],
|
||||
menuLocation = [activeMenuContainer convertGlobalToBase:globalLocation];
|
||||
|
||||
// Find out the item the mouse is currently on top of
|
||||
activeItemIndex = activeMenuContainer ? [activeMenuContainer itemIndexAtPoint:menuLocation] : CPNotFound,
|
||||
// Find out the item the mouse is currently on top of
|
||||
var activeItemIndex = activeMenuContainer ? [activeMenuContainer itemIndexAtPoint:menuLocation] : CPNotFound,
|
||||
activeItem = activeItemIndex !== CPNotFound ? [activeMenu itemAtIndex:activeItemIndex] : nil;
|
||||
|
||||
/*
|
||||
Click outside the menu structure?
|
||||
|
||||
The event which caused the menu to open is not considered even if it's
|
||||
technically a click outside of an open menu, since this would mean the same
|
||||
click which opened the menu could also close it. This is actually common.
|
||||
E.g. you click on a button and it opens a menu below itself.
|
||||
*/
|
||||
if (type === CPLeftMouseDown && _openEvent !== anEvent && (!activeMenuContainer || !CGRectContainsPoint([activeMenuContainer globalFrame], globalLocation)))
|
||||
{
|
||||
[self completeTracking];
|
||||
|
||||
/*
|
||||
You can close and interact with a control in a single click. E.g. you can have a menu open,
|
||||
click on a button outside of it and have the menu immediately close and the button activate,
|
||||
without having to click once to close the menu and once to activate the button.
|
||||
|
||||
Since we normally dequeue the event after tracking it, we'll have to put it back on the stack
|
||||
in this special case. Note that it's important the event is executed /right now/, since certain
|
||||
controls such as HTML upload buttons need a native click event at the top of the stack trace
|
||||
to activate - it's not something we can fake later.
|
||||
*/
|
||||
[CPApp sendEvent:anEvent];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
[self _trackAgain];
|
||||
|
||||
// unhighlight when mouse is moved off the menu
|
||||
if (_lastGlobalLocation && CGRectContainsPoint([activeMenuContainer globalFrame], _lastGlobalLocation)
|
||||
&& !CGRectContainsPoint([activeMenuContainer globalFrame], globalLocation))
|
||||
[activeMenu _highlightItemAtIndex:CPNotFound];
|
||||
|
||||
// Remember this for the next periodic event.
|
||||
_lastGlobalLocation = globalLocation;
|
||||
|
||||
// If the item isn't enabled its as if we clicked on nothing.
|
||||
if ([activeItem _isMenuBarButton])
|
||||
if (![activeItem isEnabled] || [activeItem _isMenuBarButton])
|
||||
{
|
||||
activeItemIndex = CPNotFound;
|
||||
activeItem = nil;
|
||||
@@ -233,13 +124,11 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
|
||||
var mouseOverMenuView = [activeItem view];
|
||||
|
||||
if (type === CPScrollWheel && ![activeMenuContainer isMenuBar])
|
||||
[activeMenuContainer scrollByDelta:[anEvent deltaY]];
|
||||
|
||||
if (type === CPPeriodic)
|
||||
{
|
||||
if (_scrollingState === _CPMenuManagerScrollingStateUp)
|
||||
[activeMenuContainer scrollUp];
|
||||
|
||||
else if (_scrollingState === _CPMenuManagerScrollingStateDown)
|
||||
[activeMenuContainer scrollDown];
|
||||
}
|
||||
@@ -249,31 +138,29 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
{
|
||||
if (!_lastMouseOverMenuView)
|
||||
[activeMenu _highlightItemAtIndex:CPNotFound];
|
||||
|
||||
|
||||
if (_lastMouseOverMenuView != mouseOverMenuView)
|
||||
{
|
||||
[_lastMouseOverMenuView mouseExited:anEvent];
|
||||
[mouseOverMenuView mouseExited:anEvent];
|
||||
// FIXME: Possibly multiple of these?
|
||||
[mouseOverMenuView mouseEntered:anEvent];
|
||||
|
||||
[_lastMouseOverMenuView mouseEntered:anEvent];
|
||||
|
||||
_lastMouseOverMenuView = mouseOverMenuView;
|
||||
}
|
||||
|
||||
var menuContainerWindow = activeMenuContainer;
|
||||
|
||||
if (![menuContainerWindow isKindOfClass:CPWindow])
|
||||
if (![menuContainerWindow isKindOfClass:[CPWindow class]])
|
||||
menuContainerWindow = [menuContainerWindow window];
|
||||
|
||||
[menuContainerWindow
|
||||
sendEvent:[CPEvent mouseEventWithType:type
|
||||
location:menuLocation
|
||||
modifierFlags:[anEvent modifierFlags]
|
||||
timestamp:[anEvent timestamp]
|
||||
windowNumber:menuContainerWindow
|
||||
context:nil
|
||||
eventNumber:0
|
||||
clickCount:[anEvent clickCount]
|
||||
pressure:[anEvent pressure]]];
|
||||
sendEvent:[CPEvent mouseEventWithType:type location:menuLocation modifierFlags:[anEvent modifierFlags]
|
||||
timestamp:[anEvent timestamp]
|
||||
windowNumber:menuContainerWindow
|
||||
context:nil
|
||||
eventNumber:0
|
||||
clickCount:[anEvent clickCount]
|
||||
pressure:[anEvent pressure]]];
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -282,15 +169,11 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
[_lastMouseOverMenuView mouseExited:anEvent];
|
||||
_lastMouseOverMenuView = nil;
|
||||
}
|
||||
|
||||
if (activeItemIndex !== CPNotFound)
|
||||
[activeMenu _highlightItemAtIndex:activeItemIndex];
|
||||
|
||||
if (type === CPMouseMoved || type === CPLeftMouseDragged || type === CPLeftMouseDown || type === CPPeriodic)
|
||||
|
||||
[activeMenu _highlightItemAtIndex:activeItemIndex];
|
||||
|
||||
if (type === CPMouseMoved || type === CPLeftMouseDragged || type === CPLeftMouseDown)
|
||||
{
|
||||
if (type === CPLeftMouseDragged)
|
||||
_mouseWasDragged = YES;
|
||||
|
||||
var oldScrollingState = _scrollingState;
|
||||
|
||||
_scrollingState = [activeMenuContainer scrollingStateForPoint:globalLocation];
|
||||
@@ -299,105 +182,34 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
{
|
||||
if (_scrollingState === _CPMenuManagerScrollingStateNone)
|
||||
[CPEvent stopPeriodicEvents];
|
||||
|
||||
else if (oldScrollingState === _CPMenuManagerScrollingStateNone)
|
||||
[CPEvent startPeriodicEventsAfterDelay:0.0 withPeriod:0.04];
|
||||
}
|
||||
}
|
||||
else if (type === CPLeftMouseUp || type === CPRightMouseUp)
|
||||
{
|
||||
/*
|
||||
There are a few possibilites:
|
||||
|
||||
1. The user clicks and releases without dragging within the sticky time.
|
||||
This is considered a regular mouse click and not a drag. In this case
|
||||
we allow the user to track the menu by moving the mouse. The next
|
||||
mouse up will end tracking.
|
||||
|
||||
2. The user clicks and releases without dragging after the sticky time.
|
||||
This is considered a drag and release and tracking ends.
|
||||
|
||||
3. The user clicks, drags and then releases. Tracking ends.
|
||||
*/
|
||||
if (_mouseWasDragged || ([anEvent timestamp] - _startTime > STICKY_TIME_INTERVAL))
|
||||
{
|
||||
/*
|
||||
Close the menu if:
|
||||
|
||||
1. The mouse was dragged.
|
||||
2. The mouse is released in the menubar.
|
||||
3. The current item has a submenu with a custom action.
|
||||
*/
|
||||
if (_mouseWasDragged ||
|
||||
[activeMenuContainer isMenuBar] ||
|
||||
[activeItem action] !== @selector(submenuAction:))
|
||||
{
|
||||
[trackingMenu cancelTracking];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent previous selected menu items from opening by stopping the timer if a
|
||||
// new item is selected before the timer runs out
|
||||
if (_previousActiveItem !== activeItem)
|
||||
{
|
||||
clearTimeout(_showTimerID);
|
||||
_showTimerID = undefined;
|
||||
else if (type === CPLeftMouseUp && ([anEvent timestamp] - _startTime > STICKY_TIME_INTERVAL))
|
||||
[trackingMenu cancelTracking];
|
||||
}
|
||||
|
||||
// If the item has a submenu, show it.
|
||||
if ([activeItem hasSubmenu]) // && [activeItem action] === @selector(submenuAction:))
|
||||
if ([activeItem hasSubmenu])// && [activeItem action] === @selector(submenuAction:))
|
||||
{
|
||||
var activeItemRect = [activeMenuContainer rectForItemAtIndex:activeItemIndex],
|
||||
newMenuOrigin;
|
||||
var activeItemRect = [activeMenuContainer rectForItemAtIndex:activeItemIndex];
|
||||
|
||||
if ([activeMenuContainer isMenuBar])
|
||||
newMenuOrigin = CGPointMake(CGRectGetMinX(activeItemRect), CGRectGetMaxY(activeItemRect));
|
||||
var newMenuOrigin = CGPointMake(CGRectGetMinX(activeItemRect), CGRectGetMaxY(activeItemRect));
|
||||
else
|
||||
{
|
||||
// New theme attributes to have more precise submenus positioning
|
||||
|
||||
var defaultTheme = [CPTheme defaultTheme],
|
||||
themeDeltaX = [defaultTheme valueForAttributeWithName:@"menu-window-submenu-delta-x" forClass:_CPMenuView],
|
||||
themeDeltaY = [defaultTheme valueForAttributeWithName:@"menu-window-submenu-delta-y" forClass:_CPMenuView],
|
||||
themeFirstDeltaY = [defaultTheme valueForAttributeWithName:@"menu-window-submenu-first-level-delta-y" forClass:_CPMenuView],
|
||||
activeMenuIndex = [_menuContainerStack indexOfObject:activeMenuContainer],
|
||||
|
||||
deltaX = themeDeltaX ? themeDeltaX : 0,
|
||||
deltaY = themeDeltaY ? themeDeltaY : 0;
|
||||
|
||||
if (themeFirstDeltaY && (activeMenuIndex == 1) && [_menuContainerStack[0] isMenuBar])
|
||||
deltaY += themeFirstDeltaY;
|
||||
|
||||
newMenuOrigin = CGPointMake(CGRectGetMaxX(activeItemRect)+deltaX, CGRectGetMinY(activeItemRect)+deltaY);
|
||||
}
|
||||
var newMenuOrigin = CGPointMake(CGRectGetMaxX(activeItemRect), CGRectGetMinY(activeItemRect));
|
||||
|
||||
newMenuOrigin = [activeMenuContainer convertBaseToGlobal:newMenuOrigin];
|
||||
|
||||
// Only start a new timer if the previous was cancelled
|
||||
if (_showTimerID === undefined)
|
||||
{
|
||||
// Close the current menu item because we are going to select a new one after a short delay
|
||||
[self showMenu:nil fromMenu:activeMenu atPoint:CGPointMakeZero()];
|
||||
|
||||
if (![activeMenuContainer isMenuBar])
|
||||
{
|
||||
_showTimerID = setTimeout(function()
|
||||
{
|
||||
[self showMenu:[activeItem submenu] fromMenu:[activeItem menu] atPoint:newMenuOrigin];
|
||||
}, 250);
|
||||
}
|
||||
else
|
||||
[self showMenu:[activeItem submenu] fromMenu:[activeItem menu] atPoint:newMenuOrigin];
|
||||
}
|
||||
[self showMenu:[activeItem submenu] fromMenu:[activeItem menu] atPoint:newMenuOrigin];
|
||||
}
|
||||
|
||||
// This handles both the case where we've moved away from the menu, and where
|
||||
// This handles both the case where we've moved away from the menu, and where
|
||||
// we've moved to an item without a submenu.
|
||||
else
|
||||
[self showMenu:nil fromMenu:activeMenu atPoint:CGPointMakeZero()];
|
||||
|
||||
_previousActiveItem = activeItem;
|
||||
}
|
||||
|
||||
- (void)trackMenuBarButtonEvent:(CPEvent)anEvent
|
||||
@@ -407,15 +219,16 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
if (type === CPAppKitDefined)
|
||||
return [self completeTracking];
|
||||
|
||||
var globalLocation = [anEvent globalLocation],
|
||||
var globalLocation = [anEvent globalLocation];
|
||||
|
||||
// Find which menu window the mouse is currently on top of
|
||||
menu = [self trackingMenu],
|
||||
// Find which menu window the mouse is currently on top of
|
||||
var menu = [self trackingMenu],
|
||||
trackingMenuContainer = [self trackingMenuContainer],
|
||||
menuLocation = [trackingMenuContainer convertGlobalToBase:globalLocation];
|
||||
|
||||
if ([trackingMenuContainer itemIndexAtPoint:menuLocation] === _menuBarButtonItemIndex)
|
||||
[menu _highlightItemAtIndex:_menuBarButtonItemIndex];
|
||||
|
||||
else
|
||||
[menu _highlightItemAtIndex:CPNotFound];
|
||||
|
||||
@@ -425,15 +238,6 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
[menu cancelTracking];
|
||||
}
|
||||
|
||||
- (void)cancelActiveMenu
|
||||
{
|
||||
if (CPApp._activeMenu)
|
||||
{
|
||||
[self completeTracking];
|
||||
_menuContainerStack = [];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)completeTracking
|
||||
{
|
||||
var trackingMenu = [self trackingMenu];
|
||||
@@ -441,15 +245,23 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
// Stop all periodic events at this point.
|
||||
[CPEvent stopPeriodicEvents];
|
||||
|
||||
// Get the highlighted item from the original menu.
|
||||
var highlightedItem = [trackingMenu highlightedItem];
|
||||
|
||||
// Hide all submenus.
|
||||
[self showMenu:nil fromMenu:trackingMenu atPoint:nil];
|
||||
[trackingMenu _menuDidClose];
|
||||
|
||||
var delegate = [trackingMenu delegate];
|
||||
|
||||
if ([delegate respondsToSelector:@selector(menuDidClose:)])
|
||||
[delegate menuDidClose:trackingMenu];
|
||||
|
||||
if (_trackingCallback)
|
||||
_trackingCallback([self trackingMenuContainer], trackingMenu);
|
||||
|
||||
[[CPNotificationCenter defaultCenter] postNotificationName:CPMenuDidEndTrackingNotification
|
||||
object:trackingMenu];
|
||||
[[CPNotificationCenter defaultCenter]
|
||||
postNotificationName:CPMenuDidEndTrackingNotification
|
||||
object:trackingMenu];
|
||||
|
||||
CPApp._activeMenu = nil;
|
||||
}
|
||||
@@ -484,8 +296,8 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
{
|
||||
var menuContainer = _menuContainerStack[index],
|
||||
menuContainerFrame = [menuContainer globalFrame],
|
||||
menuContainerMinX = CGRectGetMinX(menuContainerFrame),
|
||||
menuContainerMaxX = CGRectGetMaxX(menuContainerFrame);
|
||||
menuContainerMinX = _CGRectGetMinX(menuContainerFrame),
|
||||
menuContainerMaxX = _CGRectGetMaxX(menuContainerFrame);
|
||||
|
||||
// If within the x bounds of this menu container, return it.
|
||||
if (x < menuContainerMaxX && x >= menuContainerMinX)
|
||||
@@ -512,8 +324,6 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
var count = _menuContainerStack.length,
|
||||
index = count;
|
||||
|
||||
[newMenu _menuWillOpen];
|
||||
|
||||
// Hide all menus up to the base menu...
|
||||
while (index--)
|
||||
{
|
||||
@@ -525,7 +335,7 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
break;
|
||||
|
||||
// If this menu is already being shown, unhighlight and return.
|
||||
if (menu === newMenu) //&& [menu supermenu] === baseMenu)
|
||||
if (menu === newMenu)//&& [menu supermenu] === baseMenu)
|
||||
return [newMenu _highlightItemAtIndex:CPNotFound];
|
||||
|
||||
[menuContainer orderOut:self];
|
||||
@@ -533,8 +343,6 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
|
||||
[_CPMenuWindow poolMenuWindow:menuContainer];
|
||||
[_menuContainerStack removeObjectAtIndex:index];
|
||||
|
||||
[menu _menuDidClose];
|
||||
}
|
||||
|
||||
if (!newMenu)
|
||||
@@ -553,239 +361,10 @@ var STICKY_TIME_INTERVAL = 0.4,
|
||||
if (baseMenu === [self trackingMenu] && [[self trackingMenuContainer] isMenuBar])
|
||||
[menuWindow setBackgroundStyle:_CPMenuWindowMenuBarBackgroundStyle];
|
||||
else
|
||||
[menuWindow setBackgroundStyle:_CPMenuWindowPopUpBackgroundStyle];
|
||||
|
||||
[menuWindow setBackgroundStyle:_CPMenuWindowPopUpBackgroundStyle];
|
||||
|
||||
[menuWindow setFrameOrigin:aGlobalLocation];
|
||||
[menuWindow orderFront:self];
|
||||
}
|
||||
|
||||
/// handle keyboard navigation
|
||||
- (void)interpretKeyEvent:(CPEvent)anEvent forMenu:(CPMenu)menu
|
||||
{
|
||||
var modifierFlags = [anEvent modifierFlags],
|
||||
character = [anEvent charactersIgnoringModifiers],
|
||||
selectorNames = [CPKeyBinding selectorsForKey:character modifierFlags:modifierFlags];
|
||||
|
||||
if (selectorNames)
|
||||
{
|
||||
var iter = [selectorNames objectEnumerator],
|
||||
obj;
|
||||
|
||||
while ((obj = [iter nextObject]) != nil)
|
||||
{
|
||||
var aSelector = CPSelectorFromString(obj);
|
||||
|
||||
if ([self respondsToSelector:aSelector])
|
||||
[self performSelector:aSelector withObject:menu];
|
||||
}
|
||||
}
|
||||
else if (!(modifierFlags & (CPCommandKeyMask | CPControlKeyMask)))
|
||||
{
|
||||
if (([anEvent timestamp] - _startTime) > STICKY_TIME_INTERVAL)
|
||||
_keyBuffer = nil;
|
||||
|
||||
if (!_keyBuffer)
|
||||
{
|
||||
_startTime = [anEvent timestamp];
|
||||
_keyBuffer = character;
|
||||
|
||||
[CPEvent stopPeriodicEvents];
|
||||
[CPEvent startPeriodicEventsAfterDelay:0.1 withPeriod:0.1];
|
||||
}
|
||||
else
|
||||
_keyBuffer += character;
|
||||
|
||||
[self selectNextItemBeginningWith:_keyBuffer inMenu:menu];
|
||||
_lastGlobalLocation = nil;
|
||||
}
|
||||
|
||||
[[[anEvent window] platformWindow] _propagateCurrentDOMEvent:NO];
|
||||
}
|
||||
|
||||
- (void)selectNextItemBeginningWith:(CPString)characters inMenu:(CPMenu)menu
|
||||
{
|
||||
var iter = [[menu itemArray] objectEnumerator],
|
||||
obj;
|
||||
|
||||
while ((obj = [iter nextObject]) != nil)
|
||||
{
|
||||
if ([obj isHidden] || ![obj isEnabled])
|
||||
continue;
|
||||
|
||||
if ([[[obj title] commonPrefixWithString:characters options:CPCaseInsensitiveSearch] length] == [characters length])
|
||||
{
|
||||
[menu _highlightItemAtIndex:iter._index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_startTime = [CPEvent currentTimestamp];
|
||||
}
|
||||
|
||||
- (void)scrollToBeginningOfDocument:(CPMenu)menu
|
||||
{
|
||||
[menu _highlightItemAtIndex:0];
|
||||
}
|
||||
|
||||
- (void)scrollToEndOfDocument:(CPMenu)menu
|
||||
{
|
||||
[menu _highlightItemAtIndex:[menu numberOfItems] - 1];
|
||||
}
|
||||
|
||||
- (void)scrollPageDown:(CPMenu)menu
|
||||
{
|
||||
var menuWindow = menu._menuWindow,
|
||||
menuClipView = menuWindow._menuClipView,
|
||||
bottom = [menuClipView bounds].size.height,
|
||||
first = [menuWindow itemIndexAtPoint:CGPointMake(1, 10)],
|
||||
last = [menuWindow itemIndexAtPoint:CGPointMake(1, bottom)],
|
||||
current = [menu indexOfItem:[menu highlightedItem]];
|
||||
|
||||
if (current == CPNotFound)
|
||||
{
|
||||
[menu _highlightItemAtIndex:0];
|
||||
return;
|
||||
}
|
||||
|
||||
var next = current + (last - first);
|
||||
|
||||
if (next < [menu numberOfItems])
|
||||
[menu _highlightItemAtIndex:next];
|
||||
else
|
||||
[menu _highlightItemAtIndex:[menu numberOfItems] - 1];
|
||||
|
||||
var item = [menu highlightedItem];
|
||||
|
||||
if ([item isSeparatorItem] || [item isHidden] || ![item isEnabled])
|
||||
[self moveDown:menu];
|
||||
}
|
||||
|
||||
- (void)scrollPageUp:(CPMenu)menu
|
||||
{
|
||||
var menuWindow = menu._menuWindow,
|
||||
menuClipView = menuWindow._menuClipView,
|
||||
bottom = [menuClipView bounds].size.height,
|
||||
first = [menuWindow itemIndexAtPoint:CGPointMake(1, 10)],
|
||||
last = [menuWindow itemIndexAtPoint:CGPointMake(1, bottom)],
|
||||
current = [menu indexOfItem:[menu highlightedItem]];
|
||||
|
||||
if (current == CPNotFound)
|
||||
{
|
||||
[menu _highlightItemAtIndex:0];
|
||||
return;
|
||||
}
|
||||
|
||||
var next = current - (last - first);
|
||||
|
||||
if (next < 0)
|
||||
[menu _highlightItemAtIndex:0];
|
||||
else
|
||||
[menu _highlightItemAtIndex:next];
|
||||
|
||||
var item = [menu highlightedItem];
|
||||
|
||||
if ([item isSeparatorItem] || [item isHidden] || ![item isEnabled])
|
||||
[self moveUp:menu];
|
||||
}
|
||||
|
||||
- (void)moveLeft:(CPMenu)menu
|
||||
{
|
||||
if ([menu supermenu])
|
||||
{
|
||||
if ([menu supermenu] == [CPApp mainMenu])
|
||||
{
|
||||
[self showMenu:nil fromMenu:[menu supermenu] atPoint:CGPointMakeZero()];
|
||||
[self moveUp:[CPApp mainMenu]];
|
||||
|
||||
var activeItem = [[CPApp mainMenu] highlightedItem],
|
||||
menuLocation = CGPointMake([[activeItem _menuItemView] frameOrigin].x , [[activeItem _menuItemView] frameSize].height);
|
||||
|
||||
[self showMenu:[activeItem submenu] fromMenu:[activeItem menu] atPoint:menuLocation];
|
||||
}
|
||||
else
|
||||
[self showMenu:nil fromMenu:[menu supermenu] atPoint:CGPointMakeZero()];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)moveRight:(CPMenu)menu
|
||||
{
|
||||
var activeItem = [menu highlightedItem];
|
||||
|
||||
if ([activeItem hasSubmenu])
|
||||
{
|
||||
if ([[activeItem submenu] numberOfItems])
|
||||
{
|
||||
var activeItemIndex = [menu indexOfItem:activeItem],
|
||||
activeMenuContainer = menu._menuWindow,
|
||||
activeItemRect = [activeMenuContainer rectForItemAtIndex:activeItemIndex],
|
||||
newMenuOrigin;
|
||||
|
||||
if ([activeMenuContainer isMenuBar])
|
||||
newMenuOrigin = CGPointMake(CGRectGetMinX(activeItemRect), CGRectGetMaxY(activeItemRect));
|
||||
else
|
||||
newMenuOrigin = CGPointMake(CGRectGetMaxX(activeItemRect), CGRectGetMinY(activeItemRect));
|
||||
|
||||
newMenuOrigin = [activeMenuContainer convertBaseToGlobal:newMenuOrigin];
|
||||
|
||||
[self showMenu:[activeItem submenu] fromMenu:[activeItem menu] atPoint:newMenuOrigin];
|
||||
[self moveDown:[activeItem submenu]];
|
||||
}
|
||||
}
|
||||
else if ([self trackingMenu] == [CPApp mainMenu])
|
||||
{
|
||||
[self showMenu:nil fromMenu:menu atPoint:CGPointMakeZero()];
|
||||
[self moveDown:[CPApp mainMenu]];
|
||||
|
||||
var activeItem = [[CPApp mainMenu] highlightedItem],
|
||||
menuLocation = CGPointMake([[activeItem _menuItemView] frameOrigin].x , [[activeItem _menuItemView] frameSize].height);
|
||||
|
||||
[self showMenu:[activeItem submenu] fromMenu:[activeItem menu] atPoint:menuLocation];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)moveDown:(CPMenu)menu
|
||||
{
|
||||
var index = menu._highlightedIndex + 1,
|
||||
item;
|
||||
|
||||
// Search for the next enabled item
|
||||
while ((index < [menu numberOfItems]) && (item = [menu itemAtIndex:index]) && ([item isSeparatorItem] || [item isHidden] || ![item isEnabled]))
|
||||
index++;
|
||||
|
||||
if (index < [menu numberOfItems])
|
||||
[menu _highlightItemAtIndex:index];
|
||||
else if (menu == [CPApp mainMenu])
|
||||
[menu _highlightItemAtIndex:0];
|
||||
}
|
||||
|
||||
- (void)moveUp:(CPMenu)menu
|
||||
{
|
||||
var index = menu._highlightedIndex - 1,
|
||||
item;
|
||||
|
||||
// Search for the previous enabled item
|
||||
while ((index >= 0) && (item = [menu itemAtIndex:index]) && ([item isSeparatorItem] || [item isHidden] || ![item isEnabled]))
|
||||
index--;
|
||||
|
||||
if (index >= 0)
|
||||
[menu _highlightItemAtIndex:index];
|
||||
else if (menu == [CPApp mainMenu])
|
||||
[menu _highlightItemAtIndex:[menu numberOfItems] - 1];
|
||||
}
|
||||
|
||||
- (void)insertNewline:(CPMenu)menu
|
||||
{
|
||||
if ([[menu highlightedItem] hasSubmenu])
|
||||
[self moveRight:menu];
|
||||
else
|
||||
[menu cancelTracking]
|
||||
}
|
||||
|
||||
- (void)cancelOperation:(CPMenu)menu
|
||||
{
|
||||
[menu _highlightItemAtIndex:CPNotFound];
|
||||
[CPEvent stopPeriodicEvents];
|
||||
[[self trackingMenu] cancelTracking];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+129
-201
@@ -1,42 +1,25 @@
|
||||
/*
|
||||
* _CPMenuWindow.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPClipView.j"
|
||||
@import "CPImageView.j"
|
||||
@import "CPWindow.j"
|
||||
@import "_CPMenuManager.j"
|
||||
#include "../CoreGraphics/CGGeometry.h"
|
||||
|
||||
@class _CPMenuView
|
||||
@class CPMenuItem
|
||||
|
||||
var _CPMenuWindowPool = [],
|
||||
_CPMenuWindowPoolCapacity = 5,
|
||||
|
||||
|
||||
_CPMenuWindowBackgroundColors = [];
|
||||
|
||||
|
||||
_CPMenuWindowMenuBarBackgroundStyle = 0;
|
||||
_CPMenuWindowPopUpBackgroundStyle = 1;
|
||||
_CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
|
||||
var STICKY_TIME_INTERVAL = 500,
|
||||
|
||||
TOP_MARGIN = 5.0,
|
||||
LEFT_MARGIN = 1.0,
|
||||
RIGHT_MARGIN = 1.0,
|
||||
BOTTOM_MARGIN = 5.0,
|
||||
|
||||
SCROLL_INDICATOR_HEIGHT = 16.0;
|
||||
|
||||
/*
|
||||
@ignore
|
||||
*/
|
||||
@@ -44,10 +27,10 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
{
|
||||
_CPMenuView _menuView;
|
||||
CPClipView _menuClipView;
|
||||
|
||||
|
||||
CPImageView _moreAboveView;
|
||||
CPImageView _moreBelowView;
|
||||
|
||||
|
||||
CGRect _unconstrainedFrame;
|
||||
CGRect _constraintRect;
|
||||
}
|
||||
@@ -75,59 +58,69 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
|
||||
+ (void)poolMenuWindow:(_CPMenuWindow)aMenuWindow
|
||||
{
|
||||
// FIXME :the poolMenuWindow is called too many times somewhere....
|
||||
if (!aMenuWindow || _CPMenuWindowPool.length >= _CPMenuWindowPoolCapacity || [_CPMenuWindowPool containsObject:aMenuWindow])
|
||||
if (!aMenuWindow || _CPMenuWindowPool.length >= _CPMenuWindowPoolCapacity)
|
||||
return;
|
||||
|
||||
_CPMenuWindowPool.push(aMenuWindow);
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self != [_CPMenuWindow class])
|
||||
return;
|
||||
|
||||
var bundle = [CPBundle bundleForClass:self];
|
||||
|
||||
_CPMenuWindowMoreAboveImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowMoreAbove.png"] size:CGSizeMake(38.0, 18.0)];
|
||||
_CPMenuWindowMoreBelowImage = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowMoreBelow.png"] size:CGSizeMake(38.0, 18.0)];
|
||||
}
|
||||
|
||||
- (id)initWithContentRect:(CGRect)aRect styleMask:(unsigned)aStyleMask
|
||||
{
|
||||
_constraintRect = CGRectMakeZero();
|
||||
_unconstrainedFrame = CGRectMakeZero();
|
||||
_constraintRect = _CGRectMakeZero();
|
||||
_unconstrainedFrame = _CGRectMakeZero();
|
||||
|
||||
self = [super initWithContentRect:aRect styleMask:CPBorderlessWindowMask];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_constrainsToUsableScreen = NO;
|
||||
|
||||
[self setLevel:CPPopUpMenuWindowLevel];
|
||||
[self setHasShadow:YES];
|
||||
[self setShadowStyle:CPMenuWindowShadowStyle];
|
||||
[self setAcceptsMouseMovedEvents:YES];
|
||||
|
||||
var contentView = [self contentView];
|
||||
|
||||
|
||||
_menuView = [[_CPMenuView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
_menuClipView = [[CPClipView alloc] initWithFrame:CGRectMake([_menuView valueForThemeAttribute:@"menu-window-margin-inset"].left, [_menuView valueForThemeAttribute:@"menu-window-margin-inset"].top, 0.0, 0.0)];
|
||||
|
||||
_menuClipView = [[CPClipView alloc] initWithFrame:CGRectMake(LEFT_MARGIN, TOP_MARGIN, 0.0, 0.0)];
|
||||
[_menuClipView setDocumentView:_menuView];
|
||||
|
||||
|
||||
[contentView addSubview:_menuClipView];
|
||||
|
||||
|
||||
_moreAboveView = [[CPImageView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[_moreAboveView setImage:[_menuView valueForThemeAttribute:@"menu-window-more-above-image"]];
|
||||
[_moreAboveView setFrameSize:[[_menuView valueForThemeAttribute:@"menu-window-more-above-image"] size]];
|
||||
|
||||
|
||||
[_moreAboveView setImage:_CPMenuWindowMoreAboveImage];
|
||||
[_moreAboveView setFrameSize:[_CPMenuWindowMoreAboveImage size]];
|
||||
|
||||
[contentView addSubview:_moreAboveView];
|
||||
|
||||
|
||||
_moreBelowView = [[CPImageView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[_moreBelowView setImage:[_menuView valueForThemeAttribute:@"menu-window-more-below-image"]];
|
||||
[_moreBelowView setFrameSize:[[_menuView valueForThemeAttribute:@"menu-window-more-below-image"] size]];
|
||||
|
||||
|
||||
[_moreBelowView setImage:_CPMenuWindowMoreBelowImage];
|
||||
[_moreBelowView setFrameSize:[_CPMenuWindowMoreBelowImage size]];
|
||||
|
||||
[contentView addSubview:_moreBelowView];
|
||||
}
|
||||
|
||||
[self setShadowStyle:CPWindowShadowStyleMenu];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (float)_standardLeftMargin
|
||||
{
|
||||
return [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-window-margin-inset" forClass:_CPMenuView].left;
|
||||
return LEFT_MARGIN;
|
||||
}
|
||||
|
||||
- (void)setFont:(CPFont)aFont
|
||||
@@ -143,17 +136,43 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
+ (CPColor)backgroundColorForBackgroundStyle:(_CPMenuWindowBackgroundStyle)aBackgroundStyle
|
||||
{
|
||||
var color = _CPMenuWindowBackgroundColors[aBackgroundStyle];
|
||||
|
||||
|
||||
if (!color)
|
||||
{
|
||||
var bundle = [CPBundle bundleForClass:[self class]];
|
||||
|
||||
if (aBackgroundStyle == _CPMenuWindowPopUpBackgroundStyle)
|
||||
color = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-window-pop-up-background-style-color" forClass:_CPMenuView];
|
||||
|
||||
color = [CPColor colorWithPatternImage:[[CPNinePartImage alloc] initWithImageSlices:
|
||||
[
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowRounded0.png"] size:CGSizeMake(4.0, 4.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow1.png"] size:CGSizeMake(1.0, 4.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowRounded2.png"] size:CGSizeMake(4.0, 4.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow3.png"] size:CGSizeMake(4.0, 1.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow4.png"] size:CGSizeMake(1.0, 1.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow5.png"] size:CGSizeMake(4.0, 1.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowRounded6.png"] size:CGSizeMake(4.0, 4.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow7.png"] size:CGSizeMake(1.0, 4.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowRounded8.png"] size:CGSizeMake(4.0, 4.0)]
|
||||
]]];
|
||||
|
||||
else if (aBackgroundStyle == _CPMenuWindowMenuBarBackgroundStyle)
|
||||
color = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-window-menu-bar-background-style-color" forClass:_CPMenuView];
|
||||
|
||||
color = [CPColor colorWithPatternImage:[[CPNinePartImage alloc] initWithImageSlices:
|
||||
[
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow3.png"] size:CGSizeMake(4.0, 0.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow4.png"] size:CGSizeMake(1.0, 0.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow5.png"] size:CGSizeMake(4.0, 0.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow3.png"] size:CGSizeMake(4.0, 1.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow4.png"] size:CGSizeMake(1.0, 1.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow5.png"] size:CGSizeMake(4.0, 1.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowRounded6.png"] size:CGSizeMake(4.0, 4.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindow7.png"] size:CGSizeMake(1.0, 4.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuWindow/_CPMenuWindowRounded8.png"] size:CGSizeMake(4.0, 4.0)]
|
||||
]]];
|
||||
|
||||
_CPMenuWindowBackgroundColors[aBackgroundStyle] = color;
|
||||
}
|
||||
|
||||
@@ -169,14 +188,13 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
{
|
||||
[aMenu _setMenuWindow:self];
|
||||
[_menuView setMenu:aMenu];
|
||||
|
||||
var menuViewSize = [_menuView frame].size,
|
||||
marginInset = [_menuView valueForThemeAttribute:@"menu-window-margin-inset"];
|
||||
|
||||
[self setFrameSize:CGSizeMake(marginInset.left + menuViewSize.width + marginInset.right, marginInset.top + menuViewSize.height + marginInset.bottom)];
|
||||
|
||||
|
||||
var menuViewSize = [_menuView frame].size;
|
||||
|
||||
[self setFrameSize:CGSizeMake(LEFT_MARGIN + menuViewSize.width + RIGHT_MARGIN, TOP_MARGIN + menuViewSize.height + BOTTOM_MARGIN)];
|
||||
|
||||
[_menuView scrollPoint:CGPointMake(0.0, 0.0)];
|
||||
[_menuClipView setFrame:CGRectMake(marginInset.left, marginInset.top, menuViewSize.width, menuViewSize.height)];
|
||||
[_menuClipView setFrame:CGRectMake(LEFT_MARGIN, TOP_MARGIN, menuViewSize.width, menuViewSize.height)];
|
||||
}
|
||||
|
||||
- (void)setMinWidth:(float)aWidth
|
||||
@@ -191,16 +209,10 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
return [_menuView menu];
|
||||
}
|
||||
|
||||
- (_CPMenuView)_menuView
|
||||
{
|
||||
return _menuView;
|
||||
}
|
||||
|
||||
- (void)orderFront:(id)aSender
|
||||
{
|
||||
[[self menu] update];
|
||||
[self setFrame:_unconstrainedFrame];
|
||||
|
||||
|
||||
[super orderFront:aSender];
|
||||
}
|
||||
|
||||
@@ -213,30 +225,28 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
|
||||
- (CGRect)unconstrainedFrame
|
||||
{
|
||||
return CGRectMakeCopy(_unconstrainedFrame);
|
||||
return _CGRectMakeCopy(_unconstrainedFrame);
|
||||
}
|
||||
|
||||
// We need this because if not this will call setFrame: with -frame instead of -unconstrainedFrame, turning
|
||||
// the constrained frame into the unconstrained frame.
|
||||
- (void)setFrameOrigin:(CGPoint)aPoint
|
||||
{
|
||||
[super setFrame:CGRectMake(aPoint.x, aPoint.y, CGRectGetWidth(_unconstrainedFrame), CGRectGetHeight(_unconstrainedFrame))];
|
||||
[super setFrame:_CGRectMake(aPoint.x, aPoint.y, _CGRectGetWidth(_unconstrainedFrame), _CGRectGetHeight(_unconstrainedFrame))];
|
||||
}
|
||||
|
||||
- (void)setFrameSize:(CGSize)aSize
|
||||
{
|
||||
[super setFrame:CGRectMake(CGRectGetMinX(_unconstrainedFrame), CGRectGetMinY(_unconstrainedFrame), aSize.width, aSize.height)];
|
||||
[super setFrame:_CGRectMake(_CGRectGetMinX(_unconstrainedFrame), _CGRectGetMinY(_unconstrainedFrame), aSize.width, aSize.height)];
|
||||
}
|
||||
|
||||
- (void)setFrame:(CGRect)aFrame display:(BOOL)shouldDisplay animate:(BOOL)shouldAnimate
|
||||
{
|
||||
// FIXME: There are integral window issues with platform windows.
|
||||
// FIXME: This gets called far too often.
|
||||
_unconstrainedFrame = CGRectMakeCopy(aFrame);
|
||||
_unconstrainedFrame = _CGRectMakeCopy(aFrame);
|
||||
|
||||
var constrainedFrame = CGRectIntersection(_unconstrainedFrame, _constraintRect),
|
||||
marginInset = [_menuView valueForThemeAttribute:@"menu-window-margin-inset"],
|
||||
scrollIndicatorHeight = [_menuView valueForThemeAttribute:@"menu-window-scroll-indicator-height"];
|
||||
var constrainedFrame = CGRectIntersection(_unconstrainedFrame, _constraintRect);
|
||||
|
||||
// We don't want to simply intersect the visible frame and the unconstrained frame.
|
||||
// We should be allowing as much of the width to fit as possible (pushing back and forward).
|
||||
@@ -255,42 +265,37 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
[super setFrame:constrainedFrame display:shouldDisplay animate:shouldAnimate];
|
||||
|
||||
// This needs to happen before changing the frame.
|
||||
var menuViewOrigin = CGPointMake(CGRectGetMinX(aFrame) + marginInset.left, CGRectGetMinY(aFrame) + marginInset.top),
|
||||
moreAbove = menuViewOrigin.y < CGRectGetMinY(constrainedFrame) + marginInset.top,
|
||||
moreBelow = menuViewOrigin.y + CGRectGetHeight([_menuView frame]) > CGRectGetMaxY(constrainedFrame) - marginInset.bottom,
|
||||
|
||||
topMargin = marginInset.top,
|
||||
bottomMargin = marginInset.bottom,
|
||||
var menuViewOrigin = CGPointMake(CGRectGetMinX(aFrame) + LEFT_MARGIN, CGRectGetMinY(aFrame) + TOP_MARGIN),
|
||||
moreAbove = menuViewOrigin.y < CGRectGetMinY(constrainedFrame) + TOP_MARGIN,
|
||||
moreBelow = menuViewOrigin.y + CGRectGetHeight([_menuView frame]) > CGRectGetMaxY(constrainedFrame) - BOTTOM_MARGIN,
|
||||
|
||||
topMargin = TOP_MARGIN,
|
||||
bottomMargin = BOTTOM_MARGIN,
|
||||
|
||||
contentView = [self contentView],
|
||||
bounds = [contentView bounds];
|
||||
|
||||
if (moreAbove)
|
||||
{
|
||||
topMargin += scrollIndicatorHeight;
|
||||
|
||||
topMargin += SCROLL_INDICATOR_HEIGHT;
|
||||
|
||||
var frame = [_moreAboveView frame];
|
||||
|
||||
[_moreAboveView setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(frame)) / 2.0, (marginInset.top + scrollIndicatorHeight - CGRectGetHeight(frame)) / 2.0)];
|
||||
|
||||
[_moreAboveView setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(frame)) / 2.0, (TOP_MARGIN + SCROLL_INDICATOR_HEIGHT - CGRectGetHeight(frame)) / 2.0)];
|
||||
}
|
||||
|
||||
[_moreAboveView setHidden:!moreAbove];
|
||||
|
||||
if (moreBelow)
|
||||
{
|
||||
bottomMargin += scrollIndicatorHeight;
|
||||
|
||||
[_moreBelowView setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth([_moreBelowView frame])) / 2.0, CGRectGetHeight(bounds) - scrollIndicatorHeight - marginInset.bottom)];
|
||||
bottomMargin += SCROLL_INDICATOR_HEIGHT;
|
||||
|
||||
[_moreBelowView setFrameOrigin:CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth([_moreBelowView frame])) / 2.0, CGRectGetHeight(bounds) - SCROLL_INDICATOR_HEIGHT - BOTTOM_MARGIN)];
|
||||
}
|
||||
|
||||
|
||||
[_moreBelowView setHidden:!moreBelow];
|
||||
|
||||
var clipFrame = CGRectMakeZero();
|
||||
|
||||
clipFrame.origin.x = marginInset.left;
|
||||
clipFrame.origin.y = topMargin;
|
||||
clipFrame.size.width = CGRectGetWidth(constrainedFrame) - marginInset.left - marginInset.right;
|
||||
clipFrame.size.height = CGRectGetHeight(constrainedFrame) - topMargin - bottomMargin;
|
||||
var clipFrame = CGRectMake(LEFT_MARGIN, topMargin, CGRectGetWidth(constrainedFrame) - LEFT_MARGIN - RIGHT_MARGIN, CGRectGetHeight(constrainedFrame) - topMargin - bottomMargin)
|
||||
|
||||
[_menuClipView setFrame:clipFrame];
|
||||
[_menuView setFrameSize:CGSizeMake(CGRectGetWidth(clipFrame), CGRectGetHeight([_menuView frame]))];
|
||||
@@ -343,29 +348,24 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
return [self canScrollUp] || [self canScrollDown];
|
||||
}
|
||||
|
||||
- (void)scrollByDelta:(float)theDelta
|
||||
{
|
||||
if (theDelta === 0.0)
|
||||
return;
|
||||
|
||||
if (theDelta > 0.0 && ![self canScrollDown])
|
||||
return;
|
||||
|
||||
if (theDelta < 0.0 && ![self canScrollUp])
|
||||
return;
|
||||
|
||||
_unconstrainedFrame.origin.y -= theDelta;
|
||||
[self setFrame:_unconstrainedFrame];
|
||||
}
|
||||
|
||||
- (void)scrollUp
|
||||
{
|
||||
[self scrollByDelta:-10.0];
|
||||
if (CGRectGetMinY(_unconstrainedFrame) >= CGRectGetMinY(_constraintRect))
|
||||
return;
|
||||
|
||||
_unconstrainedFrame.origin.y += 10;
|
||||
|
||||
[self setFrame:_unconstrainedFrame];
|
||||
}
|
||||
|
||||
- (void)scrollDown
|
||||
{
|
||||
[self scrollByDelta:10.0];
|
||||
if (CGRectGetMaxY(_unconstrainedFrame) <= CGRectGetHeight(_constraintRect))
|
||||
return;
|
||||
|
||||
_unconstrainedFrame.origin.y -= 10;
|
||||
|
||||
[self setFrame:_unconstrainedFrame];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -385,15 +385,16 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
- (_CPManagerScrollingState)scrollingStateForPoint:(CGPoint)aGlobalLocation
|
||||
{
|
||||
var frame = [self frame];
|
||||
if (!CGRectContainsPoint(frame,aGlobalLocation) || ![self canScroll])
|
||||
|
||||
if (![self canScroll])
|
||||
return _CPMenuManagerScrollingStateNone;
|
||||
|
||||
// If we're at or above of the top scroll indicator...
|
||||
if (aGlobalLocation.y < CGRectGetMinY(frame) + [_menuView valueForThemeAttribute:@"menu-window-margin-inset"].top + [_menuView valueForThemeAttribute:@"menu-window-scroll-indicator-height"] && ![_moreAboveView isHidden])
|
||||
if (aGlobalLocation.y < CGRectGetMinY(frame) + TOP_MARGIN + SCROLL_INDICATOR_HEIGHT)
|
||||
return _CPMenuManagerScrollingStateUp;
|
||||
|
||||
// If we're at or below the bottom scroll indicator...
|
||||
if (aGlobalLocation.y > CGRectGetMaxY(frame) - [_menuView valueForThemeAttribute:@"menu-window-margin-inset"].bottom - [_menuView valueForThemeAttribute:@"menu-window-scroll-indicator-height"] && ![_moreBelowView isHidden])
|
||||
if (aGlobalLocation.y > CGRectGetMaxY(frame) - BOTTOM_MARGIN - SCROLL_INDICATOR_HEIGHT)
|
||||
return _CPMenuManagerScrollingStateDown;
|
||||
|
||||
return _CPMenuManagerScrollingStateNone;
|
||||
@@ -401,7 +402,7 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
|
||||
- (float)deltaYForItemAtIndex:(int)anIndex
|
||||
{
|
||||
return [_menuView valueForThemeAttribute:@"menu-window-margin-inset"].top + CGRectGetMinY([_menuView rectForItemAtIndex:anIndex]);
|
||||
return TOP_MARGIN + CGRectGetMinY([_menuView rectForItemAtIndex:anIndex]);
|
||||
}
|
||||
|
||||
- (CGPoint)rectForItemAtIndex:(int)anIndex
|
||||
@@ -413,28 +414,13 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
{
|
||||
// Don't return indexes of items that aren't visible.
|
||||
if (!CGRectContainsPoint([_menuClipView bounds], [_menuClipView convertPoint:aPoint fromView:nil]))
|
||||
return CPNotFound;
|
||||
return NO;
|
||||
|
||||
return [_menuView itemIndexAtPoint:[_menuView convertPoint:aPoint fromView:nil]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMenuWindow (CSSTheming)
|
||||
|
||||
- (void)_setThemeIncludingDescendants:(CPTheme)aTheme
|
||||
{
|
||||
[[self contentView] _setThemeIncludingDescendants:aTheme];
|
||||
[_menuView _setThemeIncludingDescendants:aTheme];
|
||||
[_menuView tile];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
/*
|
||||
@ignore
|
||||
*/
|
||||
@@ -443,52 +429,10 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
{
|
||||
CPArray _menuItemViews;
|
||||
CPArray _visibleMenuItemInfos;
|
||||
|
||||
|
||||
CPFont _font @accessors(property=font);
|
||||
}
|
||||
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
{
|
||||
return "menu-view";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"menu-window-more-above-image": [CPNull null],
|
||||
@"menu-window-more-below-image": [CPNull null],
|
||||
@"menu-window-pop-up-background-style-color": [CPNull null],
|
||||
@"menu-window-menu-bar-background-style-color": [CPNull null],
|
||||
@"menu-window-margin-inset": CGInsetMake(5.0, 1.0, 1.0, 5.0),
|
||||
@"menu-window-scroll-indicator-height": 16.0,
|
||||
@"menu-bar-window-background-color": [CPNull null],
|
||||
@"menu-bar-window-background-selected-color": [CPNull null],
|
||||
@"menu-bar-window-font": [CPNull null],
|
||||
@"menu-bar-window-first-item-font": [CPNull null],
|
||||
@"menu-bar-window-height": 30.0,
|
||||
@"menu-bar-window-margin": 10.0,
|
||||
@"menu-bar-window-left-margin": 10.0,
|
||||
@"menu-bar-window-right-margin": 10.0,
|
||||
@"menu-bar-text-color": [CPNull null],
|
||||
@"menu-bar-title-color": [CPNull null],
|
||||
@"menu-bar-text-shadow-color": [CPNull null],
|
||||
@"menu-bar-title-shadow-color": [CPNull null],
|
||||
@"menu-bar-highlight-color": [CPNull null],
|
||||
@"menu-bar-highlight-text-color": [CPNull null],
|
||||
@"menu-bar-highlight-text-shadow-color": [CPNull null],
|
||||
@"menu-bar-height": 28.0,
|
||||
@"menu-bar-icon-image": [CPNull null],
|
||||
@"menu-bar-icon-image-alpha-value": 1.0,
|
||||
@"menu-general-icon-new": [CPNull null],
|
||||
@"menu-general-icon-save": [CPNull null],
|
||||
@"menu-general-icon-open": [CPNull null],
|
||||
@"menu-window-submenu-delta-x": 0.0,
|
||||
@"menu-window-submenu-delta-y": 0.0,
|
||||
@"menu-window-submenu-first-level-delta-y": 0.0
|
||||
};
|
||||
}
|
||||
|
||||
- (unsigned)numberOfUnhiddenItems
|
||||
{
|
||||
return _visibleMenuItemInfos.length;
|
||||
@@ -519,7 +463,7 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
while (low <= high)
|
||||
{
|
||||
var middle = FLOOR(low + (high - low) / 2),
|
||||
info = _visibleMenuItemInfos[middle],
|
||||
info = _visibleMenuItemInfos[middle]
|
||||
frame = [info.view frame];
|
||||
|
||||
if (y < CGRectGetMinY(frame))
|
||||
@@ -537,7 +481,7 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
|
||||
- (void)tile
|
||||
{
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
|
||||
|
||||
_menuItemViews = [];
|
||||
_visibleMenuItemInfos = [];
|
||||
@@ -557,22 +501,21 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var item = items[index],
|
||||
view = [item _menuItemView];
|
||||
|
||||
view = [item _menuItemView];
|
||||
|
||||
_menuItemViews.push(view);
|
||||
|
||||
|
||||
if ([item isHidden])
|
||||
continue;
|
||||
|
||||
_visibleMenuItemInfos.push({ view:view, index:index });
|
||||
|
||||
|
||||
[view setFont:_font];
|
||||
[view setShowsStateColumn:showsStateColumn];
|
||||
[view synchronizeWithMenuItem];
|
||||
|
||||
[view setFrameOrigin:CGPointMake(0.0, y)];
|
||||
|
||||
[view _setThemeIncludingDescendants:[CPTheme defaultTheme]];
|
||||
[self addSubview:view];
|
||||
|
||||
var size = [view minSize],
|
||||
@@ -603,18 +546,3 @@ _CPMenuWindowAttachedMenuBackgroundStyle = 2;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMenuView (CSSTheming)
|
||||
|
||||
- (void)_setThemeIncludingDescendants:(CPTheme)aTheme
|
||||
{
|
||||
[self setTheme:aTheme];
|
||||
[_menuItemViews makeObjectsPerformSelector:@selector(_setThemeIncludingDescendants:) withObject:aTheme];
|
||||
|
||||
for (var i = 0, items = [[self menu] itemArray], count = [items count]; i < count; i++)
|
||||
[[items[i] _menuItemView] _setThemeIncludingDescendants:aTheme];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+76
-186
@@ -25,35 +25,11 @@
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
@import "CPImage.j"
|
||||
@import "CPText.j"
|
||||
@import "CPMenu.j"
|
||||
@import "CPView.j"
|
||||
@import "_CPMenuItemView.j"
|
||||
|
||||
@class CPMenu
|
||||
|
||||
@global CPApp
|
||||
|
||||
var CPMenuItemStringRepresentationDictionary = @{
|
||||
CPEscapeFunctionKey: "\u238B",
|
||||
CPTabCharacter: "\u21E5",
|
||||
CPBackTabCharacter: "\u21E4",
|
||||
CPSpaceFunctionKey: "\u2423",
|
||||
CPCarriageReturnCharacter: "\u23CE",
|
||||
CPBackspaceCharacter: "\u232B",
|
||||
CPDeleteFunctionKey: "\u232B",
|
||||
CPDeleteCharacter: "\u2326",
|
||||
CPHomeFunctionKey: "\u21F1",
|
||||
CPEndFunctionKey: "\u21F2",
|
||||
CPPageUpFunctionKey: "\u21DE",
|
||||
CPPageDownFunctionKey: "\u21DF",
|
||||
CPUpArrowFunctionKey: "\u2191",
|
||||
CPDownArrowFunctionKey: "\u2193",
|
||||
CPLeftArrowFunctionKey: "\u2190",
|
||||
CPRightArrowFunctionKey: "\u2192",
|
||||
CPClearDisplayFunctionKey: "\u2327",
|
||||
};
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPMenuItem
|
||||
|
||||
@@ -67,54 +43,42 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
|
||||
CPString _title;
|
||||
//CPAttributedString _attributedTitle;
|
||||
|
||||
|
||||
CPFont _font;
|
||||
|
||||
|
||||
id _target;
|
||||
SEL _action;
|
||||
|
||||
|
||||
BOOL _isEnabled;
|
||||
BOOL _isHidden;
|
||||
|
||||
|
||||
int _tag;
|
||||
int _state;
|
||||
|
||||
|
||||
CPImage _image;
|
||||
CPImage _alternateImage;
|
||||
CPImage _onStateImage;
|
||||
CPImage _offStateImage;
|
||||
CPImage _mixedStateImage;
|
||||
|
||||
|
||||
CPMenu _submenu;
|
||||
CPMenu _menu;
|
||||
|
||||
|
||||
CPString _keyEquivalent;
|
||||
unsigned _keyEquivalentModifierMask;
|
||||
|
||||
|
||||
int _mnemonicLocation;
|
||||
|
||||
|
||||
BOOL _isAlternate;
|
||||
int _indentationLevel;
|
||||
|
||||
|
||||
CPString _toolTip;
|
||||
id _representedObject;
|
||||
CPView _view;
|
||||
|
||||
int _changeCount;
|
||||
|
||||
|
||||
_CPMenuItemView _menuItemView;
|
||||
}
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if ([aBinding hasPrefix:CPEnabledBinding])
|
||||
return [CPMultipleValueAndBinding class];
|
||||
else if (aBinding === CPTargetBinding || [aBinding hasPrefix:CPArgumentBinding])
|
||||
return [CPActionBinding class];
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
return [self initWithTitle:@"" action:nil keyEquivalent:nil];
|
||||
@@ -130,21 +94,19 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
- (id)initWithTitle:(CPString)aTitle action:(SEL)anAction keyEquivalent:(CPString)aKeyEquivalent
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_changeCount = 0;
|
||||
_isSeparator = NO;
|
||||
|
||||
_title = aTitle;
|
||||
_action = anAction;
|
||||
|
||||
|
||||
_isEnabled = YES;
|
||||
_isHidden = NO;
|
||||
|
||||
|
||||
_tag = 0;
|
||||
_state = CPOffState;
|
||||
|
||||
|
||||
_keyEquivalent = aKeyEquivalent || @"";
|
||||
_keyEquivalentModifierMask = CPPlatformActionKeyMask;
|
||||
|
||||
@@ -152,7 +114,7 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
|
||||
_mnemonicLocation = CPNotFound;
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -163,15 +125,13 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
*/
|
||||
- (void)setEnabled:(BOOL)isEnabled
|
||||
{
|
||||
if (_isEnabled === isEnabled)
|
||||
if ([_menu autoenablesItems])
|
||||
return;
|
||||
|
||||
if (!isEnabled && [self isHighlighted])
|
||||
[_menu _highlightItemAtIndex:CPNotFound];
|
||||
|
||||
_isEnabled = !!isEnabled;
|
||||
_isEnabled = isEnabled;
|
||||
|
||||
[_menuItemView setDirty];
|
||||
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
|
||||
@@ -192,7 +152,7 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
{
|
||||
if (_isHidden == isHidden)
|
||||
return;
|
||||
|
||||
|
||||
_isHidden = isHidden;
|
||||
|
||||
[_menu itemChanged:self];
|
||||
@@ -213,9 +173,9 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
{
|
||||
if (_isHidden)
|
||||
return YES;
|
||||
|
||||
|
||||
var supermenu = [_menu supermenu];
|
||||
|
||||
|
||||
if ([[supermenu itemAtIndex:[supermenu indexOfItemWithSubmenu:_menu]] isHiddenOrHasHiddenAncestor])
|
||||
return YES;
|
||||
|
||||
@@ -268,11 +228,11 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
|
||||
if (_title == aTitle)
|
||||
return;
|
||||
|
||||
|
||||
_title = aTitle;
|
||||
|
||||
|
||||
[_menuItemView setDirty];
|
||||
|
||||
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
|
||||
@@ -298,13 +258,13 @@ var CPMenuItemStringRepresentationDictionary = @{
|
||||
*/
|
||||
- (void)setFont:(CPFont)aFont
|
||||
{
|
||||
if ([_font isEqual:aFont])
|
||||
if (_font == aFont)
|
||||
return;
|
||||
|
||||
|
||||
_font = aFont;
|
||||
|
||||
[_menu itemChanged:self];
|
||||
|
||||
|
||||
[_menuItemView setDirty];
|
||||
}
|
||||
|
||||
@@ -356,9 +316,9 @@ CPOffState
|
||||
{
|
||||
if (_state == aState)
|
||||
return;
|
||||
|
||||
|
||||
_state = aState;
|
||||
|
||||
|
||||
[_menu itemChanged:self];
|
||||
|
||||
[_menuItemView setDirty];
|
||||
@@ -386,11 +346,11 @@ CPOffState
|
||||
{
|
||||
if (_image == anImage)
|
||||
return;
|
||||
|
||||
|
||||
_image = anImage;
|
||||
|
||||
[_menuItemView setDirty];
|
||||
|
||||
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
|
||||
@@ -428,7 +388,7 @@ CPOffState
|
||||
{
|
||||
if (_onStateImage == anImage)
|
||||
return;
|
||||
|
||||
|
||||
_onStateImage = anImage;
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
@@ -449,7 +409,7 @@ CPOffState
|
||||
{
|
||||
if (_offStateImage == anImage)
|
||||
return;
|
||||
|
||||
|
||||
_offStateImage = anImage;
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
@@ -470,7 +430,7 @@ CPOffState
|
||||
{
|
||||
if (_mixedStateImage == anImage)
|
||||
return;
|
||||
|
||||
|
||||
_mixedStateImage = anImage;
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
@@ -484,7 +444,7 @@ CPOffState
|
||||
return _mixedStateImage;
|
||||
}
|
||||
|
||||
// Managing Submenus
|
||||
// Managing Subemenus
|
||||
/*!
|
||||
Sets the submenu for this item
|
||||
@param aMenu the submenu
|
||||
@@ -498,14 +458,13 @@ 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;
|
||||
|
||||
if (_submenu)
|
||||
{
|
||||
[_submenu setSupermenu:_menu];
|
||||
[_submenu setTitle:[self title]];
|
||||
|
||||
[self setTarget:_menu];
|
||||
[self setAction:@selector(submenuAction:)];
|
||||
@@ -632,25 +591,21 @@ CPControlKeyMask
|
||||
return @"";
|
||||
|
||||
var string = _keyEquivalent.toUpperCase(),
|
||||
needsShift = _keyEquivalentModifierMask & CPShiftKeyMask ||
|
||||
(string === _keyEquivalent && _keyEquivalent.toLowerCase() !== _keyEquivalent.toUpperCase());
|
||||
|
||||
if ([CPMenuItemStringRepresentationDictionary objectForKey:string])
|
||||
string = [CPMenuItemStringRepresentationDictionary objectForKey:string];
|
||||
needsShift = _keyEquivalentModifierMask & CPShiftKeyMask || string === _keyEquivalent;
|
||||
|
||||
if (CPBrowserIsOperatingSystem(CPMacOperatingSystem))
|
||||
{
|
||||
if (_keyEquivalentModifierMask & CPCommandKeyMask)
|
||||
string = "\u2318" + string;
|
||||
string = "⌘" + string;
|
||||
|
||||
if (needsShift)
|
||||
string = "\u21E7" + string;
|
||||
string = "⇧" + string;
|
||||
|
||||
if (_keyEquivalentModifierMask & CPAlternateKeyMask)
|
||||
string = "\u2325" + string;
|
||||
string = "⌥" + string;
|
||||
|
||||
if (_keyEquivalentModifierMask & CPControlKeyMask)
|
||||
string = "\u2303" + string;
|
||||
string = "^" + string;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -687,20 +642,20 @@ CPControlKeyMask
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the title of the menu item and the mnemonic character. The mnemonic character should be preceded by an '&'.
|
||||
Sets the title of the menu item and the mnemonic character. The mnemonic chracter should be preceded by an '&'.
|
||||
@param aTitle the title string with a denoted mnemonic
|
||||
*/
|
||||
- (void)setTitleWithMnemonicLocation:(CPString)aTitle
|
||||
{
|
||||
var location = [aTitle rangeOfString:@"&"].location;
|
||||
|
||||
|
||||
if (location == CPNotFound)
|
||||
[self setTitle:aTitle];
|
||||
else
|
||||
{
|
||||
[self setTitle:[aTitle substringToIndex:location] + [aTitle substringFromIndex:location + 1]];
|
||||
[self setMnemonicLocation:location];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -741,7 +696,7 @@ CPControlKeyMask
|
||||
{
|
||||
if (aLevel < 0)
|
||||
[CPException raise:CPInvalidArgumentException reason:"setIndentationLevel: argument must be greater than or equal to 0."];
|
||||
|
||||
|
||||
_indentationLevel = MIN(15, aLevel);
|
||||
}
|
||||
|
||||
@@ -800,11 +755,11 @@ CPControlKeyMask
|
||||
{
|
||||
if (_view === aView)
|
||||
return;
|
||||
|
||||
|
||||
_view = aView;
|
||||
|
||||
|
||||
[_menuItemView setDirty];
|
||||
|
||||
|
||||
[_menu itemChanged:self];
|
||||
}
|
||||
|
||||
@@ -826,48 +781,7 @@ CPControlKeyMask
|
||||
return [[self menu] highlightedItem] == self;
|
||||
}
|
||||
|
||||
#pragma mark CPObject Overrides
|
||||
|
||||
/*!
|
||||
Returns a copy of the item. The copy does not belong If the item has a submenu, it is NOT copied.
|
||||
*/
|
||||
- (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 setTarget:_target];
|
||||
[item setAction:_action];
|
||||
[item setEnabled:_isEnabled];
|
||||
[item setHidden:_isHidden];
|
||||
[item setTag:_tag];
|
||||
[item setState:_state];
|
||||
[item setImage:_image];
|
||||
[item setAlternateImage:_alternateImage];
|
||||
[item setOnStateImage:_onStateImage];
|
||||
[item setOffStateImage:_offStateImage];
|
||||
[item setMixedStateImage:_mixedStateImage];
|
||||
[item setKeyEquivalent:_keyEquivalent];
|
||||
[item setKeyEquivalentModifierMask:_keyEquivalentModifierMask];
|
||||
[item setMnemonicLocation:_mnemonicLocation];
|
||||
[item setAlternate:_isAlternate];
|
||||
[item setIndentationLevel:_indentationLevel];
|
||||
[item setToolTip:_toolTip];
|
||||
[item setRepresentedObject:_representedObject];
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
- (id)mutableCopy
|
||||
{
|
||||
return [self copy];
|
||||
}
|
||||
|
||||
#pragma mark Internal
|
||||
//
|
||||
|
||||
/*
|
||||
@ignore
|
||||
@@ -876,7 +790,7 @@ CPControlKeyMask
|
||||
{
|
||||
if (!_menuItemView)
|
||||
_menuItemView = [[_CPMenuItemView alloc] initWithFrame:CGRectMakeZero() forMenuItem:self];
|
||||
|
||||
|
||||
return _menuItemView;
|
||||
}
|
||||
|
||||
@@ -890,27 +804,8 @@ CPControlKeyMask
|
||||
return ![self submenu] && [self menu] === [CPApp mainMenu];
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return [super description] + @" target: " + [self target] + @" action: " + CPStringFromSelector([self action]);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation CPMenuItem (CSSTheming)
|
||||
|
||||
- (void)_setThemeIncludingDescendants:(CPTheme)aTheme
|
||||
{
|
||||
[_view _setThemeIncludingDescendants:aTheme];
|
||||
[_menuItemView _setThemeIncludingDescendants:aTheme];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
|
||||
|
||||
CPMenuItemTitleKey = @"CPMenuItemTitleKey",
|
||||
@@ -925,9 +820,6 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
|
||||
|
||||
CPMenuItemImageKey = @"CPMenuItemImageKey",
|
||||
CPMenuItemAlternateImageKey = @"CPMenuItemAlternateImageKey",
|
||||
CPMenuItemOnStateImageKey = @"CPMenuItemOnStateImageKey",
|
||||
CPMenuItemOffStateImageKey = @"CPMenuItemOffStateImageKey",
|
||||
CPMenuItemMixedStateImageKey = @"CPMenuItemMixedStateImageKey",
|
||||
|
||||
CPMenuItemSubmenuKey = @"CPMenuItemSubmenuKey",
|
||||
CPMenuItemMenuKey = @"CPMenuItemMenuKey",
|
||||
@@ -952,49 +844,50 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
_changeCount = 0;
|
||||
_isSeparator = [aCoder containsValueForKey:CPMenuItemIsSeparatorKey] && [aCoder decodeBoolForKey:CPMenuItemIsSeparatorKey];
|
||||
|
||||
_title = [aCoder decodeObjectForKey:CPMenuItemTitleKey];
|
||||
|
||||
|
||||
// _font;
|
||||
|
||||
|
||||
_target = [aCoder decodeObjectForKey:CPMenuItemTargetKey];
|
||||
_action = [aCoder decodeObjectForKey:CPMenuItemActionKey];
|
||||
|
||||
_isEnabled = DEFAULT_VALUE(CPMenuItemIsEnabledKey, YES);
|
||||
_isHidden = [aCoder decodeBoolForKey:CPMenuItemIsHiddenKey];
|
||||
_tag = [aCoder decodeIntForKey:CPMenuItemTagKey];
|
||||
_state = [aCoder decodeIntForKey:CPMenuItemStateKey];
|
||||
_isHidden = DEFAULT_VALUE(CPMenuItemIsHiddenKey, NO);
|
||||
_tag = DEFAULT_VALUE(CPMenuItemTagKey, 0);
|
||||
_state = DEFAULT_VALUE(CPMenuItemStateKey, CPOffState);
|
||||
// int _state;
|
||||
|
||||
_image = [aCoder decodeObjectForKey:CPMenuItemImageKey];
|
||||
_alternateImage = [aCoder decodeObjectForKey:CPMenuItemAlternateImageKey];
|
||||
_onStateImage = [aCoder decodeObjectForKey:CPMenuItemOnStateImageKey];
|
||||
_offStateImage = [aCoder decodeObjectForKey:CPMenuItemOffStateImageKey];
|
||||
_mixedStateImage = [aCoder decodeObjectForKey:CPMenuItemMixedStateImageKey];
|
||||
_image = DEFAULT_VALUE(CPMenuItemImageKey, nil);
|
||||
_alternateImage = DEFAULT_VALUE(CPMenuItemAlternateImageKey, nil);
|
||||
// CPImage _onStateImage;
|
||||
// CPImage _offStateImage;
|
||||
// CPImage _mixedStateImage;
|
||||
|
||||
// This order matters because setSubmenu: needs _menu to be around.
|
||||
_menu = [aCoder decodeObjectForKey:CPMenuItemMenuKey];
|
||||
[self setSubmenu:[aCoder decodeObjectForKey:CPMenuItemSubmenuKey]];
|
||||
_menu = DEFAULT_VALUE(CPMenuItemMenuKey, nil);
|
||||
[self setSubmenu:DEFAULT_VALUE(CPMenuItemSubmenuKey, nil)];
|
||||
|
||||
_keyEquivalent = [aCoder decodeObjectForKey:CPMenuItemKeyEquivalentKey] || @"";
|
||||
_keyEquivalentModifierMask = [aCoder decodeIntForKey:CPMenuItemKeyEquivalentModifierMaskKey];
|
||||
_keyEquivalentModifierMask = [aCoder decodeObjectForKey:CPMenuItemKeyEquivalentModifierMaskKey] || 0;
|
||||
|
||||
// int _mnemonicLocation;
|
||||
|
||||
// BOOL _isAlternate;
|
||||
|
||||
[self setIndentationLevel:[aCoder decodeIntForKey:CPMenuItemIndentationLevelKey]];
|
||||
// Default is 0.
|
||||
[self setIndentationLevel:[aCoder decodeIntForKey:CPMenuItemIndentationLevelKey] || 0];
|
||||
|
||||
// CPString _toolTip;
|
||||
|
||||
_representedObject = [aCoder decodeObjectForKey:CPMenuItemRepresentedObjectKey];
|
||||
_view = [aCoder decodeObjectForKey:CPMenuItemViewKey];
|
||||
_representedObject = DEFAULT_VALUE(CPMenuItemRepresentedObjectKey, nil);
|
||||
_view = DEFAULT_VALUE(CPMenuItemViewKey, nil);
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -1008,11 +901,11 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
|
||||
[aCoder encodeBool:_isSeparator forKey:CPMenuItemIsSeparatorKey];
|
||||
|
||||
[aCoder encodeObject:_title forKey:CPMenuItemTitleKey];
|
||||
|
||||
|
||||
[aCoder encodeObject:_target forKey:CPMenuItemTargetKey];
|
||||
[aCoder encodeObject:_action forKey:CPMenuItemActionKey];
|
||||
|
||||
ENCODE_IFNOT(CPMenuItemIsEnabledKey, _isEnabled, YES);
|
||||
ENCODE_IFNOT(CPMenuItemIsEnabledKey, _isEnabled, YES);
|
||||
ENCODE_IFNOT(CPMenuItemIsHiddenKey, _isHidden, NO);
|
||||
|
||||
ENCODE_IFNOT(CPMenuItemTagKey, _tag, 0);
|
||||
@@ -1020,10 +913,7 @@ var CPMenuItemIsSeparatorKey = @"CPMenuItemIsSeparatorKey",
|
||||
|
||||
ENCODE_IFNOT(CPMenuItemImageKey, _image, nil);
|
||||
ENCODE_IFNOT(CPMenuItemAlternateImageKey, _alternateImage, nil);
|
||||
ENCODE_IFNOT(CPMenuItemOnStateImageKey, _onStateImage, nil);
|
||||
ENCODE_IFNOT(CPMenuItemOffStateImageKey, _offStateImage, nil);
|
||||
ENCODE_IFNOT(CPMenuItemMixedStateImageKey, _mixedStateImage, nil);
|
||||
|
||||
|
||||
ENCODE_IFNOT(CPMenuItemSubmenuKey, _submenu, nil);
|
||||
ENCODE_IFNOT(CPMenuItemMenuKey, _menu, nil);
|
||||
|
||||
|
||||
@@ -1,62 +1,51 @@
|
||||
/*
|
||||
* _CPMenuItemMenuBarView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
var HORIZONTAL_MARGIN = 8.0,
|
||||
SUBMENU_INDICATOR_MARGIN = 3.0,
|
||||
VERTICAL_MARGIN = 4.0;
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "_CPImageAndTextView.j"
|
||||
|
||||
@class _CPMenuBarWindow
|
||||
@class _CPMenuView
|
||||
@class CPMenuItem
|
||||
var SelectionColor = nil,
|
||||
SUBMENU_INDICATOR_COLOR = nil,
|
||||
_CPMenuItemSelectionColor = nil,
|
||||
_CPMenuItemTextShadowColor = nil,
|
||||
|
||||
_CPMenuItemDefaultStateImages = [],
|
||||
_CPMenuItemDefaultStateHighlightedImages = [];
|
||||
|
||||
@implementation _CPMenuItemMenuBarView : CPView
|
||||
{
|
||||
CPColor _highlightColor @accessors(property=highlightColor);
|
||||
CPColor _textColor @accessors(property=textColor);
|
||||
CPColor _textShadowColor @accessors(property=textShadowColor);
|
||||
CPColor _highlightTextColor @accessors(property=highlightTextColor);
|
||||
CPColor _highlightTextShadowColor @accessors(property=highlightTextShadowColor);
|
||||
|
||||
CPMenuItem _menuItem @accessors(property=menuItem);
|
||||
|
||||
CPFont _font;
|
||||
CPColor _textColor;
|
||||
CPColor _textShadowColor;
|
||||
|
||||
BOOL _isDirty;
|
||||
BOOL _shouldHighlight;
|
||||
|
||||
_CPImageAndTextView _imageAndTextView;
|
||||
CPView _submenuIndicatorView;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (void)initialize
|
||||
{
|
||||
return "menu-item-bar-view";
|
||||
}
|
||||
if (self !== [_CPMenuItemMenuBarView class])
|
||||
return;
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"horizontal-margin": 9.0,
|
||||
@"submenu-indicator-margin": 3.0,
|
||||
@"vertical-margin": 4.0,
|
||||
};
|
||||
var bundle = [CPBundle bundleForClass:self];
|
||||
|
||||
SelectionColor = [CPColor colorWithPatternImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"_CPMenuBarWindow/_CPMenuBarWindowBackgroundSelected.png"] size:CGSizeMake(1.0, 28.0)]];
|
||||
|
||||
SUBMENU_INDICATOR_COLOR = [CPColor grayColor];
|
||||
|
||||
_CPMenuItemSelectionColor = [CPColor colorWithCalibratedRed:95.0 / 255.0 green:131.0 / 255.0 blue:185.0 / 255.0 alpha:1.0];
|
||||
_CPMenuItemTextShadowColor = [CPColor colorWithCalibratedRed:26.0 / 255.0 green: 73.0 / 255.0 blue:109.0 / 255.0 alpha:1.0];
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPOffState] = nil;
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPOffState] = nil;
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPOnState] = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPMenuItem/CPMenuItemOnState.png"] size:CGSizeMake(14.0, 14.0)];
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPOnState] = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPMenuItem/CPMenuItemOnStateHighlighted.png"] size:CGSizeMake(14.0, 14.0)];
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPMixedState] = nil;
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPMixedState] = nil;
|
||||
}
|
||||
|
||||
+ (id)view
|
||||
@@ -70,107 +59,96 @@
|
||||
|
||||
if (self)
|
||||
{
|
||||
_imageAndTextView = [[_CPImageAndTextView alloc] initWithFrame:CGRectMake([self valueForThemeAttribute:@"horizontal-margin"], 0.0, 0.0, 0.0)];
|
||||
_imageAndTextView = [[_CPImageAndTextView alloc] initWithFrame:CGRectMake(HORIZONTAL_MARGIN, 0.0, 0.0, 0.0)];
|
||||
|
||||
[_imageAndTextView setImagePosition:CPImageLeft];
|
||||
[_imageAndTextView setImageOffset:3.0];
|
||||
[_imageAndTextView setTextShadowOffset:CGSizeMake(0.0, 1.0)];
|
||||
[_imageAndTextView setAutoresizingMask:CPViewMinYMargin | CPViewMaxYMargin];
|
||||
|
||||
[self addSubview:_imageAndTextView];
|
||||
|
||||
_submenuIndicatorView = [[_CPMenuItemMenuBarSubmenuIndicatorView alloc] initWithFrame:CGRectMake(0.0, 0.0, 9.0, 6.0)];
|
||||
|
||||
[_submenuIndicatorView setAutoresizingMask:CPViewMinYMargin | CPViewMaxYMargin];
|
||||
|
||||
[self addSubview:_submenuIndicatorView];
|
||||
|
||||
[self setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)setTextColor:(CPColor)aColor
|
||||
{
|
||||
_textColor = aColor;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setTextShadowColor:(CPColor)aColor
|
||||
{
|
||||
_textShadowColor = aColor;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setHighlightTextColor:(CPColor)aColor
|
||||
{
|
||||
_highlightTextColor = aColor;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)setHighlightTextShadowColor:(CPColor)aColor
|
||||
{
|
||||
_highlightTextShadowColor = aColor;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (CPColor)textColor
|
||||
{
|
||||
if (![_menuItem isEnabled])
|
||||
return [CPColor lightGrayColor];
|
||||
|
||||
return _textColor || [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-text-color" forClass:_CPMenuView];
|
||||
return _textColor || [CPColor colorWithCalibratedRed:70.0 / 255.0 green:69.0 / 255.0 blue:69.0 / 255.0 alpha:1.0];
|
||||
}
|
||||
|
||||
- (CPColor)textShadowColor
|
||||
{
|
||||
if (![_menuItem isEnabled])
|
||||
return [CPColor clearColor];
|
||||
return [CPColor colorWithWhite:0.8 alpha:0.8];
|
||||
|
||||
return _textShadowColor || [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-text-shadow-color" forClass:_CPMenuView];
|
||||
}
|
||||
|
||||
- (CPColor)highlightTextColor
|
||||
{
|
||||
if (![_menuItem isEnabled])
|
||||
return [CPColor lightGrayColor];
|
||||
|
||||
return _highlightTextColor || [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-highlight-text-color" forClass:_CPMenuView];
|
||||
}
|
||||
|
||||
- (CPColor)highlightTextShadowColor
|
||||
{
|
||||
if (![_menuItem isEnabled])
|
||||
return [CPColor clearColor];
|
||||
|
||||
return _highlightTextShadowColor || [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-highlight-text-shadow-color" forClass:_CPMenuView];
|
||||
}
|
||||
|
||||
- (CPColor)highlightColor
|
||||
{
|
||||
return _highlightColor || [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-bar-window-background-selected-color" forClass:_CPMenuView];
|
||||
return _textShadowColor || [CPColor colorWithWhite:1.0 alpha:0.8];
|
||||
}
|
||||
|
||||
- (void)update
|
||||
{
|
||||
var x = [self valueForThemeAttribute:@"horizontal-margin"],
|
||||
var x = HORIZONTAL_MARGIN,
|
||||
height = 0.0;
|
||||
|
||||
[_imageAndTextView setText:[_menuItem title]];
|
||||
[_imageAndTextView setFont:[_menuItem font] || [_CPMenuBarWindow font]];
|
||||
[_imageAndTextView setVerticalAlignment:CPCenterVerticalTextAlignment];
|
||||
[_imageAndTextView setTextShadowOffset:CGSizeMake(0.0, 1.0)];
|
||||
[_imageAndTextView setImage:[_menuItem image]];
|
||||
[_imageAndTextView setText:[_menuItem title]];
|
||||
[_imageAndTextView setTextColor:[self textColor]];
|
||||
[_imageAndTextView setTextShadowColor:[self textShadowColor]];
|
||||
[_imageAndTextView setTextShadowOffset:CGSizeMake(0.0, 1.0)];
|
||||
[_imageAndTextView sizeToFit];
|
||||
|
||||
var imageAndTextViewFrame = [_imageAndTextView frame];
|
||||
|
||||
imageAndTextViewFrame.origin.x = x;
|
||||
x += CGRectGetWidth(imageAndTextViewFrame);
|
||||
height = MAX(height, CGRectGetHeight(imageAndTextViewFrame)) + 2.0 * [self valueForThemeAttribute:@"vertical-margin"];
|
||||
height = MAX(height, CGRectGetHeight(imageAndTextViewFrame));
|
||||
|
||||
var hasSubmenuIndicator = [_menuItem hasSubmenu] && [_menuItem action];
|
||||
|
||||
if (hasSubmenuIndicator)
|
||||
{
|
||||
[_submenuIndicatorView setHidden:NO];
|
||||
[_submenuIndicatorView setColor:[self textColor]];
|
||||
[_submenuIndicatorView setShadowColor:[self textShadowColor]];
|
||||
|
||||
var submenuViewFrame = [_submenuIndicatorView frame];
|
||||
|
||||
submenuViewFrame.origin.x = x + SUBMENU_INDICATOR_MARGIN;
|
||||
|
||||
x = CGRectGetMaxX(submenuViewFrame);
|
||||
height = MAX(height, CGRectGetHeight(submenuViewFrame));
|
||||
}
|
||||
else
|
||||
[_submenuIndicatorView setHidden:YES];
|
||||
|
||||
height += 2.0 * VERTICAL_MARGIN;
|
||||
|
||||
imageAndTextViewFrame.origin.y = FLOOR((height - CGRectGetHeight(imageAndTextViewFrame)) / 2.0);
|
||||
[_imageAndTextView setFrame:imageAndTextViewFrame];
|
||||
|
||||
if (hasSubmenuIndicator)
|
||||
{
|
||||
submenuViewFrame.origin.y = FLOOR((height - CGRectGetHeight(submenuViewFrame)) / 2.0) + 1.0;
|
||||
[_submenuIndicatorView setFrame:submenuViewFrame];
|
||||
}
|
||||
|
||||
_minSize = CGSizeMake(x + HORIZONTAL_MARGIN, height);
|
||||
|
||||
[self setAutoresizesSubviews:NO];
|
||||
[self setFrameSize:CGSizeMake(x + [self valueForThemeAttribute:@"horizontal-margin"], height)];
|
||||
[self setFrameSize:_minSize];
|
||||
[self setAutoresizesSubviews:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)highlight:(BOOL)shouldHighlight
|
||||
@@ -179,20 +157,17 @@
|
||||
if (![_menuItem isEnabled])
|
||||
shouldHighlight = NO;
|
||||
|
||||
_shouldHighlight = shouldHighlight;
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
if (_shouldHighlight)
|
||||
if (shouldHighlight)
|
||||
{
|
||||
if (![_menuItem _isMenuBarButton])
|
||||
[self setBackgroundColor:[self highlightColor]];
|
||||
[self setBackgroundColor:SelectionColor];
|
||||
|
||||
[_imageAndTextView setImage:[_menuItem alternateImage] || [_menuItem image]];
|
||||
[_imageAndTextView setTextColor:[self highlightTextColor]];
|
||||
[_imageAndTextView setTextShadowColor:[self highlightTextShadowColor]];
|
||||
[_imageAndTextView setTextColor:[CPColor whiteColor]];
|
||||
[_imageAndTextView setTextShadowColor:_CPMenuItemTextShadowColor];
|
||||
|
||||
[_submenuIndicatorView setColor:[CPColor whiteColor]];
|
||||
[_submenuIndicatorView setShadowColor:[CPColor colorWithWhite:0.1 alpha:0.7]];
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -201,7 +176,60 @@
|
||||
[_imageAndTextView setImage:[_menuItem image]];
|
||||
[_imageAndTextView setTextColor:[self textColor]];
|
||||
[_imageAndTextView setTextShadowColor:[self textShadowColor]];
|
||||
|
||||
[_submenuIndicatorView setColor:[self textColor]];
|
||||
[_submenuIndicatorView setShadowColor:[self textShadowColor]];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPMenuItemMenuBarSubmenuIndicatorView : CPView
|
||||
{
|
||||
CPColor _color;
|
||||
CPColor _shadowColor;
|
||||
}
|
||||
|
||||
- (void)setColor:(CPColor)aColor
|
||||
{
|
||||
if (_color === aColor)
|
||||
return;
|
||||
|
||||
_color = aColor;
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)setShadowColor:(CPColor)aColor
|
||||
{
|
||||
if (_shadowColor === aColor)
|
||||
return;
|
||||
|
||||
_shadowColor = aColor;
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
bounds = [self bounds];
|
||||
|
||||
bounds.size.height -= 1.0;
|
||||
bounds.size.width -= 2.0;
|
||||
bounds.origin.x += 1.0;
|
||||
|
||||
CGContextBeginPath(context);
|
||||
|
||||
CGContextMoveToPoint(context, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
|
||||
CGContextAddLineToPoint(context, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
|
||||
CGContextAddLineToPoint(context, CGRectGetMidX(bounds), CGRectGetMaxY(bounds));
|
||||
|
||||
CGContextClosePath(context);
|
||||
|
||||
CGContextSetShadowWithColor(context, CGSizeMake(0.0, 1.0), 1.1, _shadowColor || [CPColor whiteColor]);
|
||||
CGContextSetFillColor(context, _color || [CPColor blackColor]);
|
||||
CGContextFillPath(context);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,28 +1,5 @@
|
||||
/*
|
||||
* _CPMenuItemSeparatorView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPView.j"
|
||||
|
||||
@class _CPMenuItemStandardView
|
||||
@import <AppKit/CPView.j>
|
||||
|
||||
|
||||
@implementation _CPMenuItemSeparatorView : CPView
|
||||
@@ -31,9 +8,7 @@
|
||||
|
||||
+ (id)view
|
||||
{
|
||||
var themedHeight = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-item-separator-view-height" forClass:_CPMenuItemStandardView];
|
||||
|
||||
return [[self alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, (themedHeight ? themedHeight : 10.0))];
|
||||
return [[self alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 10.0)];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
@@ -49,28 +24,15 @@
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
bounds = [self bounds],
|
||||
height = CGRectGetMaxY(bounds),
|
||||
themedHeight = [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-item-separator-height" forClass:_CPMenuItemStandardView],
|
||||
lineHeight = themedHeight ? themedHeight : 1.0;
|
||||
bounds = [self bounds];
|
||||
|
||||
CGContextBeginPath(context);
|
||||
|
||||
CGContextSetLineWidth(context, lineHeight);
|
||||
|
||||
if (!!((height - lineHeight) % 2))
|
||||
{
|
||||
CGContextMoveToPoint(context, CGRectGetMinX(bounds), FLOOR(CGRectGetMidY(bounds)) - 0.5);
|
||||
CGContextAddLineToPoint(context, CGRectGetMaxX(bounds), FLOOR(CGRectGetMidY(bounds)) - 0.5);
|
||||
}
|
||||
else
|
||||
{
|
||||
CGContextMoveToPoint(context, CGRectGetMinX(bounds), FLOOR(CGRectGetMidY(bounds)));
|
||||
CGContextAddLineToPoint(context, CGRectGetMaxX(bounds), FLOOR(CGRectGetMidY(bounds)));
|
||||
}
|
||||
|
||||
CGContextSetStrokeColor(context, [[CPTheme defaultTheme] valueForAttributeWithName:@"menu-item-separator-color" forClass:_CPMenuItemStandardView]);
|
||||
|
||||
CGContextMoveToPoint(context, CGRectGetMinX(bounds), FLOOR(CGRectGetMidY(bounds)) - 0.5);
|
||||
CGContextAddLineToPoint(context, CGRectGetMaxX(bounds), FLOOR(CGRectGetMidY(bounds)) - 0.5);
|
||||
|
||||
CGContextSetStrokeColor(context, [CPColor lightGrayColor]);
|
||||
CGContextStrokePath(context);
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
@@ -1,82 +1,56 @@
|
||||
/*
|
||||
* _CPMenuItemStandardView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPControl.j"
|
||||
@import "CPImageView.j"
|
||||
@import "_CPImageAndTextView.j"
|
||||
|
||||
@class CPMenuItem
|
||||
var LEFT_MARGIN = 3.0,
|
||||
RIGHT_MARGIN = 14.0 + 3.0,
|
||||
STATE_COLUMN_WIDTH = 14.0,
|
||||
INDENTATION_WIDTH = 17.0,
|
||||
VERTICAL_MARGIN = 4.0,
|
||||
|
||||
RIGHT_COLUMNS_MARGIN = 30.0,
|
||||
KEY_EQUIVALENT_MARGIN = 10.0;
|
||||
|
||||
var SUBMENU_INDICATOR_COLOR = nil,
|
||||
_CPMenuItemSelectionColor = nil,
|
||||
_CPMenuItemTextShadowColor = nil,
|
||||
|
||||
_CPMenuItemDefaultStateImages = [],
|
||||
_CPMenuItemDefaultStateHighlightedImages = [];
|
||||
|
||||
@implementation _CPMenuItemStandardView : CPView
|
||||
{
|
||||
CPMenuItem _menuItem @accessors(property=menuItem);
|
||||
|
||||
CPFont _font;
|
||||
CPColor _textColor;
|
||||
CPColor _textShadowColor;
|
||||
|
||||
CGSize _minSize @accessors(readonly, property=minSize);
|
||||
BOOL _isDirty;
|
||||
BOOL _highlighted;
|
||||
|
||||
CPImageView _stateView;
|
||||
_CPImageAndTextView _imageAndTextView;
|
||||
_CPImageAndTextView _keyEquivalentView;
|
||||
CPView _submenuIndicatorView;
|
||||
|
||||
BOOL _hasSubmenuIndicatorImage;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (void)initialize
|
||||
{
|
||||
return "menu-item-standard-view";
|
||||
}
|
||||
if (self !== [_CPMenuItemStandardView class])
|
||||
return;
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"submenu-indicator-color": [CPNull null],
|
||||
@"menu-item-selection-color": [CPNull null],
|
||||
@"menu-item-text-shadow-color": [CPNull null],
|
||||
@"menu-item-text-color": [CPNull null],
|
||||
@"menu-item-disabled-text-color": [CPColor lightGrayColor],
|
||||
@"menu-item-default-off-state-image": [CPNull null],
|
||||
@"menu-item-default-off-state-highlighted-image": [CPNull null],
|
||||
@"menu-item-default-on-state-image": [CPNull null],
|
||||
@"menu-item-default-on-state-highlighted-image": [CPNull null],
|
||||
@"menu-item-default-mixed-state-image": [CPNull null],
|
||||
@"menu-item-default-mixed-state-highlighted-image": [CPNull null],
|
||||
@"menu-item-separator-color": [CPNull null],
|
||||
@"menu-item-separator-height": 1.0,
|
||||
@"menu-item-separator-view-height": 10.0,
|
||||
@"left-margin": 3.0,
|
||||
@"right-margin": 17.0,
|
||||
@"state-column-width": 14.0,
|
||||
@"indentation-width": 17.0,
|
||||
@"vertical-margin": 4.0,
|
||||
@"vertical-offset": 0.0,
|
||||
@"right-columns-margin": 30.0,
|
||||
@"submenu-indicator-image": [CPNull null],
|
||||
@"submenu-indicator-highlighted-image": [CPNull null]
|
||||
};
|
||||
SUBMENU_INDICATOR_COLOR = [CPColor grayColor];
|
||||
|
||||
_CPMenuItemSelectionColor = [CPColor colorWithCalibratedRed:95.0 / 255.0 green:131.0 / 255.0 blue:185.0 / 255.0 alpha:1.0];
|
||||
_CPMenuItemTextShadowColor = [CPColor colorWithCalibratedRed:26.0 / 255.0 green: 73.0 / 255.0 blue:109.0 / 255.0 alpha:1.0]
|
||||
|
||||
var bundle = [CPBundle bundleForClass:self];
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPOffState] = nil;
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPOffState] = nil;
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPOnState] = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPMenuItem/CPMenuItemOnState.png"] size:CGSizeMake(14.0, 14.0)];
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPOnState] = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPMenuItem/CPMenuItemOnStateHighlighted.png"] size:CGSizeMake(14.0, 14.0)];
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPMixedState] = nil;
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPMixedState] = nil;
|
||||
}
|
||||
|
||||
+ (id)view
|
||||
@@ -86,7 +60,7 @@
|
||||
|
||||
+ (float)_standardLeftMargin
|
||||
{
|
||||
return [[CPTheme defaultTheme] valueForAttributeWithName:@"left-margin" forClass:[self class]] + [[CPTheme defaultTheme] valueForAttributeWithName:@"state-column-width" forClass:[self class]];
|
||||
return LEFT_MARGIN + STATE_COLUMN_WIDTH;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
@@ -97,8 +71,7 @@
|
||||
{
|
||||
_stateView = [[CPImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 0.0)];
|
||||
|
||||
[_stateView setImageScaling:CPImageScaleNone];
|
||||
[_stateView setImageAlignment:CPImageAlignCenter];
|
||||
[_stateView setImageScaling:CPScaleNone];
|
||||
|
||||
[self addSubview:_stateView];
|
||||
|
||||
@@ -117,24 +90,9 @@
|
||||
|
||||
[self addSubview:_keyEquivalentView];
|
||||
|
||||
// Do we have a submenu indicator image specified in the theme ?
|
||||
_hasSubmenuIndicatorImage = !![self valueForThemeAttribute:@"submenu-indicator-image"];
|
||||
|
||||
if (_hasSubmenuIndicatorImage)
|
||||
{
|
||||
// Yes, then use an imageView
|
||||
_submenuIndicatorView = [[CPImageView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[_submenuIndicatorView setImageAlignment:CPImageAlignCenter];
|
||||
}
|
||||
else
|
||||
{
|
||||
// No, then use self drawing _CPMenuItemSubmenuIndicatorView
|
||||
_submenuIndicatorView = [[_CPMenuItemSubmenuIndicatorView alloc] initWithFrame:CGRectMake(0.0, 0.0, 8.0, 10.0)];
|
||||
|
||||
[_submenuIndicatorView setColor:[self valueForThemeAttribute:@"submenu-indicator-color"]];
|
||||
}
|
||||
_submenuIndicatorView = [[_CPMenuItemSubmenuIndicatorView alloc] initWithFrame:CGRectMake(0.0, 0.0, 8.0, 10.0)];
|
||||
|
||||
[_submenuIndicatorView setColor:SUBMENU_INDICATOR_COLOR];
|
||||
[_submenuIndicatorView setAutoresizingMask:CPViewMinXMargin];
|
||||
|
||||
[self addSubview:_submenuIndicatorView];
|
||||
@@ -148,12 +106,9 @@
|
||||
- (CPColor)textColor
|
||||
{
|
||||
if (![_menuItem isEnabled])
|
||||
return [self valueForThemeAttribute:@"menu-item-disabled-text-color"];
|
||||
return [CPColor lightGrayColor];
|
||||
|
||||
if (_highlighted)
|
||||
return [CPColor whiteColor];
|
||||
|
||||
return [self valueForThemeAttribute:@"menu-item-text-color"];
|
||||
return _textColor || [CPColor colorWithCalibratedRed:70.0 / 255.0 green:69.0 / 255.0 blue:69.0 / 255.0 alpha:1.0];
|
||||
}
|
||||
|
||||
- (CPColor)textShadowColor
|
||||
@@ -161,10 +116,7 @@
|
||||
if (![_menuItem isEnabled])
|
||||
return nil;
|
||||
|
||||
if (_highlighted)
|
||||
return nil;
|
||||
|
||||
return [self valueForThemeAttribute:@"menu-item-text-shadow-color"];
|
||||
return _textShadowColor || [CPColor colorWithWhite:1.0 alpha:0.8];
|
||||
}
|
||||
|
||||
- (void)setFont:(CPFont)aFont
|
||||
@@ -172,59 +124,23 @@
|
||||
_font = aFont;
|
||||
}
|
||||
|
||||
- (CPFont)font
|
||||
{
|
||||
// Menu item font is forced local font or _menuItem font or system font
|
||||
return _font || [_menuItem font] || [CPFont systemFontOfSize:CPFontCurrentSystemSize];
|
||||
}
|
||||
|
||||
// FIXME: update is called 2 times at each display. Find why and fix.
|
||||
- (void)update
|
||||
{
|
||||
var x = [self valueForThemeAttribute:@"left-margin"] + [_menuItem indentationLevel] * [self valueForThemeAttribute:@"indentation-width"],
|
||||
var x = LEFT_MARGIN + [_menuItem indentationLevel] * INDENTATION_WIDTH,
|
||||
height = 0.0,
|
||||
hasStateColumn = [[_menuItem menu] showsStateColumn],
|
||||
myFont = [self font],
|
||||
|
||||
// When possible, use specific vertical margin/offset value based on font size (which could have been set by control size)
|
||||
correspondingControlSize = [myFont controlSizeCorrespondingToFontSize],
|
||||
verticalMargin = [self valueForThemeAttribute:@"vertical-margin" inState:CPControlSizeThemeStates[correspondingControlSize]],
|
||||
verticalOffset = [self valueForThemeAttribute:@"vertical-offset" inState:CPControlSizeThemeStates[correspondingControlSize]];
|
||||
hasStateColumn = [[_menuItem menu] showsStateColumn];
|
||||
|
||||
if (hasStateColumn)
|
||||
{
|
||||
[_stateView setHidden:NO];
|
||||
//[_stateView setImage:_CPMenuItemDefaultStateImages[[_menuItem state]] || nil];
|
||||
[_stateView setImage:_CPMenuItemDefaultStateImages[[_menuItem state]] || nil];
|
||||
|
||||
switch ([_menuItem state])
|
||||
{
|
||||
case CPOnState:
|
||||
[_stateView setImage:[_menuItem onStateImage] || [self valueForThemeAttribute:@"menu-item-default-on-state-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
case CPOffState:
|
||||
[_stateView setImage:[_menuItem offStateImage] || [self valueForThemeAttribute:@"menu-item-default-off-state-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
case CPMixedState:
|
||||
[_stateView setImage:[_menuItem mixedStateImage] || [self valueForThemeAttribute:@"menu-item-default-mixed-state-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
var stateViewFrameOrigin = [_stateView frameOrigin];
|
||||
|
||||
stateViewFrameOrigin.x = x;
|
||||
[_stateView setFrameOrigin:stateViewFrameOrigin];
|
||||
|
||||
x += [self valueForThemeAttribute:@"state-column-width"];
|
||||
x += STATE_COLUMN_WIDTH;
|
||||
}
|
||||
else
|
||||
[_stateView setHidden:YES];
|
||||
|
||||
[_imageAndTextView setFont:myFont];
|
||||
[_imageAndTextView setFont:[_menuItem font] || _font];
|
||||
[_imageAndTextView setVerticalAlignment:CPCenterVerticalTextAlignment];
|
||||
[_imageAndTextView setImage:[_menuItem image]];
|
||||
[_imageAndTextView setText:[_menuItem title]];
|
||||
@@ -237,26 +153,26 @@
|
||||
|
||||
imageAndTextViewFrame.origin.x = x;
|
||||
x += CGRectGetWidth(imageAndTextViewFrame);
|
||||
height = MAX(height, CGRectGetHeight(imageAndTextViewFrame)); // FIXME: here, height = 0 -> MAX useless
|
||||
height = MAX(height, CGRectGetHeight(imageAndTextViewFrame));
|
||||
|
||||
var hasKeyEquivalent = !![_menuItem keyEquivalent],
|
||||
hasSubmenu = [_menuItem hasSubmenu];
|
||||
|
||||
if (hasKeyEquivalent || hasSubmenu)
|
||||
x += [self valueForThemeAttribute:@"right-columns-margin"];
|
||||
x += RIGHT_COLUMNS_MARGIN;
|
||||
|
||||
if (hasKeyEquivalent)
|
||||
{
|
||||
[_keyEquivalentView setFont:myFont];
|
||||
[_keyEquivalentView setFont:[_menuItem font] || _font];
|
||||
[_keyEquivalentView setVerticalAlignment:CPCenterVerticalTextAlignment];
|
||||
[_keyEquivalentView setImage:[_menuItem image]];
|
||||
[_keyEquivalentView setText:[_menuItem keyEquivalentStringRepresentation]];
|
||||
[_keyEquivalentView setTextColor:[self textColor]];
|
||||
[_keyEquivalentView setTextShadowColor:[self textShadowColor]];
|
||||
[_keyEquivalentView setTextShadowOffset:CGSizeMake(0, 1)];
|
||||
[_keyEquivalentView setFrameOrigin:CGPointMake(x, verticalMargin)];
|
||||
[_keyEquivalentView setFrameOrigin:CGPointMake(x, VERTICAL_MARGIN)];
|
||||
[_keyEquivalentView sizeToFit];
|
||||
|
||||
|
||||
var keyEquivalentViewFrame = [_keyEquivalentView frame];
|
||||
|
||||
keyEquivalentViewFrame.origin.x = x;
|
||||
@@ -264,21 +180,13 @@
|
||||
height = MAX(height, CGRectGetHeight(keyEquivalentViewFrame));
|
||||
|
||||
if (hasSubmenu)
|
||||
x += [self valueForThemeAttribute:@"right-columns-margin"];
|
||||
x += RIGHT_COLUMNS_MARGIN;
|
||||
}
|
||||
else
|
||||
[_keyEquivalentView setHidden:YES];
|
||||
|
||||
if (hasSubmenu)
|
||||
{
|
||||
if (_hasSubmenuIndicatorImage)
|
||||
{
|
||||
var submenuIndicatorImage = [self valueForThemeAttribute:@"submenu-indicator-image" inState:CPControlSizeThemeStates[correspondingControlSize]];
|
||||
|
||||
[_submenuIndicatorView setImage:submenuIndicatorImage];
|
||||
[_submenuIndicatorView setFrameSize:[submenuIndicatorImage size]];
|
||||
}
|
||||
|
||||
[_submenuIndicatorView setHidden:NO];
|
||||
|
||||
var submenuViewFrame = [_submenuIndicatorView frame];
|
||||
@@ -291,28 +199,28 @@
|
||||
else
|
||||
[_submenuIndicatorView setHidden:YES];
|
||||
|
||||
height += 2.0 * verticalMargin;
|
||||
height += 2.0 * VERTICAL_MARGIN;
|
||||
|
||||
imageAndTextViewFrame.origin.y = FLOOR((height - CGRectGetHeight(imageAndTextViewFrame)) / 2.0) + verticalOffset;
|
||||
imageAndTextViewFrame.origin.y = FLOOR((height - CGRectGetHeight(imageAndTextViewFrame)) / 2.0);
|
||||
[_imageAndTextView setFrame:imageAndTextViewFrame];
|
||||
|
||||
if (hasStateColumn)
|
||||
[_stateView setFrameSize:CGSizeMake([self valueForThemeAttribute:@"state-column-width"], height)];
|
||||
[_stateView setFrameSize:CGSizeMake(STATE_COLUMN_WIDTH, height)];
|
||||
|
||||
if (hasKeyEquivalent)
|
||||
{
|
||||
keyEquivalentViewFrame.origin.y = FLOOR((height - CGRectGetHeight(keyEquivalentViewFrame)) / 2.0) + verticalOffset;
|
||||
keyEquivalentViewFrame.origin.y = FLOOR((height - CGRectGetHeight(keyEquivalentViewFrame)) / 2.0);
|
||||
[_keyEquivalentView setFrame:keyEquivalentViewFrame];
|
||||
}
|
||||
|
||||
|
||||
if (hasSubmenu)
|
||||
{
|
||||
submenuViewFrame.origin.y = FLOOR((height - CGRectGetHeight(submenuViewFrame)) / 2.0);
|
||||
[_submenuIndicatorView setFrame:submenuViewFrame];
|
||||
}
|
||||
|
||||
_minSize = CGSizeMake(x + [self valueForThemeAttribute:@"right-margin"], height);
|
||||
|
||||
_minSize = CGSizeMake(x + RIGHT_MARGIN, height);
|
||||
|
||||
[self setAutoresizesSubviews:NO];
|
||||
[self setFrameSize:_minSize];
|
||||
[self setAutoresizesSubviews:YES];
|
||||
@@ -322,106 +230,41 @@
|
||||
{
|
||||
// FIXME: This should probably be even throw.
|
||||
if (![_menuItem isEnabled])
|
||||
return;
|
||||
|
||||
_highlighted = shouldHighlight;
|
||||
|
||||
var correspondingControlSize = [[self font] controlSizeCorrespondingToFontSize];
|
||||
|
||||
[_imageAndTextView setTextColor:[self textColor]];
|
||||
[_keyEquivalentView setTextColor:[self textColor]];
|
||||
[_imageAndTextView setTextShadowColor:[self textShadowColor]];
|
||||
[_keyEquivalentView setTextShadowColor:[self textShadowColor]];
|
||||
return;
|
||||
|
||||
if (shouldHighlight)
|
||||
{
|
||||
[self setBackgroundColor:[self valueForThemeAttribute:@"menu-item-selection-color"]];
|
||||
[_imageAndTextView setImage:[_menuItem alternateImage] || [_menuItem image]];
|
||||
[self setBackgroundColor:_CPMenuItemSelectionColor];
|
||||
|
||||
if (_hasSubmenuIndicatorImage)
|
||||
[_submenuIndicatorView setImage:[self valueForThemeAttribute:@"submenu-indicator-highlighted-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
else
|
||||
[_submenuIndicatorView setColor:[self textColor]];
|
||||
[_imageAndTextView setImage:[_menuItem alternateImage] || [_menuItem image]];
|
||||
[_imageAndTextView setTextColor:[CPColor whiteColor]];
|
||||
[_keyEquivalentView setTextColor:[CPColor whiteColor]];
|
||||
[_submenuIndicatorView setColor:[CPColor whiteColor]];
|
||||
|
||||
[_imageAndTextView setTextShadowColor:_CPMenuItemTextShadowColor];
|
||||
[_keyEquivalentView setTextShadowColor:_CPMenuItemTextShadowColor];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self setBackgroundColor:nil];
|
||||
|
||||
[_imageAndTextView setImage:[_menuItem image]];
|
||||
[_imageAndTextView setTextColor:[self textColor]];
|
||||
[_keyEquivalentView setTextColor:[self textColor]];
|
||||
[_submenuIndicatorView setColor:SUBMENU_INDICATOR_COLOR];
|
||||
|
||||
if (_hasSubmenuIndicatorImage)
|
||||
[_submenuIndicatorView setImage:[self valueForThemeAttribute:@"submenu-indicator-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
else
|
||||
[_submenuIndicatorView setColor:[self valueForThemeAttribute:@"submenu-indicator-color"]];
|
||||
[_imageAndTextView setTextShadowColor:[self textShadowColor]];
|
||||
[_keyEquivalentView setTextShadowColor:[self textShadowColor]];
|
||||
}
|
||||
|
||||
if ([[_menuItem menu] showsStateColumn])
|
||||
{
|
||||
if (shouldHighlight)
|
||||
{
|
||||
switch ([_menuItem state])
|
||||
{
|
||||
case CPOnState:
|
||||
[_stateView setImage:[_menuItem onStateImage] || [self valueForThemeAttribute:@"menu-item-default-on-state-highlighted-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
case CPOffState:
|
||||
[_stateView setImage:[_menuItem offStateImage] || [self valueForThemeAttribute:@"menu-item-default-off-state-highlighted-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
case CPMixedState:
|
||||
[_stateView setImage:[_menuItem mixedImage] || [self valueForThemeAttribute:@"menu-item-default-mixed-state-highlighted-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch ([_menuItem state])
|
||||
{
|
||||
case CPOnState:
|
||||
[_stateView setImage:[_menuItem onStateImage] || [self valueForThemeAttribute:@"menu-item-default-on-state-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
case CPOffState:
|
||||
[_stateView setImage:[_menuItem offStateImage] || [self valueForThemeAttribute:@"menu-item-default-off-state-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
case CPMixedState:
|
||||
[_stateView setImage:[_menuItem mixedImage] || [self valueForThemeAttribute:@"menu-item-default-mixed-state-image" inState:CPControlSizeThemeStates[correspondingControlSize]]];
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isHighlighted
|
||||
{
|
||||
return _highlighted;
|
||||
|
||||
if (shouldHighlight)
|
||||
[_stateView setImage:_CPMenuItemDefaultStateHighlightedImages[[_menuItem state]] || nil];
|
||||
else
|
||||
[_stateView setImage:_CPMenuItemDefaultStateImages[[_menuItem state]] || nil];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMenuItemStandardView (CSSTheming)
|
||||
|
||||
#pragma mark Override
|
||||
|
||||
- (void)_setThemeIncludingDescendants:(CPTheme)aTheme
|
||||
{
|
||||
[self setTheme:aTheme];
|
||||
[[self subviews] makeObjectsPerformSelector:@selector(_setThemeIncludingDescendants:) withObject:aTheme];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMenuItemSubmenuIndicatorView : CPView
|
||||
{
|
||||
CPColor _color;
|
||||
@@ -441,15 +284,15 @@
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
bounds = [self bounds];
|
||||
|
||||
|
||||
CGContextBeginPath(context);
|
||||
|
||||
|
||||
CGContextMoveToPoint(context, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
|
||||
CGContextAddLineToPoint(context, CGRectGetMaxX(bounds), CGRectGetMidY(bounds));
|
||||
CGContextAddLineToPoint(context, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
|
||||
|
||||
|
||||
CGContextClosePath(context);
|
||||
|
||||
|
||||
CGContextSetFillColor(context, _color);
|
||||
CGContextFillPath(context);
|
||||
}
|
||||
|
||||
@@ -1,33 +1,20 @@
|
||||
/*
|
||||
* _CPMenuItemView.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPControl.j"
|
||||
|
||||
@import "_CPMenuItemSeparatorView.j"
|
||||
@import "_CPMenuItemStandardView.j"
|
||||
@import "_CPMenuItemMenuBarView.j"
|
||||
|
||||
@class CPMenuItem
|
||||
@global CPApp
|
||||
|
||||
var LEFT_MARGIN = 3.0,
|
||||
RIGHT_MARGIN = 16.0,
|
||||
STATE_COLUMN_WIDTH = 14.0,
|
||||
INDENTATION_WIDTH = 17.0,
|
||||
VERTICAL_MARGIN = 4.0;
|
||||
|
||||
var _CPMenuItemSelectionColor = nil,
|
||||
_CPMenuItemTextShadowColor = nil,
|
||||
|
||||
_CPMenuItemDefaultStateImages = [],
|
||||
_CPMenuItemDefaultStateHighlightedImages = [];
|
||||
|
||||
/*
|
||||
@ignore
|
||||
@@ -35,7 +22,7 @@
|
||||
@implementation _CPMenuItemView : CPView
|
||||
{
|
||||
CPMenuItem _menuItem;
|
||||
CPView _view @accessors(property=view, readonly);
|
||||
CPView _view;
|
||||
|
||||
CPFont _font;
|
||||
CPColor _textColor;
|
||||
@@ -45,26 +32,36 @@
|
||||
BOOL _isDirty;
|
||||
BOOL _showsStateColumn;
|
||||
|
||||
CPImageView _stateView;
|
||||
_CPImageAndTextView _imageAndTextView;
|
||||
CPView _submenuView;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (void)initialize
|
||||
{
|
||||
return "menu-item-view";
|
||||
if (self != [_CPMenuItemView class])
|
||||
return;
|
||||
|
||||
_CPMenuItemSelectionColor = [CPColor colorWithCalibratedRed:95.0 / 255.0 green:131.0 / 255.0 blue:185.0 / 255.0 alpha:1.0];
|
||||
_CPMenuItemTextShadowColor = [CPColor colorWithCalibratedRed:26.0 / 255.0 green: 73.0 / 255.0 blue:109.0 / 255.0 alpha:1.0]
|
||||
|
||||
var bundle = [CPBundle bundleForClass:self];
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPOffState] = nil;
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPOffState] = nil;
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPOnState] = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPMenuItem/CPMenuItemOnState.png"] size:CGSizeMake(14.0, 14.0)];
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPOnState] = [[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPMenuItem/CPMenuItemOnStateHighlighted.png"] size:CGSizeMake(14.0, 14.0)];
|
||||
|
||||
_CPMenuItemDefaultStateImages[CPMixedState] = nil;
|
||||
_CPMenuItemDefaultStateHighlightedImages[CPMixedState] = nil;
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
+ (float)leftMargin
|
||||
{
|
||||
return @{};
|
||||
return LEFT_MARGIN + STATE_COLUMN_WIDTH;
|
||||
}
|
||||
|
||||
// Not used in the Appkit
|
||||
// + (float)leftMargin
|
||||
// {
|
||||
// return LEFT_MARGIN + STATE_COLUMN_WIDTH;
|
||||
// }
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame forMenuItem:(CPMenuItem)aMenuItem
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
@@ -74,12 +71,12 @@
|
||||
_menuItem = aMenuItem;
|
||||
_showsStateColumn = YES;
|
||||
_isDirty = YES;
|
||||
|
||||
|
||||
[self setAutoresizingMask:CPViewWidthSizable];
|
||||
|
||||
[self synchronizeWithMenuItem];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -113,6 +110,7 @@
|
||||
_view = menuItemView;
|
||||
}
|
||||
}
|
||||
|
||||
else if ([_menuItem menu] == [CPApp mainMenu])
|
||||
{
|
||||
if (![_view isKindOfClass:[_CPMenuItemMenuBarView class]])
|
||||
@@ -130,7 +128,7 @@
|
||||
[_view removeFromSuperview];
|
||||
_view = [_CPMenuItemStandardView view];
|
||||
}
|
||||
|
||||
|
||||
[_view setMenuItem:_menuItem];
|
||||
}
|
||||
|
||||
@@ -161,7 +159,7 @@
|
||||
{
|
||||
if (![_menuItem hasSubmenu])
|
||||
return NO;
|
||||
|
||||
|
||||
return CGRectContainsPoint([_submenuView frame], [self convertPoint:[anEvent locationInWindow] fromView:nil]);
|
||||
}
|
||||
|
||||
@@ -177,7 +175,7 @@
|
||||
|
||||
- (void)setFont:(CPFont)aFont
|
||||
{
|
||||
if ([_font isEqual:aFont])
|
||||
if (_font === aFont)
|
||||
return;
|
||||
|
||||
_font = aFont;
|
||||
@@ -192,7 +190,7 @@
|
||||
{
|
||||
if (_textColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_textColor = aColor;
|
||||
|
||||
[_imageAndTextView setTextColor:[self textColor]];
|
||||
@@ -208,7 +206,7 @@
|
||||
{
|
||||
if (_textShadowColor == aColor)
|
||||
return;
|
||||
|
||||
|
||||
_textShadowColor = aColor;
|
||||
|
||||
[_imageAndTextView setTextShadowColor:[self textShadowColor]];
|
||||
@@ -220,63 +218,8 @@
|
||||
return [_menuItem isEnabled] ? (_textShadowColor ? _textShadowColor : [CPColor colorWithWhite:1.0 alpha:0.8]) : [CPColor colorWithWhite:0.8 alpha:0.8];
|
||||
}
|
||||
|
||||
- (void)setParentMenuHighlightColor:(CPColor)aColor
|
||||
{
|
||||
if ([_view respondsToSelector:@selector(setHighlightColor:)])
|
||||
[_view setHighlightColor:aColor];
|
||||
}
|
||||
|
||||
- (void)setParentMenuHighlightTextColor:(CPColor)aColor
|
||||
{
|
||||
if ([_view respondsToSelector:@selector(setHighlightTextColor:)])
|
||||
[_view setHighlightTextColor:aColor];
|
||||
}
|
||||
|
||||
- (void)setParentMenuHighlightTextShadowColor:(CPColor)aColor
|
||||
{
|
||||
if ([_view respondsToSelector:@selector(setHighlightTextShadowColor:)])
|
||||
[_view setHighlightTextShadowColor:aColor];
|
||||
}
|
||||
|
||||
- (void)setParentMenuTextColor:(CPColor)aColor
|
||||
{
|
||||
if ([_view respondsToSelector:@selector(setTextColor:)])
|
||||
[_view setTextColor:aColor];
|
||||
}
|
||||
|
||||
- (void)setParentMenuTextShadowColor:(CPColor)aColor
|
||||
{
|
||||
if ([_view respondsToSelector:@selector(setTextShadowColor:)])
|
||||
[_view setTextShadowColor:aColor];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMenuItemView (CSSTheming)
|
||||
|
||||
#pragma mark Override
|
||||
|
||||
- (void)_setThemeIncludingDescendants:(CPTheme)aTheme
|
||||
{
|
||||
[self setTheme:aTheme];
|
||||
[_view _setThemeIncludingDescendants:aTheme];
|
||||
|
||||
// Items must also perform this (without this, only the selected item does)
|
||||
|
||||
[_imageAndTextView _setThemeIncludingDescendants:aTheme];
|
||||
[_submenuView _setThemeIncludingDescendants:aTheme];
|
||||
[[_menuItem view] _setThemeIncludingDescendants:aTheme];
|
||||
|
||||
if ([_view respondsToSelector:@selector(update)])
|
||||
[_view update];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@implementation _CPMenuItemArrowView : CPView
|
||||
{
|
||||
CPColor _color;
|
||||
@@ -288,23 +231,25 @@
|
||||
return;
|
||||
|
||||
_color = aColor;
|
||||
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
|
||||
|
||||
CGContextBeginPath(context);
|
||||
|
||||
|
||||
CGContextMoveToPoint(context, 1.0, 4.0);
|
||||
CGContextAddLineToPoint(context, 9.0, 4.0);
|
||||
CGContextAddLineToPoint(context, 5.0, 8.0);
|
||||
CGContextAddLineToPoint(context, 1.0, 4.0);
|
||||
|
||||
CGContextClosePath(context);
|
||||
|
||||
|
||||
CGContextSetFillColor(context, _color);
|
||||
CGContextFillPath(context);
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
@@ -1,951 +0,0 @@
|
||||
/*
|
||||
* CPObjectController.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Ross Boucher.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPDictionary.j>
|
||||
@import <Foundation/CPCountedSet.j>
|
||||
@import <Foundation/_CPCollectionKVCOperators.j>
|
||||
|
||||
@import "CPController.j"
|
||||
@import "CPKeyValueBinding.j"
|
||||
|
||||
@class _CPManagedProxy
|
||||
@class CPPredicate;
|
||||
|
||||
/*!
|
||||
@class
|
||||
|
||||
CPObjectController is a bindings-compatible controller class.
|
||||
Properties of the content object of an object of this class can be bound to user interface elements to change and access their values.
|
||||
|
||||
The content of an CPObjectController instance is an CPMutableDictionary object by default.
|
||||
This allows a single CPObjectController instance to be used to manage several properties accessed by key value paths.
|
||||
The default content object class can be changed by calling setObjectClass:, which a subclass must override.
|
||||
*/
|
||||
@implementation CPObjectController : CPController
|
||||
{
|
||||
id _contentObject;
|
||||
id _selection;
|
||||
|
||||
Class _objectClass;
|
||||
CPString _objectClassName;
|
||||
|
||||
BOOL _isEditable;
|
||||
BOOL _automaticallyPreparesContent;
|
||||
BOOL _usesLazyFetching @accessors(getter=usesLazyFetching, setter=setUsesLazyFetching:);
|
||||
BOOL _isUsingManagedProxy;
|
||||
_CPManagedProxy _managedProxy;
|
||||
|
||||
CPCountedSet _observedKeys;
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPObjectController class])
|
||||
return;
|
||||
|
||||
[self exposeBinding:@"editable"];
|
||||
[self exposeBinding:@"contentObject"];
|
||||
}
|
||||
|
||||
+ (CPSet)keyPathsForValuesAffectingContentObject
|
||||
{
|
||||
return [CPSet setWithObjects:"content"];
|
||||
}
|
||||
|
||||
+ (BOOL)automaticallyNotifiesObserversForKey:(CPString)aKey
|
||||
{
|
||||
if (aKey === @"contentObject")
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (CPSet)keyPathsForValuesAffectingCanAdd
|
||||
{
|
||||
return [CPSet setWithObject:"editable"];
|
||||
}
|
||||
|
||||
+ (CPSet)keyPathsForValuesAffectingCanInsert
|
||||
{
|
||||
return [CPSet setWithObject:"editable"];
|
||||
}
|
||||
|
||||
+ (CPSet)keyPathsForValuesAffectingCanRemove
|
||||
{
|
||||
return [CPSet setWithObjects:"editable", "selection"];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (id)init
|
||||
{
|
||||
return [self initWithContent:nil];
|
||||
}
|
||||
|
||||
/*!
|
||||
Inits and returns a CPObjectController object with the given content.
|
||||
|
||||
@param id aContent - The object the controller will use.
|
||||
@return id the CPObjectConroller instance.
|
||||
*/
|
||||
- (id)initWithContent:(id)aContent
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
[self setEditable:YES];
|
||||
[self setObjectClass:[CPMutableDictionary class]];
|
||||
|
||||
_observedKeys = [[CPCountedSet alloc] init];
|
||||
_selection = [[CPControllerSelectionProxy alloc] initWithController:self];
|
||||
|
||||
[self setContent:aContent];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the controller's content object.
|
||||
@return id - The content object of the controller.
|
||||
*/
|
||||
- (id)content
|
||||
{
|
||||
return _contentObject;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the content object for the controller.
|
||||
@param id aContent - The new content object for the controller.
|
||||
*/
|
||||
- (void)setContent:(id)aContent
|
||||
{
|
||||
[self willChangeValueForKey:@"contentObject"];
|
||||
[self _selectionWillChange];
|
||||
|
||||
_contentObject = aContent;
|
||||
|
||||
[self _selectionDidChange];
|
||||
[self didChangeValueForKey:@"contentObject"];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (void)_setContentObject:(id)aContent
|
||||
{
|
||||
[self setContent:aContent];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (id)_contentObject
|
||||
{
|
||||
return [self content];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets whether the controller automatically creates and inserts new content objects automatically when loading from a cib file.
|
||||
If you pass YES and the controller uses prepareContent to create the content object.
|
||||
The default is NO.
|
||||
|
||||
@param BOOL shouldAutomaticallyPrepareContent - YES if the content should be prepared, otherwise NO.
|
||||
*/
|
||||
- (void)setAutomaticallyPreparesContent:(BOOL)shouldAutomaticallyPrepareContent
|
||||
{
|
||||
_automaticallyPreparesContent = shouldAutomaticallyPrepareContent;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns if the controller prepares the content automatically.
|
||||
@return BOOL - YES if the content is prepared, otherwise NO.
|
||||
*/
|
||||
- (BOOL)automaticallyPreparesContent
|
||||
{
|
||||
return _automaticallyPreparesContent;
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the entity name the controller handles.
|
||||
|
||||
@param CPString newEntityName - The new entity name.
|
||||
*/
|
||||
- (void)setEntityName:(CPString)newEntityName
|
||||
{
|
||||
if (!_managedProxy)
|
||||
{
|
||||
_managedProxy = [[_CPManagedProxy alloc] init];
|
||||
_isUsingManagedProxy = YES;
|
||||
}
|
||||
|
||||
[_managedProxy setEntityName:newEntityName];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the entity name.
|
||||
|
||||
@return CPString - The name of the entity.
|
||||
*/
|
||||
- (CPString)entityName
|
||||
{
|
||||
return [_managedProxy entityName];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the predicate used to fetch content.
|
||||
|
||||
@param CPPredicate newPredicate - The fetch predicate.
|
||||
*/
|
||||
- (void)setFetchPredicate:(CPPredicate)newPredicate
|
||||
{
|
||||
[_managedProxy setFetchPredicate:newPredicate];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the fetch predicate.
|
||||
|
||||
@return CPPredicate - The predicate used to fetch content.
|
||||
*/
|
||||
- (CPPredicate)fetchPredicate
|
||||
{
|
||||
return [_managedProxy fetchPredicate];
|
||||
}
|
||||
|
||||
/*!
|
||||
Overridden by a subclass that require control over the creation of new objects.
|
||||
*/
|
||||
- (void)prepareContent
|
||||
{
|
||||
[self setContent:[self newObject]];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the object class when creating new objects.
|
||||
|
||||
@param Class - the class of new objects that will be created.
|
||||
*/
|
||||
- (void)setObjectClass:(Class)aClass
|
||||
{
|
||||
_objectClass = aClass;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the class of what new objects will be when they are created.
|
||||
|
||||
@return Class - The class of new objects.
|
||||
*/
|
||||
- (Class)objectClass
|
||||
{
|
||||
return _objectClass;
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (id)_defaultNewObject
|
||||
{
|
||||
return [[[self objectClass] alloc] init];
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates and returns a new object of the appropriate class.
|
||||
@return id - The object created.
|
||||
*/
|
||||
- (id)newObject
|
||||
{
|
||||
return [self _defaultNewObject];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the controller's content object.
|
||||
@param id anObject - The object to set for the controller.
|
||||
*/
|
||||
- (void)addObject:(id)anObject
|
||||
{
|
||||
[self setContent:anObject];
|
||||
|
||||
var binderClass = [[self class] _binderClassForBinding:@"contentObject"];
|
||||
[[binderClass getBinding:@"contentObject" forObject:self] reverseSetValueFor:@"contentObject"];
|
||||
}
|
||||
|
||||
/*!
|
||||
Removes a given object from the controller.
|
||||
@param id anObject - The object to remove from the receiver.
|
||||
*/
|
||||
- (void)removeObject:(id)anObject
|
||||
{
|
||||
if ([self content] === anObject)
|
||||
[self setContent:nil];
|
||||
|
||||
var binderClass = [[self class] _binderClassForBinding:@"contentObject"];
|
||||
[[binderClass getBinding:@"contentObject" forObject:self] reverseSetValueFor:@"contentObject"];
|
||||
}
|
||||
|
||||
/*!
|
||||
Creates and adds a sets the object as the controller's content.
|
||||
@param id aSender - The sender of the message.
|
||||
*/
|
||||
- (void)add:(id)aSender
|
||||
{
|
||||
// FIXME: This should happen on the next run loop?
|
||||
[self addObject:[self newObject]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@return BOOL - YES if you can added to the controller using add:
|
||||
*/
|
||||
- (BOOL)canAdd
|
||||
{
|
||||
return [self isEditable];
|
||||
}
|
||||
|
||||
/*!
|
||||
Removes the content object from the controller.
|
||||
@param id aSender - The sender of the message.
|
||||
*/
|
||||
- (void)remove:(id)aSender
|
||||
{
|
||||
// FIXME: This should happen on the next run loop?
|
||||
[self removeObject:[self content]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@return BOOL - Returns YES if you can remove the controller's content using remove:
|
||||
*/
|
||||
- (BOOL)canRemove
|
||||
{
|
||||
return [self isEditable] && [[self selectedObjects] count];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets whether the controller allows for the editing of the content.
|
||||
@param BOOL shouldBeEditable - YES if the content should be editable, otherwise NO.
|
||||
*/
|
||||
- (void)setEditable:(BOOL)shouldBeEditable
|
||||
{
|
||||
_isEditable = shouldBeEditable;
|
||||
}
|
||||
|
||||
/*!
|
||||
@return BOOL - Returns YES if the content of the controller is editable, otherwise NO.
|
||||
*/
|
||||
- (BOOL)isEditable
|
||||
{
|
||||
return _isEditable;
|
||||
}
|
||||
|
||||
/*!
|
||||
@return CPArray - Returns an array of all objects to be affected by editing.
|
||||
*/
|
||||
- (CPArray)selectedObjects
|
||||
{
|
||||
return [[_CPObservableArray alloc] initWithArray:[_contentObject]];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a proxy object representing the controller's selection.
|
||||
*/
|
||||
- (id)selection
|
||||
{
|
||||
return _selection;
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (void)_selectionWillChange
|
||||
{
|
||||
[_selection controllerWillChange];
|
||||
[self willChangeValueForKey:@"selection"];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (void)_selectionDidChange
|
||||
{
|
||||
if (_selection == nil)
|
||||
_selection = [[CPControllerSelectionProxy alloc] initWithController:self];
|
||||
|
||||
[_selection controllerDidChange];
|
||||
[self didChangeValueForKey:@"selection"];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
These two private methods map CPTextField notifications to the CPEditorRegistration protocol
|
||||
This should be generalized in the future:
|
||||
|
||||
The CPEditorRegistrationProtocol can be implemented in all controls that support editing, not just CPTextField.
|
||||
In CPArrayController there are other cases than selection change when we need to review all editor pending changes. They should be covered, including the selection change, by the wider concept described by the methods commitEditing: (forces to end editing) and discardEditing: (pending changes are lost).
|
||||
*/
|
||||
- (void)_objectDidBeginEditing:(CPNotification)notification
|
||||
{
|
||||
[self objectDidBeginEditing:[notification object]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (void) _objectDidEndEditing:(CPNotification)notification
|
||||
{
|
||||
[self objectDidEndEditing:[notification object]];
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
@return id - Returns the keys which are being observed.
|
||||
*/
|
||||
- (id)observedKeys
|
||||
{
|
||||
return _observedKeys;
|
||||
}
|
||||
|
||||
- (void)addObserver:(id)anObserver forKeyPath:(CPString)aKeyPath options:(CPKeyValueObservingOptions)options context:(id)context
|
||||
{
|
||||
[_observedKeys addObject:aKeyPath];
|
||||
[super addObserver:anObserver forKeyPath:aKeyPath options:options context:context];
|
||||
}
|
||||
|
||||
- (void)removeObserver:(id)anObserver forKeyPath:(CPString)aKeyPath
|
||||
{
|
||||
[_observedKeys removeObject:aKeyPath];
|
||||
[super removeObserver:anObserver forKeyPath:aKeyPath];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPObjectControllerContentKey = @"CPObjectControllerContentKey",
|
||||
CPObjectControllerObjectClassNameKey = @"CPObjectControllerObjectClassNameKey",
|
||||
CPObjectControllerIsEditableKey = @"CPObjectControllerIsEditableKey",
|
||||
CPObjectControllerAutomaticallyPreparesContentKey = @"CPObjectControllerAutomaticallyPreparesContentKey",
|
||||
CPObjectControllerUsesLazyFetchingKey = @"CPObjectControllerUsesLazyFetchingKey",
|
||||
CPObjectControllerIsUsingManagedProxyKey = @"CPObjectControllerIsUsingManagedProxyKey",
|
||||
CPObjectControllerManagedProxyKey = @"CPObjectControllerManagedProxyKey";
|
||||
|
||||
@implementation CPObjectController (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
var objectClassName = [aCoder decodeObjectForKey:CPObjectControllerObjectClassNameKey],
|
||||
objectClass = CPClassFromString(objectClassName),
|
||||
content = [aCoder decodeObjectForKey:CPObjectControllerContentKey];
|
||||
|
||||
[self setObjectClass:objectClass || [CPMutableDictionary class]];
|
||||
[self setEditable:[aCoder decodeBoolForKey:CPObjectControllerIsEditableKey]];
|
||||
[self setAutomaticallyPreparesContent:[aCoder decodeBoolForKey:CPObjectControllerAutomaticallyPreparesContentKey]];
|
||||
[self setUsesLazyFetching:[aCoder decodeBoolForKey:CPObjectControllerUsesLazyFetchingKey]];
|
||||
_isUsingManagedProxy = [aCoder decodeBoolForKey:CPObjectControllerIsUsingManagedProxyKey];
|
||||
_managedProxy = [aCoder decodeObjectForKey:CPObjectControllerManagedProxyKey];
|
||||
|
||||
if (content != nil)
|
||||
[self setContent:content];
|
||||
|
||||
_observedKeys = [[CPCountedSet alloc] init];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[aCoder encodeObject:[self content] forKey:CPObjectControllerContentKey];
|
||||
|
||||
if (_objectClass)
|
||||
[aCoder encodeObject:CPStringFromClass(_objectClass) forKey:CPObjectControllerObjectClassNameKey];
|
||||
else if (_objectClassName)
|
||||
[aCoder encodeObject:_objectClassName forKey:CPObjectControllerObjectClassNameKey];
|
||||
|
||||
[aCoder encodeBool:[self isEditable] forKey:CPObjectControllerIsEditableKey];
|
||||
[aCoder encodeBool:[self automaticallyPreparesContent] forKey:CPObjectControllerAutomaticallyPreparesContentKey];
|
||||
[aCoder encodeBool:[self usesLazyFetching] forKey:CPObjectControllerUsesLazyFetchingKey];
|
||||
[aCoder encodeBool:_isUsingManagedProxy forKey:CPObjectControllerIsUsingManagedProxyKey];
|
||||
|
||||
if (_managedProxy)
|
||||
[aCoder encodeObject:_managedProxy forKey:CPObjectControllerManagedProxyKey];
|
||||
}
|
||||
|
||||
- (void)awakeFromCib
|
||||
{
|
||||
if (![self content] && [self automaticallyPreparesContent])
|
||||
[self prepareContent];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPObservationProxy : CPObject
|
||||
{
|
||||
id _keyPath;
|
||||
id _observer;
|
||||
id _object;
|
||||
|
||||
BOOL _notifyObject;
|
||||
|
||||
id _context;
|
||||
int _options;
|
||||
}
|
||||
|
||||
- (id)initWithKeyPath:(id)aKeyPath observer:(id)anObserver object:(id)anObject
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_keyPath = aKeyPath;
|
||||
_observer = anObserver;
|
||||
_object = anObject;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)observer
|
||||
{
|
||||
return _observer;
|
||||
}
|
||||
|
||||
- (id)keyPath
|
||||
{
|
||||
return _keyPath;
|
||||
}
|
||||
|
||||
- (id)context
|
||||
{
|
||||
return _context;
|
||||
}
|
||||
|
||||
- (int)options
|
||||
{
|
||||
return _options;
|
||||
}
|
||||
|
||||
- (void)setNotifyObject:(BOOL)notify
|
||||
{
|
||||
_notifyObject = notify;
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)anObject
|
||||
{
|
||||
if (self === anObject)
|
||||
return YES;
|
||||
|
||||
if (!anObject || [anObject class] !== [self class] || anObject._observer !== _observer || anObject._keyPath !== _keyPath || anObject._object !== _object)
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)change context:(id)context
|
||||
{
|
||||
if (_notifyObject)
|
||||
[_object observeValueForKeyPath:aKeyPath ofObject:_object change:change context:context];
|
||||
|
||||
[_observer observeValueForKeyPath:aKeyPath ofObject:_object change:change context:context];
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return [super description] + [CPString stringWithFormat:@"observation proxy for %@ on key path %@", _observer, _keyPath];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
// FIXME: This should subclass CPMutableArray not _CPJavaScriptArray
|
||||
@implementation _CPObservableArray : _CPJavaScriptArray
|
||||
{
|
||||
CPArray _observationProxies;
|
||||
}
|
||||
|
||||
+ (id)alloc
|
||||
{
|
||||
var a = [];
|
||||
a.isa = self;
|
||||
|
||||
var ivars = class_copyIvarList(self),
|
||||
count = ivars.length;
|
||||
|
||||
while (count--)
|
||||
a[ivar_getName(ivars[count])] = nil;
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return "<_CPObservableArray: " + [super description] + " >";
|
||||
}
|
||||
|
||||
- (id)initWithArray:(CPArray)anArray
|
||||
{
|
||||
self = [super initWithArray:anArray];
|
||||
|
||||
self.isa = [_CPObservableArray class];
|
||||
self._observationProxies = [];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)addObserver:(id)anObserver forKeyPath:(CPString)aKeyPath options:(CPKeyValueObservingOptions)options context:(id)context
|
||||
{
|
||||
if (aKeyPath.charAt(0) === "@")
|
||||
{
|
||||
// Simple collection operators are scalar and can't be proxied
|
||||
if ([_CPCollectionKVCOperator isSimpleCollectionOperator:aKeyPath])
|
||||
return;
|
||||
|
||||
var proxy = [[_CPObservationProxy alloc] initWithKeyPath:aKeyPath observer:anObserver object:self];
|
||||
|
||||
proxy._options = options;
|
||||
proxy._context = context;
|
||||
|
||||
[_observationProxies addObject:proxy];
|
||||
|
||||
var dotIndex = aKeyPath.indexOf("."),
|
||||
remaining = aKeyPath.substring(dotIndex + 1),
|
||||
indexes = [CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, [self count])];
|
||||
|
||||
[self addObserver:proxy toObjectsAtIndexes:indexes forKeyPath:remaining options:options context:context];
|
||||
}
|
||||
else
|
||||
{
|
||||
var indexes = [CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, [self count])];
|
||||
[self addObserver:anObserver toObjectsAtIndexes:indexes forKeyPath:aKeyPath options:options context:context];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)removeObserver:(id)anObserver forKeyPath:(CPString)aKeyPath
|
||||
{
|
||||
if (aKeyPath.charAt(0) === "@")
|
||||
{
|
||||
// Simple collection operators are scalar and can't be proxied
|
||||
if ([_CPCollectionKVCOperator isSimpleCollectionOperator:aKeyPath])
|
||||
return;
|
||||
|
||||
var proxy = [[_CPObservationProxy alloc] initWithKeyPath:aKeyPath observer:anObserver object:self],
|
||||
index = [_observationProxies indexOfObject:proxy];
|
||||
|
||||
proxy = [_observationProxies objectAtIndex:index];
|
||||
|
||||
var dotIndex = aKeyPath.indexOf("."),
|
||||
remaining = aKeyPath.substring(dotIndex + 1),
|
||||
indexes = [CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, [self count])];
|
||||
|
||||
[self removeObserver:proxy fromObjectsAtIndexes:indexes forKeyPath:remaining];
|
||||
}
|
||||
else
|
||||
{
|
||||
var indexes = [CPIndexSet indexSetWithIndexesInRange:CPMakeRange(0, [self count])];
|
||||
[self removeObserver:anObserver fromObjectsAtIndexes:indexes forKeyPath:aKeyPath];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)insertObject:(id)anObject atIndex:(CPUInteger)anIndex
|
||||
{
|
||||
for (var i = 0, count = [_observationProxies count]; i < count; i++)
|
||||
{
|
||||
var proxy = [_observationProxies objectAtIndex:i],
|
||||
keyPath = [proxy keyPath],
|
||||
operator = keyPath.charAt(0) === ".";
|
||||
|
||||
if (operator)
|
||||
[self willChangeValueForKey:keyPath];
|
||||
|
||||
[anObject addObserver:proxy forKeyPath:keyPath options:[proxy options] context:[proxy context]];
|
||||
|
||||
if (operator)
|
||||
[self didChangeValueForKey:keyPath];
|
||||
}
|
||||
|
||||
[super insertObject:anObject atIndex:anIndex];
|
||||
}
|
||||
|
||||
- (void)removeObjectAtIndex:(CPUInteger)anIndex
|
||||
{
|
||||
var currentObject = [self objectAtIndex:anIndex];
|
||||
|
||||
for (var i = 0, count = [_observationProxies count]; i < count; i++)
|
||||
{
|
||||
var proxy = [_observationProxies objectAtIndex:i],
|
||||
keyPath = [proxy keyPath],
|
||||
operator = keyPath.charAt(0) === ".";
|
||||
|
||||
if (operator)
|
||||
[self willChangeValueForKey:keyPath];
|
||||
|
||||
[currentObject removeObserver:proxy forKeyPath:keyPath];
|
||||
|
||||
if (operator)
|
||||
[self didChangeValueForKey:keyPath];
|
||||
}
|
||||
|
||||
[super removeObjectAtIndex:anIndex];
|
||||
}
|
||||
|
||||
- (CPArray)objectsAtIndexes:(CPIndexSet)theIndexes
|
||||
{
|
||||
return [_CPObservableArray arrayWithArray:[super objectsAtIndexes:theIndexes]];
|
||||
}
|
||||
|
||||
- (void)addObject:(id)anObject
|
||||
{
|
||||
[self insertObject:anObject atIndex:[self count]];
|
||||
}
|
||||
|
||||
- (void)removeLastObject
|
||||
{
|
||||
[self removeObjectAtIndex:[self count]];
|
||||
}
|
||||
|
||||
- (void)replaceObjectAtIndex:(CPUInteger)anIndex withObject:(id)anObject
|
||||
{
|
||||
var currentObject = [self objectAtIndex:anIndex];
|
||||
|
||||
for (var i = 0, count = [_observationProxies count]; i < count; i++)
|
||||
{
|
||||
var proxy = [_observationProxies objectAtIndex:i],
|
||||
keyPath = [proxy keyPath],
|
||||
operator = keyPath.charAt(0) === ".";
|
||||
|
||||
if (operator)
|
||||
[self willChangeValueForKey:keyPath];
|
||||
|
||||
[currentObject removeObserver:proxy forKeyPath:keyPath];
|
||||
[anObject addObserver:proxy forKeyPath:keyPath options:[proxy options] context:[proxy context]];
|
||||
|
||||
if (operator)
|
||||
[self didChangeValueForKey:keyPath];
|
||||
}
|
||||
|
||||
[super replaceObjectAtIndex:anIndex withObject:anObject];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPControllerSelectionProxy : CPObject
|
||||
{
|
||||
id _controller;
|
||||
id _keys;
|
||||
|
||||
CPDictionary _cachedValues;
|
||||
CPArray _observationProxies;
|
||||
|
||||
Object _observedObjectsByKeyPath;
|
||||
}
|
||||
|
||||
- (id)initWithController:(id)aController
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_cachedValues = @{};
|
||||
_observationProxies = [CPArray array];
|
||||
_controller = aController;
|
||||
_observedObjectsByKeyPath = {};
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)_controllerMarkerForValues:(CPArray)theValues
|
||||
{
|
||||
var count = [theValues count],
|
||||
value;
|
||||
|
||||
if (!count)
|
||||
value = CPNoSelectionMarker;
|
||||
else if (count === 1)
|
||||
value = [theValues objectAtIndex:0];
|
||||
else
|
||||
{
|
||||
if ([_controller alwaysUsesMultipleValuesMarker])
|
||||
value = CPMultipleValuesMarker;
|
||||
else
|
||||
{
|
||||
value = [theValues objectAtIndex:0];
|
||||
|
||||
for (var i = 0, count = [theValues count]; i < count && value != CPMultipleValuesMarker; i++)
|
||||
{
|
||||
if (![value isEqual:[theValues objectAtIndex:i]])
|
||||
value = CPMultipleValuesMarker;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (value == nil || value.isa && [value isEqual:[CPNull null]])
|
||||
value = CPNullMarker;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
- (id)valueForKeyPath:(CPString)theKeyPath
|
||||
{
|
||||
var values = [[_controller selectedObjects] valueForKeyPath:theKeyPath];
|
||||
|
||||
// Simple collection operators like @count return a scalar value, not an array or set
|
||||
if ([values isKindOfClass:CPArray] || [values isKindOfClass:CPSet])
|
||||
{
|
||||
var value = [self _controllerMarkerForValues:values];
|
||||
[_cachedValues setObject:value forKey:theKeyPath];
|
||||
|
||||
return value;
|
||||
}
|
||||
else
|
||||
return values;
|
||||
}
|
||||
|
||||
- (id)valueForKey:(CPString)theKeyPath
|
||||
{
|
||||
return [self valueForKeyPath:theKeyPath];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)theValue forKeyPath:(CPString)theKeyPath
|
||||
{
|
||||
[[_controller selectedObjects] setValue:theValue forKeyPath:theKeyPath];
|
||||
[_cachedValues removeObjectForKey:theKeyPath];
|
||||
|
||||
// Allow handlesContentAsCompoundValue to work, based on observation of Cocoa's
|
||||
// NSArrayController - when handlesContentAsCompoundValue and setValue:forKey:@"selection.X"
|
||||
// is called, the array controller causes the compound value to be rewritten if
|
||||
// handlesContentAsCompoundValue == YES. Note that
|
||||
// A) this doesn't use observation (observe: X is not visible in backtraces)
|
||||
// B) it only happens through the selection proxy and not on arrangedObject.X, content.X
|
||||
// or even selectedObjects.X.
|
||||
// FIXME The main code for this should somehow be in CPArrayController and also work
|
||||
// for table based row edits.
|
||||
[[CPBinder getBinding:@"contentArray" forObject:_controller] _contentArrayDidChange];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)theValue forKey:(CPString)theKeyPath
|
||||
{
|
||||
[self setValue:theValue forKeyPath:theKeyPath];
|
||||
}
|
||||
|
||||
- (unsigned)count
|
||||
{
|
||||
return [_cachedValues count];
|
||||
}
|
||||
|
||||
- (id)keyEnumerator
|
||||
{
|
||||
return [_cachedValues keyEnumerator];
|
||||
}
|
||||
|
||||
- (void)controllerWillChange
|
||||
{
|
||||
_keys = [_cachedValues allKeys];
|
||||
|
||||
if (!_keys)
|
||||
return;
|
||||
|
||||
for (var i = 0, count = _keys.length; i < count; i++)
|
||||
[self willChangeValueForKey:_keys[i]];
|
||||
|
||||
[_cachedValues removeAllObjects];
|
||||
}
|
||||
|
||||
- (void)controllerDidChange
|
||||
{
|
||||
[_cachedValues removeAllObjects];
|
||||
|
||||
if (!_keys)
|
||||
return;
|
||||
|
||||
for (var i = 0, count = _keys.length; i < count; i++)
|
||||
[self didChangeValueForKey:_keys[i]];
|
||||
|
||||
_keys = nil;
|
||||
}
|
||||
|
||||
- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)change context:(id)context
|
||||
{
|
||||
[_cachedValues removeObjectForKey:aKeyPath];
|
||||
}
|
||||
|
||||
- (void)addObserver:(id)anObject forKeyPath:(CPString)aKeyPath options:(CPKeyValueObservingOptions)options context:(id)context
|
||||
{
|
||||
var proxy = [[_CPObservationProxy alloc] initWithKeyPath:aKeyPath observer:anObject object:self];
|
||||
|
||||
[proxy setNotifyObject:YES];
|
||||
[_observationProxies addObject:proxy];
|
||||
|
||||
// We keep a reference to the observed objects because removeObserver: will be called after the selection changes.
|
||||
var observedObjects = [_controller selectedObjects];
|
||||
_observedObjectsByKeyPath[aKeyPath] = observedObjects;
|
||||
[observedObjects addObserver:proxy forKeyPath:aKeyPath options:options context:context];
|
||||
}
|
||||
|
||||
- (void)removeObserver:(id)anObject forKeyPath:(CPString)aKeyPath
|
||||
{
|
||||
[_observationProxies enumerateObjectsUsingBlock:function(aProxy, idx, stop)
|
||||
{
|
||||
if (aProxy._object === self && aProxy._keyPath == aKeyPath && aProxy._observer === anObject)
|
||||
{
|
||||
var observedObjects = _observedObjectsByKeyPath[aKeyPath];
|
||||
|
||||
[observedObjects removeObserver:aProxy forKeyPath:aKeyPath];
|
||||
[_observationProxies removeObjectAtIndex:idx];
|
||||
|
||||
_observedObjectsByKeyPath[aKeyPath] = nil;
|
||||
|
||||
stop(YES);
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation _CPManagedProxy : CPObject
|
||||
{
|
||||
CPString _entityName @accessors(getter=entityName, setter=setEntityName:);
|
||||
CPPredicate _fetchPredicate @accessors(getter=fetchPredicate, setter=setFetchPredicate:);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPManagedProxyEntityNameKey = @"CPManagedProxyEntityNameKey",
|
||||
CPManagedProxyFetchPredicateKey = @"CPManagedProxyFetchPredicateKey";
|
||||
|
||||
@implementation _CPManagedProxy (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self setEntityName:[aCoder decodeObjectForKey:CPManagedProxyEntityNameKey]];
|
||||
[self setFetchPredicate:[aCoder decodeObjectForKey:CPManagedProxyFetchPredicateKey]];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[aCoder encodeObject:[self entityName] forKey:CPManagedProxyEntityNameKey];
|
||||
[aCoder encodeObject:[self fetchPredicate] forKey:CPManagedProxyFetchPredicateKey];
|
||||
}
|
||||
|
||||
@end
|
||||
+3
-24
@@ -1,26 +1,5 @@
|
||||
/*
|
||||
* CPOpenPanel.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Ross Boucher.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPPanel.j"
|
||||
@import <AppKit/CPPanel.j>
|
||||
|
||||
|
||||
@implementation CPOpenPanel : CPPanel
|
||||
@@ -47,9 +26,9 @@
|
||||
var options = { directoryURL: [self directoryURL],
|
||||
canChooseFiles: [self canChooseFiles],
|
||||
canChooseDirectories: [self canChooseDirectories],
|
||||
allowsMultipleSelection: [self allowsMultipleSelection] },
|
||||
allowsMultipleSelection: [self allowsMultipleSelection] };
|
||||
|
||||
result = window.cpOpenPanel(options);
|
||||
var result = window.cpOpenPanel(options);
|
||||
|
||||
_URLs = result.URLs;
|
||||
|
||||
|
||||
+361
-1523
File diff suppressed because it is too large
Load Diff
+3
-29
@@ -22,14 +22,11 @@
|
||||
|
||||
@import "CPWindow.j"
|
||||
|
||||
@global CPApp
|
||||
|
||||
CPOKButton = 1;
|
||||
CPCancelButton = 0;
|
||||
|
||||
CPDocModalWindowMask = 1 << 6;
|
||||
|
||||
/*!
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPPanel
|
||||
|
||||
@@ -54,6 +51,8 @@ CPDocModalWindowMask = 1 << 6;
|
||||
@global
|
||||
@class CPWindow
|
||||
*/
|
||||
CPDocModalWindowMask = 1 << 6;
|
||||
|
||||
@implementation CPPanel : CPWindow
|
||||
{
|
||||
BOOL _becomesKeyOnlyIfNeeded;
|
||||
@@ -115,29 +114,4 @@ CPDocModalWindowMask = 1 << 6;
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)canBecomeKeyWindow
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Overrides
|
||||
|
||||
/*!
|
||||
@ignore
|
||||
*/
|
||||
- (void)cancelOperation:(id)sender
|
||||
{
|
||||
if ([[CPApp currentEvent] _couldBeKeyEquivalent] && [self performKeyEquivalent:[CPApp currentEvent]])
|
||||
return;
|
||||
|
||||
[[self firstResponder] tryToPerform:@selector(cancel:) with:self];
|
||||
}
|
||||
|
||||
- (void)cancel:(id)sender
|
||||
{
|
||||
[self performClose:sender];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+103
-47
@@ -22,13 +22,11 @@
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPArray.j>
|
||||
@import <Foundation/CPData.j>
|
||||
@import <Foundation/CPDictionary.j>
|
||||
@import <Foundation/CPPropertyListSerialization.j>
|
||||
|
||||
@class CPWebScriptObject
|
||||
#include "Platform/Platform.h"
|
||||
|
||||
@typedef DataTransfer
|
||||
|
||||
CPGeneralPboard = @"CPGeneralPboard";
|
||||
CPFontPboard = @"CPFontPboard";
|
||||
@@ -44,9 +42,6 @@ CPStringPboardType = @"CPStringPboardType";
|
||||
CPURLPboardType = @"CPURLPboardType";
|
||||
CPImagesPboardType = @"CPImagesPboardType";
|
||||
CPVideosPboardType = @"CPVideosPboardType";
|
||||
CPRTFPboardType = @"CPRTFPboardType";
|
||||
_CPSmartPboardType = @"_CPSmartPboardType";
|
||||
_CPASPboardType = @"_CPASPboardType";
|
||||
|
||||
UTF8PboardType = @"public.utf8-plain-text";
|
||||
|
||||
@@ -54,22 +49,25 @@ UTF8PboardType = @"public.utf8-plain-text";
|
||||
CPImagePboardType = @"CPImagePboardType";
|
||||
|
||||
|
||||
var CPPasteboards = nil;
|
||||
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;
|
||||
|
||||
WebScriptObject _nativePasteboard;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -77,12 +75,15 @@ var CPPasteboards = nil;
|
||||
*/
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPPasteboard class])
|
||||
if (self != [CPPasteboard class])
|
||||
return;
|
||||
|
||||
[self setVersion:1.0];
|
||||
|
||||
CPPasteboards = [CPDictionary dictionary];
|
||||
|
||||
CPPasteboards = @{};
|
||||
if (typeof window.cpPasteboardWithName !== "undefined")
|
||||
supportsNativePasteboard = YES;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -104,10 +105,10 @@ var CPPasteboards = nil;
|
||||
|
||||
if (pasteboard)
|
||||
return pasteboard;
|
||||
|
||||
|
||||
pasteboard = [[CPPasteboard alloc] _initWithName:aName];
|
||||
[CPPasteboards setObject:pasteboard forKey:aName];
|
||||
|
||||
|
||||
return pasteboard;
|
||||
}
|
||||
|
||||
@@ -115,18 +116,24 @@ var CPPasteboards = nil;
|
||||
- (id)_initWithName:(CPString)aName
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
// _name = aName;
|
||||
_name = aName;
|
||||
_types = [];
|
||||
|
||||
_owners = @{};
|
||||
_provided = @{};
|
||||
|
||||
|
||||
_owners = [CPDictionary dictionary];
|
||||
_provided = [CPDictionary dictionary];
|
||||
|
||||
_changeCount = 0;
|
||||
}
|
||||
|
||||
if (supportsNativePasteboard)
|
||||
{
|
||||
_nativePasteboard = window.cpPasteboardWithName(aName);
|
||||
[self _synchronizePasteboard];
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -140,20 +147,29 @@ 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];
|
||||
}
|
||||
|
||||
if (_nativePasteboard)
|
||||
{
|
||||
var nativeTypes = [types copy];
|
||||
if ([types containsObject:CPStringPboardType])
|
||||
nativeTypes.push(UTF8PboardType);
|
||||
|
||||
_nativePasteboard.addTypes_(nativeTypes);
|
||||
}
|
||||
|
||||
return ++_changeCount;
|
||||
}
|
||||
|
||||
@@ -164,19 +180,32 @@ var CPPasteboards = nil;
|
||||
@return the pasteboard's change count
|
||||
*/
|
||||
- (unsigned)declareTypes:(CPArray)types owner:(id)anOwner
|
||||
{
|
||||
[self _declareTypes:types owner:anOwner updateNativePasteboard:YES];
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (unsigned)_declareTypes:(CPArray)types owner:(id)anOwner updateNativePasteboard:(BOOL)shouldUpdate
|
||||
{
|
||||
[_types setArray:types];
|
||||
|
||||
_owners = @{};
|
||||
_provided = @{};
|
||||
_owners = [CPDictionary dictionary];
|
||||
_provided = [CPDictionary dictionary];
|
||||
|
||||
if (anOwner)
|
||||
var count = _types.length;
|
||||
|
||||
while (count--)
|
||||
[_owners setObject:anOwner forKey:_types[count]];
|
||||
|
||||
if (_nativePasteboard && shouldUpdate)
|
||||
{
|
||||
var count = _types.length;
|
||||
while (count--)
|
||||
[_owners setObject:anOwner forKey:_types[count]];
|
||||
}
|
||||
var nativeTypes = [types copy];
|
||||
if ([types containsObject:CPStringPboardType])
|
||||
nativeTypes.push(UTF8PboardType);
|
||||
|
||||
_nativePasteboard.declareTypes_(nativeTypes);
|
||||
_changeCount = _nativePasteboard.changeCount();
|
||||
}
|
||||
return ++_changeCount;
|
||||
}
|
||||
|
||||
@@ -215,23 +244,19 @@ var CPPasteboards = nil;
|
||||
*/
|
||||
- (void)setString:(CPString)aString forType:(CPString)aType
|
||||
{
|
||||
// Putting a non-string on the string pasteboard can lead to strange crashes.
|
||||
if (aString && aString.isa && ![aString isKindOfClass:CPString])
|
||||
[CPException raise:CPInvalidArgumentException reason:"CPPasteboard setString:forType: must be called with a string."];
|
||||
|
||||
[self setPropertyList:aString forType:aType];
|
||||
}
|
||||
|
||||
// Determining Types
|
||||
/*!
|
||||
Checks the pasteboard's types for a match with the types listed in the specified array. The array should
|
||||
Checks the pasteboard's types for a match with the types listen in the specified array. The array should
|
||||
be ordered by the requestor's most preferred data type first.
|
||||
@param anArray an array of requested types ordered by preference
|
||||
@return the highest match with the pasteboard's supported types or \c nil if no match was found
|
||||
*/
|
||||
- (CPString)availableTypeFromArray:(CPArray)anArray
|
||||
{
|
||||
return [anArray firstObjectCommonWithArray:[self types]];
|
||||
return [[self types] firstObjectCommonWithArray:anArray];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -239,6 +264,7 @@ var CPPasteboards = nil;
|
||||
*/
|
||||
- (CPArray)types
|
||||
{
|
||||
[self _synchronizePasteboard];
|
||||
return _types;
|
||||
}
|
||||
|
||||
@@ -259,24 +285,54 @@ 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];
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)_synchronizePasteboard
|
||||
{
|
||||
if (_nativePasteboard && _nativePasteboard.changeCount() > _changeCount)
|
||||
{
|
||||
var nativeTypes = [_nativePasteboard.types() copy];
|
||||
if ([nativeTypes containsObject:UTF8PboardType])
|
||||
nativeTypes.push(CPStringPboardType);
|
||||
|
||||
[self _declareTypes:nativeTypes owner:self updateNativePasteboard:NO];
|
||||
|
||||
_changeCount = _nativePasteboard.changeCount();
|
||||
}
|
||||
}
|
||||
|
||||
/*! @ignore
|
||||
method provided for integration with native pasteboard
|
||||
*/
|
||||
- (void)pasteboard:(CPPasteboard)aPasteboard provideDataForType:(CPString)aType
|
||||
{
|
||||
if (aType === CPStringPboardType)
|
||||
{
|
||||
var string = _nativePasteboard.stringForType_(UTF8PboardType);
|
||||
|
||||
[self setString:string forType:CPStringPboardType];
|
||||
[self setString:string forType:UTF8PboardType];
|
||||
}
|
||||
else
|
||||
[self setString:_nativePasteboard.stringForType_(aType) forType:aType];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the property list for the specified data type
|
||||
@param aType the requested data type
|
||||
@@ -285,10 +341,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;
|
||||
}
|
||||
|
||||
@@ -306,9 +362,9 @@ var CPPasteboards = nil;
|
||||
- (CPString)_generateStateUID
|
||||
{
|
||||
var bits = 32;
|
||||
|
||||
|
||||
_stateUID = @"";
|
||||
|
||||
|
||||
while (bits--)
|
||||
_stateUID += FLOOR(RAND() * 16.0).toString(16).toUpperCase();
|
||||
|
||||
|
||||
+236
-600
File diff suppressed because it is too large
Load Diff
@@ -1,420 +0,0 @@
|
||||
/*
|
||||
* CPPopover.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Antoine Mercadal.
|
||||
* Copyright 2011 Antoine Mercadal.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
|
||||
@import "CPButton.j"
|
||||
@import "CPColor.j"
|
||||
@import "CPImage.j"
|
||||
@import "CPImageView.j"
|
||||
@import "CPResponder.j"
|
||||
@import "CPView.j"
|
||||
@import "CPViewController.j"
|
||||
@import "_CPPopoverWindow.j"
|
||||
|
||||
@protocol CPPopoverDelegate <CPObject>
|
||||
|
||||
@optional
|
||||
- (BOOL)popoverShouldClose:(CPPopover)aPopover;
|
||||
- (void)popoverWillClose:(CPPopover)aPopover;
|
||||
- (void)popoverDidClose:(CPPopover)aPopover;
|
||||
- (void)popoverWillShow:(CPPopover)aPopover;
|
||||
- (void)popoverDidShow:(CPPopover)aPopover;
|
||||
|
||||
@end
|
||||
|
||||
CPPopoverBehaviorApplicationDefined = 0;
|
||||
CPPopoverBehaviorTransient = 1;
|
||||
CPPopoverBehaviorSemitransient = 2;
|
||||
|
||||
var CPPopoverDelegate_popover_willShow_ = 1 << 0,
|
||||
CPPopoverDelegate_popover_didShow_ = 1 << 1,
|
||||
CPPopoverDelegate_popover_shouldClose_ = 1 << 2,
|
||||
CPPopoverDelegate_popover_willClose_ = 1 << 3,
|
||||
CPPopoverDelegate_popover_didClose_ = 1 << 4;
|
||||
|
||||
|
||||
/*! @ingroup appkit
|
||||
@class CPPopover
|
||||
|
||||
This class represent a widget that displays a popover
|
||||
view relative to another one.
|
||||
|
||||
Delegate can implement:
|
||||
|
||||
@code
|
||||
– popoverShouldClose:(CPPopover)aPopOver
|
||||
– popoverWillShow:(CPPopover)aPopOver
|
||||
– popoverDidShow:(CPPopover)aPopOver
|
||||
– popoverWillClose:(CPPopover)aPopOver
|
||||
– popoverDidClose:(CPPopover)aPopOver
|
||||
@endcode
|
||||
*/
|
||||
@implementation CPPopover : CPResponder
|
||||
{
|
||||
@outlet CPViewController _contentViewController @accessors(property=contentViewController);
|
||||
@outlet id <CPPopoverDelegate> _delegate @accessors(getter=delegate);
|
||||
|
||||
BOOL _animates @accessors(getter=animates);
|
||||
int _appearance @accessors(property=appearance);
|
||||
int _behavior @accessors(getter=behavior);
|
||||
|
||||
_CPPopoverWindow _popoverWindow;
|
||||
CPView _positioningView;
|
||||
int _implementedDelegateMethods;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Initialization
|
||||
|
||||
/*!
|
||||
Initialize the CPPopover witn default values
|
||||
|
||||
@returns an initialized CPPopover
|
||||
*/
|
||||
- (CPPopover)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_animates = YES;
|
||||
_appearance = CPPopoverAppearanceMinimal;
|
||||
_behavior = CPPopoverBehaviorApplicationDefined;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Getters / Setters
|
||||
|
||||
/*!
|
||||
Returns the current rect of the popover
|
||||
|
||||
@return CGRect representing the frame of the popover
|
||||
*/
|
||||
- (CGRect)positioningRect
|
||||
{
|
||||
if (![_popoverWindow isVisible])
|
||||
return CGRectMakeZero();
|
||||
|
||||
return [_popoverWindow frame];
|
||||
}
|
||||
|
||||
/*! Sets the frame of the popover
|
||||
@param aRect the desired frame
|
||||
*/
|
||||
- (void)setPositioningRect:(CGRect)aRect
|
||||
{
|
||||
if (![_popoverWindow isVisible])
|
||||
return;
|
||||
|
||||
[_popoverWindow setFrame:aRect];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the size of the popover's view
|
||||
|
||||
@return CGSize representing the size of the popover's view
|
||||
*/
|
||||
- (CGSize)contentSize
|
||||
{
|
||||
return [[_contentViewController view] frameSize];
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the size of of the popover's view
|
||||
|
||||
@param aSize the desired size
|
||||
*/
|
||||
- (void)setContentSize:(CGSize)aSize
|
||||
{
|
||||
if (!_popoverWindow)
|
||||
[[_contentViewController view] setFrameSize:aSize];
|
||||
else
|
||||
[_popoverWindow updateFrameWithSize:aSize];
|
||||
}
|
||||
|
||||
/*!
|
||||
Indicates if CPPopover is visible
|
||||
|
||||
@returns \c YES if visible
|
||||
*/
|
||||
- (BOOL)isShown
|
||||
{
|
||||
return [_popoverWindow isVisible];
|
||||
}
|
||||
|
||||
/*!
|
||||
Set if the popover should animate for open/close actions.
|
||||
|
||||
@param shouldAnimate if YES, the popover will be animated.
|
||||
*/
|
||||
- (void)setAnimates:(BOOL)shouldAnimate
|
||||
{
|
||||
if (_animates == shouldAnimate)
|
||||
return;
|
||||
|
||||
_animates = shouldAnimate;
|
||||
[_popoverWindow setAnimates:_animates];
|
||||
}
|
||||
|
||||
/*!
|
||||
Set the behavior of the CPPopover. It can be:
|
||||
|
||||
- \c CPPopoverBehaviorTransient: the popover will close if another control outside the popover becomes the responder
|
||||
- \c CPPopoverBehaviorApplicationDefined: (DEFAULT) the application is responsible for closing the popover
|
||||
|
||||
@param aBehavior the desired behavior
|
||||
*/
|
||||
- (void)setBehavior:(int)aBehavior
|
||||
{
|
||||
if (_behavior == aBehavior)
|
||||
return;
|
||||
|
||||
_behavior = aBehavior;
|
||||
[_popoverWindow setStyleMask:[self _styleMaskForBehavior]];
|
||||
}
|
||||
|
||||
- (void)setDelegate:(id <CPPopoverDelegate>)aDelegate
|
||||
{
|
||||
if (_delegate === aDelegate)
|
||||
return;
|
||||
|
||||
_delegate = aDelegate;
|
||||
_implementedDelegateMethods = 0;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(popoverWillShow:)])
|
||||
_implementedDelegateMethods |= CPPopoverDelegate_popover_willShow_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(popoverDidShow:)])
|
||||
_implementedDelegateMethods |= CPPopoverDelegate_popover_didShow_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(popoverShouldClose:)])
|
||||
_implementedDelegateMethods |= CPPopoverDelegate_popover_shouldClose_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(popoverWillClose:)])
|
||||
_implementedDelegateMethods |= CPPopoverDelegate_popover_willClose_;
|
||||
|
||||
if ([_delegate respondsToSelector:@selector(popoverDidClose:)])
|
||||
_implementedDelegateMethods |= CPPopoverDelegate_popover_didClose_;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Positioning
|
||||
|
||||
/*!
|
||||
Show the popover
|
||||
|
||||
@param positioningRect if set, the popover will be positionned to a random rect relative to the window
|
||||
@param positioningView if set, the popover will be positioned relative to this view
|
||||
@param preferredEdge: \c CPRectEdge representing the preferred positioning.
|
||||
*/
|
||||
- (void)showRelativeToRect:(CGRect)positioningRect ofView:(CPView)positioningView preferredEdge:(CPRectEdge)preferredEdge
|
||||
{
|
||||
if (!positioningView)
|
||||
[CPException raise:CPInvalidArgumentException reason:"positionView must not be nil"];
|
||||
|
||||
if (!_contentViewController)
|
||||
[CPException raise:CPInternalInconsistencyException reason:@"contentViewController must not be nil"];
|
||||
|
||||
// If the popover is currently closing or opening, do nothing. That is what Cocoa does.
|
||||
if ([_popoverWindow isClosing] || [_popoverWindow isOpening])
|
||||
return;
|
||||
|
||||
_positioningView = positioningView;
|
||||
|
||||
if (!_popoverWindow)
|
||||
_popoverWindow = [[_CPPopoverWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:[self _styleMaskForBehavior]];
|
||||
|
||||
[_popoverWindow setPlatformWindow:[[positioningView window] platformWindow]];
|
||||
[_popoverWindow setAppearance:_appearance];
|
||||
[_popoverWindow setAnimates:_animates];
|
||||
[_popoverWindow setDelegate:self];
|
||||
[_popoverWindow setMovableByWindowBackground:NO];
|
||||
[_popoverWindow setFrame:[_popoverWindow frameRectForContentRect:[[_contentViewController view] frame]]];
|
||||
[_popoverWindow setContentView:[_contentViewController view]];
|
||||
|
||||
if (![self isShown])
|
||||
[self _popoverWillShow];
|
||||
|
||||
[_popoverWindow positionRelativeToRect:positioningRect ofView:positioningView preferredEdge:preferredEdge];
|
||||
|
||||
if (![self isShown])
|
||||
[self _popoverWindowDidShow];
|
||||
}
|
||||
|
||||
- (unsigned)_styleMaskForBehavior
|
||||
{
|
||||
if (_behavior == CPPopoverBehaviorApplicationDefined)
|
||||
return 0;
|
||||
|
||||
return CPClosableOnBlurWindowMask
|
||||
}
|
||||
|
||||
/*!
|
||||
Closes the popover
|
||||
*/
|
||||
- (void)close
|
||||
{
|
||||
[self _close];
|
||||
}
|
||||
|
||||
/*!
|
||||
Closes the popover
|
||||
*/
|
||||
- (void)_close
|
||||
{
|
||||
if ([_popoverWindow isClosing] || ![self isShown])
|
||||
return;
|
||||
|
||||
[self _popoverWillClose];
|
||||
|
||||
_positioningView = nil;
|
||||
[_popoverWindow close];
|
||||
|
||||
// popoverDidClose will be sent from popoverWindowDidClose, since
|
||||
// the popover window will close asynchronously when animating.
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Action
|
||||
|
||||
/*!
|
||||
Close the popover
|
||||
|
||||
@param sender the sender of the action
|
||||
*/
|
||||
- (IBAction)performClose:(id)sender
|
||||
{
|
||||
if ([_popoverWindow isClosing])
|
||||
return;
|
||||
|
||||
if (![self _popoverShouldClose])
|
||||
return;
|
||||
|
||||
[self _close];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Delegates
|
||||
|
||||
/*! @ignore */
|
||||
- (BOOL)_popoverWindowShouldClose
|
||||
{
|
||||
[self performClose:self];
|
||||
|
||||
// We return NO, because we want the CPPopover to determine
|
||||
// if the popover window can be closed and to give us a chance
|
||||
// to send delegate messages.
|
||||
return NO;
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (void)_popoverWindowDidClose
|
||||
{
|
||||
if (_implementedDelegateMethods & CPPopoverDelegate_popover_didClose_)
|
||||
[_delegate popoverDidClose:self];
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (void)_popoverWindowDidShow
|
||||
{
|
||||
if (_implementedDelegateMethods & CPPopoverDelegate_popover_didShow_)
|
||||
[_delegate popoverDidShow:self];
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (BOOL)_popoverShouldClose
|
||||
{
|
||||
if (_implementedDelegateMethods & CPPopoverDelegate_popover_shouldClose_)
|
||||
return [_delegate popoverShouldClose:self];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (void)_popoverWillClose
|
||||
{
|
||||
if (_implementedDelegateMethods & CPPopoverDelegate_popover_willClose_)
|
||||
[_delegate popoverWillClose:self];
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (void)_popoverWillShow
|
||||
{
|
||||
if (_implementedDelegateMethods & CPPopoverDelegate_popover_willShow_)
|
||||
[_delegate popoverWillShow:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPPopover (Deprecated)
|
||||
|
||||
- (void)setBehaviour:(int)aBehavior
|
||||
{
|
||||
_CPReportLenientDeprecation(self, _cmd, @selector(setBehavior:));
|
||||
|
||||
[self setBehavior:aBehavior];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPPopoverNeedsNewPopoverWindowKey = @"CPPopoverNeedsNewPopoverWindowKey",
|
||||
CPPopoverAppearanceKey = @"CPPopoverAppearanceKey",
|
||||
CPPopoverAnimatesKey = @"CPPopoverAnimatesKey",
|
||||
CPPopoverContentViewControllerKey = @"CPPopoverContentViewControllerKey",
|
||||
CPPopoverDelegateKey = @"CPPopoverDelegateKey",
|
||||
CPPopoverBehaviorKey = @"CPPopoverBehaviorKey";
|
||||
|
||||
@implementation CPPopover (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_appearance = [aCoder decodeIntForKey:CPPopoverAppearanceKey];
|
||||
_animates = [aCoder decodeBoolForKey:CPPopoverAnimatesKey];
|
||||
_contentViewController = [aCoder decodeObjectForKey:CPPopoverContentViewControllerKey];
|
||||
[self setDelegate:[aCoder decodeObjectForKey:CPPopoverDelegateKey]];
|
||||
[self setBehavior:[aCoder decodeIntForKey:CPPopoverBehaviorKey]];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
[aCoder encodeInt:_appearance forKey:CPPopoverAppearanceKey];
|
||||
[aCoder encodeBool:_animates forKey:CPPopoverAnimatesKey];
|
||||
[aCoder encodeObject:_contentViewController forKey:CPPopoverContentViewControllerKey];
|
||||
[aCoder encodeObject:_delegate forKey:CPPopoverDelegateKey];
|
||||
[aCoder encodeInt:_behavior forKey:CPPopoverBehaviorKey];
|
||||
}
|
||||
|
||||
@end
|
||||
+140
-261
@@ -20,32 +20,36 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CGGeometry.j"
|
||||
@import "CPImageView.j"
|
||||
@import "CPView.j"
|
||||
@import "CPWindow_Constants.j"
|
||||
@import <AppKit/CGGeometry.j>
|
||||
@import <AppKit/CPImageView.j>
|
||||
@import <AppKit/CPView.j>
|
||||
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
|
||||
@typedef CPProgressIndicatorStyle
|
||||
/*
|
||||
@global
|
||||
@group CPProgressIndicatorStyle
|
||||
*/
|
||||
CPProgressIndicatorBarStyle = 0;
|
||||
CPProgressIndicatorBarStyle = 0;
|
||||
/*
|
||||
@global
|
||||
@group CPProgressIndicatorStyle
|
||||
*/
|
||||
CPProgressIndicatorSpinningStyle = 1;
|
||||
CPProgressIndicatorSpinningStyle = 1;
|
||||
/*
|
||||
@global
|
||||
@group CPProgressIndicatorStyle
|
||||
*/
|
||||
CPProgressIndicatorHUDBarStyle = 2;
|
||||
CPProgressIndicatorHUDBarStyle = 2;
|
||||
|
||||
var CPProgressIndicatorSpinningStyleColors = [];
|
||||
var CPProgressIndicatorSpinningStyleColors = nil,
|
||||
|
||||
/*!
|
||||
CPProgressIndicatorClassName = nil,
|
||||
CPProgressIndicatorStyleIdentifiers = nil,
|
||||
CPProgressIndicatorStyleSizes = nil;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPProgressIndicator
|
||||
|
||||
@@ -57,68 +61,104 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
{
|
||||
double _minValue;
|
||||
double _maxValue;
|
||||
|
||||
|
||||
double _doubleValue;
|
||||
|
||||
|
||||
CPControlSize _controlSize;
|
||||
|
||||
BOOL _indeterminate;
|
||||
|
||||
BOOL _isIndeterminate;
|
||||
CPProgressIndicatorStyle _style;
|
||||
|
||||
|
||||
BOOL _isAnimating;
|
||||
|
||||
|
||||
BOOL _isDisplayedWhenStoppedSet;
|
||||
BOOL _isDisplayedWhenStopped;
|
||||
|
||||
CPView _barView;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
/*
|
||||
@ignore
|
||||
*/
|
||||
+ (void)initialize
|
||||
{
|
||||
return @"progress-indicator";
|
||||
}
|
||||
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:
|
||||
[bundle pathForResource:@"CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif"] size:CGSizeMake(64.0, 64.0)]];
|
||||
CPProgressIndicatorSpinningStyleColors[CPRegularControlSize] = [CPColor colorWithPatternImage:[[CPImage alloc] initWithContentsOfFile:
|
||||
[bundle pathForResource:@"CPProgressIndicator/CPProgressIndicatorSpinningStyleRegular.gif"] size:CGSizeMake(64.0, 64.0)]];
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"indeterminate-bar-color": [CPNull null],
|
||||
@"bar-color": [CPNull null],
|
||||
@"default-height": 20,
|
||||
@"bezel-color": [CPNull null],
|
||||
@"spinning-mini-gif": [CPNull null],
|
||||
@"spinning-small-gif": [CPNull null],
|
||||
@"spinning-regular-gif": [CPNull null],
|
||||
@"circular-border-color": [CPNull null],
|
||||
@"circular-border-size": 1,
|
||||
@"circular-color": [CPNull null]
|
||||
};
|
||||
}
|
||||
CPProgressIndicatorBezelBorderViewPool = [];
|
||||
|
||||
var start = CPProgressIndicatorBarStyle,
|
||||
end = CPProgressIndicatorHUDBarStyle;
|
||||
|
||||
for (; start <= end; ++start)
|
||||
{
|
||||
CPProgressIndicatorBezelBorderViewPool[start] = [];
|
||||
CPProgressIndicatorBezelBorderViewPool[start][CPMiniControlSize] = [];
|
||||
CPProgressIndicatorBezelBorderViewPool[start][CPSmallControlSize] = [];
|
||||
CPProgressIndicatorBezelBorderViewPool[start][CPRegularControlSize] = [];
|
||||
}
|
||||
|
||||
CPProgressIndicatorClassName = [self className];
|
||||
CPProgressIndicatorStyleIdentifiers = [];
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding === CPValueBinding || aBinding === @"isIndeterminate")
|
||||
return [_CPProgressIndicatorBinder class];
|
||||
CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle] = @"Bar";
|
||||
CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorSpinningStyle] = @"Spinny";
|
||||
CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorHUDBarStyle] = @"HUDBar";
|
||||
|
||||
var regularIdentifier = _CPControlIdentifierForControlSize(CPRegularControlSize),
|
||||
smallIdentifier = _CPControlIdentifierForControlSize(CPSmallControlSize),
|
||||
miniIdentifier = _CPControlIdentifierForControlSize(CPMiniControlSize);
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
CPProgressIndicatorStyleSizes = [];
|
||||
|
||||
// Bar Sttyle
|
||||
var prefixes = [
|
||||
CPProgressIndicatorClassName + @"BezelBorder" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle],
|
||||
CPProgressIndicatorClassName + @"Bar" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle],
|
||||
CPProgressIndicatorClassName + @"BezelBorder" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorHUDBarStyle],
|
||||
CPProgressIndicatorClassName + @"Bar" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorHUDBarStyle]
|
||||
];
|
||||
|
||||
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)];
|
||||
CPProgressIndicatorStyleSizes[prefix + smallIdentifier] = [_CGSizeMake(3.0, 16.0), _CGSizeMake(1.0, 16.0), _CGSizeMake(3.0, 16.0)];
|
||||
CPProgressIndicatorStyleSizes[prefix + miniIdentifier] = [_CGSizeMake(3.0, 16.0), _CGSizeMake(1.0, 16.0), _CGSizeMake(3.0, 16.0)];
|
||||
}
|
||||
}
|
||||
|
||||
- (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 setNeedsLayout];
|
||||
|
||||
[self updateBackgroundColor];
|
||||
[self drawBar];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -136,7 +176,7 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
- (void)startAnimation:(id)aSender
|
||||
{
|
||||
_isAnimating = YES;
|
||||
|
||||
|
||||
[self _hideOrDisplay];
|
||||
}
|
||||
|
||||
@@ -175,7 +215,7 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
- (void)setDoubleValue:(double)aValue
|
||||
{
|
||||
_doubleValue = MIN(MAX(aValue, _minValue), _maxValue);
|
||||
|
||||
|
||||
[self drawBar];
|
||||
}
|
||||
|
||||
@@ -230,7 +270,7 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
{
|
||||
if (_controlSize == aControlSize)
|
||||
return;
|
||||
|
||||
|
||||
_controlSize = aControlSize;
|
||||
|
||||
[self updateBackgroundColor];
|
||||
@@ -252,7 +292,7 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
}
|
||||
|
||||
/*
|
||||
Not yet implemented.
|
||||
Not yet impemented.
|
||||
*/
|
||||
- (CPControlTint)controlTint
|
||||
{
|
||||
@@ -278,12 +318,12 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
Specifies whether this progress indicator should be indeterminate or display progress based on it's max and min.
|
||||
@param isDeterminate \c YES makes the indicator indeterminate
|
||||
*/
|
||||
- (void)setIndeterminate:(BOOL)indeterminate
|
||||
- (void)setIndeterminate:(BOOL)isIndeterminate
|
||||
{
|
||||
if (_indeterminate == indeterminate)
|
||||
if (_isIndeterminate == isIndeterminate)
|
||||
return;
|
||||
|
||||
_indeterminate = indeterminate;
|
||||
|
||||
_isIndeterminate = isIndeterminate;
|
||||
|
||||
[self updateBackgroundColor];
|
||||
}
|
||||
@@ -293,7 +333,7 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
*/
|
||||
- (BOOL)isIndeterminate
|
||||
{
|
||||
return _indeterminate;
|
||||
return _isIndeterminate;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -304,11 +344,9 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
{
|
||||
if (_style == aStyle)
|
||||
return;
|
||||
|
||||
|
||||
_style = aStyle;
|
||||
|
||||
[self setTheme:(_style === CPProgressIndicatorHUDBarStyle) ? [CPTheme defaultHudTheme] : [CPTheme defaultTheme]];
|
||||
|
||||
|
||||
[self updateBackgroundColor];
|
||||
}
|
||||
|
||||
@@ -320,7 +358,9 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
if (_style == CPProgressIndicatorSpinningStyle)
|
||||
[self setFrameSize:[[CPProgressIndicatorSpinningStyleColors[_controlSize] patternImage] size]];
|
||||
else
|
||||
[self setFrameSize:CGSizeMake(CGRectGetWidth([self frame]), [self valueForThemeAttribute:@"default-height"])];
|
||||
[self setFrameSize:CGSizeMake(CGRectGetWidth([self frame]), CPProgressIndicatorStyleSizes[
|
||||
CPProgressIndicatorClassName + @"BezelBorder" + CPProgressIndicatorStyleIdentifiers[CPProgressIndicatorBarStyle] +
|
||||
_CPControlIdentifierForControlSize(_controlSize)][0].height)];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -332,11 +372,11 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
{
|
||||
if (_isDisplayedWhenStoppedSet && _isDisplayedWhenStopped == isDisplayedWhenStopped)
|
||||
return;
|
||||
|
||||
|
||||
_isDisplayedWhenStoppedSet = YES;
|
||||
|
||||
|
||||
_isDisplayedWhenStopped = isDisplayedWhenStopped;
|
||||
|
||||
|
||||
[self _hideOrDisplay];
|
||||
}
|
||||
|
||||
@@ -347,10 +387,10 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
{
|
||||
if (_isDisplayedWhenStoppedSet)
|
||||
return _isDisplayedWhenStopped;
|
||||
|
||||
|
||||
if (_style == CPProgressIndicatorBarStyle || _style == CPProgressIndicatorHUDBarStyle)
|
||||
return YES;
|
||||
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
@@ -363,228 +403,67 @@ var CPProgressIndicatorSpinningStyleColors = [];
|
||||
- (void)setFrameSize:(CGSize)aSize
|
||||
{
|
||||
[super setFrameSize:aSize];
|
||||
|
||||
|
||||
[self drawBar];
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (void)drawBar
|
||||
{
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (CPView)createEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
return [[CPView alloc] initWithFrame:CGRectMakeZero()];
|
||||
}
|
||||
|
||||
- (CGRect)rectForEphemeralSubviewNamed:(CPString)aViewName
|
||||
{
|
||||
if (aViewName === @"bar-view" && _style !== CPProgressIndicatorSpinningStyle)
|
||||
if (_style == CPProgressIndicatorSpinningStyle)
|
||||
return;
|
||||
|
||||
if (!_barView)
|
||||
{
|
||||
var width = CGRectGetWidth([self bounds]),
|
||||
barWidth = width * ((_doubleValue - _minValue) / (_maxValue - _minValue));
|
||||
|
||||
if (barWidth > 0.0 && barWidth < 4.0)
|
||||
barWidth = 4.0;
|
||||
|
||||
if (_indeterminate)
|
||||
barWidth = width;
|
||||
|
||||
return CGRectMake(0, 0, barWidth, [self valueForThemeAttribute:@"default-height"]);
|
||||
_barView = [[CPView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 16.0)];
|
||||
[self addSubview:_barView];
|
||||
}
|
||||
|
||||
[_barView setBackgroundColor:_CPControlThreePartImagePattern(
|
||||
NO,
|
||||
CPProgressIndicatorStyleSizes,
|
||||
CPProgressIndicatorClassName,
|
||||
@"Bar",
|
||||
CPProgressIndicatorStyleIdentifiers[_style],
|
||||
_CPControlIdentifierForControlSize(_controlSize))];
|
||||
|
||||
return nil;
|
||||
var width = CGRectGetWidth([self bounds]),
|
||||
barWidth = width * ((_doubleValue - _minValue) / (_maxValue - _minValue));
|
||||
|
||||
if (barWidth > 0.0 && barWidth < 4.0)
|
||||
barWidth = 4.0;
|
||||
|
||||
[_barView setFrameSize:CGSizeMake(barWidth, 16.0)];
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (void)updateBackgroundColor
|
||||
{
|
||||
if ([CPProgressIndicatorSpinningStyleColors count] === 0)
|
||||
{
|
||||
CPProgressIndicatorSpinningStyleColors[CPMiniControlSize] = [self valueForThemeAttribute:@"spinning-mini-gif"];
|
||||
CPProgressIndicatorSpinningStyleColors[CPSmallControlSize] = [self valueForThemeAttribute:@"spinning-small-gif"];
|
||||
CPProgressIndicatorSpinningStyleColors[CPRegularControlSize] = [self valueForThemeAttribute:@"spinning-regular-gif"];
|
||||
}
|
||||
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
if (YES)//_isBezeled)
|
||||
{
|
||||
if (_style == CPProgressIndicatorSpinningStyle)
|
||||
{
|
||||
if (!_indeterminate)
|
||||
return;
|
||||
|
||||
// This will cause the bar view to go away due to having a nil rect when _style == CPProgressIndicatorSpinningStyle.
|
||||
[self layoutEphemeralSubviewNamed:"bar-view"
|
||||
positioned:CPWindowBelow
|
||||
relativeToEphemeralSubviewNamed:nil];
|
||||
|
||||
[_barView removeFromSuperview];
|
||||
|
||||
_barView = nil;
|
||||
|
||||
[self setBackgroundColor:CPProgressIndicatorSpinningStyleColors[_controlSize]];
|
||||
}
|
||||
else
|
||||
{
|
||||
[self setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
|
||||
|
||||
var barView = [self layoutEphemeralSubviewNamed:"bar-view"
|
||||
positioned:CPWindowBelow
|
||||
relativeToEphemeralSubviewNamed:nil];
|
||||
|
||||
if (_indeterminate)
|
||||
[barView setBackgroundColor:[self currentValueForThemeAttribute:@"indeterminate-bar-color"]];
|
||||
else
|
||||
[barView setBackgroundColor:[self currentValueForThemeAttribute:@"bar-color"]];
|
||||
[self setBackgroundColor:_CPControlThreePartImagePattern(
|
||||
NO,
|
||||
CPProgressIndicatorStyleSizes,
|
||||
CPProgressIndicatorClassName,
|
||||
@"BezelBorder",
|
||||
CPProgressIndicatorStyleIdentifiers[_style],
|
||||
_CPControlIdentifierForControlSize(_controlSize))];
|
||||
|
||||
[self drawBar];
|
||||
}
|
||||
}
|
||||
else
|
||||
[self setBackgroundColor:nil];
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)aRect
|
||||
{
|
||||
if (_style == CPProgressIndicatorSpinningStyle && !_indeterminate)
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
rect = CGRectMakeCopy(aRect),
|
||||
borderSize = [self currentValueForThemeAttribute:@"circular-border-size"];
|
||||
|
||||
rect.origin.x += borderSize;
|
||||
rect.origin.y += borderSize;
|
||||
rect.size.width = rect.size.width - borderSize * 2;
|
||||
rect.size.height = rect.size.height - borderSize * 2;
|
||||
|
||||
if ([self doubleValue] > [self minValue] && [self doubleValue] < [self maxValue])
|
||||
{
|
||||
var midX = CGRectGetMidX(rect),
|
||||
midY = CGRectGetMidY(rect),
|
||||
endAngle = Math.PI * 2 * (([self doubleValue] - [self minValue]) / ([self maxValue] - [self minValue])) - Math.PI / 2,
|
||||
radius = MIN(rect.size.width / 2, rect.size.height / 2);
|
||||
|
||||
CGContextBeginPath(context);
|
||||
CGContextSetLineWidth(context, borderSize);
|
||||
CGContextSetFillColor(context, [self currentValueForThemeAttribute:@"circular-color"]);
|
||||
CGContextMoveToPoint(context, midX, midY);
|
||||
CGContextAddArc(context, midX, midY, radius, 3 * Math.PI / 2, endAngle, YES);
|
||||
CGContextAddLineToPoint(context, midX, midY);
|
||||
CGContextClosePath(context);
|
||||
CGContextFillPath(context);
|
||||
CGContextStrokePath(context);
|
||||
}
|
||||
else if ([self doubleValue] == [self maxValue])
|
||||
{
|
||||
CGContextBeginPath(context);
|
||||
CGContextSetFillColor(context, [self currentValueForThemeAttribute:@"circular-color"]);
|
||||
CGContextAddEllipseInRect(context, rect);
|
||||
CGContextClosePath(context);
|
||||
CGContextFillPath(context);
|
||||
}
|
||||
|
||||
CGContextBeginPath(context);
|
||||
CGContextSetStrokeColor(context , [self currentValueForThemeAttribute:@"circular-border-color"]);
|
||||
CGContextSetLineWidth(context, borderSize);
|
||||
CGContextAddEllipseInRect(context, rect);
|
||||
CGContextClosePath(context);
|
||||
CGContextStrokePath(context);
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation CPProgressIndicator (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
if (self = [super initWithCoder:aCoder])
|
||||
{
|
||||
_minValue = [aCoder decodeObjectForKey:@"_minValue"];
|
||||
_maxValue = [aCoder decodeObjectForKey:@"_maxValue"];
|
||||
_doubleValue = [aCoder decodeObjectForKey:@"_doubleValue"];
|
||||
_controlSize = [aCoder decodeObjectForKey:@"_controlSize"];
|
||||
_indeterminate = [aCoder decodeObjectForKey:@"_indeterminate"];
|
||||
_style = [aCoder decodeIntForKey:@"_style"];
|
||||
_isAnimating = [aCoder decodeObjectForKey:@"_isAnimating"];
|
||||
_isDisplayedWhenStoppedSet = [aCoder decodeObjectForKey:@"_isDisplayedWhenStoppedSet"];
|
||||
_isDisplayedWhenStopped = [aCoder decodeObjectForKey:@"_isDisplayedWhenStopped"];
|
||||
|
||||
[self updateBackgroundColor];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
// Don't encode the background colour. It can be recreated based on the flags
|
||||
// and if encoded causes hardcoded image paths in the cib while just wasting space.
|
||||
var backgroundColor = [self backgroundColor];
|
||||
[self setBackgroundColor:nil];
|
||||
[super encodeWithCoder:aCoder];
|
||||
[self setBackgroundColor:backgroundColor];
|
||||
|
||||
[aCoder encodeObject:_minValue forKey:@"_minValue"];
|
||||
[aCoder encodeObject:_maxValue forKey:@"_maxValue"];
|
||||
[aCoder encodeObject:_doubleValue forKey:@"_doubleValue"];
|
||||
[aCoder encodeObject:_controlSize forKey:@"_controlSize"];
|
||||
[aCoder encodeObject:_indeterminate forKey:@"_indeterminate"];
|
||||
[aCoder encodeInt:_style forKey:@"_style"];
|
||||
[aCoder encodeObject:_isAnimating forKey:@"_isAnimating"];
|
||||
[aCoder encodeObject:_isDisplayedWhenStoppedSet forKey:@"_isDisplayedWhenStoppedSet"];
|
||||
[aCoder encodeObject:_isDisplayedWhenStopped forKey:@"_isDisplayedWhenStopped"];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation _CPProgressIndicatorBinder : CPBinder
|
||||
|
||||
- (void)_updatePlaceholdersWithOptions:(CPDictionary)options forBinding:(CPString)aBinding
|
||||
{
|
||||
var value = aBinding === CPValueBinding ? 0.0 : YES;
|
||||
|
||||
[self _setPlaceholder:value forMarker:CPMultipleValuesMarker isDefault:YES];
|
||||
[self _setPlaceholder:value forMarker:CPNoSelectionMarker isDefault:YES];
|
||||
[self _setPlaceholder:value forMarker:CPNotApplicableMarker isDefault:YES];
|
||||
[self _setPlaceholder:value forMarker:CPNullMarker isDefault:YES];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding === CPValueBinding)
|
||||
return [_source doubleValue];
|
||||
else if (aBinding === @"isIndeterminate")
|
||||
[_source isIndeterminate];
|
||||
else
|
||||
return [super valueForBinding:aBinding];
|
||||
}
|
||||
|
||||
- (BOOL)_setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding === CPValueBinding)
|
||||
[_source setDoubleValue:aValue];
|
||||
else if (aBinding === @"isIndeterminate")
|
||||
[_source setIndeterminate:aValue];
|
||||
else
|
||||
return NO;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
if (![self _setValue:aValue forBinding:aBinding])
|
||||
[super setValue:aValue forBinding:aBinding];
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
if (![self _setValue:aValue forBinding:aBinding])
|
||||
[super setPlaceholderValue:aValue withMarker:aMarker forBinding:aBinding];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+30
-339
@@ -25,34 +25,28 @@
|
||||
|
||||
@import "CPButton.j"
|
||||
|
||||
@class CPRadioGroup
|
||||
|
||||
@global CPApp
|
||||
|
||||
CPRadioImageOffset = 4.0;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
|
||||
|
||||
from this mailing list thread:
|
||||
http://groups.google.com/group/objectivej/browse_thread/thread/7c41cbd9cbee9ea3
|
||||
|
||||
http://groups.google.com/group/objectivej/browse_thread/thread/7c41cbd9cbee9ea3
|
||||
|
||||
-----------------------------------
|
||||
|
||||
|
||||
Creating a checkbox is easy enough:
|
||||
|
||||
|
||||
checkbox = [[CPCheckBox alloc] initWithFrame:aFrame];
|
||||
|
||||
|
||||
That's basically all there is to it. Radio buttons are very similar,
|
||||
the key difference is the introduction of a new class CPRadioGroup,
|
||||
which defines which radio buttons are part of the same group:
|
||||
|
||||
|
||||
[myRadioButton setRadioGroup:aRadioGroup];
|
||||
|
||||
|
||||
Every radio button receives a unique radio group by default (so if you
|
||||
do nothing further, they will all behave independently), but you can
|
||||
use an existing radio button's group with other buttons as so:
|
||||
|
||||
|
||||
button1 = [[CPRadio alloc] initWithFrame:aFrame];
|
||||
...
|
||||
button2 = [[CPRadio alloc] initWithFrame:aFrame radioGroup:[button1
|
||||
@@ -61,24 +55,12 @@ CPRadioImageOffset = 4.0;
|
||||
button3 = [[CPRadio alloc] initWithFrame:aFrame radioGroup:[button1
|
||||
radioGroup]];
|
||||
...etc...
|
||||
|
||||
|
||||
Here, all the radio buttons will act "together". [[button1 radioGroup]
|
||||
allRadios] returns every button that's part of this group, and
|
||||
[[button1 radioGroup] selectedRadio] returns the currently selected
|
||||
option.
|
||||
|
||||
UPDATE 09/2020 : Implementation of modern Cocoa behavior :
|
||||
|
||||
As in Cocoa, radio buttons grouping is now automatic.
|
||||
|
||||
To be associated in a common group (and so being mutually exclusive),
|
||||
radio buttons must combine 2 criteria :
|
||||
|
||||
- same superview (enclosing view)
|
||||
- same action
|
||||
|
||||
TODO: This first implementation uses "as is" CPRadioGroup. This could
|
||||
be simplified (no more need for radio group action, for example)
|
||||
*/
|
||||
@implementation CPRadio : CPButton
|
||||
{
|
||||
@@ -104,7 +86,7 @@ CPRadioImageOffset = 4.0;
|
||||
return button;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (CPString)themeClass
|
||||
{
|
||||
return @"radio";
|
||||
}
|
||||
@@ -113,7 +95,7 @@ CPRadioImageOffset = 4.0;
|
||||
- (id)initWithFrame:(CGRect)aFrame radioGroup:(CPRadioGroup)aRadioGroup
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self setRadioGroup:aRadioGroup];
|
||||
@@ -127,8 +109,8 @@ CPRadioImageOffset = 4.0;
|
||||
|
||||
[self setBordered:YES];
|
||||
}
|
||||
|
||||
return self;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
@@ -159,80 +141,7 @@ CPRadioImageOffset = 4.0;
|
||||
- (void)setObjectValue:(id)aValue
|
||||
{
|
||||
[super setObjectValue:aValue];
|
||||
|
||||
if ([self state] === CPOnState)
|
||||
[_radioGroup _setSelectedRadio:self];
|
||||
}
|
||||
|
||||
- (BOOL)sendAction:(SEL)anAction to:(id)anObject
|
||||
{
|
||||
[super sendAction:anAction to:anObject];
|
||||
|
||||
if (_radioGroup)
|
||||
[CPApp sendAction:[_radioGroup action] to:[_radioGroup target] from:_radioGroup];
|
||||
}
|
||||
|
||||
- (void)viewDidMoveToSuperview
|
||||
{
|
||||
[self _setRadioGroup];
|
||||
[super viewDidMoveToSuperview];
|
||||
}
|
||||
|
||||
- (void)setAction:(SEL)anAction
|
||||
{
|
||||
if (anAction === _action)
|
||||
return;
|
||||
|
||||
[super setAction:anAction];
|
||||
[self _setRadioGroup];
|
||||
}
|
||||
|
||||
#pragma mark Private methods
|
||||
|
||||
- (void)_setRadioGroup
|
||||
{
|
||||
// Implementation of modern Cocoa behavior : automatic radio group
|
||||
|
||||
// If no action is set or no superview, no grouping can be done.
|
||||
if (![self action] || ![self superview])
|
||||
{
|
||||
// If this radio is in a group (size > 1), remove it.
|
||||
if ([[self radioGroup] size] > 1)
|
||||
{
|
||||
[self setRadioGroup:[CPRadioGroup new]];
|
||||
|
||||
if ([self state] === CPOnState)
|
||||
[_radioGroup _setSelectedRadio:self];
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Search in superview subviews for other radio buttons having the same action.
|
||||
// Take the one with the radio group having the greatest number of members.
|
||||
|
||||
var radioGroup;
|
||||
|
||||
for (var i = 0, superviewSubviews = [[self superview] subviews], count = [superviewSubviews count], aSubview, myAction = [self action], radioGroupSize = -1; (i < count); i++)
|
||||
{
|
||||
aSubview = superviewSubviews[i];
|
||||
|
||||
if ([aSubview isKindOfClass:CPRadio] && (aSubview !== self) && ([aSubview action] === myAction) && ([[aSubview radioGroup] size] > radioGroupSize))
|
||||
{
|
||||
radioGroup = [aSubview radioGroup];
|
||||
radioGroupSize = [radioGroup size];
|
||||
}
|
||||
}
|
||||
|
||||
if (radioGroup)
|
||||
[self setRadioGroup:radioGroup];
|
||||
else
|
||||
// No other radio buttons to group with found.
|
||||
// It may be because this radio button was in a radio group and its action was changed.
|
||||
// If this is the case, we must reisolate it in a new radio group.
|
||||
if ([_radioGroup size] > 1)
|
||||
[self setRadioGroup:[CPRadioGroup new]];
|
||||
|
||||
|
||||
if ([self state] === CPOnState)
|
||||
[_radioGroup _setSelectedRadio:self];
|
||||
}
|
||||
@@ -260,164 +169,33 @@ var CPRadioRadioGroupKey = @"CPRadioRadioGroupKey";
|
||||
[aCoder encodeObject:_radioGroup forKey:CPRadioRadioGroupKey];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Override methods from CPButton
|
||||
|
||||
- (CPThemeState)_contentVisualState
|
||||
{
|
||||
// Note : Behavior differs from CPButton as title doesn't follow the highlightsBy content flag
|
||||
|
||||
var visualState = [self themeState] || CPThemeStateNormal, // Needed during theme compilation
|
||||
currentState = [self state];
|
||||
|
||||
if ((currentState !== CPOffState) && (_showsStateBy & CPContentsCellMask))
|
||||
visualState = visualState.and((currentState === CPOnState) ? CPThemeStateSelected : CPButtonStateMixed);
|
||||
|
||||
return visualState;
|
||||
}
|
||||
|
||||
- (CPThemeState)_imageVisualState
|
||||
{
|
||||
// Note : Behavior differs from CPButton as we don't force "not selected" theme state
|
||||
// when button is highglighted and selected
|
||||
|
||||
var visualState = [self themeState] || CPThemeStateNormal, // Needed during theme compilation
|
||||
currentState = [self state];
|
||||
|
||||
if (_isHighlighted && (_highlightsBy & CPContentsCellMask))
|
||||
visualState = visualState.and(CPThemeStateHighlighted);
|
||||
|
||||
if ((currentState !== CPOffState) && (_showsStateBy & CPContentsCellMask))
|
||||
visualState = visualState.and((currentState === CPOnState) ? CPThemeStateSelected : CPButtonStateMixed);
|
||||
|
||||
return visualState;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPRadioGroup : CPObject
|
||||
{
|
||||
CPArray _radios;
|
||||
CPSet _radios;
|
||||
CPRadio _selectedRadio;
|
||||
|
||||
BOOL _enabled @accessors(getter=enabled);
|
||||
BOOL _hidden @accessors(getter=hidden);
|
||||
|
||||
id _target @accessors(property=target);
|
||||
SEL _action @accessors(property=action);
|
||||
}
|
||||
|
||||
+ (void)initialize
|
||||
{
|
||||
if (self !== [CPRadioGroup class])
|
||||
return;
|
||||
|
||||
[self exposeBinding:CPSelectedValueBinding];
|
||||
[self exposeBinding:CPSelectedTagBinding];
|
||||
[self exposeBinding:CPSelectedIndexBinding];
|
||||
|
||||
[self exposeBinding:CPEnabledBinding];
|
||||
[self exposeBinding:CPHiddenBinding];
|
||||
}
|
||||
|
||||
- (id)init
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_radios = [];
|
||||
_radios = [CPSet set];
|
||||
_selectedRadio = nil;
|
||||
_enabled = YES;
|
||||
_hidden = NO;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
Selects the radio button at the given index within the group.
|
||||
If index is -1, all of the radio buttons are turned off.
|
||||
*/
|
||||
- (void)selectRadioAtIndex:(int)index
|
||||
{
|
||||
if (index === -1)
|
||||
[self _setSelectedRadio:nil];
|
||||
else
|
||||
{
|
||||
var radio = [_radios objectAtIndex:index];
|
||||
|
||||
[self _setSelectedRadio:radio];
|
||||
[radio setState:CPOnState];
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Selects the first radio button within the group with the given tag.
|
||||
If a radio button with the given tag is found, selects it
|
||||
and returns YES. Otherwise returns NO.
|
||||
*/
|
||||
- (BOOL)selectRadioWithTag:(int)tag
|
||||
{
|
||||
var index = [_radios indexOfObjectPassingTest:function(radio)
|
||||
{
|
||||
return [radio tag] === tag;
|
||||
}];
|
||||
|
||||
if (index !== CPNotFound)
|
||||
{
|
||||
[self selectRadioAtIndex:index];
|
||||
return YES;
|
||||
}
|
||||
else
|
||||
return NO;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the CPRadio that is currently selected within the group,
|
||||
or nil if none are selected.
|
||||
*/
|
||||
- (CPRadio)selectedRadio
|
||||
{
|
||||
return _selectedRadio;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the index of the selected radio within the array of radio buttons.
|
||||
Buttons are numbered going left to right and top to bottom. Returns -1
|
||||
if no radio within the group is selected.
|
||||
*/
|
||||
- (int)selectedRadioIndex
|
||||
{
|
||||
return [_radios indexOfObject:_selectedRadio];
|
||||
}
|
||||
|
||||
- (CPArray)radios
|
||||
{
|
||||
return _radios;
|
||||
}
|
||||
|
||||
- (int)size
|
||||
{
|
||||
return [_radios count];
|
||||
}
|
||||
|
||||
- (void)setEnabled:(BOOL)enabled
|
||||
{
|
||||
[_radios makeObjectsPerformSelector:@selector(setEnabled:) withObject:enabled];
|
||||
}
|
||||
|
||||
- (void)setHidden:(BOOL)hidden
|
||||
{
|
||||
[_radios makeObjectsPerformSelector:@selector(setHidden:) withObject:hidden];
|
||||
}
|
||||
|
||||
#pragma mark Private
|
||||
|
||||
- (void)_addRadio:(CPRadio)aRadio
|
||||
{
|
||||
if ([_radios indexOfObject:aRadio] === CPNotFound)
|
||||
[_radios addObject:aRadio];
|
||||
[_radios addObject:aRadio];
|
||||
|
||||
if ([aRadio state] === CPOnState)
|
||||
[self _setSelectedRadio:aRadio];
|
||||
@@ -431,30 +209,25 @@ var CPRadioRadioGroupKey = @"CPRadioRadioGroupKey";
|
||||
[_radios removeObject:aRadio];
|
||||
}
|
||||
|
||||
/*!
|
||||
Selects the first radio button within the group with the given tag.
|
||||
If a radio button with the given tag is found, selects it
|
||||
and returns YES. Otherwise returns NO.
|
||||
*/
|
||||
- (void)_selectRadioWithTitle:(CPString)aTitle
|
||||
{
|
||||
var index = [_radios indexOfObjectPassingTest:function(radio)
|
||||
{
|
||||
return [radio title] === aTitle;
|
||||
}];
|
||||
|
||||
[self selectRadioAtIndex:index];
|
||||
}
|
||||
|
||||
- (void)_setSelectedRadio:(CPRadio)aRadio
|
||||
{
|
||||
if (_selectedRadio === aRadio)
|
||||
return;
|
||||
|
||||
[_selectedRadio setState:CPOffState];
|
||||
|
||||
_selectedRadio = aRadio;
|
||||
[_CPRadioGroupSelectionBinder _reverseSetValueFromExclusiveBinderForObject:self];
|
||||
|
||||
[CPApp sendAction:_action to:_target from:self];
|
||||
}
|
||||
|
||||
- (CPRadio)selectedRadio
|
||||
{
|
||||
return _selectedRadio;
|
||||
}
|
||||
|
||||
- (CPArray)radios
|
||||
{
|
||||
return [_radios allObjects];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -484,85 +257,3 @@ var CPRadioGroupRadiosKey = @"CPRadioGroupRadiosKey",
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPRadioGroup (BindingSupport)
|
||||
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding === CPSelectedValueBinding ||
|
||||
aBinding === CPSelectedTagBinding ||
|
||||
aBinding === CPSelectedIndexBinding)
|
||||
{
|
||||
var capitalizedBinding = aBinding.charAt(0).toUpperCase() + aBinding.substr(1);
|
||||
|
||||
return [CPClassFromString(@"_CPRadioGroup" + capitalizedBinding + "Binder") class];
|
||||
}
|
||||
else if ([aBinding hasPrefix:CPEnabledBinding])
|
||||
return [CPMultipleValueAndBinding class];
|
||||
else if ([aBinding hasPrefix:CPHiddenBinding])
|
||||
return [CPMultipleValueOrBinding class];
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
}
|
||||
|
||||
+ (BOOL)isBindingExclusive:(CPString)aBinding
|
||||
{
|
||||
return (aBinding == CPSelectedIndexBinding ||
|
||||
aBinding == CPSelectedTagBinding ||
|
||||
aBinding == CPSelectedValueBinding);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPRadioGroupSelectionBinder : CPBinder
|
||||
{
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
[self setValue:aValue forBinding:aBinding];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPRadioGroupSelectedIndexBinder : _CPRadioGroupSelectionBinder
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source selectRadioAtIndex:aValue];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
return [_source selectedRadioIndex];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPRadioGroupSelectedTagBinder : _CPRadioGroupSelectionBinder
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source selectRadioWithTag:aValue];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
return [[_source selectedRadio] tag];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation _CPRadioGroupSelectedValueBinder : _CPRadioGroupSelectionBinder
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source _selectRadioWithTitle:aValue];
|
||||
}
|
||||
|
||||
- (id)valueForBinding:(CPString)aBinding
|
||||
{
|
||||
return [[_source selectedRadio] title];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+61
-80
@@ -21,31 +21,24 @@
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
@import <Foundation/CPObjJRuntime.j>
|
||||
|
||||
@import "CPEvent.j"
|
||||
@import "CPCursor.j"
|
||||
|
||||
@class CPKeyBinding
|
||||
@class CPMenu
|
||||
|
||||
CPDeleteKeyCode = 8;
|
||||
CPTabKeyCode = 9;
|
||||
CPReturnKeyCode = 13;
|
||||
CPEscapeKeyCode = 27;
|
||||
CPSpaceKeyCode = 32;
|
||||
CPPageUpKeyCode = 33;
|
||||
CPPageDownKeyCode = 34;
|
||||
CPLeftArrowKeyCode = 37;
|
||||
CPUpArrowKeyCode = 38;
|
||||
CPRightArrowKeyCode = 39;
|
||||
CPDownArrowKeyCode = 40;
|
||||
CPDeleteForwardKeyCode = 46;
|
||||
CPDeleteKeyCode = 8;
|
||||
CPTabKeyCode = 9;
|
||||
CPReturnKeyCode = 13;
|
||||
CPEscapeKeyCode = 27;
|
||||
CPSpaceKeyCode = 32;
|
||||
CPPageUpKeyCode = 33;
|
||||
CPPageDownKeyCode = 34;
|
||||
CPLeftArrowKeyCode = 37;
|
||||
CPUpArrowKeyCode = 38;
|
||||
CPRightArrowKeyCode = 39;
|
||||
CPDownArrowKeyCode = 40;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPResponder
|
||||
|
||||
|
||||
Subclasses of CPResonder can be part of the responder chain.
|
||||
*/
|
||||
@implementation CPResponder : CPObject
|
||||
@@ -111,24 +104,42 @@ CPDeleteForwardKeyCode = 46;
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var event = events[index],
|
||||
modifierFlags = [event modifierFlags],
|
||||
character = [event charactersIgnoringModifiers],
|
||||
selectorNames = [CPKeyBinding selectorsForKey:character modifierFlags:modifierFlags];
|
||||
var event = events[index];
|
||||
|
||||
if (selectorNames)
|
||||
switch([event keyCode])
|
||||
{
|
||||
for (var s = 0, scount = selectorNames.length; s < scount; s++)
|
||||
{
|
||||
var selector = selectorNames[s];
|
||||
if (!selector)
|
||||
continue;
|
||||
case CPPageUpKeyCode: [self doCommandBySelector:@selector(pageUp:)];
|
||||
break;
|
||||
case CPPageDownKeyCode: [self doCommandBySelector:@selector(pageDown:)];
|
||||
break;
|
||||
case CPLeftArrowKeyCode: [self doCommandBySelector:@selector(moveLeft:)];
|
||||
break;
|
||||
case CPRightArrowKeyCode: [self doCommandBySelector:@selector(moveRight:)];
|
||||
break;
|
||||
case CPUpArrowKeyCode: [self doCommandBySelector:@selector(moveUp:)];
|
||||
break;
|
||||
case CPDownArrowKeyCode: [self doCommandBySelector:@selector(moveDown:)];
|
||||
break;
|
||||
case CPDeleteKeyCode: [self doCommandBySelector:@selector(deleteBackward:)];
|
||||
break;
|
||||
case CPReturnKeyCode:
|
||||
case 3: [self doCommandBySelector:@selector(insertLineBreak:)];
|
||||
break;
|
||||
|
||||
case CPEscapeKeyCode: [self doCommandBySelector:@selector(cancel:)];
|
||||
break;
|
||||
|
||||
[self doCommandBySelector:CPSelectorFromString(selector)];
|
||||
}
|
||||
case CPTabKeyCode: var shift = [event modifierFlags] & CPShiftKeyMask;
|
||||
|
||||
if (!shift)
|
||||
[self doCommandBySelector:@selector(insertTab:)];
|
||||
else
|
||||
[self doCommandBySelector:@selector(insertBackTab:)];
|
||||
|
||||
break;
|
||||
|
||||
default: [self insertText:[event characters]];
|
||||
}
|
||||
else if (!(modifierFlags & (CPCommandKeyMask | CPControlKeyMask)) && [self respondsToSelector:@selector(insertText:)])
|
||||
[self insertText:[event characters]];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,18 +212,6 @@ CPDeleteForwardKeyCode = 46;
|
||||
[_nextResponder performSelector:_cmd withObject:anEvent];
|
||||
}
|
||||
|
||||
/*!
|
||||
Notifies the receiver that the mouse entered the receiver's area and that it can adapt the cursor.
|
||||
@param anEvent contains information about the exit
|
||||
*/
|
||||
- (void)cursorUpdate:(CPEvent)anEvent
|
||||
{
|
||||
if (_nextResponder)
|
||||
[_nextResponder performSelector:_cmd withObject:anEvent];
|
||||
else
|
||||
[[CPCursor arrowCursor] set];
|
||||
}
|
||||
|
||||
/*!
|
||||
Notifies the receiver that the mouse scroll wheel has moved.
|
||||
@param anEvent information about the scroll
|
||||
@@ -240,27 +239,11 @@ CPDeleteForwardKeyCode = 46;
|
||||
[_nextResponder performSelector:_cmd withObject:anEvent];
|
||||
}
|
||||
|
||||
/*!
|
||||
Notifies the receiver that the user has pressed or released a modifier key (Shift, Control, and so on).
|
||||
@param anEvent information about the key press
|
||||
*/
|
||||
- (void)flagsChanged:(CPEvent)anEvent
|
||||
{
|
||||
[_nextResponder performSelector:_cmd withObject:anEvent];
|
||||
}
|
||||
|
||||
/*!
|
||||
Overridden by subclasses to handle a key equivalent.
|
||||
|
||||
If the character code or codes in \c anEvent match the receiver’s key equivalent,
|
||||
the receiver should respond to the event and return \c YES. The default implementation
|
||||
does nothing and returns \c NO.
|
||||
|
||||
You should extract the characters for a key equivalent using
|
||||
\ref CPEvent::charactersIgnoringModifiers "[anEvent charactersIgnoringModifiers]".
|
||||
|
||||
@param anEvent An event object that represents the key equivalent pressed
|
||||
@return \c YES if theEvent is a key equivalent that the receiver handled, \c NO if it is not a key equivalent that it should handle.
|
||||
/*
|
||||
FIXME This description is bad.
|
||||
Based on \c anEvent, the receiver should simulate the event.
|
||||
@param anEvent the event to simulate
|
||||
@return \c YES if the event receiver simulated the event
|
||||
*/
|
||||
- (BOOL)performKeyEquivalent:(CPEvent)anEvent
|
||||
{
|
||||
@@ -286,6 +269,10 @@ CPDeleteForwardKeyCode = 46;
|
||||
[[self nextResponder] insertNewline:aSender];
|
||||
}
|
||||
|
||||
- (void)cancel:(id)sender
|
||||
{
|
||||
}
|
||||
|
||||
- (void)insertTab:(id)sender
|
||||
{
|
||||
}
|
||||
@@ -325,10 +312,10 @@ CPDeleteForwardKeyCode = 46;
|
||||
*/
|
||||
- (BOOL)tryToPerform:(SEL)aSelector with:(id)anObject
|
||||
{
|
||||
if ([self respondsToSelector:aSelector])
|
||||
if([self respondsToSelector:aSelector])
|
||||
{
|
||||
[self performSelector:aSelector withObject:anObject];
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -367,10 +354,9 @@ CPDeleteForwardKeyCode = 46;
|
||||
|
||||
@end
|
||||
|
||||
var CPResponderNextResponderKey = @"CPResponderNextResponderKey",
|
||||
CPResponderMenuKey = @"CPResponderMenuKey";
|
||||
var CPResponderNextResponderKey = @"CPResponderNextResponderKey";
|
||||
|
||||
@implementation CPResponder (CPCoding) <CPCoding>
|
||||
@implementation CPResponder (CPCoding)
|
||||
|
||||
/*!
|
||||
Initializes the responder with data from a coder.
|
||||
@@ -380,13 +366,10 @@ var CPResponderNextResponderKey = @"CPResponderNextResponderKey",
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super init];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self setNextResponder:[aCoder decodeObjectForKey:CPResponderNextResponderKey]];
|
||||
[self setMenu:[aCoder decodeObjectForKey:CPResponderMenuKey]];
|
||||
}
|
||||
|
||||
_nextResponder = [aCoder decodeObjectForKey:CPResponderNextResponderKey];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -397,10 +380,8 @@ var CPResponderNextResponderKey = @"CPResponderNextResponderKey",
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
// This will come out nil on the other side with decodeObjectForKey:
|
||||
if (_nextResponder != nil)
|
||||
if (_nextResponder !== nil)
|
||||
[aCoder encodeConditionalObject:_nextResponder forKey:CPResponderNextResponderKey];
|
||||
|
||||
[aCoder encodeObject:_menu forKey:CPResponderMenuKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,557 +0,0 @@
|
||||
/*
|
||||
* CPPredicateEditor.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by cacaodev.
|
||||
* Copyright 2011, cacaodev.
|
||||
*
|
||||
* 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 "CPRuleEditor.j"
|
||||
@import "_CPPredicateEditorTree.j"
|
||||
@import "_CPPredicateEditorRowNode.j"
|
||||
@import "CPPredicateEditorRowTemplate.j"
|
||||
|
||||
@implementation CPPredicateEditor : CPRuleEditor
|
||||
{
|
||||
CPArray _allTemplates;
|
||||
CPArray _rootTrees;
|
||||
CPArray _rootHeaderTrees;
|
||||
id _predicateTarget @accessors(property=target);
|
||||
SEL _predicateAction @accessors(property=action);
|
||||
}
|
||||
|
||||
#pragma mark public methods
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPPredicateEditor
|
||||
|
||||
@brief CPPredicateEditor is a subclass of CPRuleEditor that is specialized for editing CPPredicate objects.
|
||||
|
||||
CPPredicateEditor provides a CPPredicate property—objectValue (inherited from CPControl)—that you can get and set directly, and that you can bind using bindings (you typically configure a predicate editor in Interface Builder). CPPredicateEditor depends on another class, CPPredicateEditorRowTemplate, that describes the available predicates and how to display them.
|
||||
|
||||
Unlike CPRuleEditor, CPPredicateEditor does not depend on its delegate to populate its rows (and does not call the populating delegate methods). Instead, its rows are populated from its objectValue property (an instance of CPPredicate). CPPredicateEditor relies on instances CPPredicateEditorRowTemplate, which are responsible for mapping back and forth between the displayed view values and various predicates.
|
||||
|
||||
CPPredicateEditor exposes one property, rowTemplates, which is an array of CPPredicateEditorRowTemplate objects.
|
||||
*/
|
||||
|
||||
/*!
|
||||
@brief Returns the row templates for the receiver.
|
||||
@return The row templates for the receiver.
|
||||
@discussion Until otherwise set, this contains a single compound CPPredicateEditorRowTemplate object.
|
||||
@see setRowTemplates:
|
||||
*/
|
||||
- (CPArray)rowTemplates
|
||||
{
|
||||
return _allTemplates;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Sets the row templates for the receiver.
|
||||
@param rowTemplates An array of CPPredicateEditorRowTemplate objects.
|
||||
@see rowTemplates
|
||||
*/
|
||||
- (void)setRowTemplates:(id)rowTemplates
|
||||
{
|
||||
if (_allTemplates == rowTemplates)
|
||||
return;
|
||||
|
||||
_allTemplates = rowTemplates;
|
||||
|
||||
[self _updateItemsByCompoundTemplates];
|
||||
[self _updateItemsBySimpleTemplates];
|
||||
|
||||
if ([self numberOfRows] > 0)
|
||||
{
|
||||
var predicate = [super predicate];
|
||||
[self _reflectPredicate:predicate];
|
||||
}
|
||||
}
|
||||
|
||||
/*! @cond */
|
||||
+ (Class)_binderClassForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding == CPValueBinding)
|
||||
return [CPPredicateEditorValueBinder class];
|
||||
|
||||
return [super _binderClassForBinding:aBinding];
|
||||
}
|
||||
|
||||
- (CPString)_replacementKeyPathForBinding:(CPString)aBinding
|
||||
{
|
||||
if (aBinding == CPValueBinding)
|
||||
return @"predicate";
|
||||
|
||||
return [super _replacementKeyPathForBinding:aBinding];
|
||||
}
|
||||
|
||||
- (void)_initRuleEditorShared
|
||||
{
|
||||
[super _initRuleEditorShared];
|
||||
|
||||
_rootTrees = [CPArray array];
|
||||
_rootHeaderTrees = [CPArray array];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
if (self != nil)
|
||||
{
|
||||
var initialTemplate = [[CPPredicateEditorRowTemplate alloc] initWithCompoundTypes:[CPAndPredicateType, CPOrPredicateType]];
|
||||
_allTemplates = [CPArray arrayWithObject:initialTemplate];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)objectValue
|
||||
{
|
||||
return [super predicate];
|
||||
}
|
||||
|
||||
- (void)_updateItemsBySimpleTemplates
|
||||
{
|
||||
var templates = [CPMutableArray array],
|
||||
count = [_allTemplates count],
|
||||
t;
|
||||
|
||||
while (count--)
|
||||
{
|
||||
var t = _allTemplates[count];
|
||||
if ([t _rowType] == CPRuleEditorRowTypeSimple)
|
||||
[templates insertObject:t atIndex:0];
|
||||
}
|
||||
|
||||
var trees = [self _constructTreesForTemplates:templates];
|
||||
if ([trees count] > 0)
|
||||
_rootTrees = [self _mergeTree:trees];
|
||||
}
|
||||
|
||||
- (void)_updateItemsByCompoundTemplates
|
||||
{
|
||||
var templates = [CPMutableArray array],
|
||||
count = [_allTemplates count],
|
||||
t;
|
||||
|
||||
while (count--)
|
||||
{
|
||||
var t = _allTemplates[count];
|
||||
if ([t _rowType] == CPRuleEditorRowTypeCompound)
|
||||
[templates insertObject:t atIndex:0];
|
||||
}
|
||||
|
||||
var trees = [self _constructTreesForTemplates:templates];
|
||||
if ([trees count] > 0)
|
||||
_rootHeaderTrees = [self _mergeTree:trees];
|
||||
}
|
||||
|
||||
- (CPArray)_constructTreesForTemplates:(id)templates
|
||||
{
|
||||
var trees = [CPMutableArray array],
|
||||
count = [templates count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var tree = [self _constructTreeForTemplate:templates[i]];
|
||||
[trees addObjectsFromArray:tree];
|
||||
}
|
||||
|
||||
return trees;
|
||||
}
|
||||
|
||||
- (CPMutableArray)_mergeTree:(CPArray)aTree
|
||||
{
|
||||
var mergedTree = [CPMutableArray array];
|
||||
if (aTree == nil)
|
||||
return mergedTree;
|
||||
|
||||
var icount = [aTree count];
|
||||
for (var i = 0; i < icount; i++)
|
||||
{
|
||||
var anode = [aTree objectAtIndex:i],
|
||||
jcount = [mergedTree count],
|
||||
merged = NO;
|
||||
|
||||
for (var j = 0; j < jcount; j++)
|
||||
{
|
||||
var mergednode = [mergedTree objectAtIndex:j];
|
||||
|
||||
if ([[mergednode title] isEqualToString:[anode title]])
|
||||
{
|
||||
var children1 = [mergednode children],
|
||||
children2 = [anode children],
|
||||
children12 = [children1 arrayByAddingObjectsFromArray:children2],
|
||||
mergedChildren = [self _mergeTree:children12];
|
||||
|
||||
[mergednode setChildren:mergedChildren];
|
||||
merged = YES;
|
||||
}
|
||||
}
|
||||
|
||||
if (!merged)
|
||||
[mergedTree addObject:anode];
|
||||
}
|
||||
|
||||
return mergedTree;
|
||||
}
|
||||
|
||||
- (id)_constructTreeForTemplate:(CPPredicateEditorRowTemplate)aTemplate
|
||||
{
|
||||
var tree = [CPArray array],
|
||||
templateViews = [aTemplate templateViews],
|
||||
count = [templateViews count];
|
||||
|
||||
while (count--)
|
||||
{
|
||||
var children = [CPArray array],
|
||||
itemsCount = 0,
|
||||
menuIndex = -1,
|
||||
itemArray,
|
||||
|
||||
templateView = [templateViews objectAtIndex:count],
|
||||
isPopup = [templateView isKindOfClass:[CPPopUpButton class]];
|
||||
|
||||
if (isPopup)
|
||||
{
|
||||
itemArray = [[templateView itemArray] valueForKey:@"title"];
|
||||
itemsCount = [itemArray count];
|
||||
menuIndex = 0;
|
||||
}
|
||||
|
||||
for (; menuIndex < itemsCount; menuIndex++)
|
||||
{
|
||||
var item = [_CPPredicateEditorTree new];
|
||||
[item setIndexIntoTemplate:count];
|
||||
[item setTemplate:aTemplate];
|
||||
[item setMenuItemIndex:menuIndex];
|
||||
if (isPopup)
|
||||
[item setTitle:[itemArray objectAtIndex:menuIndex]];
|
||||
|
||||
[children addObject:item];
|
||||
}
|
||||
|
||||
[children makeObjectsPerformSelector:@selector(setChildren:) withObject:tree];
|
||||
tree = children;
|
||||
}
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
#pragma mark Set the Predicate
|
||||
|
||||
- (void)setObjectValue:(id)objectValue
|
||||
{
|
||||
var ov = [self objectValue];
|
||||
if ((ov == nil) != (objectValue == nil) || ![ov isEqual:objectValue])
|
||||
{
|
||||
[self _setPredicate:objectValue];
|
||||
[self _reflectPredicate:objectValue];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_reflectPredicate:(id)predicate
|
||||
{
|
||||
var animation = _currentAnimation;
|
||||
_currentAnimation = nil;
|
||||
_sendAction = NO;
|
||||
|
||||
if (predicate != nil)
|
||||
{
|
||||
if ((_nestingMode == CPRuleEditorNestingModeSimple || _nestingMode == CPRuleEditorNestingModeCompound)
|
||||
&& [predicate isKindOfClass:[CPComparisonPredicate class]])
|
||||
predicate = [[CPCompoundPredicate alloc] initWithType:[self _compoundPredicateTypeForRootRows] subpredicates:[CPArray arrayWithObject:predicate]];
|
||||
|
||||
var row = [self _rowObjectFromPredicate:predicate];
|
||||
if (row != nil)
|
||||
[_boundArrayOwner setValue:[CPArray arrayWithObject:row] forKey:_boundArrayKeyPath];
|
||||
}
|
||||
|
||||
[self setAnimation:animation];
|
||||
}
|
||||
|
||||
- (id)_rowObjectFromPredicate:(CPPredicate)predicate
|
||||
{
|
||||
var quality, // TODO: We should use this ref somewhere !
|
||||
type,
|
||||
matchedTemplate = [CPPredicateEditorRowTemplate _bestMatchForPredicate:predicate inTemplates:[self rowTemplates] quality:quality];
|
||||
|
||||
if (matchedTemplate == nil)
|
||||
return nil;
|
||||
|
||||
var copyTemplate = [matchedTemplate copy],
|
||||
subpredicates = [matchedTemplate displayableSubpredicatesOfPredicate:predicate];
|
||||
|
||||
if (subpredicates == nil)
|
||||
{
|
||||
[copyTemplate _setComparisonPredicate:predicate];
|
||||
type = CPRuleEditorRowTypeSimple;
|
||||
}
|
||||
else
|
||||
{
|
||||
[copyTemplate _setCompoundPredicate:predicate];
|
||||
type = CPRuleEditorRowTypeCompound;
|
||||
}
|
||||
|
||||
var row = [self _rowFromTemplate:copyTemplate originalTemplate:matchedTemplate withRowType:type];
|
||||
|
||||
if (subpredicates == nil)
|
||||
return row;
|
||||
|
||||
var count = [subpredicates count],
|
||||
subrows = [CPMutableArray array];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var subrow = [self _rowObjectFromPredicate:subpredicates[i]];
|
||||
if (subrow != nil)
|
||||
[subrows addObject:subrow];
|
||||
}
|
||||
|
||||
[row setValue:subrows forKey:[super subrowsKeyPath]];
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
- (id)_rowFromTemplate:(CPPredicateEditorRowTemplate)aTemplate originalTemplate:(CPPredicateEditorRowTemplate)originalTemplate withRowType:(CPRuleEditorRowType)rowType
|
||||
{
|
||||
var criteria = [CPArray array],
|
||||
values = [CPArray array],
|
||||
templateViews = [aTemplate templateViews],
|
||||
rootItems,
|
||||
count;
|
||||
|
||||
rootItems = (rowType == CPRuleEditorRowTypeSimple) ? _rootTrees : _rootHeaderTrees;
|
||||
|
||||
while ((count = [rootItems count]) > 0)
|
||||
{
|
||||
var treeChild;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
treeChild = [rootItems objectAtIndex:i];
|
||||
|
||||
var currentView = [templateViews objectAtIndex:[treeChild indexIntoTemplate]],
|
||||
title = [treeChild title];
|
||||
|
||||
if (title == nil || [title isEqual:[currentView titleOfSelectedItem]])
|
||||
{
|
||||
var node = [_CPPredicateEditorRowNode rowNodeFromTree:treeChild];
|
||||
[node applyTemplate:aTemplate withViews:templateViews forOriginalTemplate:originalTemplate];
|
||||
|
||||
[criteria addObject:node];
|
||||
[values addObject:[node displayValue]];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
rootItems = [treeChild children];
|
||||
}
|
||||
|
||||
var row = @{
|
||||
@"criteria": criteria,
|
||||
@"displayValues": values,
|
||||
@"rowType": rowType,
|
||||
};
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
#pragma mark Get the predicate
|
||||
|
||||
- (void)_updatePredicate
|
||||
{
|
||||
[self _updatePredicateFromRows];
|
||||
}
|
||||
|
||||
- (void)_updatePredicateFromRows
|
||||
{
|
||||
var rootRowsArray = [super _rootRowsArray],
|
||||
subpredicates = [CPMutableArray array],
|
||||
count,
|
||||
count2 = count = [rootRowsArray count],
|
||||
predicate;
|
||||
|
||||
while (count--)
|
||||
{
|
||||
var item = [rootRowsArray objectAtIndex:count],
|
||||
subpredicate = [self _predicateFromRowItem:item];
|
||||
|
||||
if (subpredicate != nil)
|
||||
[subpredicates insertObject:subpredicate atIndex:0];
|
||||
}
|
||||
|
||||
if (_nestingMode != CPRuleEditorNestingModeList && count2 == 1)
|
||||
predicate = [subpredicates lastObject];
|
||||
else
|
||||
predicate = [[CPCompoundPredicate alloc] initWithType:[self _compoundPredicateTypeForRootRows] subpredicates:subpredicates];
|
||||
|
||||
[self _setPredicate:predicate];
|
||||
}
|
||||
|
||||
- (id)_predicateFromRowItem:(id)rowItem
|
||||
{
|
||||
var subpredicates = [CPArray array],
|
||||
rowType = [rowItem valueForKey:_typeKeyPath];
|
||||
|
||||
if (rowType == CPRuleEditorRowTypeCompound)
|
||||
{
|
||||
var subrows = [rowItem valueForKey:_subrowsArrayKeyPath],
|
||||
count = [subrows count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var subrow = [subrows objectAtIndex:i],
|
||||
predicate = [self _predicateFromRowItem:subrow];
|
||||
|
||||
[subpredicates addObject:predicate];
|
||||
}
|
||||
}
|
||||
|
||||
var criteria = [rowItem valueForKey:_itemsKeyPath],
|
||||
displayValues = [rowItem valueForKey:_valuesKeyPath],
|
||||
count = [criteria count],
|
||||
lastItem = [criteria lastObject],
|
||||
template = [lastItem templateForRow],
|
||||
templateViews = [template templateViews];
|
||||
|
||||
for (var j = 0; j < count; j++)
|
||||
{
|
||||
var view = [templateViews objectAtIndex:j],
|
||||
value = [displayValues objectAtIndex:j];
|
||||
[[criteria objectAtIndex:j] setTemplateViews:templateViews];
|
||||
|
||||
if ([view isKindOfClass:[CPPopUpButton class]])
|
||||
[view selectItemWithTitle:value];
|
||||
else if ([view respondsToSelector:@selector(setObjectValue:)])
|
||||
[view setObjectValue:[value objectValue]];
|
||||
}
|
||||
|
||||
return [template predicateWithSubpredicates:subpredicates];
|
||||
}
|
||||
|
||||
- (CPCompoundPredicateType)_compoundPredicateTypeForRootRows
|
||||
{
|
||||
return CPAndPredicateType;
|
||||
}
|
||||
|
||||
#pragma mark Control delegate
|
||||
|
||||
- (void)_sendRuleAction
|
||||
{
|
||||
[super _sendRuleAction];
|
||||
}
|
||||
|
||||
- (BOOL)_sendsActionOnIncompleteTextChange
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
/*
|
||||
- (void)_setDefaultTargetAndActionOnView:(CPView)view
|
||||
{
|
||||
if ([view isKindOfClass:[CPControl class]])
|
||||
{
|
||||
[view setTarget:self];
|
||||
[view setAction:@selector(_templateControlValueDidChange:)];
|
||||
}
|
||||
}
|
||||
- (void)_templateControlValueDidChange:(id)sender
|
||||
{
|
||||
}
|
||||
- (void)controlTextDidBeginEditing:(CPNotification)notification
|
||||
{
|
||||
}
|
||||
- (void)controlTextDidEndEditing:(CPNotification)notification
|
||||
{
|
||||
}
|
||||
- (void)controlTextDidChange:(CPNotification)notification
|
||||
{
|
||||
}
|
||||
*/
|
||||
|
||||
#pragma mark RuleEditor delegate methods
|
||||
|
||||
- (int)_queryNumberOfChildrenOfItem:(id)rowItem withRowType:(CPRuleEditorRowType)type
|
||||
{
|
||||
if (rowItem == nil)
|
||||
{
|
||||
var trees = (type == CPRuleEditorRowTypeSimple) ? _rootTrees : _rootHeaderTrees;
|
||||
return [trees count];
|
||||
}
|
||||
return [[rowItem children] count];
|
||||
}
|
||||
|
||||
- (id)_queryChild:(int)childIndex ofItem:(id)rowItem withRowType:(CPRuleEditorRowType)type
|
||||
{
|
||||
if (rowItem == nil)
|
||||
{
|
||||
var trees = (type == CPRuleEditorRowTypeSimple) ? _rootTrees : _rootHeaderTrees;
|
||||
return [_CPPredicateEditorRowNode rowNodeFromTree:trees[childIndex]];
|
||||
}
|
||||
|
||||
return [[rowItem children] objectAtIndex:childIndex];
|
||||
}
|
||||
|
||||
- (id)_queryValueForItem:(id)rowItem inRow:(CPInteger)rowIndex
|
||||
{
|
||||
return [rowItem displayValue];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPPredicateTemplatesKey = @"CPPredicateTemplates";
|
||||
|
||||
@implementation CPPredicateEditor (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
self = [super initWithCoder:aCoder];
|
||||
|
||||
if (self != nil)
|
||||
{
|
||||
var nibTemplates = [aCoder decodeObjectForKey:CPPredicateTemplatesKey];
|
||||
|
||||
if (nibTemplates != nil)
|
||||
[self setRowTemplates:nibTemplates];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[super encodeWithCoder:aCoder];
|
||||
[aCoder encodeObject:_allTemplates forKey:CPPredicateTemplatesKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation CPPredicateEditorValueBinder : CPBinder
|
||||
{
|
||||
}
|
||||
|
||||
- (void)setPlaceholderValue:(id)aValue withMarker:(CPString)aMarker forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source _reflectPredicate:nil];
|
||||
}
|
||||
|
||||
- (void)setValue:(id)aValue forBinding:(CPString)aBinding
|
||||
{
|
||||
[_source _reflectPredicate:aValue];
|
||||
}
|
||||
|
||||
@end
|
||||
/*! @endcond */
|
||||
@@ -1,860 +0,0 @@
|
||||
/*
|
||||
* CPPredicateEditorRowTemplate.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by cacaodev.
|
||||
* Copyright 2011, cacaodev.
|
||||
*
|
||||
* 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 <Foundation/CPPredicate.j>
|
||||
|
||||
@import "CPCheckBox.j"
|
||||
@import "CPPopUpButton.j"
|
||||
@import "CPMenuItem.j"
|
||||
@import "CPTextField.j"
|
||||
|
||||
@import "CPDatePicker.j"
|
||||
|
||||
|
||||
CPUndefinedAttributeType = 0;
|
||||
CPInteger16AttributeType = 100;
|
||||
CPInteger32AttributeType = 200;
|
||||
CPInteger64AttributeType = 300;
|
||||
CPDecimalAttributeType = 400;
|
||||
CPDoubleAttributeType = 500;
|
||||
CPFloatAttributeType = 600;
|
||||
CPStringAttributeType = 700;
|
||||
CPBooleanAttributeType = 800;
|
||||
CPDateAttributeType = 900;
|
||||
CPBinaryDataAttributeType = 1000;
|
||||
CPTransformableAttributeType = 1800;
|
||||
|
||||
@implementation CPPredicateEditorRowTemplate : CPObject
|
||||
{
|
||||
int _templateType @accessors(readwrite, getter=_templateType, setter=_setTemplateType:);
|
||||
unsigned _predicateOptions @accessors(readwrite, setter=_setOptions:);
|
||||
unsigned _predicateModifier @accessors(readwrite, setter=_setModifier:);
|
||||
unsigned _leftAttributeType @accessors(readwrite, getter=leftAttributeType, setter=_setLeftAttributeType:);
|
||||
unsigned _rightAttributeType @accessors(readwrite, getter=rightAttributeType, setter=_setRightAttributeType:);
|
||||
BOOL _leftIsWildcard @accessors(property=leftIsWildcard);
|
||||
BOOL _rightIsWildcard @accessors(property=rightIsWildcard);
|
||||
CPArray _views @accessors(setter=setTemplateViews:);
|
||||
|
||||
}
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPPredicateEditorRowTemplate
|
||||
|
||||
@brief CPPredicateEditorRowTemplate describes available predicates and how to display them.
|
||||
|
||||
You can create instances of CPPredicateEditorRowTemplate programmatically or in Interface Builder. By default, a non-compound row template has three views: a popup (or static text field) on the left, a popup or static text field for operators, and either a popup or other view on the right. You can subclass CPPredicateEditorRowTemplate to create a row template with different numbers or types of views.
|
||||
|
||||
CPPredicateEditorRowTemplate is a concrete class, but it has five primitive methods which are called by CPPredicateEditor: -#templateViews, -#matchForPredicate:, -#setPredicate:, -#displayableSubpredicatesOfPredicate:, and -#predicateWithSubpredicates:. CPPredicateEditorRowTemplate implements all of them, but you can override them for custom templates. The primitive methods are used by an instance of CPPredicateEditor as follows.
|
||||
|
||||
First, an instance of CPPredicateEditor is created, and some row templates are set on it—either through a nib file or programmatically. The first thing predicate editor does is ask each of the templates for their views, using templateViews.
|
||||
|
||||
After setting up the predicate editor, you typically send it a CPPredicateEditor#setObjectValue: message to restore a saved predicate. CPPredicateEditor needs to determine which of its templates should display each predicate in the predicate tree. It does this by sending each of its row templates a matchForPredicate: message and choosing the one that returns the highest value.
|
||||
|
||||
After finding the best match for a predicate, CPPredicateEditor copies that template to get fresh views, inserts them into the proper row, and then sets the predicate on the template using setPredicate:. Within that method, the CPPredicateEditorRowTemplate object must set its views' values to represent that predicate.
|
||||
|
||||
CPPredicateEditorRowTemplate next asks the template for the “displayable sub-predicates” of the predicate by sending a -#displayableSubpredicatesOfPredicate: message. If a template represents a predicate in its entirety, or if the predicate has no subpredicates, it can return nil for this. Otherwise, it should return a list of predicates to be made into sub-rows of that template's row. The whole process repeats for each sub-predicate.
|
||||
|
||||
At this point, the user sees the predicate that was saved. If the user then makes some changes to the views of the templates, this causes CPPredicateEditor to recompute its predicate by asking each of the templates to return the predicate represented by the new view values, passing in the subpredicates represented by the sub-rows (an empty array if there are none, or nil if they aren't supported by that predicate type).
|
||||
*/
|
||||
|
||||
/*!
|
||||
@name Initializing a Template
|
||||
*/
|
||||
|
||||
/*!
|
||||
@brief Initializes and returns a “pop-up-pop-up-pop-up”-style row template.
|
||||
@param leftExpressions An array of CPExpression objects that represent the left hand side of a predicate.
|
||||
@param rightExpressions An array of CPExpression objects that represent the right hand side of a predicate.
|
||||
@param modifier A modifier for the predicate (see @c CPComparisonPredicateModifier for possible values).
|
||||
@param operators An array of CPNumber objects specifying the operator type (see @c CPPredicateOperatorType for possible values).
|
||||
@param options Options for the predicate (see @c CPComparisonPredicateOptions for possible values).
|
||||
@return A row template of the “pop-up-pop-up-pop-up”-form, with the left and right popups representing the left and right expression arrays -#leftExpressions and -#rightExpressions, and the center popup representing the operators.
|
||||
*/
|
||||
- (id)initWithLeftExpressions:(CPArray)leftExpressions rightExpressions:(CPArray)rightExpressions modifier:(int)modifier operators:(CPArray)operators options:(int)options
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
_templateType = 1;
|
||||
_leftIsWildcard = NO;
|
||||
_rightIsWildcard = NO;
|
||||
_leftAttributeType = 0;
|
||||
_rightAttributeType = 0;
|
||||
_predicateModifier = modifier;
|
||||
_predicateOptions = options;
|
||||
|
||||
var leftView = [self _viewFromExpressions:leftExpressions],
|
||||
rightView = [self _viewFromExpressions:rightExpressions],
|
||||
middleView = [self _viewFromOperatorTypes:operators];
|
||||
|
||||
_views = [[CPArray alloc] initWithObjects:leftView, middleView, rightView];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Initializes and returns a “pop-up-pop-up-view”-style row template.
|
||||
@param leftExpressions An array of CPExpression objects that represent the left hand side of a predicate.
|
||||
@param attributeType An attribute type for the right hand side of a predicate. This value dictates the type of view created, and how the control’s object value is coerced before putting it into a predicate.
|
||||
@param modifier A modifier for the predicate (see @c CPComparisonPredicateModifier for possible values).
|
||||
@param operators An array of CPNumber objects specifying the operator type (see @c CPPredicateOperatorType for possible values).
|
||||
@param options Options for the predicate (see CPComparisonPredicateOptions for possible values).
|
||||
@return A row template initialized using the given arguments.
|
||||
*/
|
||||
- (id)initWithLeftExpressions:(CPArray )leftExpressions rightExpressionAttributeType:(CPAttributeType)attributeType modifier:(CPComparisonPredicateModifier)modifier operators:(CPArray )operators options:(int)options
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
var leftView = [self _viewFromExpressions:leftExpressions],
|
||||
middleView = [self _viewFromOperatorTypes:operators],
|
||||
rightView = [self _viewFromAttributeType:attributeType];
|
||||
|
||||
_templateType = 1;
|
||||
_leftIsWildcard = NO;
|
||||
_rightIsWildcard = YES;
|
||||
_leftAttributeType = 0;
|
||||
_rightAttributeType = attributeType;
|
||||
_predicateModifier = modifier;
|
||||
_predicateOptions = options;
|
||||
_views = [[CPArray alloc] initWithObjects:leftView, middleView, rightView];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Initializes and returns a row template suitable for displaying compound predicates.
|
||||
@param compoundTypes An array of CPNumber objects specifying compound predicate types. See @c CPCompoundPredicateTypes for possible values.
|
||||
@return A row template initialized for displaying compound predicates of the types specified by @a compoundTypes.
|
||||
@discussion CPPredicateEditor contains such a template by default.
|
||||
*/
|
||||
- (id)initWithCompoundTypes:(CPArray )compoundTypes
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
var leftView = [self _viewFromCompoundTypes:compoundTypes],
|
||||
rightView = [[CPPopUpButton alloc] init];
|
||||
|
||||
[rightView addItemWithTitle:@"of the following are true"];
|
||||
|
||||
_templateType = 2;
|
||||
_leftIsWildcard = NO;
|
||||
_rightIsWildcard = NO;
|
||||
_rightAttributeType = 0;
|
||||
_views = [[CPArray alloc] initWithObjects:leftView, rightView];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
/*!
|
||||
@name Primitive Methods
|
||||
*/
|
||||
|
||||
/*!
|
||||
@brief Returns a positive number if the receiver can represent a given predicate, and 0 if it cannot.
|
||||
@return A positive number if the template can represent predicate, and @c 0 if it cannot.
|
||||
@discussion By default, returns values in the range @c 0 to @c 1.
|
||||
The highest match among all the templates determines which template is responsible for displaying the predicate. You can override this to determine which predicates your custom template handles.
|
||||
*/
|
||||
- (double)matchForPredicate:(CPPredicate)predicate
|
||||
{
|
||||
// How exactly this value (float 0-1) is computed ?
|
||||
if ([self _templateType] == 2 && [predicate isKindOfClass:[CPCompoundPredicate class]])
|
||||
{
|
||||
if ([[self compoundTypes] containsObject:[predicate compoundPredicateType]])
|
||||
return 1;
|
||||
}
|
||||
else if ([self _templateType] == 1 && [predicate isKindOfClass:[CPComparisonPredicate class]])
|
||||
{
|
||||
if (!_leftIsWildcard && ![[self leftExpressions] containsObject:[predicate leftExpression]])
|
||||
return 0;
|
||||
|
||||
if (![[self operators] containsObject:[predicate predicateOperatorType]])
|
||||
return 0;
|
||||
|
||||
if (!_rightIsWildcard && ![[self rightExpressions] containsObject:[predicate rightExpression]])
|
||||
return 0;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the views for the receiver.
|
||||
@return The views for the receiver.
|
||||
@discussion Instances of CPPopUpButton are treated specially by CPPredicateEditor; their menu items are merged into a single popup button, and matching menu item titles are combined. In this way, a single tree is built from the separate templates.
|
||||
*/
|
||||
- (CPArray)templateViews
|
||||
{
|
||||
return _views;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Sets the value of the views according to the given predicate.
|
||||
@param predicate The predicate value for the receiver.
|
||||
@discussion This method is only called if -#matchForPredicate: returned a positive value for the receiver.
|
||||
|
||||
You can override this to set the values of custom views.
|
||||
*/
|
||||
- (void)setPredicate:(CPPredicate)predicate
|
||||
{
|
||||
if (_templateType == 2)
|
||||
[self _setCompoundPredicate:predicate];
|
||||
else
|
||||
[self _setComparisonPredicate:predicate];
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the subpredicates that should be made sub-rows of a given predicate.
|
||||
@param predicate A predicate object.
|
||||
@return The subpredicates that should be made sub-rows of @a predicate. For compound predicates (instances of CPCompoundPredicate), the array of subpredicates; for other types of predicate, returns @c nil. If a template represents a predicate in its entirety, or if the predicate has no subpredicates, returns @c nil.
|
||||
@discussion You can override this method to create custom templates that handle complicated compound predicates.
|
||||
*/
|
||||
- (CPArray)displayableSubpredicatesOfPredicate:(CPPredicate)predicate
|
||||
{
|
||||
if ([predicate isKindOfClass:[CPCompoundPredicate class]])
|
||||
{
|
||||
var subpredicates = [predicate subpredicates];
|
||||
if ([subpredicates count] == 0)
|
||||
return nil;
|
||||
|
||||
return subpredicates;
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the predicate represented by the receiver’s views' values and the given sub-predicates.
|
||||
@param subpredicates An array of predicates.
|
||||
@return The predicate represented by the values of the template's views and the given @a subpredicates. You can override this method to return the predicate represented by your custom views.
|
||||
@discussion This method is only called if -#matchForPredicate: returned a positive value for the receiver.
|
||||
|
||||
You can override this method to return the predicate represented by a custom view.
|
||||
*/
|
||||
- (CPPredicate)predicateWithSubpredicates:(CPArray)subpredicates
|
||||
{
|
||||
if (_templateType == 2)
|
||||
{
|
||||
var type = [[_views[0] selectedItem] representedObject];
|
||||
return [[CPCompoundPredicate alloc] initWithType:type subpredicates:subpredicates];
|
||||
}
|
||||
|
||||
if (_templateType == 1)
|
||||
{
|
||||
var lhs = [self _leftExpression],
|
||||
rhs = [self _rightExpression],
|
||||
operator = [[_views[1] selectedItem] representedObject];
|
||||
|
||||
return [CPComparisonPredicate predicateWithLeftExpression:lhs
|
||||
rightExpression:rhs
|
||||
modifier:[self modifier]
|
||||
type:operator
|
||||
options:[self options]];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@name Information About a Row Template
|
||||
*/
|
||||
|
||||
/*!
|
||||
@brief Returns the left hand expressions for the receiver.
|
||||
@return The left hand expressions for the receiver.
|
||||
*/
|
||||
- (CPArray)leftExpressions
|
||||
{
|
||||
if (_templateType == 1 && !_leftIsWildcard)
|
||||
{
|
||||
var view = [_views objectAtIndex:0];
|
||||
return [[view itemArray] valueForKey:@"representedObject"];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the right hand expressions for the receiver.
|
||||
@return The right hand expressions for the receiver.
|
||||
*/
|
||||
- (CPArray)rightExpressions
|
||||
{
|
||||
if (_templateType == 1 && !_rightIsWildcard)
|
||||
{
|
||||
var view = [_views objectAtIndex:2];
|
||||
return [[view itemArray] valueForKey:@"representedObject"];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the compound predicate types for the receiver.
|
||||
@return An array of CPNumber objects specifying compound predicate types. See @c CompoundPredicateTypes for possible values.
|
||||
*/
|
||||
- (CPArray)compoundTypes
|
||||
{
|
||||
if (_templateType == 2)
|
||||
{
|
||||
var view = [_views objectAtIndex:0];
|
||||
return [[view itemArray] valueForKey:@"representedObject"];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the comparison predicate modifier for the receiver.
|
||||
@return The comparison predicate modifier for the receiver.
|
||||
*/
|
||||
- (CPComparisonPredicateModifier)modifier
|
||||
{
|
||||
if (_templateType == 1)
|
||||
return _predicateModifier;
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns Returns the array of operators for the receiver.
|
||||
@return The array of operators for the receiver.
|
||||
*/
|
||||
- (CPArray)operators
|
||||
{
|
||||
if (_templateType == 1)
|
||||
{
|
||||
var view = [_views objectAtIndex:1];
|
||||
return [[view itemArray] valueForKey:@"representedObject"];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the comparison predicate options for the receiver.
|
||||
@return The comparison predicate options for the receiver. See @c CPComparisonPredicateOptions for possible values. Returns @c 0 if this does not apply (for example, for a compound template initialized with -#initWithCompoundTypes:).
|
||||
*/
|
||||
- (int)options
|
||||
{
|
||||
if (_templateType == 1)
|
||||
return _predicateOptions;
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the attribute type of the receiver’s right expression.
|
||||
@return The attribute type of the receiver’s right expression.
|
||||
*/
|
||||
- (CPAttributeType)rightExpressionAttributeType
|
||||
{
|
||||
return _rightAttributeType;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief Returns the attribute type of the receiver’s left expression.
|
||||
@return The attribute type of the receiver’s left expression.
|
||||
*/
|
||||
- (CPAttributeType)leftExpressionAttributeType
|
||||
{
|
||||
return _leftAttributeType;
|
||||
}
|
||||
|
||||
/*! @cond */
|
||||
+ (id)_bestMatchForPredicate:(CPPredicate)predicate inTemplates:(CPArray)templates quality:(double)quality
|
||||
{
|
||||
var count = [templates count],
|
||||
match_value = 0,
|
||||
templateIndex = CPNotFound,
|
||||
i;
|
||||
|
||||
for (i = 0; i < count; i++)
|
||||
{
|
||||
var template = [templates objectAtIndex:i],
|
||||
amatch = [template matchForPredicate:predicate];
|
||||
|
||||
if (amatch > match_value)
|
||||
{
|
||||
templateIndex = i;
|
||||
match_value = amatch;
|
||||
}
|
||||
}
|
||||
|
||||
if (templateIndex == CPNotFound)
|
||||
{
|
||||
[CPException raise:CPRangeException reason:@"Unable to find template matching predicate: " + [predicate predicateFormat]];
|
||||
return nil;
|
||||
}
|
||||
|
||||
return [templates objectAtIndex:templateIndex];
|
||||
}
|
||||
|
||||
- (void)_setCompoundPredicate:(CPCompoundPredicate)predicate
|
||||
{
|
||||
var left = [_views objectAtIndex:0],
|
||||
type = [predicate compoundPredicateType],
|
||||
index = [left indexOfItemWithRepresentedObject:type];
|
||||
|
||||
[left selectItemAtIndex:index];
|
||||
}
|
||||
|
||||
- (void)_setComparisonPredicate:(CPComparisonPredicate)predicate
|
||||
{
|
||||
var left = [_views objectAtIndex:0],
|
||||
middle = [_views objectAtIndex:1],
|
||||
right = [_views objectAtIndex:2],
|
||||
leftExpression = [predicate leftExpression],
|
||||
rightExpression = [predicate rightExpression],
|
||||
operator = [predicate predicateOperatorType];
|
||||
|
||||
if (_leftIsWildcard)
|
||||
[left setObjectValue:[leftExpression constantValue]];
|
||||
else
|
||||
{
|
||||
var index = [left indexOfItemWithRepresentedObject:leftExpression];
|
||||
[left selectItemAtIndex:index];
|
||||
}
|
||||
|
||||
var op_index = [middle indexOfItemWithRepresentedObject:operator];
|
||||
[middle selectItemAtIndex:op_index];
|
||||
|
||||
if (_rightIsWildcard)
|
||||
[right setObjectValue:[rightExpression constantValue]];
|
||||
else
|
||||
{
|
||||
var index = [right indexOfItemWithRepresentedObject:rightExpression];
|
||||
[right selectItemAtIndex:index];
|
||||
}
|
||||
}
|
||||
|
||||
- (CPExpression)_leftExpression
|
||||
{
|
||||
return [self _expressionFromView:_views[0] forAttributeType:_leftAttributeType];
|
||||
}
|
||||
|
||||
- (CPExpression)_rightExpression
|
||||
{
|
||||
return [self _expressionFromView:_views[2] forAttributeType:_rightAttributeType];
|
||||
}
|
||||
|
||||
- (CPExpression)_expressionFromView:(CPView)aView forAttributeType:(CPAttributeType)attributeType
|
||||
{
|
||||
if (attributeType == 0)
|
||||
return [[aView selectedItem] representedObject];
|
||||
|
||||
var value;
|
||||
if (attributeType >= CPInteger16AttributeType && attributeType <= CPFloatAttributeType)
|
||||
value = [aView floatValue];
|
||||
else if (attributeType == CPBooleanAttributeType)
|
||||
value = [aView state];
|
||||
else if (attributeType == CPDateAttributeType)
|
||||
value = [aView dateValue];
|
||||
else
|
||||
value = [aView stringValue];
|
||||
|
||||
return [CPExpression expressionForConstantValue:value];
|
||||
}
|
||||
|
||||
- (int)_rowType
|
||||
{
|
||||
return (_templateType - 1);
|
||||
}
|
||||
|
||||
- (id)copy
|
||||
{
|
||||
var views = [CPArray array],
|
||||
copy = [[[self class] alloc] init];
|
||||
|
||||
[copy _setTemplateType:_templateType];
|
||||
[copy _setOptions:_predicateOptions];
|
||||
[copy _setModifier:_predicateModifier];
|
||||
[copy _setLeftAttributeType:_leftAttributeType];
|
||||
[copy _setRightAttributeType:_rightAttributeType];
|
||||
[copy setLeftIsWildcard:_leftIsWildcard];
|
||||
[copy setRightIsWildcard:_rightIsWildcard];
|
||||
|
||||
[_views enumerateObjectsUsingBlock:function(aView, idx, stop)
|
||||
{
|
||||
var vcopy;
|
||||
|
||||
if ([aView implementsSelector:@selector(copy)])
|
||||
{
|
||||
vcopy = [aView copy];
|
||||
}
|
||||
else
|
||||
{
|
||||
vcopy = [CPKeyedUnarchiver unarchiveObjectWithData:[CPKeyedArchiver archivedDataWithRootObject:aView]];
|
||||
}
|
||||
|
||||
[views addObject:vcopy];
|
||||
}];
|
||||
|
||||
[copy setTemplateViews:views];
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
+ (id)_operatorsForAttributeType:(CPAttributeType)attributeType
|
||||
{
|
||||
var operators_array = [CPMutableArray array];
|
||||
|
||||
switch (attributeType)
|
||||
{
|
||||
case CPInteger16AttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
case CPInteger32AttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
case CPInteger64AttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
case CPDecimalAttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
case CPDoubleAttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
case CPFloatAttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
case CPStringAttributeType : [operators_array addObjects:99,4,5,8,9];
|
||||
break;
|
||||
case CPBooleanAttributeType : [operators_array addObjects:4,5];
|
||||
break;
|
||||
case CPDateAttributeType : [operators_array addObjects:4,5,0,2,1,3];
|
||||
break;
|
||||
default : CPLogConsole("Cannot create operators for an CPAttributeType " + attributeType);
|
||||
break;
|
||||
}
|
||||
|
||||
return operators_array;
|
||||
}
|
||||
|
||||
- (int)_templateType
|
||||
{
|
||||
return _templateType;
|
||||
}
|
||||
|
||||
- (id)_displayValueForPredicateOperator:(int)operator
|
||||
{
|
||||
var value;
|
||||
|
||||
switch (operator)
|
||||
{
|
||||
case CPLessThanPredicateOperatorType : value = @"is less than";
|
||||
break;
|
||||
case CPLessThanOrEqualToPredicateOperatorType : value = @"is less than or equal to";
|
||||
break;
|
||||
case CPGreaterThanPredicateOperatorType : value = @"is greater than";
|
||||
break;
|
||||
case CPGreaterThanOrEqualToPredicateOperatorType : value = @"is greater than or equal to";
|
||||
break;
|
||||
case CPEqualToPredicateOperatorType : value = @"is";
|
||||
break;
|
||||
case CPNotEqualToPredicateOperatorType : value = @"is not";
|
||||
break;
|
||||
case CPMatchesPredicateOperatorType : value = @"matches";
|
||||
break;
|
||||
case CPLikePredicateOperatorType : value = @"is like";
|
||||
break;
|
||||
case CPBeginsWithPredicateOperatorType : value = @"begins with";
|
||||
break;
|
||||
case CPEndsWithPredicateOperatorType : value = @"ends with";
|
||||
break;
|
||||
case CPInPredicateOperatorType : value = @"in";
|
||||
break;
|
||||
case CPContainsPredicateOperatorType : value = @"contains";
|
||||
break;
|
||||
case CPBetweenPredicateOperatorType : value = @"between";
|
||||
break;
|
||||
default : CPLogConsole(@"unknown predicate operator %d" + operator);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
- (id)_displayValueForCompoundPredicateType:(unsigned int)predicateType
|
||||
{
|
||||
var value;
|
||||
switch (predicateType)
|
||||
{
|
||||
case CPNotPredicateType: value = @"None";
|
||||
break;
|
||||
case CPAndPredicateType: value = @"All";
|
||||
break;
|
||||
case CPOrPredicateType: value = @"Any";
|
||||
break;
|
||||
default : value = [CPString stringWithFormat:@"unknown compound predicate type %d",predicateType];
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
- (id)_displayValueForConstantValue:(id)value
|
||||
{
|
||||
return [value description]; // number, date, string, ... localize
|
||||
}
|
||||
|
||||
- (id)_displayValueForKeyPath:(CPString)keyPath
|
||||
{
|
||||
return keyPath; // localize
|
||||
}
|
||||
|
||||
- (CPPopUpButton)_viewFromExpressions:(CPArray)expressions
|
||||
{
|
||||
var popup = [[CPPopUpButton alloc] initWithFrame:CGRectMake(0, 0, 100, 18)],
|
||||
count = [expressions count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var exp = expressions[i],
|
||||
type = [exp expressionType],
|
||||
title;
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case CPKeyPathExpressionType: title = [self _displayValueForKeyPath:[exp keyPath]];
|
||||
break;
|
||||
case CPConstantValueExpressionType: title = [self _displayValueForConstantValue:[exp constantValue]];
|
||||
break;
|
||||
default: [CPException raise:CPInvalidArgumentException reason:@"Invalid Expression type " + type];
|
||||
break;
|
||||
}
|
||||
|
||||
var item = [[CPMenuItem alloc] initWithTitle:title action:nil keyEquivalent:@""];
|
||||
[item setRepresentedObject:exp];
|
||||
[popup addItem:item];
|
||||
}
|
||||
|
||||
[popup sizeToFit];
|
||||
|
||||
return popup;
|
||||
}
|
||||
|
||||
- (CPPopUpButton)_viewFromOperatorTypes:(CPArray)operators
|
||||
{
|
||||
var popup = [[CPPopUpButton alloc] initWithFrame:CGRectMake(0, 0, 100, 18)],
|
||||
count = [operators count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var op = operators[i],
|
||||
title = [self _displayValueForPredicateOperator:op],
|
||||
item = [[CPMenuItem alloc] initWithTitle:title action:nil keyEquivalent:@""];
|
||||
|
||||
[item setRepresentedObject:op];
|
||||
[popup addItem:item];
|
||||
}
|
||||
|
||||
[popup sizeToFit];
|
||||
|
||||
return popup;
|
||||
}
|
||||
|
||||
- (CPView)_viewFromCompoundTypes:(CPArray)compoundTypes
|
||||
{
|
||||
var popup = [[CPPopUpButton alloc] initWithFrame:CGRectMake(0, 0, 100, 18)],
|
||||
count = [compoundTypes count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var type = compoundTypes[i],
|
||||
title = [self _displayValueForCompoundPredicateType:type],
|
||||
item = [[CPMenuItem alloc] initWithTitle:title action:nil keyEquivalent:@""];
|
||||
|
||||
[item setRepresentedObject:type];
|
||||
[popup addItem:item];
|
||||
}
|
||||
|
||||
[popup sizeToFit];
|
||||
|
||||
return popup;
|
||||
}
|
||||
|
||||
- (CPView)_viewFromAttributeType:(CPAttributeType)attributeType
|
||||
{
|
||||
var view;
|
||||
|
||||
if (attributeType >= CPInteger16AttributeType && attributeType <= CPFloatAttributeType)
|
||||
{
|
||||
view = [self _textFieldWithFrame:CGRectMake(0, 0, 50, 26)];
|
||||
}
|
||||
else if (attributeType == CPStringAttributeType)
|
||||
{
|
||||
view = [self _textFieldWithFrame:CGRectMake(0, 0, 150, 26)];
|
||||
}
|
||||
else if (attributeType == CPBooleanAttributeType)
|
||||
{
|
||||
view = [[CPCheckBox alloc] initWithFrame:CGRectMake(0, 0, 50, 26)];
|
||||
}
|
||||
else if (attributeType == CPDateAttributeType)
|
||||
{
|
||||
view = [[CPDatePicker alloc] initWithFrame:CGRectMake(0, 0, 180, 26)];
|
||||
[view setDatePickerElements:CPYearMonthDayDatePickerElementFlag];
|
||||
}
|
||||
else
|
||||
return nil;
|
||||
|
||||
[view setTag:attributeType];
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
- (CPTextField)_textFieldWithFrame:(CGRect)frame
|
||||
{
|
||||
var textField = [[CPTextField alloc] initWithFrame:frame];
|
||||
[textField setBezeled:YES];
|
||||
[textField setBezelStyle:CPTextFieldSquareBezel];
|
||||
[textField setBordered:YES];
|
||||
[textField setEditable:YES];
|
||||
[textField setFont:[CPFont systemFontOfSize:10]];
|
||||
[textField setSendsActionOnEndEditing:YES];
|
||||
|
||||
return textField;
|
||||
}
|
||||
|
||||
- (void)_setOptions:(unsigned)options
|
||||
{
|
||||
_predicateOptions = options;
|
||||
}
|
||||
|
||||
- (void)_setModifier:(unsigned)modifier
|
||||
{
|
||||
_predicateModifier = modifier;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
if (_templateType == 2)
|
||||
return [CPString stringWithFormat:@"<%@ %p %@>",[self className],self,[[self compoundTypes] componentsJoinedByString:@", "]];
|
||||
else if (_templateType == 1 && _rightIsWildcard)
|
||||
return [CPString stringWithFormat:@"<%@ %p [%@] [%@] %d>",[self className],self,[[self leftExpressions] componentsJoinedByString:@", "],[[self operators] componentsJoinedByString:@", "],[self rightExpressionAttributeType]];
|
||||
else
|
||||
return [CPString stringWithFormat:@"<%@ %p [%@] [%@] [%@]>",[self className],self,[[self leftExpressions] componentsJoinedByString:@", "],[[self operators] componentsJoinedByString:@", "],[[self rightExpressions] componentsJoinedByString:@", "]];
|
||||
}
|
||||
|
||||
/*
|
||||
- (void)_setLeftExpressionObject:(id)object
|
||||
{
|
||||
}
|
||||
- (void)_setRightExpressionObject:(id)object
|
||||
{
|
||||
}
|
||||
- (BOOL)_predicateIsNoneAreTrue:(id)predicate
|
||||
{
|
||||
}
|
||||
- (id)_viewFromExpressionObject:(id)object
|
||||
{
|
||||
}
|
||||
*/
|
||||
@end
|
||||
|
||||
var CPPredicateTemplateTypeKey = @"CPPredicateTemplateType",
|
||||
CPPredicateTemplateOptionsKey = @"CPPredicateTemplateOptions",
|
||||
CPPredicateTemplateModifierKey = @"CPPredicateTemplateModifier",
|
||||
CPPredicateTemplateLeftAttributeTypeKey = @"CPPredicateTemplateLeftAttributeType",
|
||||
CPPredicateTemplateRightAttributeTypeKey = @"CPPredicateTemplateRightAttributeType",
|
||||
CPPredicateTemplateLeftIsWildcardKey = @"CPPredicateTemplateLeftIsWildcard",
|
||||
CPPredicateTemplateRightIsWildcardKey = @"CPPredicateTemplateRightIsWildcard",
|
||||
CPPredicateTemplateViewsKey = @"CPPredicateTemplateViews";
|
||||
|
||||
@implementation CPPredicateEditorRowTemplate (CPCoding)
|
||||
|
||||
- (id)initWithCoder:(CPCoder)coder
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil)
|
||||
{
|
||||
_templateType = [coder decodeIntForKey:CPPredicateTemplateTypeKey];
|
||||
_predicateOptions = [coder decodeIntForKey:CPPredicateTemplateOptionsKey];
|
||||
_predicateModifier = [coder decodeIntForKey:CPPredicateTemplateModifierKey];
|
||||
_leftAttributeType = [coder decodeIntForKey:CPPredicateTemplateLeftAttributeTypeKey];
|
||||
_rightAttributeType = [coder decodeIntForKey:CPPredicateTemplateRightAttributeTypeKey];
|
||||
_leftIsWildcard = [coder decodeBoolForKey:CPPredicateTemplateLeftIsWildcardKey];
|
||||
_rightIsWildcard = [coder decodeBoolForKey:CPPredicateTemplateRightIsWildcardKey];
|
||||
_views = [coder decodeObjectForKey:CPPredicateTemplateViewsKey];
|
||||
|
||||
// In Xcode 4, when the menu item title == template's expression keypath, representedObject is empty.
|
||||
// So we need to regenerate expressions from titles.
|
||||
if (_templateType == 1 && _leftIsWildcard == NO)
|
||||
{
|
||||
var itemArray = [_views[0] itemArray],
|
||||
count = [itemArray count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var item = itemArray[i];
|
||||
if ([item representedObject] == nil)
|
||||
{
|
||||
var exp = [CPExpression expressionForKeyPath:[item title]];
|
||||
[item setRepresentedObject:exp];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)coder
|
||||
{
|
||||
[coder encodeInt:_templateType forKey:CPPredicateTemplateTypeKey];
|
||||
[coder encodeInt:_predicateOptions forKey:CPPredicateTemplateOptionsKey];
|
||||
[coder encodeInt:_predicateModifier forKey:CPPredicateTemplateModifierKey];
|
||||
[coder encodeInt:_leftAttributeType forKey:CPPredicateTemplateLeftAttributeTypeKey];
|
||||
[coder encodeInt:_rightAttributeType forKey:CPPredicateTemplateRightAttributeTypeKey];
|
||||
[coder encodeBool:_leftIsWildcard forKey:CPPredicateTemplateLeftIsWildcardKey];
|
||||
[coder encodeBool:_rightIsWildcard forKey:CPPredicateTemplateRightIsWildcardKey];
|
||||
[coder encodeObject:_views forKey:CPPredicateTemplateViewsKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
// Copy support for built-in types
|
||||
@implementation CPDatePicker (CPCopying)
|
||||
|
||||
- (id)copy
|
||||
{
|
||||
var ret = [[[self class] alloc] initWithFrame:[self frame]];
|
||||
|
||||
[ret setTextFont:[self textFont]];
|
||||
[ret setMinDate:[self minDate]];
|
||||
[ret setMaxDate:[self maxDate]];
|
||||
[ret setTimeInterval:[self timeInterval]];
|
||||
[ret setDatePickerMode:[self datePickerMode]];
|
||||
[ret setDatePickerElements:[self datePickerElements]];
|
||||
[ret setDatePickerStyle:[self datePickerStyle]];
|
||||
[ret setLocale:[self locale]];
|
||||
[ret setDateValue:[self dateValue]];
|
||||
[ret setBackgroundColor:[self backgroundColor]];
|
||||
[ret setDrawsBackground:[self drawsBackground]];
|
||||
[ret setBordered:[self isBordered]];
|
||||
[ret _init];
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
@end
|
||||
/*! @endcond */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* CPRuleEditor_Constants.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by cacaodev.
|
||||
* Copyright 2011, cacaodev.
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
|
||||
|
||||
CPRuleEditorPredicateLeftExpression = "CPRuleEditorPredicateLeftExpression";
|
||||
CPRuleEditorPredicateRightExpression = "CPRuleEditorPredicateRightExpression";
|
||||
CPRuleEditorPredicateComparisonModifier = "CPRuleEditorPredicateComparisonModifier";
|
||||
CPRuleEditorPredicateOptions = "CPRuleEditorPredicateOptions";
|
||||
CPRuleEditorPredicateOperatorType = "CPRuleEditorPredicateOperatorType";
|
||||
CPRuleEditorPredicateCustomSelector = "CPRuleEditorPredicateCustomSelector";
|
||||
CPRuleEditorPredicateCompoundType = "CPRuleEditorPredicateCompoundType";
|
||||
|
||||
CPRuleEditorRowsDidChangeNotification = "CPRuleEditorRowsDidChangeNotification";
|
||||
CPRuleEditorRulesDidChangeNotification = "CPRuleEditorRulesDidChangeNotification";
|
||||
|
||||
CPRuleEditorNestingModeSingle = 0; // Only a single row is allowed. Plus/minus buttons will not be shown
|
||||
CPRuleEditorNestingModeList = 1; // Allows a single list, with no nesting and no compound rows
|
||||
CPRuleEditorNestingModeCompound = 2; // Unlimited nesting and compound rows; this is the default
|
||||
CPRuleEditorNestingModeSimple = 3; // One compound row at the top with subrows beneath it, and no further nesting allowed
|
||||
|
||||
@typedef CPRuleEditorRowType
|
||||
CPRuleEditorRowTypeSimple = 0;
|
||||
CPRuleEditorRowTypeCompound = 1;
|
||||
@@ -1,145 +0,0 @@
|
||||
/*
|
||||
* Created by cacaodev@gmail.com.
|
||||
* Copyright (c) 2011 Pear, Inc. All rights reserved.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
@implementation _CPPredicateEditorRowNode : CPObject
|
||||
{
|
||||
_CPPredicateEditorTree tree @accessors;
|
||||
CPMutableArray templateViews @accessors;
|
||||
CPMutableArray copiedTemplateContainer @accessors;
|
||||
CPArray children @accessors(copy);
|
||||
}
|
||||
|
||||
+ (id)rowNodeFromTree:(id)aTree
|
||||
{
|
||||
return [_CPPredicateEditorRowNode _rowNodeFromTree:aTree withTemplateTable:{}];
|
||||
}
|
||||
|
||||
+ (id)_rowNodeFromTree:(id)aTree withTemplateTable:(id)templateTable
|
||||
{
|
||||
var views,
|
||||
copiedContainer;
|
||||
|
||||
var uuid = [[aTree template] UID],
|
||||
cachedNode = templateTable[uuid],
|
||||
node = [[_CPPredicateEditorRowNode alloc] init];
|
||||
|
||||
[node setTree:aTree];
|
||||
|
||||
if (!cachedNode)
|
||||
{
|
||||
views = [CPMutableArray array];
|
||||
copiedContainer = [CPMutableArray array];
|
||||
templateTable[uuid] = node;
|
||||
}
|
||||
else
|
||||
{
|
||||
views = [cachedNode templateViews];
|
||||
copiedContainer = [cachedNode copiedTemplateContainer];
|
||||
}
|
||||
|
||||
[node setTemplateViews:views];
|
||||
[node setCopiedTemplateContainer:copiedContainer];
|
||||
|
||||
var nodeChildren = [CPMutableArray array],
|
||||
treeChildren = [aTree children],
|
||||
count = [treeChildren count];
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var treeChild = treeChildren[i],
|
||||
child = [_CPPredicateEditorRowNode _rowNodeFromTree:treeChild withTemplateTable:templateTable];
|
||||
|
||||
[nodeChildren addObject:child];
|
||||
}
|
||||
|
||||
[node setChildren:nodeChildren];
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
- (BOOL)applyTemplate:(id)template withViews:(id)views forOriginalTemplate:(id)originalTemplate
|
||||
{
|
||||
var t = [tree template],
|
||||
count = [children count];
|
||||
|
||||
if (t !== template)
|
||||
{
|
||||
[templateViews setArray:views];
|
||||
[copiedTemplateContainer removeAllObjects];
|
||||
[copiedTemplateContainer addObject:template];
|
||||
}
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
[children[i] applyTemplate:template withViews:views forOriginalTemplate:originalTemplate];
|
||||
}
|
||||
|
||||
- (BOOL)isEqual:(id)node
|
||||
{
|
||||
if (![node isKindOfClass:[_CPPredicateEditorRowNode class]])
|
||||
return NO;
|
||||
|
||||
return (tree === [node tree]);
|
||||
}
|
||||
|
||||
- (void)copyTemplateIfNecessary
|
||||
{
|
||||
if ([copiedTemplateContainer count] === 0)
|
||||
{
|
||||
var copy = [[tree template] copy];
|
||||
[copiedTemplateContainer addObject:copy];
|
||||
[templateViews addObjectsFromArray:[copy templateViews]];
|
||||
}
|
||||
}
|
||||
|
||||
- (CPView)templateView
|
||||
{
|
||||
[self copyTemplateIfNecessary];
|
||||
return [templateViews objectAtIndex:[tree indexIntoTemplate]];
|
||||
}
|
||||
|
||||
- (id)templateForRow
|
||||
{
|
||||
[self copyTemplateIfNecessary];
|
||||
return [copiedTemplateContainer lastObject];
|
||||
}
|
||||
|
||||
- (CPString)title
|
||||
{
|
||||
return [tree title];
|
||||
}
|
||||
|
||||
- (id)displayValue
|
||||
{
|
||||
var title = [self title];
|
||||
|
||||
if (title != nil)
|
||||
return title;
|
||||
|
||||
return [self templateView];
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return [CPString stringWithFormat:@"<%@ %@ %@ tree:%@ tviews:%@", [self className],[self UID], [self title], [tree UID], [templateViews description]];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Created by cacaodev@gmail.com.
|
||||
* Copyright (c) 2011 Pear, Inc. All rights reserved.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
@import <Foundation/CPString.j>
|
||||
|
||||
@class CPPredicateEditorRowTemplate
|
||||
|
||||
@implementation _CPPredicateEditorTree : CPObject
|
||||
{
|
||||
CPPredicateEditorRowTemplate template @accessors;
|
||||
CPString title @accessors(copy);
|
||||
CPArray children @accessors(copy);
|
||||
CPInteger indexIntoTemplate @accessors;
|
||||
CPInteger menuItemIndex @accessors;
|
||||
}
|
||||
|
||||
- (id)copy
|
||||
{
|
||||
var tree = [[_CPPredicateEditorTree alloc] init];
|
||||
[tree setTemplate:template];
|
||||
[tree setTitle:title];
|
||||
[tree setMenuItemIndex:menuItemIndex];
|
||||
[tree setIndexIntoTemplate:indexIntoTemplate];
|
||||
[tree setChildren:children];
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
- (CPString)description
|
||||
{
|
||||
return [CPString stringWithFormat:@"<%@: %p (%@) [%d-%d] T:%p at:%d> [\r%@\r]", [self className], self, title, indexIntoTemplate, menuItemIndex, template, [template rightExpressionAttributeType], children];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
* Created by cacaodev@gmail.com.
|
||||
* Copyright (c) 2011 Pear, Inc. All rights reserved.
|
||||
*
|
||||
* 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 <Foundation/CPObject.j>
|
||||
@import <Foundation/CPDictionary.j>
|
||||
@import <Foundation/CPString.j>
|
||||
@import <Foundation/CPURLConnection.j>
|
||||
@import <Foundation/CPURLRequest.j>
|
||||
|
||||
var LocalizerStringsRegex = new RegExp("\"(.+)\"\\s*=\\s*\"(.+)\"\\s*;\\s*(//.+)?");
|
||||
|
||||
@implementation _CPRuleEditorLocalizer : CPObject
|
||||
{
|
||||
CPDictionary _dictionary @accessors(property=dictionary);
|
||||
CPURLConnection connection;
|
||||
CPURLRequest request;
|
||||
}
|
||||
|
||||
- (void)loadContentOfURL:(CPURL)aURL
|
||||
{
|
||||
request = [CPURLRequest requestWithURL:aURL];
|
||||
connection = [CPURLConnection connectionWithRequest:request delegate:self];
|
||||
}
|
||||
|
||||
- (void)reloadIfNeeded
|
||||
{
|
||||
if (connection != nil) // Connection waiting
|
||||
{
|
||||
connection = nil;
|
||||
|
||||
var data = [CPURLConnection sendSynchronousRequest:request returningResponse:NULL];
|
||||
[self loadContent:[data rawString]];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)rawString
|
||||
{
|
||||
if (connection != nil && rawString != nil)
|
||||
[self loadContent:rawString];
|
||||
|
||||
connection = nil;
|
||||
}
|
||||
|
||||
- (void)loadContent:(CPString)aContent
|
||||
{
|
||||
var dict = @{},
|
||||
lines = [aContent componentsSeparatedByString:"\n"],
|
||||
count = [lines count];
|
||||
|
||||
for (var i = 0 ; i < count ; i++)
|
||||
{
|
||||
var line = [lines objectAtIndex:i];
|
||||
|
||||
if (line.length > 1)
|
||||
{
|
||||
var match = LocalizerStringsRegex.exec(line);
|
||||
|
||||
if (match && match.length >= 3)
|
||||
[dict setObject:match[2] forKey:match[1]];
|
||||
}
|
||||
}
|
||||
|
||||
_dictionary = [CPDictionary dictionaryWithDictionary:dict];
|
||||
}
|
||||
|
||||
- (CPString)localizedStringForString:(CPString)aString
|
||||
{
|
||||
[self reloadIfNeeded];
|
||||
|
||||
if (_dictionary != nil && aString != nil)
|
||||
{
|
||||
var localized = [_dictionary objectForKey:aString];
|
||||
|
||||
if (localized != nil)
|
||||
return localized;
|
||||
}
|
||||
|
||||
return aString;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,127 +0,0 @@
|
||||
/*
|
||||
* Created by cacaodev@gmail.com.
|
||||
* Copyright (c) 2011 Pear, Inc. All rights reserved.
|
||||
*
|
||||
* 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 "CPView.j"
|
||||
|
||||
@class CPRuleEditor
|
||||
|
||||
@implementation _CPRuleEditorViewSlice : CPView
|
||||
{
|
||||
CPRuleEditor _ruleEditor;
|
||||
int _indentation @accessors(property=indentation);
|
||||
int _rowIndex @accessors(property=rowIndex);
|
||||
CGRect _animationTargetRect @accessors(property=_animationTargetRect);
|
||||
BOOL _selected @accessors(getter=_isSelected, setter=_setSelected:);
|
||||
BOOL _lastSelected @accessors(getter=_isLastSelected, setter=_setLastSelected:);
|
||||
BOOL _editable @accessors(getter=isEditable, setter=setEditable:);
|
||||
}
|
||||
|
||||
- (void)removeFromSuperview
|
||||
{
|
||||
[super removeFromSuperview];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)frame ruleEditorView:(id)editor
|
||||
{
|
||||
if (self = [super initWithFrame:frame])
|
||||
{
|
||||
_ruleEditor = editor;
|
||||
_selected = NO;
|
||||
_lastSelected = NO;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_setSelected:(BOOL)select
|
||||
{
|
||||
if (select == _selected)
|
||||
return;
|
||||
|
||||
var selector = select ? @selector(setThemeState:) : @selector(unsetThemeState:);
|
||||
[[self subviews] makeObjectsPerformSelector:selector withObject:CPThemeStateSelectedDataView];
|
||||
_selected = select;
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)rect
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort],
|
||||
bounds = [self bounds],
|
||||
maxX = CGRectGetWidth(bounds),
|
||||
maxY = CGRectGetHeight(bounds);
|
||||
|
||||
// Draw background
|
||||
if ([self _isSelected])
|
||||
_backgroundColor = [_ruleEditor _selectedRowColor];
|
||||
else
|
||||
{
|
||||
var colors = [_ruleEditor _backgroundColors],
|
||||
count = [colors count];
|
||||
_backgroundColor = [colors objectAtIndex:(_rowIndex % count)];
|
||||
}
|
||||
|
||||
CGContextSetFillColor(context, _backgroundColor);
|
||||
CGContextFillRect(context, rect);
|
||||
|
||||
// Draw Top Border
|
||||
CGContextBeginPath(context);
|
||||
CGContextMoveToPoint(context, 0, 0);
|
||||
CGContextAddLineToPoint(context, maxX, 0);
|
||||
CGContextSetStrokeColor(context, [_ruleEditor _sliceTopBorderColor]);
|
||||
CGContextStrokePath(context);
|
||||
|
||||
// Draw Bottom Border
|
||||
CGContextBeginPath(context);
|
||||
CGContextMoveToPoint(context, 0, maxY);
|
||||
CGContextAddLineToPoint(context, maxX, maxY);
|
||||
|
||||
var bottomColor = (_rowIndex == [_ruleEditor _lastRow]) ? [_ruleEditor _sliceLastBottomBorderColor] : [_ruleEditor _sliceBottomBorderColor];
|
||||
|
||||
CGContextSetStrokeColor(context, bottomColor);
|
||||
CGContextStrokePath(context);
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)theEvent
|
||||
{
|
||||
if (_editable)
|
||||
[_ruleEditor _mouseDownOnSlice:self withEvent:theEvent];
|
||||
}
|
||||
|
||||
- (void)mouseUp:(CPEvent)theEvent
|
||||
{
|
||||
if (_editable)
|
||||
[_ruleEditor _mouseUpOnSlice:self withEvent:theEvent];
|
||||
}
|
||||
|
||||
/*
|
||||
- (void)rightMouseDown:(CPEvent)theEvent
|
||||
{
|
||||
[_ruleEditor _rightMouseDownOnSlice:self withEvent:theEvent];
|
||||
}
|
||||
*/
|
||||
|
||||
// =========
|
||||
// ! DEBUG
|
||||
// =========
|
||||
- (CPString)description
|
||||
{
|
||||
return [CPString stringWithFormat:@"<%@ %p index:%d indentation:%d>",[self className],self,[self rowIndex],[self indentation]];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,543 +0,0 @@
|
||||
/*
|
||||
* Created by cacaodev@gmail.com.
|
||||
* Copyright (c) 2011 Pear, Inc. All rights reserved.
|
||||
*
|
||||
* 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 "CPRuleEditor_Constants.j"
|
||||
@import "_CPRuleEditorViewSlice.j"
|
||||
|
||||
@import "CPButton.j"
|
||||
@import "CPDatePicker.j"
|
||||
@import "CPPopUpButton.j"
|
||||
|
||||
@global CPApp
|
||||
@global CPMiniControlSize
|
||||
@global CPSmallControlSize
|
||||
|
||||
@implementation _CPRuleEditorViewSliceRow : _CPRuleEditorViewSlice
|
||||
{
|
||||
CPButton _addButton;
|
||||
CPButton _subtractButton;
|
||||
CPMutableArray _correspondingRuleItems;
|
||||
CPMutableArray _ruleOptionFrames;
|
||||
CPMutableArray _ruleOptionInitialViewFrames;
|
||||
CPMutableArray _ruleOptionViews;
|
||||
|
||||
|
||||
CPRuleEditorRowType _rowType @accessors;
|
||||
CPRuleEditorRowType _plusButtonRowType;
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)frame ruleEditorView:(id)editor
|
||||
{
|
||||
if (self = [super initWithFrame:frame ruleEditorView:editor])
|
||||
[self _initShared];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)_initShared
|
||||
{
|
||||
_correspondingRuleItems = [[CPMutableArray alloc] init];
|
||||
_ruleOptionFrames = [[CPMutableArray alloc] init];
|
||||
_ruleOptionInitialViewFrames = [[CPMutableArray alloc] init];
|
||||
_ruleOptionViews = [[CPMutableArray alloc] init];
|
||||
_editable = [_ruleEditor isEditable];
|
||||
|
||||
_addButton = [self _createAddRowButton];
|
||||
_subtractButton = [self _createDeleteRowButton];
|
||||
|
||||
[self addSubview:_addButton];
|
||||
[self addSubview:_subtractButton];
|
||||
|
||||
[self setAutoresizingMask:CPViewWidthSizable];
|
||||
}
|
||||
|
||||
- (CPButton)_createRowButton
|
||||
{
|
||||
var button = [[CPButton alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
[button setFont:[_ruleEditor font]];
|
||||
[button setTextColor:[_ruleEditor _fontColor]];
|
||||
|
||||
[button setAlignment:CPCenterTextAlignment];
|
||||
[button setAutoresizingMask:CPViewMinXMargin];
|
||||
[button setButtonType:CPMomentaryChangeButton];
|
||||
[button setBordered:NO];
|
||||
[button setHidden:!_editable];
|
||||
[button setImagePosition:CPImageOnly];
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
- (CPButton)_createAddRowButton
|
||||
{
|
||||
var button = [self _createRowButton];
|
||||
|
||||
[button setToolTip:[_ruleEditor _toolTipForAddSimpleRowButton]];
|
||||
[button setValue:[_ruleEditor _imageAdd] forThemeAttribute:@"image" inState:CPThemeStateNormal];
|
||||
[button setValue:[_ruleEditor _imageAddHighlighted] forThemeAttribute:@"image" inState:CPThemeStateHighlighted];
|
||||
|
||||
[button setAction:@selector(_addOption:)];
|
||||
[button setTarget:self];
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
- (CPButton)_createDeleteRowButton
|
||||
{
|
||||
var button = [self _createRowButton];
|
||||
|
||||
[button setToolTip:[_ruleEditor _toolTipForDeleteRowButton]];
|
||||
[button setValue:[_ruleEditor _imageRemove] forThemeAttribute:@"image" inState:CPThemeStateNormal];
|
||||
[button setValue:[_ruleEditor _imageRemoveHighlighted] forThemeAttribute:@"image" inState:CPThemeStateHighlighted];
|
||||
|
||||
[button setAction:@selector(_deleteOption:)];
|
||||
[button setTarget:self];
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
- (CPMenuItem)_createMenuItemWithTitle:(CPString )title
|
||||
{
|
||||
title = [[_ruleEditor standardLocalizer] localizedStringForString:title];
|
||||
return [[CPMenuItem alloc] initWithTitle:title action:nil keyEquivalent:@""];
|
||||
}
|
||||
|
||||
- (CPPopUpButton)_createPopUpButtonWithItems:(CPArray)itemsArray selectedItemIndex:(int)index
|
||||
{
|
||||
var title = [[itemsArray objectAtIndex:index] title],
|
||||
font = [_ruleEditor font],
|
||||
width = [title sizeWithFont:font].width + 35, // 35 for right arrows + margins
|
||||
rect = CGRectMake(0, 0, width, [_ruleEditor rowHeight]),
|
||||
popup = [[CPPopUpButton alloc] initWithFrame:rect];
|
||||
|
||||
[popup setValue:font forThemeAttribute:@"font"];
|
||||
|
||||
var count = [itemsArray count];
|
||||
for (var i = 0; i < count; i++)
|
||||
[popup addItem:[itemsArray objectAtIndex:i]];
|
||||
|
||||
[popup selectItemAtIndex:index];
|
||||
|
||||
return popup;
|
||||
}
|
||||
|
||||
- (CPMenuItem)_createMenuSeparatorItem
|
||||
{
|
||||
return [CPMenuItem separatorItem];
|
||||
}
|
||||
|
||||
- (CPTextField)_createStaticTextFieldWithStringValue:(CPString)text
|
||||
{
|
||||
var textField = [[CPTextField alloc] initWithFrame:CGRectMakeZero()],
|
||||
ruleEditorFont = [_ruleEditor font],
|
||||
font = [CPFont fontWithName:[ruleEditorFont familyName] size:[ruleEditorFont size] + 2],
|
||||
localizedText = [[_ruleEditor standardLocalizer] localizedStringForString:text],
|
||||
size = [localizedText sizeWithFont:font];
|
||||
|
||||
[textField setFrameSize:CGSizeMake(size.width + 4, [_ruleEditor rowHeight])];
|
||||
[textField setValue:font forThemeAttribute:@"font"];
|
||||
[textField setValue:[_ruleEditor _verticalAlignment] forThemeAttribute:@"vertical-alignment"];
|
||||
[textField setStringValue:localizedText];
|
||||
|
||||
return textField;
|
||||
}
|
||||
|
||||
- (void)_addOption:(id)sender
|
||||
{
|
||||
if (_rowIndex == [_ruleEditor numberOfRows] - 1)
|
||||
[self setNeedsDisplay:YES];
|
||||
|
||||
var type = _plusButtonRowType;
|
||||
|
||||
if ([_ruleEditor nestingMode] == CPRuleEditorNestingModeCompound && ([[CPApp currentEvent] modifierFlags] & CPAlternateKeyMask))
|
||||
type = CPRuleEditorRowTypeCompound;
|
||||
|
||||
[_ruleEditor _addOptionFromSlice:self ofRowType:type];
|
||||
}
|
||||
|
||||
- (void)_deleteOption:(id)sender
|
||||
{
|
||||
[_ruleEditor _deleteSlice:self];
|
||||
}
|
||||
|
||||
- (void)_ruleOptionPopupChangedAction:(CPMenuItem)sender
|
||||
{
|
||||
var layoutdict = [sender representedObject],
|
||||
newItem = [layoutdict objectForKey:@"item"],
|
||||
indexInCriteria = [layoutdict objectForKey:@"indexInCriteria"],
|
||||
oldItem = [_correspondingRuleItems objectAtIndex:indexInCriteria];
|
||||
|
||||
if (![newItem isEqual:oldItem])
|
||||
{
|
||||
[_correspondingRuleItems replaceObjectAtIndex:indexInCriteria withObject:newItem];
|
||||
[_ruleEditor _changedItem:oldItem toItem:newItem inRow:_rowIndex atCriteriaIndex:indexInCriteria];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)validateMenuItem:(CPMenuItem )menuItem
|
||||
{
|
||||
return [_ruleEditor _validateItem:menuItem value:[[menuItem representedObject] valueForKey:@"item"] inRow:_rowIndex];
|
||||
}
|
||||
|
||||
- (void)_emptyRulePartSubviews
|
||||
{
|
||||
var count = [_ruleOptionViews count];
|
||||
|
||||
while (count--)
|
||||
[_ruleOptionViews[count] removeFromSuperview];
|
||||
|
||||
[_ruleOptionViews removeAllObjects];
|
||||
[_ruleOptionFrames removeAllObjects];
|
||||
[_ruleOptionInitialViewFrames removeAllObjects];
|
||||
}
|
||||
|
||||
- (void)_reconfigureSubviews
|
||||
{
|
||||
var criteria,
|
||||
repObject,
|
||||
menuItem,
|
||||
ruleView,
|
||||
criterion,
|
||||
parent,
|
||||
numberOfCriteria,
|
||||
numberOfChildren,
|
||||
firstResponderIndex,
|
||||
|
||||
ruleItems = [CPMutableArray array],
|
||||
responder = [[self window] firstResponder];
|
||||
|
||||
[self _emptyRulePartSubviews];
|
||||
|
||||
criteria = [_ruleEditor criteriaForRow:_rowIndex];
|
||||
numberOfCriteria = [criteria count];
|
||||
|
||||
firstResponderIndex = numberOfCriteria - 1;
|
||||
if (responder)
|
||||
firstResponderIndex = [_ruleOptionViews indexOfObjectIdenticalTo:responder];
|
||||
|
||||
for (var i = 0; i < numberOfCriteria; i++)
|
||||
{
|
||||
ruleView = nil;
|
||||
parent = nil;
|
||||
criterion = [criteria objectAtIndex:i];
|
||||
|
||||
if (i > 0)
|
||||
parent = [criteria objectAtIndex:i - 1];
|
||||
|
||||
var childItems = [],
|
||||
childValues = [];
|
||||
|
||||
[_ruleEditor _getAllAvailableItems:childItems values:childValues asChildrenOfItem:parent inRow:_rowIndex];
|
||||
|
||||
numberOfChildren = [childItems count];
|
||||
if (numberOfChildren > 1)
|
||||
{
|
||||
var menuItems = [CPMutableArray arrayWithCapacity:numberOfChildren],
|
||||
selectedIndex = [childItems indexOfObject:criterion];
|
||||
|
||||
if (selectedIndex == CPNotFound)
|
||||
break;
|
||||
|
||||
for (var j = 0; j < numberOfChildren; ++j)
|
||||
{
|
||||
var childItem = [childItems objectAtIndex:j],
|
||||
childValue = [childValues objectAtIndex:j];
|
||||
|
||||
if ([childValue isKindOfClass:[CPMenuItem class]])
|
||||
{
|
||||
[[childValue menu] removeItem:childValue];
|
||||
menuItem = childValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if ([childValue isEqualToString:@""])
|
||||
menuItem = [self _createMenuSeparatorItem];
|
||||
else
|
||||
{
|
||||
menuItem = [self _createMenuItemWithTitle:childValue];
|
||||
[menuItem setTarget:self];
|
||||
[menuItem setAction:@selector(_ruleOptionPopupChangedAction:)];
|
||||
}
|
||||
}
|
||||
|
||||
repObject = @{
|
||||
@"item": childItem,
|
||||
@"value": childValue,
|
||||
@"indexInCriteria": i
|
||||
};
|
||||
[menuItem setRepresentedObject:repObject];
|
||||
[menuItems addObject:menuItem];
|
||||
}
|
||||
|
||||
ruleView = [self _createPopUpButtonWithItems:menuItems selectedItemIndex:selectedIndex];
|
||||
}
|
||||
else
|
||||
{
|
||||
var value = [childValues objectAtIndex:0],
|
||||
type = [value valueType];
|
||||
|
||||
if (type === 0)
|
||||
ruleView = [self _createStaticTextFieldWithStringValue:value];
|
||||
else
|
||||
{
|
||||
if (type !== 1)
|
||||
{
|
||||
[CPException raise:CPInternalInconsistencyException reason:@"Display value must be a string or a menu item"];
|
||||
continue;
|
||||
}
|
||||
|
||||
ruleView = value;
|
||||
[ruleView setTarget:self];
|
||||
[ruleView setAction:@selector(_sendRuleAction:)];
|
||||
if ([ruleView respondsToSelector:@selector(setDelegate:)])
|
||||
[ruleView setDelegate:self];
|
||||
}
|
||||
}
|
||||
|
||||
if (ruleView != nil)
|
||||
{
|
||||
[ruleView setControlSize:CPSmallControlSize];
|
||||
|
||||
var minSize = [ruleView currentValueForThemeAttribute:@"min-size"],
|
||||
frame = [ruleView frame];
|
||||
|
||||
// Force controls to their minimum size
|
||||
frame.size.height = minSize.height;
|
||||
[ruleView setFrame:frame];
|
||||
|
||||
[_ruleOptionViews addObject:ruleView];
|
||||
[_ruleOptionInitialViewFrames addObject:frame];
|
||||
[_ruleOptionFrames addObject:frame];
|
||||
|
||||
if (!criterion)
|
||||
criterion = [CPNull null];
|
||||
|
||||
[ruleItems addObject:criterion];
|
||||
}
|
||||
}
|
||||
|
||||
[_correspondingRuleItems setArray:ruleItems];
|
||||
|
||||
if (!_editable)
|
||||
[self _updateEnabledStateForSubviews];
|
||||
|
||||
[self _relayoutSubviewsWidthChanged:YES];
|
||||
|
||||
if (firstResponderIndex != CPNotFound)
|
||||
{
|
||||
var aView = [_ruleOptionViews objectAtIndex:firstResponderIndex];
|
||||
[[self window] makeFirstResponder:aView]; // This is not working. bug in CPPopUpButton firstResponder ?
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_updateEnabledStateForSubviews
|
||||
{
|
||||
[_ruleOptionViews makeObjectsPerformSelector:@selector(setEnabled:) withObject:NO];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[self _relayoutSubviewsWidthChanged:YES];
|
||||
}
|
||||
|
||||
- (void)_relayoutSubviewsWidthChanged:(BOOL)widthChanged
|
||||
{
|
||||
var optionViewOriginX,
|
||||
leftHorizontalPadding,
|
||||
leftButtonMinX,
|
||||
rowHeight = [_ruleEditor rowHeight],
|
||||
count = [_ruleOptionViews count],
|
||||
sliceFrame = [self frame],
|
||||
image = [_ruleEditor _imageAdd],
|
||||
imageSize = image ? [image size] : CGSizeMake(0,0),
|
||||
|
||||
buttonFrame = CGRectMake(CGRectGetWidth(sliceFrame) - imageSize.width - [self _rowButtonsRightHorizontalPadding], ([_ruleEditor rowHeight] - imageSize.height) / 2 - 1, imageSize.width, imageSize.height);
|
||||
|
||||
[_addButton setFrame:buttonFrame];
|
||||
buttonFrame.origin.x -= imageSize.width + [self _rowButtonsInterviewHorizontalPadding];
|
||||
[_subtractButton setFrame:buttonFrame];
|
||||
|
||||
if (widthChanged)
|
||||
{
|
||||
optionViewOriginX = [self _leftmostViewFixedHorizontalPadding] + [self _indentationHorizontalPadding] * _indentation;
|
||||
leftHorizontalPadding = [self _rowButtonsLeftHorizontalPadding];
|
||||
leftButtonMinX = CGRectGetMinX(buttonFrame);
|
||||
}
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var ruleOptionView = _ruleOptionViews[i],
|
||||
optionFrame = _ruleOptionFrames[i];
|
||||
|
||||
// Use a pixel correction to align controls
|
||||
optionFrame.origin.y = (rowHeight - CGRectGetHeight(optionFrame)) / 2;
|
||||
|
||||
if (widthChanged)
|
||||
{
|
||||
optionFrame.origin.x = optionViewOriginX;
|
||||
if (i == count - 1 && ![self _isRulePopup:ruleOptionView])
|
||||
{
|
||||
var initialFrame = _ruleOptionInitialViewFrames[i];
|
||||
optionFrame.size.width = MIN(CGRectGetWidth(initialFrame), leftButtonMinX - leftHorizontalPadding - optionViewOriginX);
|
||||
}
|
||||
}
|
||||
|
||||
[ruleOptionView setFrame:optionFrame];
|
||||
[self addSubview:ruleOptionView];
|
||||
|
||||
if (widthChanged)
|
||||
optionViewOriginX += CGRectGetWidth(optionFrame) + [self _interviewHorizontalPadding];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)_updateButtonVisibilities
|
||||
{
|
||||
[_addButton setHidden:[_ruleEditor _shouldHideAddButtonForSlice:self]];
|
||||
[_subtractButton setHidden:[_ruleEditor _shouldHideSubtractButtonForSlice:self]];
|
||||
}
|
||||
|
||||
- (void)_configurePlusButtonByRowType:(CPRuleEditorRowType)type
|
||||
{
|
||||
[self _setRowTypeToAddFromPlusButton:type];
|
||||
}
|
||||
|
||||
- (void)setEditable:(BOOL)value
|
||||
{
|
||||
[super setEditable:value]
|
||||
// [self _updateEnabledStateForSubviews];
|
||||
[self _updateButtonVisibilities];
|
||||
}
|
||||
|
||||
- (float)_alignmentGridWidth
|
||||
{
|
||||
return [_ruleEditor _alignmentGridWidth];
|
||||
}
|
||||
|
||||
- (float)_indentationHorizontalPadding
|
||||
{
|
||||
return 30.;
|
||||
}
|
||||
|
||||
- (float)_interviewHorizontalPadding
|
||||
{
|
||||
return 6.;
|
||||
}
|
||||
|
||||
- (float)_leftmostViewFixedHorizontalPadding
|
||||
{
|
||||
return 7.;
|
||||
}
|
||||
|
||||
- (float)_minimumVerticalPopupPadding
|
||||
{
|
||||
return 2.;
|
||||
}
|
||||
|
||||
- (float)_rowButtonsInterviewHorizontalPadding
|
||||
{
|
||||
return 6.;
|
||||
}
|
||||
|
||||
- (float)_rowButtonsLeftHorizontalPadding
|
||||
{
|
||||
return 10.;
|
||||
}
|
||||
|
||||
- (float)_rowButtonsRightHorizontalPadding
|
||||
{
|
||||
return ([[_ruleEditor superview] isKindOfClass:[CPClipView class]]) ? 18. : 10.;
|
||||
}
|
||||
|
||||
- (void)_setRowTypeToAddFromPlusButton:(int)type
|
||||
{
|
||||
_plusButtonRowType = type;
|
||||
}
|
||||
|
||||
- (void)setNeedsDisplay:(BOOL)flag
|
||||
{
|
||||
[super setNeedsDisplay:flag];
|
||||
}
|
||||
|
||||
- (BOOL)_nestingModeShouldHideAddButton
|
||||
{
|
||||
return [_ruleEditor _applicableNestingMode] == CPRuleEditorNestingModeSingle;
|
||||
}
|
||||
|
||||
- (BOOL)_nestingModeShouldHideSubtractButton
|
||||
{
|
||||
return [_ruleEditor _applicableNestingMode] == CPRuleEditorNestingModeSingle;
|
||||
}
|
||||
|
||||
- (BOOL)containsDisplayValue:(id)value
|
||||
{
|
||||
return [[_ruleEditor displayValuesForRow:_rowIndex] containsObject:value];
|
||||
// Ou alors avec _correspondingRuleItems
|
||||
}
|
||||
|
||||
- (void)viewDidMoveToWindow
|
||||
{
|
||||
[self layoutSubviews];
|
||||
}
|
||||
|
||||
- (void)_addObservers
|
||||
{
|
||||
if (_isObserving)
|
||||
return;
|
||||
|
||||
[super _addObservers];
|
||||
|
||||
[[CPNotificationCenter defaultCenter] addObserver:self selector:@selector(_textDidChange:) name:CPControlTextDidChangeNotification object:nil];
|
||||
}
|
||||
|
||||
- (void)_removeObservers
|
||||
{
|
||||
if (!_isObserving)
|
||||
return;
|
||||
|
||||
[super _removeObservers];
|
||||
|
||||
[[CPNotificationCenter defaultCenter] removeObserver:self name:CPControlTextDidChangeNotification object:nil];
|
||||
}
|
||||
|
||||
- (void)drawRect:(CGRect)rect
|
||||
{
|
||||
[super drawRect:rect];
|
||||
}
|
||||
|
||||
- (BOOL)_isRulePopup:(CPView)view
|
||||
{
|
||||
if ([view isKindOfClass:[CPPopUpButton class]])
|
||||
return YES;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)_sendRuleAction:(id)sender
|
||||
{
|
||||
[_ruleEditor _updatePredicate];
|
||||
[_ruleEditor _sendRuleAction];
|
||||
}
|
||||
|
||||
- (void)_textDidChange:(CPNotification)aNotif
|
||||
{
|
||||
if ([[aNotif object] superview] == self && [_ruleEditor _sendsActionOnIncompleteTextChange])
|
||||
[self _sendRuleAction:nil];
|
||||
}
|
||||
|
||||
@end
|
||||
+1
-27
@@ -1,26 +1,5 @@
|
||||
/*
|
||||
* CPSavePanel.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPPanel.j"
|
||||
@import <AppKit/CPPanel.j>
|
||||
|
||||
|
||||
@implementation CPSavePanel : CPPanel
|
||||
@@ -35,11 +14,6 @@
|
||||
CPArray _allowedFileTypes @accessors(property=allowedFileTypes);
|
||||
}
|
||||
|
||||
+ (CPURL)proposedFileURLWithDocumentName:(CPString)aDocumentName
|
||||
{
|
||||
return [CPURL URLWithString:aDocumentName];
|
||||
}
|
||||
|
||||
+ (id)savePanel
|
||||
{
|
||||
return [[CPSavePanel alloc] init];
|
||||
|
||||
+5
-41
@@ -1,52 +1,16 @@
|
||||
/*
|
||||
* CPScreen.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2009, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPScreen
|
||||
|
||||
A CPScreen object describes the attributes of a display device available
|
||||
to Cappuccino.
|
||||
*/
|
||||
#import "CoreGraphics/CGGeometry.h"
|
||||
|
||||
@implementation CPScreen : CPObject
|
||||
{
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the position and size of the visible area of the receiving screen.
|
||||
This will normally be smaller than the full size of the screen to account
|
||||
for system UI elements. For example, on a Mac the top of the visible frame
|
||||
is placed below the bottom of the menu bar.
|
||||
|
||||
@return the visible screen rectangle
|
||||
*/
|
||||
- (CGRect)visibleFrame
|
||||
{
|
||||
#if PLATFORM(DOM)
|
||||
return CGRectMake(window.screen.availLeft, window.screen.availTop, window.screen.availWidth, window.screen.availHeight);
|
||||
#else
|
||||
return CGRectMakeZero();
|
||||
#endif
|
||||
return _CGRectMake(window.screen.availLeft, window.screen.availTop, window.screen.availWidth, window.screen.availHeight);
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
+389
-1286
File diff suppressed because it is too large
Load Diff
+195
-414
@@ -5,9 +5,6 @@
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
*
|
||||
* Modified to match Lion style by Antoine Mercadal 2011
|
||||
* <antoine.mercadal@archipelproject.org>
|
||||
*
|
||||
* 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
|
||||
@@ -23,17 +20,12 @@
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include "../Foundation/Foundation.h"
|
||||
|
||||
@import "CPAnimation.j"
|
||||
@import "CPControl.j"
|
||||
@import "CPWindow_Constants.j"
|
||||
@import "CPViewAnimation.j"
|
||||
|
||||
@global CPApp
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
|
||||
// CPScroller Constants
|
||||
@typedef CPScrollerPart
|
||||
CPScrollerNoPart = 0;
|
||||
CPScrollerDecrementPage = 1;
|
||||
CPScrollerKnob = 2;
|
||||
@@ -45,42 +37,28 @@ CPScrollerKnobSlot = 6;
|
||||
CPScrollerIncrementArrow = 0;
|
||||
CPScrollerDecrementArrow = 1;
|
||||
|
||||
@typedef CPUsableScrollerParts
|
||||
CPNoScrollerParts = 0;
|
||||
CPOnlyScrollerArrows = 1;
|
||||
CPAllScrollerParts = 2;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPScroller
|
||||
*/
|
||||
|
||||
var PARTS_ARRANGEMENT = [CPScrollerKnobSlot, CPScrollerDecrementLine, CPScrollerIncrementLine, CPScrollerKnob],
|
||||
NAMES_FOR_PARTS = {},
|
||||
PARTS_FOR_NAMES = {};
|
||||
|
||||
var _CACHED_THEME_SCROLLER = nil; // This is used by the class methods to pull the theme attributes.
|
||||
|
||||
NAMES_FOR_PARTS[CPScrollerDecrementLine] = @"decrement-line";
|
||||
NAMES_FOR_PARTS[CPScrollerIncrementLine] = @"increment-line";
|
||||
NAMES_FOR_PARTS[CPScrollerKnobSlot] = @"knob-slot";
|
||||
NAMES_FOR_PARTS[CPScrollerKnob] = @"knob";
|
||||
|
||||
|
||||
@typedef CPScrollerStyle
|
||||
CPScrollerStyleLegacy = 0;
|
||||
CPScrollerStyleOverlay = 1;
|
||||
|
||||
CPScrollerKnobStyleDefault = 0;
|
||||
CPScrollerKnobStyleDark = 1;
|
||||
CPScrollerKnobStyleLight = 2;
|
||||
|
||||
CPThemeStateScrollViewLegacy = CPThemeState("scroller-style-legacy");
|
||||
CPThemeStateScrollerKnobLight = CPThemeState("scroller-knob-light");
|
||||
CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
@class CPScroller
|
||||
*/
|
||||
|
||||
@implementation CPScroller : CPControl
|
||||
{
|
||||
CPControlSize _controlSize;
|
||||
CPUsableScrollerParts _usableParts;
|
||||
CPArray _partRects;
|
||||
|
||||
@@ -92,69 +70,58 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
CPScrollerPart _trackingPart;
|
||||
float _trackingFloatValue;
|
||||
CGPoint _trackingStartPoint;
|
||||
|
||||
CPViewAnimation _animationScroller;
|
||||
|
||||
BOOL _allowFadingOut @accessors(getter=allowFadingOut);
|
||||
int _style;
|
||||
CPTimer _timerFadeOut;
|
||||
BOOL _isMouseOver;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Class methods
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (CPString)themeClass
|
||||
{
|
||||
return "scroller";
|
||||
}
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
+ (id)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"scroller-width": 7.0,
|
||||
@"knob-slot-color": [CPNull null],
|
||||
@"decrement-line-color": [CPNull null],
|
||||
@"increment-line-color": [CPNull null],
|
||||
@"knob-color": [CPNull null],
|
||||
@"decrement-line-size": CGSizeMakeZero(),
|
||||
@"increment-line-size": CGSizeMakeZero(),
|
||||
@"track-inset": CGInsetMakeZero(),
|
||||
@"knob-inset": CGInsetMakeZero(),
|
||||
@"minimum-knob-length": 21.0,
|
||||
@"track-border-overlay": 9.0
|
||||
};
|
||||
return [CPDictionary dictionaryWithObjects:[ [CPNull null], [CPNull null], [CPNull null], [CPNull null],
|
||||
_CGSizeMakeZero(), _CGSizeMakeZero(), _CGInsetMakeZero(), _CGInsetMakeZero(), _CGSizeMakeZero()]
|
||||
forKeys:[ @"knob-slot-color",
|
||||
@"decrement-line-color",
|
||||
@"increment-line-color",
|
||||
@"knob-color",
|
||||
@"decrement-line-size",
|
||||
@"increment-line-size",
|
||||
@"track-inset",
|
||||
@"knob-inset",
|
||||
@"minimum-knob-length"]];
|
||||
}
|
||||
|
||||
+ (float)scrollerWidth
|
||||
|
||||
// Calculating Layout
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
return [self scrollerWidthInStyle:CPScrollerStyleLegacy];
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
if (self)
|
||||
{
|
||||
_controlSize = CPRegularControlSize;
|
||||
_partRects = [];
|
||||
|
||||
[self setFloatValue:0.0];
|
||||
[self setKnobProportion:1.0];
|
||||
|
||||
_hitPart = CPScrollerNoPart;
|
||||
|
||||
[self _calculateIsVertical];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
// Determining CPScroller Size
|
||||
/*!
|
||||
Returns the CPScroller's width for a CPRegularControlSize.
|
||||
*/
|
||||
+ (float)scrollerWidthInStyle:(CPScrollerStyle)aStyle
|
||||
+ (float)scrollerWidth
|
||||
{
|
||||
if (!_CACHED_THEME_SCROLLER)
|
||||
_CACHED_THEME_SCROLLER = [[self alloc] init];
|
||||
|
||||
if (aStyle == CPScrollerStyleLegacy)
|
||||
return [_CACHED_THEME_SCROLLER valueForThemeAttribute:@"scroller-width" inState:CPThemeStateScrollViewLegacy];
|
||||
|
||||
return [_CACHED_THEME_SCROLLER currentValueForThemeAttribute:@"scroller-width"];
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the CPScroller's overlay value.
|
||||
*/
|
||||
+ (float)scrollerOverlay
|
||||
{
|
||||
if (!_CACHED_THEME_SCROLLER)
|
||||
_CACHED_THEME_SCROLLER = [[self alloc] init];
|
||||
|
||||
return [_CACHED_THEME_SCROLLER currentValueForThemeAttribute:@"track-border-overlay"];
|
||||
return 15.0;//[self scrollerWidthForControlSize:CPRegularControlSize];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -163,81 +130,30 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
*/
|
||||
+ (float)scrollerWidthForControlSize:(CPControlSize)aControlSize
|
||||
{
|
||||
return [self scrollerWidth];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Initialization
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
if (self = [super initWithFrame:aFrame])
|
||||
{
|
||||
_partRects = [];
|
||||
|
||||
[self setFloatValue:0.0];
|
||||
[self setKnobProportion:1.0];
|
||||
|
||||
_hitPart = CPScrollerNoPart;
|
||||
_allowFadingOut = YES;
|
||||
_isMouseOver = NO;
|
||||
_style = CPScrollerStyleOverlay;
|
||||
|
||||
var paramAnimFadeOut = @{
|
||||
CPViewAnimationTargetKey: self,
|
||||
CPViewAnimationEffectKey: CPViewAnimationFadeOutEffect,
|
||||
};
|
||||
|
||||
_animationScroller = [[CPViewAnimation alloc] initWithDuration:0.2 animationCurve:CPAnimationEaseInOut];
|
||||
[_animationScroller setViewAnimations:[paramAnimFadeOut]];
|
||||
[_animationScroller setDelegate:self];
|
||||
[self setAlphaValue:0.0];
|
||||
|
||||
// We have to choose an orientation. If for some bizarre reason width === height,
|
||||
// punt and choose vertical.
|
||||
[self _setIsVertical:CGRectGetHeight(aFrame) >= CGRectGetWidth(aFrame)];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Getters / Setters
|
||||
|
||||
/*!
|
||||
Returns the scroller's style
|
||||
*/
|
||||
- (int)style
|
||||
{
|
||||
return _style;
|
||||
return 15.0;//_CPScrollerWidths[aControlSize];
|
||||
}
|
||||
|
||||
/*!
|
||||
Set the scroller's control size
|
||||
@param aStyle the scroller style: CPScrollerStyleLegacy or CPScrollerStyleOverlay
|
||||
Sets the scroller's size.
|
||||
@param aControlSize the scroller's size
|
||||
*/
|
||||
- (void)setStyle:(CPScrollerStyle)aStyle
|
||||
- (void)setControlSize:(CPControlSize)aControlSize
|
||||
{
|
||||
if (_style != nil && _style === aStyle)
|
||||
if (_controlSize == aControlSize)
|
||||
return;
|
||||
|
||||
_style = aStyle;
|
||||
_controlSize = aControlSize;
|
||||
|
||||
if (_style === CPScrollerStyleLegacy)
|
||||
{
|
||||
_allowFadingOut = NO;
|
||||
[self fadeIn];
|
||||
[self setThemeState:CPThemeStateScrollViewLegacy];
|
||||
}
|
||||
else
|
||||
{
|
||||
_allowFadingOut = YES;
|
||||
[self unsetThemeState:CPThemeStateScrollViewLegacy];
|
||||
}
|
||||
[self setNeedsLayout];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
//[self _adjustScrollerSize];
|
||||
/*!
|
||||
Returns the scroller's control size
|
||||
*/
|
||||
- (CPControlSize)controlSize
|
||||
{
|
||||
return _controlSize;
|
||||
}
|
||||
|
||||
- (void)setObjectValue:(id)aValue
|
||||
@@ -245,6 +161,14 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
[super setObjectValue:MIN(1.0, MAX(0.0, +aValue))];
|
||||
}
|
||||
|
||||
- (void)setKnobProportion:(float)aProportion
|
||||
{
|
||||
_knobProportion = MIN(1.0, MAX(0.0001, aProportion));
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
/*!
|
||||
Return's the knob's proportion
|
||||
*/
|
||||
@@ -253,55 +177,22 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
return _knobProportion;
|
||||
}
|
||||
|
||||
/*!
|
||||
Set the knob's proportion
|
||||
@param aProportion the desired proportion
|
||||
*/
|
||||
- (void)setKnobProportion:(float)aProportion
|
||||
- (id)currentValueForThemeAttribute:(CPString)anAttributeName
|
||||
{
|
||||
if (!_IS_NUMERIC(aProportion))
|
||||
[CPException raise:CPInvalidArgumentException reason:"aProportion must be numeric, was: "+aProportion];
|
||||
|
||||
_knobProportion = MIN(1.0, MAX(0.0001, aProportion));
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
[self setNeedsLayout];
|
||||
var themeState = _themeState;
|
||||
|
||||
if (NAMES_FOR_PARTS[_hitPart] + "-color" !== anAttributeName)
|
||||
themeState &= ~CPThemeStateHighlighted;
|
||||
|
||||
return [self valueForThemeAttribute:anAttributeName inState:themeState];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Privates
|
||||
|
||||
/*! @ignore */
|
||||
- (void)_adjustScrollerSize
|
||||
{
|
||||
var frame = [self frame],
|
||||
scrollerWidth = [self currentValueForThemeAttribute:@"scroller-width"];
|
||||
|
||||
if ([self isVertical] && CGRectGetWidth(frame) !== scrollerWidth)
|
||||
frame.size.width = scrollerWidth;
|
||||
|
||||
if (![self isVertical] && CGRectGetHeight(frame) !== scrollerWidth)
|
||||
frame.size.height = scrollerWidth;
|
||||
|
||||
[self setFrame:frame];
|
||||
}
|
||||
|
||||
/*! @ignore */
|
||||
- (void)_performFadeOut:(CPTimer)aTimer
|
||||
{
|
||||
[self fadeOut];
|
||||
_timerFadeOut = nil;
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Utilities
|
||||
// Calculating Layout
|
||||
|
||||
- (CGRect)rectForPart:(CPScrollerPart)aPart
|
||||
{
|
||||
if (aPart == CPScrollerNoPart)
|
||||
return CGRectMakeZero();
|
||||
return _CGRectMakeZero();
|
||||
|
||||
return _partRects[aPart];
|
||||
}
|
||||
@@ -314,28 +205,25 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
- (CPScrollerPart)testPart:(CGPoint)aPoint
|
||||
{
|
||||
aPoint = [self convertPoint:aPoint fromView:nil];
|
||||
|
||||
// The ordering of these tests is important. We check the knob and
|
||||
|
||||
// The ordering of these tests is important. We check the knob and
|
||||
// page rects first since they may overlap with the arrows.
|
||||
|
||||
if (![self hasThemeState:CPThemeStateSelected] && ![self hasThemeState:CPThemeStateScrollViewLegacy])
|
||||
return CPScrollerNoPart;
|
||||
|
||||
|
||||
if (CGRectContainsPoint([self rectForPart:CPScrollerKnob], aPoint))
|
||||
return CPScrollerKnob;
|
||||
|
||||
|
||||
if (CGRectContainsPoint([self rectForPart:CPScrollerDecrementPage], aPoint))
|
||||
return CPScrollerDecrementPage;
|
||||
|
||||
|
||||
if (CGRectContainsPoint([self rectForPart:CPScrollerIncrementPage], aPoint))
|
||||
return CPScrollerIncrementPage;
|
||||
|
||||
|
||||
if (CGRectContainsPoint([self rectForPart:CPScrollerDecrementLine], aPoint))
|
||||
return CPScrollerDecrementLine;
|
||||
|
||||
|
||||
if (CGRectContainsPoint([self rectForPart:CPScrollerIncrementLine], aPoint))
|
||||
return CPScrollerIncrementLine;
|
||||
|
||||
|
||||
if (CGRectContainsPoint([self rectForPart:CPScrollerKnobSlot], aPoint))
|
||||
return CPScrollerKnobSlot;
|
||||
|
||||
@@ -353,7 +241,7 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
if (_knobProportion === 1.0)
|
||||
{
|
||||
_usableParts = CPNoScrollerParts;
|
||||
|
||||
|
||||
_partRects[CPScrollerDecrementPage] = CGRectMakeZero();
|
||||
_partRects[CPScrollerKnob] = CGRectMakeZero();
|
||||
_partRects[CPScrollerIncrementPage] = CGRectMakeZero();
|
||||
@@ -362,7 +250,7 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
|
||||
// In this case, the slot is the entirety of the scroller.
|
||||
_partRects[CPScrollerKnobSlot] = CGRectMakeCopy(bounds);
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -371,37 +259,36 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
|
||||
var knobInset = [self currentValueForThemeAttribute:@"knob-inset"],
|
||||
trackInset = [self currentValueForThemeAttribute:@"track-inset"],
|
||||
width = CGRectGetWidth(bounds),
|
||||
height = CGRectGetHeight(bounds);
|
||||
|
||||
width = _CGRectGetWidth(bounds),
|
||||
height = _CGRectGetHeight(bounds);
|
||||
|
||||
if ([self isVertical])
|
||||
{
|
||||
var decrementLineSize = [self currentValueForThemeAttribute:"decrement-line-size"],
|
||||
incrementLineSize = [self currentValueForThemeAttribute:"increment-line-size"],
|
||||
effectiveDecrementLineHeight = decrementLineSize.height + trackInset.top,
|
||||
effectiveIncrementLineHeight = incrementLineSize.height + trackInset.bottom,
|
||||
slotSize = height - effectiveDecrementLineHeight - effectiveIncrementLineHeight,
|
||||
slotHeight = height - effectiveDecrementLineHeight - effectiveIncrementLineHeight,
|
||||
minimumKnobLength = [self currentValueForThemeAttribute:"minimum-knob-length"],
|
||||
knobVerticalInset = knobInset.top + knobInset.bottom,
|
||||
knobWidth = width - knobInset.left - knobInset.right,
|
||||
knobHeight = MAX(minimumKnobLength, ((slotSize - knobVerticalInset) * _knobProportion)),
|
||||
knobLocation = effectiveDecrementLineHeight + (slotSize - knobHeight - knobVerticalInset) * [self floatValue] + knobInset.top;
|
||||
knobHeight = MAX(minimumKnobLength, (slotHeight * _knobProportion)),
|
||||
knobLocation = effectiveDecrementLineHeight + (slotHeight - knobHeight) * [self floatValue];
|
||||
|
||||
_partRects[CPScrollerDecrementPage] = CGRectMake(0.0, effectiveDecrementLineHeight, width, knobLocation - effectiveDecrementLineHeight);
|
||||
_partRects[CPScrollerKnob] = CGRectMake(knobInset.left, knobLocation, knobWidth, knobHeight);
|
||||
_partRects[CPScrollerIncrementPage] = CGRectMake(0.0, knobLocation + knobHeight, width, height - (knobLocation + knobHeight) - effectiveIncrementLineHeight);
|
||||
_partRects[CPScrollerKnobSlot] = CGRectMake(trackInset.left, effectiveDecrementLineHeight, width - trackInset.left - trackInset.right, slotSize);
|
||||
_partRects[CPScrollerDecrementLine] = CGRectMake(0.0, 0.0, decrementLineSize.width, decrementLineSize.height);
|
||||
_partRects[CPScrollerIncrementLine] = CGRectMake(0.0, height - incrementLineSize.height, incrementLineSize.width, incrementLineSize.height);
|
||||
|
||||
if (height < knobHeight + decrementLineSize.height + incrementLineSize.height + trackInset.top + trackInset.bottom)
|
||||
_partRects[CPScrollerKnob] = CGRectMakeZero();
|
||||
|
||||
if (height < decrementLineSize.height + incrementLineSize.height - 2)
|
||||
_partRects[CPScrollerDecrementPage] = _CGRectMake(0.0, effectiveDecrementLineHeight, width, knobLocation - effectiveDecrementLineHeight);
|
||||
_partRects[CPScrollerKnob] = _CGRectMake(knobInset.left, knobLocation, knobWidth, knobHeight);
|
||||
_partRects[CPScrollerIncrementPage] = _CGRectMake(0.0, knobLocation + knobHeight, width, height - (knobLocation + knobHeight) - effectiveIncrementLineHeight);
|
||||
_partRects[CPScrollerKnobSlot] = _CGRectMake(trackInset.left, effectiveDecrementLineHeight, width - trackInset.left - trackInset.right, slotHeight);
|
||||
_partRects[CPScrollerDecrementLine] = _CGRectMake(0.0, 0.0, decrementLineSize.width, decrementLineSize.height);
|
||||
_partRects[CPScrollerIncrementLine] = _CGRectMake(0.0, height - incrementLineSize.height, incrementLineSize.width, incrementLineSize.height);
|
||||
|
||||
if(height < knobHeight + decrementLineSize.height + incrementLineSize.height + trackInset.top + trackInset.bottom)
|
||||
_partRects[CPScrollerKnob] = _CGRectMakeZero();
|
||||
|
||||
if(height < decrementLineSize.height + incrementLineSize.height - 2)
|
||||
{
|
||||
_partRects[CPScrollerIncrementLine] = CGRectMakeZero();
|
||||
_partRects[CPScrollerDecrementLine] = CGRectMakeZero();
|
||||
_partRects[CPScrollerKnobSlot] = CGRectMake(trackInset.left, 0, width - trackInset.left - trackInset.right, height);
|
||||
_partRects[CPScrollerIncrementLine] = _CGRectMakeZero();
|
||||
_partRects[CPScrollerDecrementLine] = _CGRectMakeZero();
|
||||
_partRects[CPScrollerKnobSlot] = _CGRectMake(trackInset.left, 0, width - trackInset.left - trackInset.right, height);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -409,29 +296,28 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
var decrementLineSize = [self currentValueForThemeAttribute:"decrement-line-size"],
|
||||
incrementLineSize = [self currentValueForThemeAttribute:"increment-line-size"],
|
||||
effectiveDecrementLineWidth = decrementLineSize.width + trackInset.left,
|
||||
effectiveIncrementLineWidth = incrementLineSize.width + trackInset.right,
|
||||
slotSize = width - effectiveDecrementLineWidth - effectiveIncrementLineWidth,
|
||||
effectiveIncrementLineWidth = incrementLineSize.width + trackInset.right;
|
||||
slotWidth = width - effectiveDecrementLineWidth - effectiveIncrementLineWidth,
|
||||
minimumKnobLength = [self currentValueForThemeAttribute:"minimum-knob-length"],
|
||||
knobHorizontalInset = knobInset.left + knobInset.right,
|
||||
knobWidth = MAX(minimumKnobLength, ((slotSize - knobHorizontalInset) * _knobProportion)),
|
||||
knobWidth = MAX(minimumKnobLength, (slotWidth * _knobProportion)),
|
||||
knobHeight = height - knobInset.top - knobInset.bottom,
|
||||
knobLocation = effectiveDecrementLineWidth + (slotSize - knobWidth - knobHorizontalInset) * [self floatValue] + knobInset.left;
|
||||
knobLocation = effectiveDecrementLineWidth + (slotWidth - knobWidth) * [self floatValue];
|
||||
|
||||
_partRects[CPScrollerDecrementPage] = CGRectMake(effectiveDecrementLineWidth, 0.0, knobLocation - effectiveDecrementLineWidth, height);
|
||||
_partRects[CPScrollerKnob] = CGRectMake(knobLocation, knobInset.top, knobWidth, knobHeight);
|
||||
_partRects[CPScrollerIncrementPage] = CGRectMake(knobLocation + knobWidth, 0.0, width - (knobLocation + knobWidth) - effectiveIncrementLineWidth, height);
|
||||
_partRects[CPScrollerKnobSlot] = CGRectMake(effectiveDecrementLineWidth, trackInset.top, slotSize, height - trackInset.top - trackInset.bottom);
|
||||
_partRects[CPScrollerDecrementLine] = CGRectMake(0.0, 0.0, decrementLineSize.width, decrementLineSize.height);
|
||||
_partRects[CPScrollerIncrementLine] = CGRectMake(width - incrementLineSize.width, 0.0, incrementLineSize.width, incrementLineSize.height);
|
||||
|
||||
if (width < knobWidth + decrementLineSize.width + incrementLineSize.width + trackInset.left + trackInset.right)
|
||||
_partRects[CPScrollerKnob] = CGRectMakeZero();
|
||||
|
||||
if (width < decrementLineSize.width + incrementLineSize.width - 2)
|
||||
_partRects[CPScrollerDecrementPage] = _CGRectMake(effectiveDecrementLineWidth, 0.0, knobLocation - effectiveDecrementLineWidth, height);
|
||||
_partRects[CPScrollerKnob] = _CGRectMake(knobLocation, knobInset.top, knobWidth, knobHeight);
|
||||
_partRects[CPScrollerIncrementPage] = _CGRectMake(knobLocation + knobWidth, 0.0, width - (knobLocation + knobWidth) - effectiveIncrementLineWidth, height);
|
||||
_partRects[CPScrollerKnobSlot] = _CGRectMake(effectiveDecrementLineWidth, trackInset.top, slotWidth, height - trackInset.top - trackInset.bottom);
|
||||
_partRects[CPScrollerDecrementLine] = _CGRectMake(0.0, 0.0, decrementLineSize.width, decrementLineSize.height);
|
||||
_partRects[CPScrollerIncrementLine] = _CGRectMake(width - incrementLineSize.width, 0.0, incrementLineSize.width, incrementLineSize.height);
|
||||
|
||||
if(width < knobWidth + decrementLineSize.width + incrementLineSize.width + trackInset.left + trackInset.right)
|
||||
_partRects[CPScrollerKnob] = _CGRectMakeZero();
|
||||
|
||||
if(width < decrementLineSize.width + incrementLineSize.width - 2)
|
||||
{
|
||||
_partRects[CPScrollerIncrementLine] = CGRectMakeZero();
|
||||
_partRects[CPScrollerDecrementLine] = CGRectMakeZero();
|
||||
_partRects[CPScrollerKnobSlot] = CGRectMake(0.0, 0.0, width, slotSize);
|
||||
_partRects[CPScrollerIncrementLine] = _CGRectMakeZero();
|
||||
_partRects[CPScrollerDecrementLine] = _CGRectMakeZero();
|
||||
_partRects[CPScrollerKnobSlot] = _CGRectMake(0.0, 0.0, width, slotHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -445,32 +331,7 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
return _usableParts;
|
||||
}
|
||||
|
||||
/*!
|
||||
Display the scroller
|
||||
*/
|
||||
- (void)fadeIn
|
||||
{
|
||||
if (_isMouseOver && _knobProportion != 1.0)
|
||||
[self setThemeState:CPThemeStateSelected];
|
||||
|
||||
if (_timerFadeOut)
|
||||
[_timerFadeOut invalidate];
|
||||
|
||||
[self setAlphaValue:1.0];
|
||||
}
|
||||
|
||||
/*!
|
||||
Start the fade out anination
|
||||
*/
|
||||
- (void)fadeOut
|
||||
{
|
||||
[_animationScroller startAnimation];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Drawing
|
||||
|
||||
// Drawing the Parts
|
||||
/*!
|
||||
Draws the specified arrow and sets the highlight.
|
||||
@param anArrow the arrow to draw
|
||||
@@ -496,10 +357,10 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
|
||||
- (CPView)createViewForPart:(CPScrollerPart)aPart
|
||||
{
|
||||
var view = [[CPView alloc] initWithFrame:CGRectMakeZero()];
|
||||
|
||||
var view = [[CPView alloc] initWithFrame:_CGRectMakeZero()];
|
||||
|
||||
[view setHitTests:NO];
|
||||
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
@@ -510,31 +371,29 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
|
||||
- (CPView)createEphemeralSubviewNamed:(CPString)aName
|
||||
{
|
||||
var view = [[CPView alloc] initWithFrame:CGRectMakeZero()];
|
||||
var view = [[CPView alloc] initWithFrame:_CGRectMakeZero()];
|
||||
|
||||
[view setHitTests:NO];
|
||||
|
||||
|
||||
return view;
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[self _adjustScrollerSize];
|
||||
[self checkSpaceForParts];
|
||||
|
||||
var index = 0,
|
||||
count = PARTS_ARRANGEMENT.length,
|
||||
view;
|
||||
count = PARTS_ARRANGEMENT.length;
|
||||
|
||||
for (; index < count; ++index)
|
||||
{
|
||||
var part = PARTS_ARRANGEMENT[index];
|
||||
|
||||
|
||||
if (index === 0)
|
||||
view = [self layoutEphemeralSubviewNamed:part positioned:CPWindowBelow relativeToEphemeralSubviewNamed:PARTS_ARRANGEMENT[index + 1]];
|
||||
else
|
||||
view = [self layoutEphemeralSubviewNamed:part positioned:CPWindowAbove relativeToEphemeralSubviewNamed:PARTS_ARRANGEMENT[index - 1]];
|
||||
|
||||
|
||||
if (view)
|
||||
[view setBackgroundColor:[self currentValueForThemeAttribute:NAMES_FOR_PARTS[part] + "-color"]];
|
||||
}
|
||||
@@ -544,7 +403,7 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
Caches images for the scroll arrow and knob.
|
||||
*/
|
||||
- (void)drawParts
|
||||
{
|
||||
{
|
||||
[self drawKnobSlot];
|
||||
[self drawKnob];
|
||||
[self drawArrow:CPScrollerDecrementArrow highlight:NO];
|
||||
@@ -567,41 +426,40 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
- (void)trackKnob:(CPEvent)anEvent
|
||||
{
|
||||
var type = [anEvent type];
|
||||
|
||||
|
||||
if (type === CPLeftMouseUp)
|
||||
{
|
||||
_hitPart = CPScrollerNoPart;
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (type === CPLeftMouseDown)
|
||||
{
|
||||
_trackingFloatValue = [self floatValue];
|
||||
_trackingStartPoint = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
}
|
||||
|
||||
|
||||
else if (type === CPLeftMouseDragged)
|
||||
{
|
||||
var knobRect = [self rectForPart:CPScrollerKnob],
|
||||
knobSlotRect = [self rectForPart:CPScrollerKnobSlot],
|
||||
remainder = ![self isVertical] ? (CGRectGetWidth(knobSlotRect) - CGRectGetWidth(knobRect)) : (CGRectGetHeight(knobSlotRect) - CGRectGetHeight(knobRect));
|
||||
|
||||
remainder = ![self isVertical] ? (_CGRectGetWidth(knobSlotRect) - _CGRectGetWidth(knobRect)) : (_CGRectGetHeight(knobSlotRect) - _CGRectGetHeight(knobRect));
|
||||
|
||||
if (remainder <= 0)
|
||||
[self setFloatValue:0.0];
|
||||
else
|
||||
{
|
||||
var location = [self convertPoint:[anEvent locationInWindow] fromView:nil],
|
||||
var location = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
delta = ![self isVertical] ? location.x - _trackingStartPoint.x : location.y - _trackingStartPoint.y;
|
||||
|
||||
[self setFloatValue:_trackingFloatValue + delta / remainder];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[CPApp setTarget:self selector:@selector(trackKnob:) forNextEventMatchingMask:CPLeftMouseDraggedMask | CPLeftMouseUpMask untilDate:nil inMode:nil dequeue:YES];
|
||||
|
||||
if (type === CPLeftMouseDragged)
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -616,81 +474,86 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
{
|
||||
[self highlight:NO];
|
||||
[CPEvent stopPeriodicEvents];
|
||||
|
||||
|
||||
_hitPart = CPScrollerNoPart;
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (type === CPLeftMouseDown)
|
||||
{
|
||||
_trackingPart = [self hitPart];
|
||||
|
||||
|
||||
_trackingStartPoint = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
|
||||
if ([anEvent modifierFlags] & CPAlternateKeyMask)
|
||||
{
|
||||
if (_trackingPart === CPScrollerDecrementLine)
|
||||
if (_trackingPart == CPScrollerDecrementLine)
|
||||
_hitPart = CPScrollerDecrementPage;
|
||||
|
||||
else if (_trackingPart === CPScrollerIncrementLine)
|
||||
|
||||
else if (_trackingPart == CPScrollerIncrementLine)
|
||||
_hitPart = CPScrollerIncrementPage;
|
||||
|
||||
else if (_trackingPart === CPScrollerDecrementPage || _trackingPart === CPScrollerIncrementPage)
|
||||
|
||||
else if (_trackingPart == CPScrollerDecrementPage || _trackingPart == CPScrollerIncrementPage)
|
||||
{
|
||||
var knobRect = [self rectForPart:CPScrollerKnob],
|
||||
knobWidth = ![self isVertical] ? CGRectGetWidth(knobRect) : CGRectGetHeight(knobRect),
|
||||
knobWidth = ![self isVertical] ? _CGRectGetWidth(knobRect) : _CGRectGetHeight(knobRect),
|
||||
knobSlotRect = [self rectForPart:CPScrollerKnobSlot],
|
||||
remainder = (![self isVertical] ? CGRectGetWidth(knobSlotRect) : CGRectGetHeight(knobSlotRect)) - knobWidth;
|
||||
|
||||
[self setFloatValue:((![self isVertical] ? _trackingStartPoint.x - CGRectGetMinX(knobSlotRect) : _trackingStartPoint.y - CGRectGetMinY(knobSlotRect)) - knobWidth / 2.0) / remainder];
|
||||
remainder = (![self isVertical] ? _CGRectGetWidth(knobSlotRect) : _CGRectGetHeight(knobSlotRect)) - knobWidth;
|
||||
|
||||
[self setFloatValue:((![self isVertical] ? _trackingStartPoint.x - _CGRectGetMinX(knobSlotRect) : _trackingStartPoint.y - _CGRectGetMinY(knobSlotRect)) - knobWidth / 2.0) / remainder];
|
||||
|
||||
_hitPart = CPScrollerKnob;
|
||||
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
|
||||
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
|
||||
// Now just track the knob.
|
||||
return [self trackKnob:anEvent];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[self highlight:YES];
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
|
||||
|
||||
[CPEvent startPeriodicEventsAfterDelay:0.5 withPeriod:0.04];
|
||||
}
|
||||
|
||||
|
||||
else if (type === CPLeftMouseDragged)
|
||||
{
|
||||
_trackingStartPoint = [self convertPoint:[anEvent locationInWindow] fromView:nil];
|
||||
|
||||
if (_trackingPart === CPScrollerDecrementPage || _trackingPart === CPScrollerIncrementPage)
|
||||
|
||||
if (_trackingPart == CPScrollerDecrementPage || _trackingPart == CPScrollerIncrementPage)
|
||||
{
|
||||
var hitPart = [self testPart:[anEvent locationInWindow]];
|
||||
|
||||
if (hitPart === CPScrollerDecrementPage || hitPart === CPScrollerIncrementPage)
|
||||
|
||||
if (hitPart == CPScrollerDecrementPage || hitPart == CPScrollerIncrementPage)
|
||||
{
|
||||
_trackingPart = hitPart;
|
||||
_hitPart = hitPart;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[self highlight:CGRectContainsPoint([self rectForPart:_trackingPart], _trackingStartPoint)];
|
||||
}
|
||||
else if (type == CPPeriodic && CGRectContainsPoint([self rectForPart:_trackingPart], _trackingStartPoint))
|
||||
[self sendAction:[self action] to:[self target]];
|
||||
|
||||
|
||||
[CPApp setTarget:self selector:@selector(trackScrollButtons:) forNextEventMatchingMask:CPPeriodicMask | CPLeftMouseDraggedMask | CPLeftMouseUpMask untilDate:nil inMode:nil dequeue:YES];
|
||||
|
||||
}
|
||||
|
||||
- (void)_setIsVertical:(BOOL)isVertical
|
||||
- (void)_calculateIsVertical
|
||||
{
|
||||
_isVertical = isVertical;
|
||||
// Recalculate isVertical.
|
||||
var bounds = [self bounds],
|
||||
width = _CGRectGetWidth(bounds),
|
||||
height = _CGRectGetHeight(bounds);
|
||||
|
||||
if (_isVertical)
|
||||
_isVertical = width < height ? 1 : (width > height ? 0 : -1);
|
||||
|
||||
if (_isVertical === 1)
|
||||
[self setThemeState:CPThemeStateVertical];
|
||||
else
|
||||
else if (_isVertical === 0)
|
||||
[self unsetThemeState:CPThemeStateVertical];
|
||||
}
|
||||
|
||||
@@ -702,97 +565,28 @@ CPThemeStateScrollerKnobDark = CPThemeState("scroller-knob-dark");
|
||||
[self setNeedsLayout];
|
||||
}
|
||||
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Overrides
|
||||
|
||||
- (id)currentValueForThemeAttribute:(CPString)anAttributeName
|
||||
{
|
||||
var themeState = _themeState;
|
||||
|
||||
if (NAMES_FOR_PARTS[_hitPart] + "-color" !== anAttributeName)
|
||||
themeState = themeState.without(CPThemeStateHighlighted);
|
||||
|
||||
return [self valueForThemeAttribute:anAttributeName inState:themeState];
|
||||
}
|
||||
|
||||
- (void)mouseDown:(CPEvent)anEvent
|
||||
{
|
||||
if (![self isEnabled])
|
||||
return;
|
||||
|
||||
|
||||
_hitPart = [self testPart:[anEvent locationInWindow]];
|
||||
|
||||
|
||||
switch (_hitPart)
|
||||
{
|
||||
case CPScrollerKnob:
|
||||
return [self trackKnob:anEvent];
|
||||
|
||||
case CPScrollerDecrementLine:
|
||||
case CPScrollerIncrementLine:
|
||||
case CPScrollerKnob: return [self trackKnob:anEvent];
|
||||
|
||||
case CPScrollerDecrementLine:
|
||||
case CPScrollerIncrementLine:
|
||||
case CPScrollerDecrementPage:
|
||||
case CPScrollerIncrementPage:
|
||||
return [self trackScrollButtons:anEvent];
|
||||
case CPScrollerIncrementPage: return [self trackScrollButtons:anEvent];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)mouseEntered:(CPEvent)anEvent
|
||||
{
|
||||
[super mouseEntered:anEvent];
|
||||
|
||||
if (_timerFadeOut)
|
||||
[_timerFadeOut invalidate];
|
||||
|
||||
if (![self isEnabled])
|
||||
return;
|
||||
|
||||
_allowFadingOut = NO;
|
||||
_isMouseOver = YES;
|
||||
|
||||
if ([self alphaValue] > 0 && _knobProportion != 1.0)
|
||||
[self setThemeState:CPThemeStateSelected];
|
||||
}
|
||||
|
||||
- (void)mouseExited:(CPEvent)anEvent
|
||||
{
|
||||
[super mouseExited:anEvent];
|
||||
|
||||
if ([self isHidden] || ![self isEnabled] || !_isMouseOver)
|
||||
return;
|
||||
|
||||
_allowFadingOut = (_style !== CPScrollerStyleLegacy);
|
||||
_isMouseOver = NO;
|
||||
|
||||
if (_timerFadeOut)
|
||||
[_timerFadeOut invalidate];
|
||||
|
||||
if ([self hasThemeState:CPThemeStateScrollViewLegacy])
|
||||
[self unsetThemeState:CPThemeStateSelected];
|
||||
else
|
||||
_timerFadeOut = [CPTimer scheduledTimerWithTimeInterval:1.2 target:self selector:@selector(_performFadeOut:) userInfo:nil repeats:NO];
|
||||
}
|
||||
|
||||
- (float)scrollerWidth
|
||||
{
|
||||
if (_style == CPScrollerStyleLegacy)
|
||||
return [self valueForThemeAttribute:@"scroller-width" inState:CPThemeStateScrollViewLegacy];
|
||||
|
||||
return [self currentValueForThemeAttribute:@"scroller-width"];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
#pragma mark Delegates
|
||||
|
||||
- (void)animationDidEnd:(CPAnimation)animation
|
||||
{
|
||||
[self unsetThemeState:CPThemeStateSelected];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
var CPScrollerIsVerticalKey = @"CPScrollerIsVerticalKey",
|
||||
CPScrollerKnobProportionKey = @"CPScrollerKnobProportion",
|
||||
CPScrollerStyleKey = @"CPScrollerStyleKey";
|
||||
var CPScrollerControlSizeKey = "CPScrollerControlSize",
|
||||
CPScrollerKnobProportionKey = "CPScrollerKnobProportion";
|
||||
|
||||
@implementation CPScroller (CPCoding)
|
||||
|
||||
@@ -800,43 +594,30 @@ var CPScrollerIsVerticalKey = @"CPScrollerIsVerticalKey",
|
||||
{
|
||||
if (self = [super initWithCoder:aCoder])
|
||||
{
|
||||
_knobProportion = 1.0;
|
||||
_controlSize = CPRegularControlSize;
|
||||
if ([aCoder containsValueForKey:CPScrollerControlSizeKey])
|
||||
_controlSize = [aCoder decodeIntForKey:CPScrollerControlSizeKey];
|
||||
|
||||
_knobProportion = 1.0;
|
||||
if ([aCoder containsValueForKey:CPScrollerKnobProportionKey])
|
||||
_knobProportion = [aCoder decodeFloatForKey:CPScrollerKnobProportionKey];
|
||||
|
||||
_partRects = [];
|
||||
|
||||
|
||||
_hitPart = CPScrollerNoPart;
|
||||
|
||||
_allowFadingOut = YES;
|
||||
_isMouseOver = NO;
|
||||
|
||||
var paramAnimFadeOut = @{
|
||||
CPViewAnimationTargetKey: self,
|
||||
CPViewAnimationEffectKey: CPViewAnimationFadeOutEffect,
|
||||
};
|
||||
|
||||
_animationScroller = [[CPViewAnimation alloc] initWithDuration:0.2 animationCurve:CPAnimationEaseInOut];
|
||||
[_animationScroller setViewAnimations:[paramAnimFadeOut]];
|
||||
[_animationScroller setDelegate:self];
|
||||
[self setAlphaValue:0.0];
|
||||
|
||||
[self setStyle:[aCoder decodeIntForKey:CPScrollerStyleKey]];
|
||||
|
||||
[self _setIsVertical:[aCoder decodeBoolForKey:CPScrollerIsVerticalKey]];
|
||||
[self _calculateIsVertical];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(CPCoder)aCoder
|
||||
{
|
||||
[super encodeWithCoder:aCoder];
|
||||
|
||||
[aCoder encodeInt:_isVertical forKey:CPScrollerIsVerticalKey];
|
||||
|
||||
[aCoder encodeInt:_controlSize forKey:CPScrollerControlSizeKey];
|
||||
[aCoder encodeFloat:_knobProportion forKey:CPScrollerKnobProportionKey];
|
||||
[aCoder encodeInt:_style forKey:CPScrollerStyleKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+246
-665
File diff suppressed because it is too large
Load Diff
@@ -1,28 +1,6 @@
|
||||
/*
|
||||
* CPSecureTextField.j
|
||||
* AppKit
|
||||
*
|
||||
* Created by Francisco Tolmasky.
|
||||
* Copyright 2008, 280 North, Inc.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
@import "CPTextField.j"
|
||||
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
*/
|
||||
|
||||
+275
-523
File diff suppressed because it is too large
Load Diff
+34
-16
@@ -22,21 +22,20 @@
|
||||
|
||||
@import <Foundation/CPObject.j>
|
||||
|
||||
@import "CGGeometry.j"
|
||||
@import "CPColor.j"
|
||||
@import "CPGraphicsContext.j"
|
||||
|
||||
/*!
|
||||
@deprecated
|
||||
/*!
|
||||
@deprecated
|
||||
@class CPShadow
|
||||
|
||||
Instances of this class contain the attributes of a drop shadow used in Cappuccino.
|
||||
*/
|
||||
@implementation CPShadow : CPObject
|
||||
{
|
||||
CGSize _offset @accessors(property=shadowOffset);
|
||||
float _blurRadius @accessors(property=shadowBlurRadius);
|
||||
CPColor _color @accessors(property=shadowColor);
|
||||
CPSize _offset;
|
||||
float _blurRadius;
|
||||
CPColor _color;
|
||||
|
||||
CPString _cssString;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -52,25 +51,44 @@
|
||||
}
|
||||
|
||||
/* @ignore */
|
||||
- (id)_initWithOffset:(CGSize)anOffset blurRadius:(float)aBlurRadius color:(CPColor)aColor
|
||||
- (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;
|
||||
}
|
||||
|
||||
- (void)set
|
||||
/*!
|
||||
Returns the shadow's offset.
|
||||
*/
|
||||
- (CGSize)shadowOffset
|
||||
{
|
||||
var context = [[CPGraphicsContext currentContext] graphicsPort];
|
||||
return _offset;
|
||||
}
|
||||
|
||||
CGContextSetShadowWithColor(context, _offset, _blurRadius, _color);
|
||||
/*!
|
||||
Returns the shadow's blur radius
|
||||
*/
|
||||
- (float)shadowBlurRadius
|
||||
{
|
||||
return _blurRadius;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the shadow's color.
|
||||
*/
|
||||
- (CPColor)shadowColor
|
||||
{
|
||||
return _color;
|
||||
}
|
||||
|
||||
/*!
|
||||
@@ -78,7 +96,7 @@
|
||||
*/
|
||||
- (CPString)cssString
|
||||
{
|
||||
return [_color cssString] + " " + ROUND(_offset.width) + @"px " + ROUND(_offset.height) + @"px " + ROUND(_blurRadius) + @"px";
|
||||
return _cssString;
|
||||
}
|
||||
|
||||
@end
|
||||
@end
|
||||
+81
-77
@@ -24,86 +24,88 @@
|
||||
|
||||
@import "CGGeometry.j"
|
||||
@import "CPImage.j"
|
||||
@import "CPImageView.j"
|
||||
@import "CPView.j"
|
||||
|
||||
@typedef CPShadowWeight
|
||||
|
||||
#include "CoreGraphics/CGGeometry.h"
|
||||
|
||||
CPLightShadow = 0;
|
||||
CPHeavyShadow = 1;
|
||||
|
||||
CPThemeStateShadowViewLight = CPThemeState("shadowview-style-light");
|
||||
CPThemeStateShadowViewHeavy = CPThemeState("shadowview-style-heavy");
|
||||
|
||||
var CPShadowViewLightBackgroundColor = nil,
|
||||
CPShadowViewHeavyBackgroundColor = nil;
|
||||
|
||||
var LIGHT_LEFT_INSET = 3.0,
|
||||
LIGHT_RIGHT_INSET = 3.0,
|
||||
LIGHT_TOP_INSET = 3.0,
|
||||
LIGHT_BOTTOM_INSET = 5.0,
|
||||
|
||||
HEAVY_LEFT_INSET = 7.0,
|
||||
HEAVY_RIGHT_INSET = 7.0,
|
||||
HEAVY_TOP_INSET = 5.0,
|
||||
HEAVY_BOTTOM_INSET = 5.0;
|
||||
|
||||
/*!
|
||||
@ingroup appkit
|
||||
*/
|
||||
|
||||
@implementation CPShadowView : CPView
|
||||
{
|
||||
CPShadowWeight _weight;
|
||||
}
|
||||
|
||||
+ (CPString)defaultThemeClass
|
||||
+ (void)initialize
|
||||
{
|
||||
return "shadow-view";
|
||||
}
|
||||
if (self != [CPShadowView class])
|
||||
return;
|
||||
|
||||
+ (CPDictionary)themeAttributes
|
||||
{
|
||||
return @{
|
||||
@"bezel-color": [CPNull null],
|
||||
@"content-inset": CGInsetMakeZero()
|
||||
};
|
||||
}
|
||||
|
||||
+ (CGRect)frameForContentFrame:(CGRect)aFrame withWeight:(CPShadowWeight)aWeight
|
||||
{
|
||||
var shadowView = [CPShadowView new],
|
||||
inset = [shadowView valueForThemeAttribute:@"content-inset" inState:(aWeight == CPLightShadow) ? CPThemeStateShadowViewLight : CPThemeStateShadowViewHeavy];
|
||||
|
||||
return CGRectMake(CGRectGetMinX(aFrame) - inset.left, CGRectGetMinY(aFrame) - inset.top, CGRectGetWidth(aFrame) + inset.left + inset.right, CGRectGetHeight(aFrame) + inset.top + inset.bottom);
|
||||
}
|
||||
|
||||
+ (id)shadowViewEnclosingView:(CPView)aView
|
||||
{
|
||||
return [self shadowViewEnclosingView:aView withWeight:CPLightShadow];
|
||||
}
|
||||
|
||||
+ (id)shadowViewEnclosingView:(CPView)aView withWeight:(CPShadowWeight)aWeight
|
||||
{
|
||||
var shadowView = [[self alloc] initWithFrame:[aView frame]];
|
||||
|
||||
if (shadowView)
|
||||
{
|
||||
[shadowView setWeight:aWeight];
|
||||
|
||||
var size = [shadowView frame].size,
|
||||
inset = [shadowView currentValueForThemeAttribute:@"content-inset"],
|
||||
width = size.width - inset.left - inset.right,
|
||||
height = size.height - inset.top - inset.bottom,
|
||||
enclosingView = [aView superview];
|
||||
|
||||
[shadowView setHitTests:[aView hitTests]];
|
||||
[shadowView setAutoresizingMask:[aView autoresizingMask]];
|
||||
[aView removeFromSuperview];
|
||||
[shadowView addSubview:aView];
|
||||
[aView setFrame:CGRectMake(inset.left, inset.top, width, height)];
|
||||
[enclosingView addSubview:shadowView];
|
||||
}
|
||||
|
||||
return shadowView;
|
||||
var bundle = [CPBundle bundleForClass:[self class]];
|
||||
|
||||
CPShadowViewLightBackgroundColor = [CPColor colorWithPatternImage:[[CPNinePartImage alloc] initWithImageSlices:
|
||||
[
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightTopLeft.png"] size:CGSizeMake(9.0, 9.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightTop.png"] size:CGSizeMake(1.0, 9.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightTopRight.png"] size:CGSizeMake(9.0, 9.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightLeft.png"] size:CGSizeMake(9.0, 1.0)],
|
||||
nil,
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightRight.png"] size:CGSizeMake(9.0, 1.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightBottomLeft.png"] size:CGSizeMake(9.0, 9.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightBottom.png"] size:CGSizeMake(1.0, 9.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewLightBottomRight.png"] size:CGSizeMake(9.0, 9.0)]
|
||||
]]];
|
||||
|
||||
CPShadowViewHeavyBackgroundColor = [CPColor colorWithPatternImage:[[CPNinePartImage alloc] initWithImageSlices:
|
||||
[
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyTopLeft.png"] size:CGSizeMake(17.0, 17.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyTop.png"] size:CGSizeMake(1.0, 17.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyTopRight.png"] size:CGSizeMake(17.0, 17.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyLeft.png"] size:CGSizeMake(17.0, 1.0)],
|
||||
nil,
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyRight.png"] size:CGSizeMake(17.0, 1.0)],
|
||||
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyBottomLeft.png"] size:CGSizeMake(17.0, 17.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyBottom.png"] size:CGSizeMake(1.0, 17.0)],
|
||||
[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPShadowView/CPShadowViewHeavyBottomRight.png"] size:CGSizeMake(17.0, 17.0)]
|
||||
]]];
|
||||
}
|
||||
|
||||
- (id)initWithFrame:(CGRect)aFrame
|
||||
{
|
||||
self = [super initWithFrame:aFrame];
|
||||
|
||||
|
||||
if (self)
|
||||
{
|
||||
[self setWeight:CPLightShadow];
|
||||
|
||||
_weight = CPLightShadow;
|
||||
|
||||
[self setBackgroundColor:CPShadowViewLightBackgroundColor];
|
||||
|
||||
[self setHitTests:NO];
|
||||
}
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -111,49 +113,58 @@ CPThemeStateShadowViewHeavy = CPThemeState("shadowview-style-heavy");
|
||||
{
|
||||
if (_weight == aWeight)
|
||||
return;
|
||||
|
||||
|
||||
_weight = aWeight;
|
||||
|
||||
|
||||
if (_weight == CPLightShadow)
|
||||
[self setThemeState:CPThemeStateShadowViewLight];
|
||||
else
|
||||
[self setThemeState:CPThemeStateShadowViewHeavy];
|
||||
[self setBackgroundColor:CPShadowViewLightBackgroundColor];
|
||||
|
||||
[self setNeedsLayout];
|
||||
else
|
||||
[self setBackgroundColor:CPShadowViewHeavyBackgroundColor];
|
||||
}
|
||||
|
||||
- (float)leftInset
|
||||
{
|
||||
return [self currentValueForThemeAttribute:@"content-inset"].left;
|
||||
return _weight == CPLightShadow ? LIGHT_LEFT_INSET : HEAVY_LEFT_INSET;
|
||||
}
|
||||
|
||||
- (float)rightInset
|
||||
{
|
||||
return [self currentValueForThemeAttribute:@"content-inset"].right;
|
||||
return _weight == CPLightShadow ? LIGHT_RIGHT_INSET : HEAVY_RIGHT_INSET;
|
||||
}
|
||||
|
||||
- (float)topInset
|
||||
{
|
||||
return [self currentValueForThemeAttribute:@"content-inset"].top;
|
||||
return _weight == CPLightShadow ? LIGHT_TOP_INSET : HEAVY_TOP_INSET;
|
||||
}
|
||||
|
||||
- (float)bottomInset
|
||||
{
|
||||
return [self currentValueForThemeAttribute:@"content-inset"].bottom;
|
||||
return _weight == CPLightShadow ? LIGHT_BOTTOM_INSET : HEAVY_BOTTOM_INSET;
|
||||
}
|
||||
|
||||
- (float)horizontalInset
|
||||
{
|
||||
var currentContentInset = [self currentValueForThemeAttribute:@"content-inset"];
|
||||
|
||||
return currentContentInset.left + currentContentInset.right;
|
||||
if (_weight == CPLightShadow)
|
||||
return LIGHT_LEFT_INSET + LIGHT_RIGHT_INSET;
|
||||
|
||||
return HEAVY_LEFT_INSET + HEAVY_RIGHT_INSET;
|
||||
}
|
||||
|
||||
- (float)verticalInset
|
||||
{
|
||||
var currentContentInset = [self currentValueForThemeAttribute:@"content-inset"];
|
||||
if (_weight == CPLightShadow)
|
||||
return LIGHT_TOP_INSET + LIGHT_BOTTOM_INSET;
|
||||
|
||||
return HEAVY_TOP_INSET + HEAVY_BOTTOM_INSET;
|
||||
}
|
||||
|
||||
return currentContentInset.top + currentContentInset.bottom;
|
||||
+ (CGRect)frameForContentFrame:(CGRect)aFrame withWeight:(CPShadowWeight)aWeight
|
||||
{
|
||||
if (aWeight == CPLightShadow)
|
||||
return CGRectMake(_CGRectGetMinX(aFrame) - LIGHT_LEFT_INSET, _CGRectGetMinY(aFrame) - LIGHT_TOP_INSET, _CGRectGetWidth(aFrame) + LIGHT_LEFT_INSET + LIGHT_RIGHT_INSET, _CGRectGetHeight(aFrame) + LIGHT_TOP_INSET + LIGHT_BOTTOM_INSET);
|
||||
else
|
||||
return CGRectMake(_CGRectGetMinX(aFrame) - HEAVY_LEFT_INSET, _CGRectGetMinY(aFrame) - HEAVY_TOP_INSET, _CGRectGetWidth(aFrame) + HEAVY_LEFT_INSET + HEAVY_RIGHT_INSET, _CGRectGetHeight(aFrame) + HEAVY_TOP_INSET + HEAVY_BOTTOM_INSET);
|
||||
}
|
||||
|
||||
- (CGRect)frameForContentFrame:(CGRect)aFrame
|
||||
@@ -166,11 +177,4 @@ CPThemeStateShadowViewHeavy = CPThemeState("shadowview-style-heavy");
|
||||
[self setFrame:[self frameForContentFrame:aFrame]];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[super layoutSubviews];
|
||||
|
||||
[self setBackgroundColor:[self currentValueForThemeAttribute:@"bezel-color"]];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+185
-857
File diff suppressed because it is too large
Load Diff
+278
-229
@@ -21,29 +21,21 @@
|
||||
*/
|
||||
|
||||
@import "CPColorPicker.j"
|
||||
@import "CPSlider.j"
|
||||
@import "CPTextField.j"
|
||||
@import "CPView.j"
|
||||
|
||||
@global CPColorPickerViewWidth
|
||||
@global CPColorPickerViewHeight
|
||||
@global CPSliderColorPickerMode
|
||||
|
||||
|
||||
/*
|
||||
@ignore
|
||||
*/
|
||||
@implementation CPSliderColorPicker : CPColorPicker
|
||||
{
|
||||
{
|
||||
CPView _contentView;
|
||||
|
||||
|
||||
CPSlider _redSlider;
|
||||
CPSlider _greenSlider;
|
||||
CPSlider _blueSlider;
|
||||
CPSlider _hueSlider;
|
||||
CPSlider _saturationSlider;
|
||||
CPSlider _brightnessSlider;
|
||||
|
||||
|
||||
CPTextField _rgbLabel;
|
||||
CPTextField _hsbLabel;
|
||||
CPTextField _redLabel;
|
||||
@@ -53,247 +45,346 @@
|
||||
CPTextField _saturationLabel;
|
||||
CPTextField _brightnessLabel;
|
||||
CPTextField _hexLabel;
|
||||
CPTextField _hexValue;
|
||||
|
||||
CPTextField _redValue;
|
||||
CPTextField _greenValue;
|
||||
CPTextField _blueValue;
|
||||
CPTextField _hueValue;
|
||||
CPTextField _saturationValue;
|
||||
CPTextField _brightnessValue;
|
||||
#if PLATFORM(DOM)
|
||||
DOMElement _redValue;
|
||||
DOMElement _greenValue;
|
||||
DOMElement _blueValue;
|
||||
DOMElement _hueValue;
|
||||
DOMElement _saturationValue;
|
||||
DOMElement _brightnessValue;
|
||||
DOMElement _hexValue;
|
||||
#endif
|
||||
}
|
||||
|
||||
- (id)initWithPickerMask:(int)mask colorPanel:(CPColorPanel)owningColorPanel
|
||||
- (id)initWithPickerMask:(int)mask colorPanel:(CPColorPanel)owningColorPanel
|
||||
{
|
||||
return [super initWithPickerMask:mask colorPanel:owningColorPanel];
|
||||
return [super initWithPickerMask:mask colorPanel: owningColorPanel];
|
||||
}
|
||||
|
||||
- (id)initView
|
||||
|
||||
-(id)initView
|
||||
{
|
||||
var aFrame = CGRectMake(0, 0, CPColorPickerViewWidth, CPColorPickerViewHeight);
|
||||
|
||||
aFrame = CPRectMake(0, 0, CPColorPickerViewWidth, CPColorPickerViewHeight);
|
||||
|
||||
_contentView = [[CPView alloc] initWithFrame:aFrame];
|
||||
[_contentView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
|
||||
|
||||
_rgbLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 10, 100, 20)];
|
||||
[_rgbLabel setStringValue:"Red, Green, Blue"];
|
||||
[_contentView setAutoresizingMask:CPViewWidthSizable|CPViewHeightSizable];
|
||||
|
||||
_rgbLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 10, 100, 20)];
|
||||
[_rgbLabel setStringValue: "Red, Green, Blue"];
|
||||
[_rgbLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_redLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 37, 15, 20)];
|
||||
[_redLabel setStringValue:"R"];
|
||||
_redLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 35, 15, 20)];
|
||||
[_redLabel setStringValue: "R"];
|
||||
[_redLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_redSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 35, aFrame.size.width - 70, 20)];
|
||||
[_redSlider setMaxValue: 1.0];
|
||||
[_redSlider setMinValue: 0.0];
|
||||
[_redSlider setTarget: self];
|
||||
[_redSlider setAction: @selector(sliderChanged:)];
|
||||
[_redSlider setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
_redSlider = [[CPSlider alloc] initWithFrame:CGRectMake(15, 35, aFrame.size.width - 70, 20)];
|
||||
[_redSlider setMaxValue:1.0];
|
||||
[_redSlider setMinValue:0.0];
|
||||
[_redSlider setTarget:self];
|
||||
[_redSlider setAction:@selector(sliderChanged:)];
|
||||
[_redSlider setAutoresizingMask:CPViewWidthSizable];
|
||||
#if PLATFORM(DOM)
|
||||
var updateFunction = function(aDOMEvent)
|
||||
{
|
||||
if(isNaN(this.value))
|
||||
return;
|
||||
|
||||
switch(this)
|
||||
{
|
||||
case _redValue: [_redSlider setFloatValue:MAX(MIN(ROUND(this.value), 255) / 255.0, 0)];
|
||||
//[self sliderChanged: _redSlider];
|
||||
break;
|
||||
|
||||
case _greenValue: [_greenSlider setFloatValue:MAX(MIN(ROUND(this.value), 255) / 255.0, 0)];
|
||||
//[self sliderChanged: _greenSlider];
|
||||
break;
|
||||
|
||||
case _blueValue: [_blueSlider setFloatValue:MAX(MIN(ROUND(this.value), 255) / 255.0, 0)];
|
||||
//[self sliderChanged: _blueSlider];
|
||||
break;
|
||||
|
||||
// red value input box
|
||||
_redValue = [[CPTextField alloc] initWithFrame:CGRectMake(aFrame.size.width - 45, 30, 45, 28)];
|
||||
[_redValue setAutoresizingMask:CPViewMinXMargin];
|
||||
[_redValue setEditable:YES];
|
||||
[_redValue setBezeled:YES];
|
||||
[_redValue setDelegate:self];
|
||||
[_contentView addSubview:_redValue];
|
||||
case _hueValue: [_hueSlider setFloatValue:MAX(MIN(ROUND(this.value), 360), 0)];
|
||||
//[self sliderChanged: _hueSlider];
|
||||
break;
|
||||
|
||||
case _saturationValue: [_saturationSlider setFloatValue:MAX(MIN(ROUND(this.value), 100), 0)];
|
||||
//[self sliderChanged: _saturationSlider];
|
||||
break;
|
||||
|
||||
_greenLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 63, 15, 20)];
|
||||
[_greenLabel setStringValue:"G"];
|
||||
case _brightnessValue: [_brightnessSlider setFloatValue:MAX(MIN(ROUND(this.value), 100), 0)];
|
||||
//[self sliderChanged: _brightnessSlider];
|
||||
break;
|
||||
}
|
||||
|
||||
this.blur();
|
||||
};
|
||||
|
||||
var keypressFunction = function(aDOMEvent)
|
||||
{
|
||||
aDOMEvent = aDOMEvent || window.event;
|
||||
if (aDOMEvent.keyCode == 13)
|
||||
{
|
||||
updateFunction(aDOMEvent);
|
||||
|
||||
if(aDOMEvent.preventDefault)
|
||||
aDOMEvent.preventDefault();
|
||||
else if(aDOMEvent.stopPropagation)
|
||||
aDOMEvent.stopPropagation();
|
||||
}
|
||||
}
|
||||
|
||||
//red value input box
|
||||
var redValue = [[CPView alloc] initWithFrame: CPRectMake(aFrame.size.width - 45, 35, 45, 20)];
|
||||
[redValue setAutoresizingMask: CPViewMinXMargin];
|
||||
|
||||
_redValue = document.createElement("input");
|
||||
_redValue.style.width = "40px";
|
||||
_redValue.style.backgroundColor = "transparent";
|
||||
_redValue.style.border = "1px solid black";
|
||||
_redValue.style.color = "black";
|
||||
_redValue.style.position = "absolute";
|
||||
_redValue.style.top = "0px";
|
||||
_redValue.style.left = "0px";
|
||||
_redValue.onchange = updateFunction;
|
||||
|
||||
redValue._DOMElement.appendChild(_redValue);
|
||||
[_contentView addSubview: redValue];
|
||||
#endif
|
||||
|
||||
_greenLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 58, 15, 20)];
|
||||
[_greenLabel setStringValue: "G"];
|
||||
[_greenLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_greenSlider = [[CPSlider alloc] initWithFrame:CGRectMake(15, 61, aFrame.size.width - 70, 20)];
|
||||
[_greenSlider setMaxValue:1.0];
|
||||
[_greenSlider setMinValue:0.0];
|
||||
[_greenSlider setTarget:self];
|
||||
[_greenSlider setAction:@selector(sliderChanged:)];
|
||||
[_greenSlider setAutoresizingMask:CPViewWidthSizable];
|
||||
_greenSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 58, aFrame.size.width - 70, 20)];
|
||||
[_greenSlider setMaxValue: 1.0];
|
||||
[_greenSlider setMinValue: 0.0];
|
||||
[_greenSlider setTarget: self];
|
||||
[_greenSlider setAction: @selector(sliderChanged:)];
|
||||
[_greenSlider setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
// green value input box
|
||||
_greenValue = [[CPTextField alloc] initWithFrame:CGRectMake(aFrame.size.width - 45, 56, 45, 28)];
|
||||
[_greenValue setAutoresizingMask:CPViewMinXMargin];
|
||||
[_greenValue setEditable:YES];
|
||||
[_greenValue setBezeled:YES];
|
||||
[_greenValue setDelegate:self];
|
||||
[_contentView addSubview:_greenValue];
|
||||
#if PLATFORM(DOM)
|
||||
//green value input box
|
||||
var greenValue = [[CPView alloc] initWithFrame: CPRectMake(aFrame.size.width - 45, 58, 45, 20)];
|
||||
[greenValue setAutoresizingMask: CPViewMinXMargin];
|
||||
|
||||
_blueLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 90, 15, 20)];
|
||||
[_blueLabel setStringValue:"B"];
|
||||
_greenValue = _redValue.cloneNode(false);
|
||||
_greenValue.onchange = updateFunction;
|
||||
|
||||
greenValue._DOMElement.appendChild(_greenValue);
|
||||
[_contentView addSubview: greenValue];
|
||||
#endif
|
||||
|
||||
_blueLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 81, 15, 20)];
|
||||
[_blueLabel setStringValue: "B"];
|
||||
[_blueLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_blueSlider = [[CPSlider alloc] initWithFrame:CGRectMake(15, 87, aFrame.size.width - 70, 20)];
|
||||
[_blueSlider setMaxValue:1.0];
|
||||
[_blueSlider setMinValue:0.0];
|
||||
[_blueSlider setTarget:self];
|
||||
[_blueSlider setAction:@selector(sliderChanged:)];
|
||||
[_blueSlider setAutoresizingMask:CPViewWidthSizable];
|
||||
_blueSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 81, aFrame.size.width - 70, 20)];
|
||||
[_blueSlider setMaxValue: 1.0];
|
||||
[_blueSlider setMinValue: 0.0];
|
||||
[_blueSlider setTarget: self];
|
||||
[_blueSlider setAction: @selector(sliderChanged:)];
|
||||
[_blueSlider setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
// blue value input box
|
||||
_blueValue = [[CPTextField alloc] initWithFrame:CGRectMake(aFrame.size.width - 45, 82, 45, 28)];
|
||||
[_blueValue setAutoresizingMask:CPViewMinXMargin];
|
||||
[_blueValue setEditable:YES];
|
||||
[_blueValue setBezeled:YES];
|
||||
[_blueValue setDelegate:self];
|
||||
[_contentView addSubview:_blueValue];
|
||||
#if PLATFORM(DOM)
|
||||
//blue value input box
|
||||
var blueValue = [[CPView alloc] initWithFrame: CPRectMake(aFrame.size.width - 45, 81, 45, 20)];
|
||||
[blueValue setAutoresizingMask: CPViewMinXMargin];
|
||||
|
||||
_hsbLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 120, 190, 20)];
|
||||
[_hsbLabel setStringValue:"Hue, Saturation, Brightness"];
|
||||
_blueValue = _redValue.cloneNode(false);
|
||||
_blueValue.onchange = updateFunction;
|
||||
|
||||
blueValue._DOMElement.appendChild(_blueValue);
|
||||
[_contentView addSubview: blueValue];
|
||||
#endif
|
||||
_hsbLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 120, 190, 20)];
|
||||
[_hsbLabel setStringValue: "Hue, Saturation, Brightness"];
|
||||
[_hsbLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_hueLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 145, 15, 20)];
|
||||
[_hueLabel setStringValue:"H"];
|
||||
_hueLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 145, 15, 20)];
|
||||
[_hueLabel setStringValue: "H"];
|
||||
[_hueLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_hueSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 145, aFrame.size.width - 70, 20)];
|
||||
[_hueSlider setMaxValue: 359.0];
|
||||
[_hueSlider setMinValue: 0.0];
|
||||
[_hueSlider setTarget: self];
|
||||
[_hueSlider setAction: @selector(sliderChanged:)];
|
||||
[_hueSlider setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
_hueSlider = [[CPSlider alloc] initWithFrame:CGRectMake(15, 143, aFrame.size.width - 70, 20)];
|
||||
[_hueSlider setMaxValue:0.999];
|
||||
[_hueSlider setMinValue:0.0];
|
||||
[_hueSlider setTarget:self];
|
||||
[_hueSlider setAction:@selector(sliderChanged:)];
|
||||
[_hueSlider setAutoresizingMask:CPViewWidthSizable];
|
||||
#if PLATFORM(DOM)
|
||||
//red value input box
|
||||
var hueValue = [[CPView alloc] initWithFrame: CPRectMake(aFrame.size.width - 45, 145, 45, 20)];
|
||||
[hueValue setAutoresizingMask: CPViewMinXMargin];
|
||||
|
||||
// hue value input box
|
||||
_hueValue = [[CPTextField alloc] initWithFrame:CGRectMake(aFrame.size.width - 45, 138, 45, 28)];
|
||||
[_hueValue setAutoresizingMask:CPViewMinXMargin];
|
||||
[_hueValue setEditable:YES];
|
||||
[_hueValue setBezeled:YES];
|
||||
[_hueValue setDelegate:self];
|
||||
[_contentView addSubview:_hueValue];
|
||||
_hueValue = _redValue.cloneNode(false);
|
||||
_hueValue.onchange = updateFunction;
|
||||
|
||||
_saturationLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 170, 15, 20)];
|
||||
[_saturationLabel setStringValue:"S"];
|
||||
hueValue._DOMElement.appendChild(_hueValue);
|
||||
[_contentView addSubview: hueValue];
|
||||
#endif
|
||||
_saturationLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 168, 15, 20)];
|
||||
[_saturationLabel setStringValue: "S"];
|
||||
[_saturationLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_saturationSlider = [[CPSlider alloc] initWithFrame:CGRectMake(15, 168, aFrame.size.width - 70, 20)];
|
||||
[_saturationSlider setMaxValue:1.0];
|
||||
[_saturationSlider setMinValue:0.0];
|
||||
[_saturationSlider setTarget:self];
|
||||
[_saturationSlider setAction:@selector(sliderChanged:)];
|
||||
[_saturationSlider setAutoresizingMask:CPViewWidthSizable];
|
||||
_saturationSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 168, aFrame.size.width - 70, 20)];
|
||||
[_saturationSlider setMaxValue: 100.0];
|
||||
[_saturationSlider setMinValue: 0.0];
|
||||
[_saturationSlider setTarget: self];
|
||||
[_saturationSlider setAction: @selector(sliderChanged:)];
|
||||
[_saturationSlider setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
// saturation value input box
|
||||
_saturationValue = [[CPTextField alloc] initWithFrame:CGRectMake(aFrame.size.width - 45, 164, 45, 28)];
|
||||
[_saturationValue setAutoresizingMask:CPViewMinXMargin];
|
||||
[_saturationValue setEditable:YES];
|
||||
[_saturationValue setBezeled:YES];
|
||||
[_saturationValue setDelegate:self];
|
||||
[_contentView addSubview:_saturationValue];
|
||||
#if PLATFORM(DOM)
|
||||
//green value input box
|
||||
var saturationValue = [[CPView alloc] initWithFrame: CPRectMake(aFrame.size.width - 45, 168, 45, 20)];
|
||||
[saturationValue setAutoresizingMask: CPViewMinXMargin];
|
||||
|
||||
_brightnessLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 196, 15, 20)];
|
||||
[_brightnessLabel setStringValue:"B"];
|
||||
_saturationValue = _redValue.cloneNode(false);
|
||||
_saturationValue.onchange = updateFunction;
|
||||
|
||||
saturationValue._DOMElement.appendChild(_saturationValue);
|
||||
[_contentView addSubview: saturationValue];
|
||||
#endif
|
||||
_brightnessLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 191, 15, 20)];
|
||||
[_brightnessLabel setStringValue: "B"];
|
||||
[_brightnessLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
_brightnessSlider = [[CPSlider alloc] initWithFrame:CGRectMake(15, 194, aFrame.size.width - 70, 20)];
|
||||
[_brightnessSlider setMaxValue:1.0];
|
||||
[_brightnessSlider setMinValue:0.0];
|
||||
[_brightnessSlider setTarget:self];
|
||||
[_brightnessSlider setAction:@selector(sliderChanged:)];
|
||||
[_brightnessSlider setAutoresizingMask:CPViewWidthSizable];
|
||||
_brightnessSlider = [[CPSlider alloc] initWithFrame: CPRectMake(15, 191, aFrame.size.width - 70, 20)];
|
||||
[_brightnessSlider setMaxValue: 100.0];
|
||||
[_brightnessSlider setMinValue: 0.0];
|
||||
[_brightnessSlider setTarget: self];
|
||||
[_brightnessSlider setAction: @selector(sliderChanged:)];
|
||||
[_brightnessSlider setAutoresizingMask: CPViewWidthSizable];
|
||||
|
||||
// brightness value input box
|
||||
_brightnessValue = [[CPTextField alloc] initWithFrame:CGRectMake(aFrame.size.width - 45, 190, 45, 28)];
|
||||
[_brightnessValue setAutoresizingMask:CPViewMinXMargin];
|
||||
[_brightnessValue setEditable:YES];
|
||||
[_brightnessValue setBezeled:YES];
|
||||
[_brightnessValue setDelegate:self];
|
||||
[_contentView addSubview:_brightnessValue];
|
||||
#if PLATFORM(DOM)
|
||||
//blue value input box
|
||||
var brightnessValue = [[CPView alloc] initWithFrame: CPRectMake(aFrame.size.width - 45, 191, 45, 20)];
|
||||
[brightnessValue setAutoresizingMask: CPViewMinXMargin];
|
||||
|
||||
_hexLabel = [[CPTextField alloc] initWithFrame:CGRectMake(0, 230, 30, 20)];
|
||||
[_hexLabel setStringValue:"Hex"];
|
||||
_brightnessValue = _redValue.cloneNode(false);
|
||||
_brightnessValue.onchange = updateFunction;
|
||||
|
||||
brightnessValue._DOMElement.appendChild(_brightnessValue);
|
||||
[_contentView addSubview: brightnessValue];
|
||||
#endif
|
||||
_hexLabel = [[CPTextField alloc] initWithFrame: CPRectMake(0, 230, 30, 20)];
|
||||
[_hexLabel setStringValue: "Hex"];
|
||||
[_hexLabel setTextColor:[CPColor blackColor]];
|
||||
|
||||
#if PLATFORM(DOM)
|
||||
//hex input box
|
||||
_hexValue = [[CPTextField alloc] initWithFrame:CGRectMake(32, 225, 80, 28)];
|
||||
[_hexValue setEditable:YES];
|
||||
[_hexValue setBezeled:YES];
|
||||
[_hexValue setDelegate:self];
|
||||
[_contentView addSubview:_hexValue];
|
||||
_hexValue = _redValue.cloneNode(false);
|
||||
_hexValue.style.top = "228px";
|
||||
_hexValue.style.width = "80px";
|
||||
_hexValue.style.left = "35px";
|
||||
_hexValue.onkeypress = function(aDOMEvent)
|
||||
{
|
||||
aDOMEvent = aDOMEvent || window.event;
|
||||
if (aDOMEvent.keyCode == 13)
|
||||
{
|
||||
var newColor = [CPColor colorWithHexString: this.value];
|
||||
|
||||
if(newColor)
|
||||
{
|
||||
[self setColor: newColor];
|
||||
[[self colorPanel] setColor: newColor];
|
||||
}
|
||||
|
||||
if(aDOMEvent.preventDefault)
|
||||
aDOMEvent.preventDefault();
|
||||
else if(aDOMEvent.stopPropagation)
|
||||
aDOMEvent.stopPropagation();
|
||||
|
||||
this.blur();
|
||||
}
|
||||
};
|
||||
|
||||
[_contentView addSubview:_rgbLabel];
|
||||
[_contentView addSubview:_redLabel];
|
||||
[_contentView addSubview:_greenLabel];
|
||||
[_contentView addSubview:_blueLabel];
|
||||
[_contentView addSubview:_redSlider];
|
||||
[_contentView addSubview:_greenSlider];
|
||||
[_contentView addSubview:_blueSlider];
|
||||
_contentView._DOMElement.appendChild(_hexValue);
|
||||
#endif
|
||||
|
||||
[_contentView addSubview:_hsbLabel];
|
||||
[_contentView addSubview:_hueLabel];
|
||||
[_contentView addSubview:_saturationLabel];
|
||||
[_contentView addSubview:_brightnessLabel];
|
||||
[_contentView addSubview:_hueSlider];
|
||||
[_contentView addSubview:_saturationSlider];
|
||||
[_contentView addSubview:_brightnessSlider];
|
||||
|
||||
[_contentView addSubview:_hexLabel];
|
||||
[_contentView addSubview: _rgbLabel];
|
||||
[_contentView addSubview: _redLabel];
|
||||
[_contentView addSubview: _greenLabel];
|
||||
[_contentView addSubview: _blueLabel];
|
||||
[_contentView addSubview: _redSlider];
|
||||
[_contentView addSubview: _greenSlider];
|
||||
[_contentView addSubview: _blueSlider];
|
||||
|
||||
[_contentView addSubview: _hsbLabel];
|
||||
[_contentView addSubview: _hueLabel];
|
||||
[_contentView addSubview: _saturationLabel];
|
||||
[_contentView addSubview: _brightnessLabel];
|
||||
[_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;
|
||||
}
|
||||
|
||||
- (void)sliderChanged:(id)sender
|
||||
-(void)sliderChanged:(id)sender
|
||||
{
|
||||
var newColor,
|
||||
colorPanel = [self colorPanel],
|
||||
alpha = [colorPanel opacity];
|
||||
|
||||
switch (sender)
|
||||
switch(sender)
|
||||
{
|
||||
case _hueSlider:
|
||||
case _saturationSlider:
|
||||
case _brightnessSlider: newColor = [CPColor colorWithHue:[_hueSlider floatValue]
|
||||
saturation:[_saturationSlider floatValue]
|
||||
brightness:[_brightnessSlider floatValue]
|
||||
alpha:alpha];
|
||||
|
||||
[self updateRGBSliders:newColor];
|
||||
case _brightnessSlider: newColor = [CPColor colorWithHue: [_hueSlider floatValue]
|
||||
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];
|
||||
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];
|
||||
[self updateHex: newColor];
|
||||
[colorPanel setColor: newColor];
|
||||
}
|
||||
|
||||
- (void)setColor:(CPColor)aColor
|
||||
-(void)setColor:(CPColor)aColor
|
||||
{
|
||||
if (!aColor)
|
||||
[CPException raise:CPInvalidArgumentException reason:"aColor can't be nil"];
|
||||
|
||||
[self updateRGBSliders:aColor];
|
||||
[self updateHSBSliders:aColor];
|
||||
[self updateHex:aColor];
|
||||
[self updateRGBSliders: aColor];
|
||||
[self updateHSBSliders: aColor];
|
||||
[self updateHex: aColor];
|
||||
[self updateLabels];
|
||||
}
|
||||
|
||||
- (void)updateHSBSliders:(CPColor)aColor
|
||||
-(void)updateHSBSliders:(CPColor)aColor
|
||||
{
|
||||
var hsb = [aColor hsbComponents];
|
||||
|
||||
|
||||
[_hueSlider setFloatValue:hsb[0]];
|
||||
[_saturationSlider setFloatValue:hsb[1]];
|
||||
[_brightnessSlider setFloatValue:hsb[2]];
|
||||
@@ -301,7 +392,9 @@
|
||||
|
||||
- (void)updateHex:(CPColor)aColor
|
||||
{
|
||||
[_hexValue setStringValue:[aColor hexString]];
|
||||
#if PLATFORM(DOM)
|
||||
_hexValue.value = [aColor hexString];
|
||||
#endif
|
||||
}
|
||||
|
||||
- (void)updateRGBSliders:(CPColor)aColor
|
||||
@@ -315,13 +408,15 @@
|
||||
|
||||
- (void)updateLabels
|
||||
{
|
||||
[_hueValue setStringValue:ROUND([_hueSlider floatValue] * 360.0)];
|
||||
[_saturationValue setStringValue:ROUND([_saturationSlider floatValue] * 100.0)];
|
||||
[_brightnessValue setStringValue:ROUND([_brightnessSlider floatValue] * 100.0)];
|
||||
|
||||
[_redValue setStringValue:ROUND([_redSlider floatValue] * 255)];
|
||||
[_greenValue setStringValue:ROUND([_greenSlider floatValue] * 255)];
|
||||
[_blueValue setStringValue:ROUND([_blueSlider floatValue] * 255)];
|
||||
#if PLATFORM(DOM)
|
||||
_hueValue.value = ROUND([_hueSlider floatValue]);
|
||||
_saturationValue.value = ROUND([_saturationSlider floatValue]);
|
||||
_brightnessValue.value = ROUND([_brightnessSlider floatValue]);
|
||||
|
||||
_redValue.value = ROUND([_redSlider floatValue] * 255);
|
||||
_greenValue.value = ROUND([_greenSlider floatValue] * 255);
|
||||
_blueValue.value = ROUND([_blueSlider floatValue] * 255);
|
||||
#endif
|
||||
}
|
||||
|
||||
- (CPImage)provideNewButtonImage
|
||||
@@ -334,50 +429,4 @@
|
||||
return [[CPImage alloc] initWithContentsOfFile:[[CPBundle bundleForClass:CPColorPicker] pathForResource:"slider_button_h.png"] size:CGSizeMake(32, 32)];
|
||||
}
|
||||
|
||||
- (void)controlTextDidEndEditing:(CPNotification)aNotification
|
||||
{
|
||||
var field = [aNotification object],
|
||||
value = [[field stringValue] stringByTrimmingWhitespace];
|
||||
|
||||
if (field === _hexValue)
|
||||
{
|
||||
var newColor = [CPColor colorWithHexString:value];
|
||||
|
||||
if (newColor)
|
||||
{
|
||||
[self setColor:newColor];
|
||||
[[self colorPanel] setColor:newColor];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case _redValue: [_redSlider setFloatValue:MAX(MIN(ROUND(value), 255) / 255.0, 0)];
|
||||
[self sliderChanged:_redSlider];
|
||||
break;
|
||||
|
||||
case _greenValue: [_greenSlider setFloatValue:MAX(MIN(ROUND(value), 255) / 255.0, 0)];
|
||||
[self sliderChanged:_greenSlider];
|
||||
break;
|
||||
|
||||
case _blueValue: [_blueSlider setFloatValue:MAX(MIN(ROUND(value), 255) / 255.0, 0)];
|
||||
[self sliderChanged:_blueSlider];
|
||||
break;
|
||||
|
||||
case _hueValue: [_hueSlider setFloatValue:MAX(MIN(ROUND(value), 360) / 360.0, 0)];
|
||||
[self sliderChanged:_hueSlider];
|
||||
break;
|
||||
|
||||
case _saturationValue: [_saturationSlider setFloatValue:MAX(MIN(ROUND(value), 100) / 100.0, 0)];
|
||||
[self sliderChanged:_saturationSlider];
|
||||
break;
|
||||
|
||||
case _brightnessValue: [_brightnessSlider setFloatValue:MAX(MIN(ROUND(value), 100) / 100.0, 0)];
|
||||
[self sliderChanged:_brightnessSlider];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user