/**
NSView is an abstract class which provides facilities for drawing in a window and receiving events. It is the superclass of many of the visual elements of the GUI.
In order to display itself, a view must be placed in a window (represented by an NSWindow object). Within the window is a hierarchy of NSViews, headed by the window's content view. Every other view in a window is a descendant of this view.
Subclasses can override -drawRect: in order to implement their appearance. Other methods of NSView and NSResponder can also be overridden to handle user generated events.
Removes the receiver from its superviews list of subviews and marks the rectangle that the reciever occupied in the superview as needing redisplay.
This is dangerous to use during display, since it alters the rectangles needing display. In this case, you can use the -removeFromSuperviewWithoutNeedingDisplay method instead.
*/ - (void) removeFromSuperview { if (_super_view != nil) { [_super_view setNeedsDisplayInRect: _frame]; [self removeFromSuperviewWithoutNeedingDisplay]; } } /**Removes aSubview from the receivers list of subviews and from the responder chain.
Also invokes -viewWillMoveToWindow: on aView with a nil argument, to handle removal of aView (and recursively, its children) from its window - performing tidyup by invalidating cursor rects etc.
*/ - (void) removeSubview: (NSView*)aView { id view; /* * This must be first because it invokes -resignFirstResponder:, * which assumes the view is still in the view hierarchy */ for (view = [_window firstResponder]; view != nil && [view respondsToSelector: @selector(superview)]; view = [view superview]) { if (view == aView) { [_window makeFirstResponder: _window]; break; } } [self willRemoveSubview: aView]; aView->_super_view = nil; [aView _viewWillMoveToWindow: nil]; [aView _viewWillMoveToSuperview: nil]; [aView setNextResponder: nil]; RETAIN(aView); [_sub_views removeObjectIdenticalTo: aView]; [aView setNeedsDisplay: NO]; [aView _viewDidMoveToWindow]; [aView viewDidMoveToSuperview]; RELEASE(aView); if ([_sub_views count] == 0) { _rFlags.has_subviews = 0; } } /** * Removes oldView, which should be a subview of the receiver, from the * receiver and places newView in its place. If newView is nil, just * removes oldView. If oldView is nil, just adds newView. */ - (void) replaceSubview: (NSView*)oldView with: (NSView*)newView { if (newView == oldView) { return; } /* * NB. we implement the replacement in full rather than calling addSubview: * since classes like NSBox override these methods but expect to be able to * call [super replaceSubview:with:] safely. */ if (oldView == nil) { /* * Strictly speaking, the docs say that if 'oldView' is not a subview * of the receiver then we do nothing - but here we add newView anyway. * So a replacement with no oldView is an addition. */ RETAIN(newView); [newView removeFromSuperview]; [newView _viewWillMoveToWindow: _window]; [newView _viewWillMoveToSuperview: self]; [newView setNextResponder: self]; [_sub_views addObject: newView]; _rFlags.has_subviews = 1; [newView resetCursorRects]; [newView setNeedsDisplay: YES]; [newView _viewDidMoveToWindow]; [newView viewDidMoveToSuperview]; [self didAddSubview: newView]; RELEASE(newView); } else if ([_sub_views indexOfObjectIdenticalTo: oldView] != NSNotFound) { if (newView == nil) { /* * If there is no new view to add - we just remove the old one. * So a replacement with no newView is a removal. */ [oldView removeFromSuperview]; } else { NSUInteger index; /* * Ok - the standard case - we remove the newView from wherever it * was (which may have been in this view), locate the position of * the oldView (which may have changed due to the removal of the * newView), remove the oldView, and insert the newView in it's * place. */ RETAIN(newView); [newView removeFromSuperview]; index = [_sub_views indexOfObjectIdenticalTo: oldView]; [oldView removeFromSuperview]; [newView _viewWillMoveToWindow: _window]; [newView _viewWillMoveToSuperview: self]; [newView setNextResponder: self]; [_sub_views insertObject: newView atIndex: index]; _rFlags.has_subviews = 1; [newView resetCursorRects]; [newView setNeedsDisplay: YES]; [newView _viewDidMoveToWindow]; [newView viewDidMoveToSuperview]; [self didAddSubview: newView]; RELEASE(newView); } } } - (void) setSubviews: (NSArray *)newSubviews { NSEnumerator *en; NSView *aView; NSMutableArray *uniqNew = [NSMutableArray array]; if (nil == newSubviews) { [NSException raise: NSInvalidArgumentException format: @"Setting nil as new subviews."]; } // Use a copy as we remove from the subviews array en = [[NSArray arrayWithArray: _sub_views] objectEnumerator]; while ((aView = [en nextObject])) { if (NO == [newSubviews containsObject: aView]) { [aView removeFromSuperview]; } } en = [newSubviews objectEnumerator]; while ((aView = [en nextObject])) { id supersub = [aView superview]; if (supersub != nil && supersub != self) { [NSException raise: NSInvalidArgumentException format: @"Superviews of new subviews must be either nil or receiver."]; } if ([uniqNew containsObject: aView]) { [NSException raise: NSInvalidArgumentException format: @"Duplicated new subviews."]; } if (NO == [_sub_views containsObject: aView]) { [self addSubview: aView]; } [uniqNew addObject: aView]; } ASSIGN(_sub_views, uniqNew); // The order of the subviews may have changed [self setNeedsDisplay: YES]; } - (void) sortSubviewsUsingFunction: (NSComparisonResult (*)(id ,id ,void*))compare context: (void*)context { [_sub_views sortUsingFunction: compare context: context]; } /** * Notifies the receiver that its superview is being changed to newSuper. */ - (void) viewWillMoveToSuperview: (NSView*)newSuper { } /** * Notifies the receiver that it will now be a view of newWindow. * Note, this method is also used when removing a view from a window * (in which case, newWindow is nil) to let all the subviews know * that they have also been removed from the window. */ - (void) viewWillMoveToWindow: (NSWindow*)newWindow { } - (void) didAddSubview: (NSView *)subview {} - (void) viewDidMoveToSuperview {} - (void) viewDidMoveToWindow {} - (void) willRemoveSubview: (NSView *)subview {} static NSSize _computeScale(NSSize fs, NSSize bs) { NSSize scale; if (bs.width == 0) { if (fs.width == 0) scale.width = 1; else scale.width = FLT_MAX; } else { scale.width = fs.width / bs.width; } if (bs.height == 0) { if (fs.height == 0) scale.height = 1; else scale.height = FLT_MAX; } else { scale.height = fs.height / bs.height; } return scale; } - (void) _setFrameAndClearAutoresizingError: (NSRect)frameRect { _frame = frameRect; _autoresizingFrameError = NSZeroRect; } - (void) setFrame: (NSRect)frameRect { BOOL changedOrigin = NO; BOOL changedSize = NO; NSSize old_size = _frame.size; if (frameRect.size.width < 0) { NSWarnMLog(@"given negative width"); frameRect.size.width = 0; } if (frameRect.size.height < 0) { NSWarnMLog(@"given negative height"); frameRect.size.height = 0; } if (NSEqualPoints(_frame.origin, frameRect.origin) == NO) { changedOrigin = YES; } if (NSEqualSizes(_frame.size, frameRect.size) == NO) { changedSize = YES; } if (changedSize == YES || changedOrigin == YES) { [self _setFrameAndClearAutoresizingError: frameRect]; if (changedSize == YES) { if (_is_rotated_or_scaled_from_base == YES) { NSAffineTransform *matrix; NSRect frame = _frame; frame.origin = NSMakePoint(0, 0); matrix = [_boundsMatrix copy]; [matrix invert]; [matrix boundingRectFor: frame result: &_bounds]; RELEASE(matrix); } else { _bounds.size = frameRect.size; } } if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; [self resizeSubviewsWithOldSize: old_size]; if (_post_frame_changes) { [nc postNotificationName: NSViewFrameDidChangeNotification object: self]; } } } - (void) setFrameOrigin: (NSPoint)newOrigin { if (NSEqualPoints(_frame.origin, newOrigin) == NO) { NSRect newFrame = _frame; newFrame.origin = newOrigin; if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self _setFrameAndClearAutoresizingError: newFrame]; [self resetCursorRects]; if (_post_frame_changes) { [nc postNotificationName: NSViewFrameDidChangeNotification object: self]; } } } - (void) setFrameSize: (NSSize)newSize { NSRect newFrame = _frame; if (newSize.width < 0) { NSWarnMLog(@"given negative width"); newSize.width = 0; } if (newSize.height < 0) { NSWarnMLog(@"given negative height"); newSize.height = 0; } if (NSEqualSizes(_frame.size, newSize) == NO) { NSSize old_size = _frame.size; if (_is_rotated_or_scaled_from_base) { if (_boundsMatrix == nil) { CGFloat sx = _bounds.size.width / _frame.size.width; CGFloat sy = _bounds.size.height / _frame.size.height; newFrame.size = newSize; [self _setFrameAndClearAutoresizingError: newFrame]; _bounds.size.width = _frame.size.width * sx; _bounds.size.height = _frame.size.height * sy; } else { NSAffineTransform *matrix; NSRect frame; newFrame.size = newSize; [self _setFrameAndClearAutoresizingError: newFrame]; frame = _frame; frame.origin = NSMakePoint(0, 0); matrix = [_boundsMatrix copy]; [matrix invert]; [matrix boundingRectFor: frame result: &_bounds]; RELEASE(matrix); } } else { newFrame.size = _bounds.size = newSize; [self _setFrameAndClearAutoresizingError: newFrame]; } if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; [self resizeSubviewsWithOldSize: old_size]; if (_post_frame_changes) { [nc postNotificationName: NSViewFrameDidChangeNotification object: self]; } } } - (void) setFrameRotation: (CGFloat)angle { CGFloat oldAngle = [self frameRotation]; if (oldAngle != angle) { /* no frame matrix, create one since it is needed for rotation */ if (_frameMatrix == nil) { // Map from superview to frame _frameMatrix = [NSAffineTransform new]; } [_frameMatrix rotateByDegrees: angle - oldAngle]; _is_rotated_from_base = _is_rotated_or_scaled_from_base = YES; if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; if (_post_frame_changes) { [nc postNotificationName: NSViewFrameDidChangeNotification object: self]; } } } - (BOOL) isRotatedFromBase { if (_is_rotated_from_base) { return YES; } else if (_super_view) { return [_super_view isRotatedFromBase]; } else { return NO; } } - (BOOL) isRotatedOrScaledFromBase { if (_is_rotated_or_scaled_from_base) { return YES; } else if (_super_view) { return [_super_view isRotatedOrScaledFromBase]; } else { return NO; } } - (void) setBounds: (NSRect)aRect { NSDebugLLog(@"NSView", @"setBounds %@", NSStringFromRect(aRect)); if (aRect.size.width < 0) { NSWarnMLog(@"given negative width"); aRect.size.width = 0; } if (aRect.size.height < 0) { NSWarnMLog(@"given negative height"); aRect.size.height = 0; } if (_is_rotated_from_base || (NSEqualRects(_bounds, aRect) == NO)) { NSAffineTransform *matrix; NSPoint oldOrigin; NSSize scale; if (_boundsMatrix == nil) { _boundsMatrix = [NSAffineTransform new]; } // Adjust scale scale = _computeScale(_frame.size, aRect.size); if (scale.width != 1 || scale.height != 1) { _is_rotated_or_scaled_from_base = YES; } [_boundsMatrix scaleTo: scale.width : scale.height]; { matrix = [_boundsMatrix copy]; [matrix invert]; oldOrigin = [matrix transformPoint: NSMakePoint(0, 0)]; RELEASE(matrix); } [_boundsMatrix translateXBy: oldOrigin.x - aRect.origin.x yBy: oldOrigin.y - aRect.origin.y]; if (!_is_rotated_from_base) { // Adjust bounds _bounds = aRect; } else { // Adjust bounds NSRect frame = _frame; frame.origin = NSMakePoint(0, 0); matrix = [_boundsMatrix copy]; [matrix invert]; [matrix boundingRectFor: frame result: &_bounds]; RELEASE(matrix); } if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; if (_post_bounds_changes) { [nc postNotificationName: NSViewBoundsDidChangeNotification object: self]; } } } - (void) setBoundsOrigin: (NSPoint)newOrigin { NSPoint oldOrigin; if (_boundsMatrix == nil) { oldOrigin = NSMakePoint(NSMinX(_bounds), NSMinY(_bounds)); } else { NSAffineTransform *matrix = [_boundsMatrix copy]; [matrix invert]; oldOrigin = [matrix transformPoint: NSMakePoint(0, 0)]; RELEASE(matrix); } [self translateOriginToPoint: NSMakePoint(oldOrigin.x - newOrigin.x, oldOrigin.y - newOrigin.y)]; } - (void) setBoundsSize: (NSSize)newSize { NSSize scale; NSDebugLLog(@"NSView", @"%@ setBoundsSize: %@", self, NSStringFromSize(newSize)); if (newSize.width < 0) { NSWarnMLog(@"given negative width"); newSize.width = 0; } if (newSize.height < 0) { NSWarnMLog(@"given negative height"); newSize.height = 0; } scale = _computeScale(_frame.size, newSize); if (scale.width != 1 || scale.height != 1) { _is_rotated_or_scaled_from_base = YES; } if (_boundsMatrix == nil) { _boundsMatrix = [NSAffineTransform new]; } [_boundsMatrix scaleTo: scale.width : scale.height]; if (!_is_rotated_from_base) { scale = _computeScale(_bounds.size, newSize); _bounds.origin.x = _bounds.origin.x / scale.width; _bounds.origin.y = _bounds.origin.y / scale.height; _bounds.size = newSize; } else { NSAffineTransform *matrix; NSRect frame = _frame; frame.origin = NSMakePoint(0, 0); matrix = [_boundsMatrix copy]; [matrix invert]; [matrix boundingRectFor: frame result: &_bounds]; RELEASE(matrix); } if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; if (_post_bounds_changes) { [nc postNotificationName: NSViewBoundsDidChangeNotification object: self]; } } - (void) setBoundsRotation: (CGFloat)angle { [self rotateByAngle: angle - [self boundsRotation]]; } - (void) translateOriginToPoint: (NSPoint)point { NSDebugLLog(@"NSView", @"%@ translateOriginToPoint: %@", self, NSStringFromPoint(point)); if (NSEqualPoints(NSZeroPoint, point) == NO) { if (_boundsMatrix == nil) { _boundsMatrix = [NSAffineTransform new]; } [_boundsMatrix translateXBy: point.x yBy: point.y]; // Adjust bounds _bounds.origin.x -= point.x; _bounds.origin.y -= point.y; if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; if (_post_bounds_changes) { [nc postNotificationName: NSViewBoundsDidChangeNotification object: self]; } } } - (void) scaleUnitSquareToSize: (NSSize)newSize { if (newSize.width != 1.0 || newSize.height != 1.0) { if (newSize.width < 0) { NSWarnMLog(@"given negative width"); newSize.width = 0; } if (newSize.height < 0) { NSWarnMLog(@"given negative height"); newSize.height = 0; } if (_boundsMatrix == nil) { _boundsMatrix = [NSAffineTransform new]; } [_boundsMatrix scaleXBy: newSize.width yBy: newSize.height]; // Adjust bounds _bounds.origin.x = _bounds.origin.x / newSize.width; _bounds.origin.y = _bounds.origin.y / newSize.height; _bounds.size.width = _bounds.size.width / newSize.width; _bounds.size.height = _bounds.size.height / newSize.height; _is_rotated_or_scaled_from_base = YES; if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; if (_post_bounds_changes) { [nc postNotificationName: NSViewBoundsDidChangeNotification object: self]; } } } - (void) rotateByAngle: (CGFloat)angle { if (angle != 0.0) { NSAffineTransform *matrix; NSRect frame = _frame; frame.origin = NSMakePoint(0, 0); if (_boundsMatrix == nil) { _boundsMatrix = [NSAffineTransform new]; } [_boundsMatrix rotateByDegrees: angle]; // Adjust bounds matrix = [_boundsMatrix copy]; [matrix invert]; [matrix boundingRectFor: frame result: &_bounds]; RELEASE(matrix); _is_rotated_from_base = _is_rotated_or_scaled_from_base = YES; if (_coordinates_valid) { (*invalidateImp)(self, invalidateSel); } [self resetCursorRects]; if (_post_bounds_changes) { [nc postNotificationName: NSViewBoundsDidChangeNotification object: self]; } } } - (CGFloat) alphaValue { return _alphaValue; } - (void)setAlphaValue: (CGFloat)alpha { _alphaValue = alpha; } - (CGFloat) frameCenterRotation { // FIXME this is dummy, we don't have layers yet return 0.0; } - (void) setFrameCenterRotation:(CGFloat)rot { // FIXME this is dummy, we don't have layers yet // we probably need a Matrix akin frame rotation. } - (NSRect) centerScanRect: (NSRect)aRect { NSAffineTransform *matrix; CGFloat x_org; CGFloat y_org; /* * Hmm - we assume that the windows coordinate system is centered on the * pixels of the screen - this may not be correct of course. * Plus - this is all pretty meaningless is we are not in a window! */ matrix = [self _matrixToWindow]; aRect.origin = [matrix transformPoint: aRect.origin]; aRect.size = [matrix transformSize: aRect.size]; if (aRect.size.height < 0.0) { aRect.size.height = -aRect.size.height; } x_org = aRect.origin.x; y_org = aRect.origin.y; aRect.origin.x = GSRoundTowardsInfinity(aRect.origin.x); aRect.origin.y = [self isFlipped] ? GSRoundTowardsNegativeInfinity(aRect.origin.y) : GSRoundTowardsInfinity(aRect.origin.y); aRect.size.width = GSRoundTowardsInfinity(aRect.size.width + (x_org - aRect.origin.x) / 2.0); aRect.size.height = GSRoundTowardsInfinity(aRect.size.height + (y_org - aRect.origin.y) / 2.0); matrix = [self _matrixFromWindow]; aRect.origin = [matrix transformPoint: aRect.origin]; aRect.size = [matrix transformSize: aRect.size]; if (aRect.size.height < 0.0) { aRect.size.height = -aRect.size.height; } return aRect; } - (NSPoint) convertPoint: (NSPoint)aPoint fromView: (NSView*)aView { NSPoint inBase; if (aView == self) { return aPoint; } if (aView != nil) { NSAssert(_window == [aView window], NSInvalidArgumentException); inBase = [[aView _matrixToWindow] transformPoint: aPoint]; } else { inBase = aPoint; } return [[self _matrixFromWindow] transformPoint: inBase]; } - (NSPoint) convertPoint: (NSPoint)aPoint toView: (NSView*)aView { NSPoint inBase; if (aView == self) return aPoint; inBase = [[self _matrixToWindow] transformPoint: aPoint]; if (aView != nil) { NSAssert(_window == [aView window], NSInvalidArgumentException); return [[aView _matrixFromWindow] transformPoint: inBase]; } else { return inBase; } } /* Helper for -convertRect:fromView: and -convertRect:toView:. */ static NSRect convert_rect_using_matrices(NSRect aRect, NSAffineTransform *matrix1, NSAffineTransform *matrix2) { NSRect r; NSPoint p[4], min, max; int i; for (i = 0; i < 4; i++) p[i] = aRect.origin; p[1].x += aRect.size.width; p[2].y += aRect.size.height; p[3].x += aRect.size.width; p[3].y += aRect.size.height; for (i = 0; i < 4; i++) p[i] = [matrix1 transformPoint: p[i]]; min = max = p[0] = [matrix2 transformPoint: p[0]]; for (i = 1; i < 4; i++) { p[i] = [matrix2 transformPoint: p[i]]; min.x = MIN(min.x, p[i].x); min.y = MIN(min.y, p[i].y); max.x = MAX(max.x, p[i].x); max.y = MAX(max.y, p[i].y); } r.origin = min; r.size.width = max.x - min.x; r.size.height = max.y - min.y; return r; } /** * Converts aRect from the coordinate system of aView to the coordinate * system of the receiver, ie. returns the bounding rectangle in the * receiver of aRect in aView. *Tell the view to maintain a private gstate object which encapsulates all the information about drawing, such as coordinate transforms, line widths, etc. If you do not invoke this method, a gstate object is constructed each time the view is lockFocused. Allocating a private gstate may improve the performance of views that are focused a lot and have a lot of customized drawing parameters.
View subclasses should override the setUpGstate method to set these custom parameters.
*/ - (void) allocateGState { _allocate_gstate = YES; _renew_gstate = YES; } /** Frees the gstate object, if there is one. */ - (void) releaseGState { if (_allocate_gstate && _gstate && _window && ([_window graphicsContext] != nil)) { GSUndefineGState([_window graphicsContext], _gstate); } _gstate = 0; _allocate_gstate = NO; } /** Returns an identifier that represents the view's gstate object, which is used to encapsulate drawing information about the view. Most of the time a gstate object is created from scratch when the view is focused, so if the view is not currently focused or allocateGState has not been called, then this method will return 0. FIXME: The above is what the OpenStep and Cocoa specification say, but gState is 0 unless allocateGState has been called. */ - (NSInteger) gState { if (_allocate_gstate && (!_gstate || _renew_gstate)) { // Set the gstate by locking and unlocking focus. [self lockFocus]; [self unlockFocusNeedsFlush: NO]; } return _gstate; } /** Invalidates the view's gstate object so it will be set up again using setUpGState the next time the view is focused. */ - (void) renewGState { _renew_gstate = YES; /* Note that the next time we lock focus, we'll realloc a gstate (if _allocate_gstate). This seems to make sense, and also allows us to call this method each time we invalidate the coordinates */ } /* Overridden by subclasses to setup custom gstate */ - (void) setUpGState { } - (void) lockFocusInRect: (NSRect)rect { [self _lockFocusInContext: nil inRect: rect]; } - (void) lockFocus { [self lockFocusInRect: [self visibleRect]]; } - (void) unlockFocus { [self unlockFocusNeedsFlush: YES]; } - (BOOL) lockFocusIfCanDraw { return [self lockFocusIfCanDrawInContext: nil]; } - (BOOL) lockFocusIfCanDrawInContext: (NSGraphicsContext *)context { if ([self canDraw]) { [self _lockFocusInContext: context inRect: [self visibleRect]]; return YES; } else { return NO; } } - (BOOL) canDraw { if (((viewIsPrinting != nil) && [self isDescendantOf: viewIsPrinting]) || ((_window != nil) && ([_window windowNumber] != 0) && ![self isHiddenOrHasHiddenAncestor])) { return YES; } else { return NO; } } /* * The following display* methods work based on these invariants: * - When a view is marked as needing display, all views above it * in the hierarchy are marked as well. * - When a view has an invalid rectangle, all views above it up * to the next opaque view also include this invalid rectangle. * * After drawing an area in a view give, subviews a chance to draw * there too. * When drawing a non-opaque subview we need to make sure any area * we draw in has been drawn by the opaque superview as well. * * When drawing the invalid area of a view, we need to make sure * that invalid areas in opaque subviews get drawn as well. These * areas will not be included in the invalid area of the view. * * IfNeeded means we only draw if the view is marked as needing display * and will only draw in the _invalidRect of this view and that of all * the opaque subviews. For non-opaque subviews we need to draw where * ever a superview has already drawn. * * InRect means we will only draw in this rectangle. If non is given the * visibleRect gets used. * * IgnoringOpacity means we start drawing at the current view. Otherwise * we go up to the next opaque view. * */ - (void) display { [self displayRect: [self visibleRect]]; } - (void) displayIfNeeded { if (_rFlags.needs_display == YES) { [self displayIfNeededInRect: [self visibleRect]]; } } - (void) displayIfNeededIgnoringOpacity { if (_rFlags.needs_display == YES) { [self displayIfNeededInRectIgnoringOpacity: [self visibleRect]]; } } - (void) displayIfNeededInRect: (NSRect)aRect { if (_rFlags.needs_display == YES) { if ([self isOpaque] == YES) { [self displayIfNeededInRectIgnoringOpacity: aRect]; } else { NSView *firstOpaque = [self opaqueAncestor]; aRect = [firstOpaque convertRect: aRect fromView: self]; [firstOpaque displayIfNeededInRectIgnoringOpacity: aRect]; } } } - (void) displayIfNeededInRectIgnoringOpacity: (NSRect)aRect { if (_rFlags.needs_display == YES) { NSRect rect; /* * Restrict the drawing of self onto the invalid rectangle. */ rect = NSIntersectionRect(aRect, _invalidRect); [self displayRectIgnoringOpacity: rect]; /* * If we still need display after displaying the invalid rectangle, * this means that some subviews still need to display. * For opaque subviews their invalid rectangle may even overlap the * original aRect. * Display any subview that need display. */ if (_rFlags.needs_display == YES) { NSEnumerator *enumerator = [_sub_views objectEnumerator]; NSView *subview; BOOL subviewNeedsDisplay = NO; while ((subview = [enumerator nextObject]) != nil) { if (subview->_rFlags.needs_display) { NSRect subviewFrame = [subview _frameExtend]; NSRect isect; isect = NSIntersectionRect(aRect, subviewFrame); if (NSIsEmptyRect(isect) == NO) { isect = [subview convertRect: isect fromView: self]; [subview displayIfNeededInRectIgnoringOpacity: isect]; } if (subview->_rFlags.needs_display) { subviewNeedsDisplay = YES; } } } /* * Make sure our needs_display flag matches that of the subviews. * Only set to NO when there is no _invalidRect. */ if (NSIsEmptyRect(_invalidRect)) { _rFlags.needs_display = subviewNeedsDisplay; } } } } /** * Causes the area of the view specified by aRect to be displayed. * This is done by moving up the view hierarchy until an opaque view * is found, then asking that view to update the appropriate area. */ - (void) displayRect: (NSRect)aRect { if ([self isOpaque] == YES) { [self displayRectIgnoringOpacity: aRect]; } else { NSView *firstOpaque = [self opaqueAncestor]; aRect = [firstOpaque convertRect: aRect fromView: self]; [firstOpaque displayRectIgnoringOpacity: aRect]; } } - (void) displayRectIgnoringOpacity: (NSRect)aRect { [self displayRectIgnoringOpacity: aRect inContext: nil]; } - (void) displayRectIgnoringOpacity: (NSRect)aRect inContext: (NSGraphicsContext *)context { NSGraphicsContext *wContext; BOOL flush = NO; BOOL subviewNeedsDisplay = NO; if (![self canDraw]) { return; } wContext = [_window graphicsContext]; if (context == nil) { context = wContext; } if (context == wContext) { NSRect neededRect; NSRect visibleRect = [self visibleRect]; flush = YES; [_window disableFlushWindow]; aRect = NSIntersectionRect(aRect, visibleRect); neededRect = NSIntersectionRect(_invalidRect, visibleRect); /* * If the rect we are going to display contains the _invalidRect * then we can empty _invalidRect. Do this before the drawing, * as drawRect: may change this value. * FIXME: If the drawn rectangle cuts of a complete part of the * _invalidRect, we should try to reduce this. */ if (NSEqualRects(aRect, NSUnionRect(neededRect, aRect)) == YES) { _invalidRect = NSZeroRect; _rFlags.needs_display = NO; } } if (NSIsEmptyRect(aRect) == NO) { /* * Now we draw this view. */ [self _lockFocusInContext: context inRect: aRect]; [self drawRect: aRect]; [self unlockFocusNeedsFlush: flush]; } /* * Even when aRect is empty we need to loop over the subviews to see, * if there is anything left to draw. */ if (_rFlags.has_subviews == YES) { NSUInteger count = [_sub_views count]; if (count > 0) { NSView *array[count]; NSUInteger i; [_sub_views getObjects: array]; for (i = 0; i < count; ++i) { NSView *subview = array[i]; NSRect subviewFrame = [subview _frameExtend]; NSRect isect; /* * Having drawn ourself into the rect, we must make sure that * subviews overlapping the area are redrawn. */ isect = NSIntersectionRect(aRect, subviewFrame); if (NSIsEmptyRect(isect) == NO) { isect = [subview convertRect: isect fromView: self]; [subview displayRectIgnoringOpacity: isect inContext: context]; } /* * Is there still something to draw in the subview? * This keeps the invariant that views further up are marked * for redraw when ever a view further down needs to redraw. */ if (subview->_rFlags.needs_display == YES) { subviewNeedsDisplay = YES; } } } } if (context == wContext) { if (subviewNeedsDisplay) { /* * If not all subviews have been fully displayed, we cannot turn off * the 'needs_display' flag. This is to keep the invariant that when * a view is marked as needing to display, all its ancestors will be * marked too. */ _rFlags.needs_display = YES; } [_window enableFlushWindow]; [_window flushWindowIfNeeded]; } } /** This method is invoked to handle drawing inside the view. The default NSView's implementation does nothing; subclasses might override it to draw something inside the view. Since NSView's implementation is guaranteed to be empty, you should not call super's implementation when you override it in subclasses. drawRect: is invoked when the focus has already been locked on the view; you can use arbitrary postscript functions in drawRect: to draw inside your view; the coordinate system in which you draw is the view's own coordinate system (this means for example that you should refer to the rectangle covered by the view using its bounds, and not its frame). The argument of drawRect: is the rectangle which needs to be redrawn. In a lossy implementation, you can ignore the argument and redraw the whole view; if you are aiming at performance, you may want to redraw only what is inside the rectangle which needs to be redrawn; this usually improves drawing performance considerably. */ - (void) drawRect: (NSRect)rect {} - (NSRect) visibleRect { if ([self isHiddenOrHasHiddenAncestor]) { return NSZeroRect; } if (_coordinates_valid == NO) { [self _rebuildCoordinates]; } return _visibleRect; } - (BOOL) wantsDefaultClipping { return YES; } - (BOOL) needsToDrawRect: (NSRect)aRect { const NSRect *rects; NSInteger i, count; [self getRectsBeingDrawn: &rects count: &count]; for (i = 0; i < count; i++) { if (NSIntersectsRect(aRect, rects[i])) return YES; } return NO; } - (void) getRectsBeingDrawn: (const NSRect **)rects count: (NSInteger *)count { // FIXME static NSRect rect; rect = [[_window->_rectsBeingDrawn lastObject] rectValue]; rect = [self convertRect: rect fromView: nil]; if (rects != NULL) { *rects = ▭ } if (count != NULL) { *count = 1; } } - (NSBitmapImageRep *) bitmapImageRepForCachingDisplayInRect: (NSRect)rect { NSBitmapImageRep *bitmap; [self lockFocus]; bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect: rect]; [self unlockFocus]; return AUTORELEASE(bitmap); } - (void) cacheDisplayInRect: (NSRect)rect toBitmapImageRep: (NSBitmapImageRep *)bitmap { NSDictionary *dict; NSData *imageData; [self lockFocus]; dict = [GSCurrentContext() GSReadRect: rect]; [self unlockFocus]; imageData = [dict objectForKey: @"Data"]; if (imageData != nil) { // Copy the image data to the bitmap memcpy([bitmap bitmapData], [imageData bytes], [imageData length]); } } extern NSThread *GSAppKitThread; /* TODO */ /* For -setNeedsDisplay*, the real work is done in the ..._real methods, and the actual public method simply calls it, but makes sure that the call is in the main thread. */ - (void) _setNeedsDisplay_real: (NSNumber *)n { BOOL flag = [n boolValue]; if (flag) { [self setNeedsDisplayInRect: _bounds]; } else { _rFlags.needs_display = NO; _invalidRect = NSZeroRect; } } /** * As an exception to the general rules for threads and gui, this * method is thread-safe and may be called from any thread. Display * will always be done in the main thread. (Note that other methods are * in general not thread-safe; if you want to access other properties of * views from multiple threads, you need to provide the synchronization.) */ - (void) setNeedsDisplay: (BOOL)flag { NSNumber *n = [[NSNumber alloc] initWithBool: flag]; if (GSCurrentThread() != GSAppKitThread) { NSDebugMLLog (@"MacOSXCompatibility", @"setNeedsDisplay: called on secondary thread"); [self performSelectorOnMainThread: @selector(_setNeedsDisplay_real:) withObject: n waitUntilDone: NO]; } else { [self _setNeedsDisplay_real: n]; } DESTROY(n); } - (void) _setNeedsDisplayInRect_real: (NSValue *)v { NSRect invalidRect = [v rectValue]; NSView *currentView = _super_view; /* * Limit to bounds, combine with old _invalidRect, and then check to see * if the result is the same as the old _invalidRect - if it isn't then * set the new _invalidRect. */ invalidRect = NSIntersectionRect(invalidRect, _bounds); invalidRect = NSUnionRect(_invalidRect, invalidRect); if (NSEqualRects(invalidRect, _invalidRect) == NO) { NSView *firstOpaque = [self opaqueAncestor]; _rFlags.needs_display = YES; _invalidRect = invalidRect; if (firstOpaque == self) { /** * Enlarge (if necessary) _invalidRect so it lies on integral device pixels */ const NSRect inBase = [self convertRectToBase: _invalidRect]; const NSRect inBaseRounded = NSIntegralRect(inBase); _invalidRect = [self convertRectFromBase: inBaseRounded]; [_window setViewsNeedDisplay: YES]; } else { invalidRect = [firstOpaque convertRect: _invalidRect fromView: self]; [firstOpaque setNeedsDisplayInRect: invalidRect]; } } /* * Must make sure that superviews know that we need display. * NB. we may have been marked as needing display and then moved to another * parent, so we can't assume that our parent is marked simply because we are. */ while (currentView) { currentView->_rFlags.needs_display = YES; currentView = currentView->_super_view; } // Also mark the window, as this may not happen above [_window setViewsNeedDisplay: YES]; } /** * Inform the view system that the specified rectangle is invalid and * requires updating. This automatically informs any superviews of * any updating they need to do. * * As an exception to the general rules for threads and gui, this * method is thread-safe and may be called from any thread. Display * will always be done in the main thread. (Note that other methods are * in general not thread-safe; if you want to access other properties of * views from multiple threads, you need to provide the synchronization.) */ - (void) setNeedsDisplayInRect: (NSRect)invalidRect { NSValue *v; if (NSIsEmptyRect(invalidRect)) return; // avoid unnecessary work when rectangle is empty v = [[NSValue alloc] initWithBytes: &invalidRect objCType: @encode(NSRect)]; if (GSCurrentThread() != GSAppKitThread) { NSDebugMLLog (@"MacOSXCompatibility", @"setNeedsDisplayInRect: called on secondary thread"); [self performSelectorOnMainThread: @selector(_setNeedsDisplayInRect_real:) withObject: v waitUntilDone: NO]; } else { [self _setNeedsDisplayInRect_real: v]; } DESTROY(v); } + (NSFocusRingType) defaultFocusRingType { return NSFocusRingTypeDefault; } - (void) setKeyboardFocusRingNeedsDisplayInRect: (NSRect)rect { // FIXME For external type special handling is needed [self setNeedsDisplayInRect: rect]; } - (void) setFocusRingType: (NSFocusRingType)focusRingType { _focusRingType = focusRingType; } - (NSFocusRingType) focusRingType { return _focusRingType; } /* * Hidding Views */ - (void) setHidden: (BOOL)flag { id view; if (_is_hidden == flag) return; _is_hidden = flag; if (_is_hidden) { for (view = [_window firstResponder]; view != nil && [view respondsToSelector: @selector(superview)]; view = [view superview]) { if (view == self) { [_window makeFirstResponder: [self nextValidKeyView]]; break; } } if (_rFlags.has_draginfo) { if (_window != nil) { NSArray *t = GSGetDragTypes(self); [GSDisplayServer removeDragTypes: t fromWindow: _window]; } } [[self superview] setNeedsDisplay: YES]; } else { if (_rFlags.has_draginfo) { if (_window != nil) { NSArray *t = GSGetDragTypes(self); [GSDisplayServer addDragTypes: t toWindow: _window]; } } if (_rFlags.has_subviews) { // The _visibleRect of subviews will be NSZeroRect, because when they // were calculated in -[_rebuildCoordinates], they were intersected // with the result of calling -[visibleRect] on the hidden superview, // which returns NSZeroRect for hidden views. // // So, recalculate the subview coordinates now to make them correct. [_sub_views makeObjectsPerformSelector: @selector(_invalidateCoordinates)]; } [self setNeedsDisplay: YES]; } } - (BOOL) isHidden { return _is_hidden; } - (BOOL) isHiddenOrHasHiddenAncestor { return ([self isHidden] || [_super_view isHiddenOrHasHiddenAncestor]); } /* * Live resize support */ - (BOOL) inLiveResize { return _in_live_resize; } - (void) viewWillStartLiveResize { // FIXME _in_live_resize = YES; } - (void) viewDidEndLiveResize { // FIXME _in_live_resize = NO; } - (BOOL) preservesContentDuringLiveResize { return NO; } - (void) getRectsExposedDuringLiveResize: (NSRect[4])exposedRects count: (NSInteger *)count { // FIXME if (count != NULL) { *count = 1; } exposedRects[0] = _bounds; } - (NSRect) rectPreservedDuringLiveResize { return NSZeroRect; } /* * Scrolling */ - (NSRect) adjustScroll: (NSRect)newVisible { return newVisible; } /** * Finds the nearest enclosing NSClipView and, if the location of the event * is outside it, scrolls the NSClipView in the direction of the event. The * amount scrolled is proportional to how far outside the NSClipView the * event's location is. * * This method is suitable for calling periodically from a modal event * tracking loop when the mouse is dragged outside the tracking view. The * suggested period of the calls is 0.1 seconds. */ - (BOOL) autoscroll: (NSEvent*)theEvent { if (_super_view) return [_super_view autoscroll: theEvent]; return NO; } - (void) reflectScrolledClipView: (NSClipView*)aClipView { } - (void) scrollClipView: (NSClipView*)aClipView toPoint: (NSPoint)aPoint { [aClipView scrollToPoint: aPoint]; } - (NSClipView*) _enclosingClipView { static Class clipViewClass; id aView = [self superview]; if (!clipViewClass) { clipViewClass = [NSClipView class]; } while (aView != nil) { if ([aView isKindOfClass: clipViewClass]) { break; } aView = [aView superview]; } return aView; } - (void) scrollPoint: (NSPoint)aPoint { NSClipView *s = [self _enclosingClipView]; if (s == nil) return; aPoint = [self convertPoint: aPoint toView: s]; if (NSEqualPoints(aPoint, [s bounds].origin) == NO) { [s scrollToPoint: aPoint]; } } /** Copy on scroll method, should be called from [NSClipView setBoundsOrigin]. */ - (void) scrollRect: (NSRect)aRect by: (NSSize)delta { NSPoint destPoint; aRect = NSIntersectionRect(aRect, _bounds); // Don't copy stuff outside. destPoint = aRect.origin; destPoint.x += delta.width; destPoint.y += delta.height; if ([self isFlipped]) { destPoint.y += aRect.size.height; } //NSLog(@"destPoint %@ in %@", NSStringFromPoint(destPoint), NSStringFromRect(_bounds)); [self lockFocus]; //NSCopyBits(0, aRect, destPoint); NSCopyBits([[self window] gState], [self convertRect: aRect toView: nil], destPoint); [self unlockFocus]; } /** Scrolls the nearest enclosing clip view the minimum required distance necessary to make aRect (or as much of it possible) in the receiver visible. Returns YES iff any scrolling was done. */ - (BOOL) scrollRectToVisible: (NSRect)aRect { NSClipView *s = [self _enclosingClipView]; if (s != nil) { NSRect vRect = [s documentVisibleRect]; NSPoint aPoint = vRect.origin; // Ok we assume that the rectangle is origined at the bottom left // and goes to the top and right as it grows in size for the naming // of these variables CGFloat ldiff, rdiff, tdiff, bdiff; if (vRect.size.width == 0 && vRect.size.height == 0) return NO; aRect = [self convertRect: aRect toView: [s documentView]]; // Find the differences on each side. ldiff = NSMinX(vRect) - NSMinX(aRect); rdiff = NSMaxX(aRect) - NSMaxX(vRect); bdiff = NSMinY(vRect) - NSMinY(aRect); tdiff = NSMaxY(aRect) - NSMaxY(vRect); // If the diff's have the same sign then nothing needs to be scrolled if ((ldiff * rdiff) >= 0.0) ldiff = rdiff = 0.0; if ((bdiff * tdiff) >= 0.0) bdiff = tdiff = 0.0; // Move the smallest difference aPoint.x += (fabs(ldiff) < fabs(rdiff)) ? (-ldiff) : rdiff; aPoint.y += (fabs(bdiff) < fabs(tdiff)) ? (-bdiff) : tdiff; if (aPoint.x != vRect.origin.x || aPoint.y != vRect.origin.y) { aPoint = [[s documentView] convertPoint: aPoint toView: s]; [s scrollToPoint: aPoint]; return YES; } } return NO; } - (NSScrollView*) enclosingScrollView { static Class scrollViewClass; id aView = [self superview]; if (!scrollViewClass) { scrollViewClass = [NSScrollView class]; } while (aView != nil) { if ([aView isKindOfClass: scrollViewClass]) { break; } aView = [aView superview]; } return aView; } /* * Managing the Cursor * * We use the tracking rectangle class to maintain the cursor rects */ - (void) addCursorRect: (NSRect)aRect cursor: (NSCursor*)anObject { if (_window != nil) { GSTrackingRect *m; aRect = [self convertRect: aRect toView: nil]; m = [rectClass allocWithZone: NSDefaultMallocZone()]; m = [m initWithRect: aRect tag: 0 owner: RETAIN(anObject) userData: NULL inside: YES]; [_cursor_rects addObject: m]; RELEASE(m); _rFlags.has_currects = 1; _rFlags.valid_rects = 1; } } - (void) discardCursorRects { if (_rFlags.has_currects != 0) { NSUInteger count = [_cursor_rects count]; if (count > 0) { GSTrackingRect *rects[count]; [_cursor_rects getObjects: rects]; if (_rFlags.valid_rects != 0) { NSPoint loc = _window->_lastPoint; NSUInteger i; for (i = 0; i < count; ++i) { GSTrackingRect *r = rects[i]; if (NSMouseInRect(loc, r->rectangle, NO)) { [r->owner mouseExited: nil]; } [r invalidate]; } _rFlags.valid_rects = 0; } while (count-- > 0) { RELEASE([rects[count] owner]); } [_cursor_rects removeAllObjects]; } _rFlags.has_currects = 0; } } - (void) removeCursorRect: (NSRect)aRect cursor: (NSCursor*)anObject { id e = [_cursor_rects objectEnumerator]; GSTrackingRect *o; NSCursor *c; NSPoint loc = [_window mouseLocationOutsideOfEventStream]; /* Base remove test upon cursor object */ o = [e nextObject]; while (o) { c = [o owner]; if (c == anObject) { if (NSMouseInRect(loc, o->rectangle, NO)) { [c mouseExited: nil]; } [o invalidate]; [_cursor_rects removeObject: o]; if ([_cursor_rects count] == 0) { _rFlags.has_currects = 0; _rFlags.valid_rects = 0; } RELEASE(c); break; } else { o = [e nextObject]; } } } - (void) resetCursorRects { } static NSView* findByTag(NSView *view, NSInteger aTag, NSUInteger *level) { NSUInteger i, count; NSArray *sub = [view subviews]; count = [sub count]; if (count > 0) { NSView *array[count]; [sub getObjects: array]; for (i = 0; i < count; i++) { if ([array[i] tag] == aTag) return array[i]; } *level += 1; for (i = 0; i < count; i++) { NSView *v; v = findByTag(array[i], aTag, level); if (v != nil) return v; } *level -= 1; } return nil; } - (id) viewWithTag: (NSInteger)aTag { NSView *view = nil; /* * If we have the specified tag - return self. */ if ([self tag] == aTag) { view = self; } else if (_rFlags.has_subviews) { NSUInteger count = [_sub_views count]; if (count > 0) { NSView *array[count]; NSUInteger i; [_sub_views getObjects: array]; /* * Quick check to see if any of our direct descendents has the tag. */ for (i = 0; i < count; i++) { NSView *subView = array[i]; if ([subView tag] == aTag) { view = subView; break; } } if (view == nil) { NSUInteger level = 0xffffffff; /* * Ok - do it the long way - search the whole tree for each of * our descendents and see which has the closest view matching * the tag. */ for (i = 0; i < count; i++) { NSUInteger l = 0; NSView *v; v = findByTag(array[i], aTag, &l); if (v != nil && l < level) { view = v; level = l; } } } } } return view; } /* * Aiding Event Handling */ /** * Returns YES if the view object will accept the first * click received when in an inactive window, and NO * otherwise. */ - (BOOL) acceptsFirstMouse: (NSEvent*)theEvent { return NO; } /** * Returns the subview, lowest in the receiver's hierarchy, which * contains aPoint, or nil if there is no such view. */ - (NSView*) hitTest: (NSPoint)aPoint { NSPoint p; NSView *v = nil, *w; /* If not within our frame then it can't be a hit. As a special case, always assume that it's a hit if our _super_view is nil, ie. if we're the top-level view in a window. */ if ([self isHidden]) { return nil; } if (_is_rotated_or_scaled_from_base) { p = [self convertPoint: aPoint fromView: _super_view]; if (!NSPointInRect (p, _bounds)) { return nil; } } else if (_super_view && ![_super_view mouse: aPoint inRect: _frame]) { return nil; } else { p = [self convertPoint: aPoint fromView: _super_view]; } if (_rFlags.has_subviews) { NSUInteger count; count = [_sub_views count]; if (count > 0) { NSView *array[count]; [_sub_views getObjects: array]; while (count > 0) { w = array[--count]; v = [w hitTest: p]; if (v) break; } } } /* * mouse is either in the subview or within self */ if (v) return v; else return self; } /** * Returns whether or not aPoint lies within aRect. */ - (BOOL) mouse: (NSPoint)aPoint inRect: (NSRect)aRect { return NSMouseInRect (aPoint, aRect, [self isFlipped]); } - (BOOL) performKeyEquivalent: (NSEvent*)theEvent { NSUInteger i; for (i = 0; i < [_sub_views count]; i++) if ([[_sub_views objectAtIndex: i] performKeyEquivalent: theEvent] == YES) return YES; return NO; } - (BOOL) performMnemonic: (NSString *)aString { NSUInteger i; for (i = 0; i < [_sub_views count]; i++) if ([[_sub_views objectAtIndex: i] performMnemonic: aString] == YES) return YES; return NO; } - (BOOL) mouseDownCanMoveWindow { return ![self isOpaque]; } - (void) removeTrackingRect: (NSTrackingRectTag)tag { NSUInteger i, j; GSTrackingRect *m; j = [_tracking_rects count]; for (i = 0;i < j; ++i) { m = (GSTrackingRect*)[_tracking_rects objectAtIndex: i]; if ([m tag] == tag) { [m invalidate]; [_tracking_rects removeObjectAtIndex: i]; if ([_tracking_rects count] == 0) { _rFlags.has_trkrects = 0; } return; } } } - (BOOL) shouldDelayWindowOrderingForEvent: (NSEvent*)anEvent { return NO; } - (NSTrackingRectTag) addTrackingRect: (NSRect)aRect owner: (id)anObject userData: (void*)data assumeInside: (BOOL)flag { NSTrackingRectTag t; NSUInteger i, j; GSTrackingRect *m; t = 0; j = [_tracking_rects count]; for (i = 0; i < j; ++i) { m = (GSTrackingRect*)[_tracking_rects objectAtIndex: i]; if ([m tag] > t) t = [m tag]; } ++t; m = [[rectClass alloc] initWithRect: aRect tag: t owner: anObject userData: data inside: flag]; [_tracking_rects addObject: m]; RELEASE(m); _rFlags.has_trkrects = 1; return t; } -(BOOL) needsPanelToBecomeKey { return NO; } /** *The effect of the -setNextKeyView: method is to set aView to be the * value returned by subsequent calls to the receivers -nextKeyView method. * This also has the effect of setting the previous key view of aView, * so that subsequent calls to its -previousKeyView method will return * the receiver. *
*As a special case, if you pass nil as aView then the -previousKeyView
* of the receivers current -nextKeyView is set to nil as well as the
* receivers -nextKeyView being set to nil.
* This behavior provides MacOS-X compatibility.
*
If you pass a non-view object other than nil, an * NSInternaInconsistencyException is raised. *
*NB This method does NOT cause aView to be * retained, and if aView is deallocated, the [NSView-dealloc] method will * automatically remove it from the key view chain it is in. *
*For keyboard navigation, views are linked together in a chain, so that * the current first responder view can be changed by stepping backward * and forward in that chain. This is the method for building and modifying * that chain. *
*The MacOS-X documentation refers to this chain as a loop, but * the actual implementation is not a loop at all (except as a special case * when you make the chain into a loop). In fact, while each view may have * only zero or one next view, and zero or one previous * view, several views may have their next view set to a single * view and/or their previous views set to a single view. So the * actual setup is a directed graph rather than a loop. *
*While a directed graph is a very powerful and flexible way of managing * the way views get keyboard focus in response to tabs etc, it can be * confusing if misused. It is probably best therefore, to set your views * up as a single loop within each window. *
*Returns the default menu to be used for instances of the * current class; if no menu has been set through setMenu: * this default menu will be used. *
*NSView's implementation returns nil. You should override * this method if you want all instances of your custom view * to use the same menu. *
*/ + (NSMenu *)defaultMenu { return nil; } /** *NSResponder's method, overriden by NSView.
*If no menu has been set through the use of setMenu:, or * if a nil value has been set through setMenu:, then the * value returned by defaultMenu is used. Otherwise this * method returns the menu set through NSResponder. *
*
see [NSResponder -menu], [NSResponder -setMenu:], * [NSView +defaultMenu] and [NSView -menuForEvent:]. *
*/ - (NSMenu *)menu { NSMenu *m = [super menu]; if (m) { return m; } else { return [[self class] defaultMenu]; } } /** *Returns the menu that it appropriates for the given * event. NSView's implementation returns the default menu of * the view.
*This methods is intended to be overriden so that it can * return a context-sensitive for appropriate mouse's events. ( * (although it seems it can be used for any kind of event)
*This method is used by NSView's rightMouseDown: method, * and the returned NSMenu is displayed as a context menu
*Use of this method is discouraged in GNUstep as it breaks many * user interface guidelines. At the very least, menu items that appear * in a context sensitive menu should also always appear in a normal * menu. Otherwise, users are faced with an inconsistant interface where * the menu items they want are only available in certain (possibly * unknown) cases, making it difficult for the user to understand how * the application operates
*see [NSResponder -menu], [NSResponder -setMenu:], * [NSView +defaultMenu] and [NSView -menu]. *
*/ - (NSMenu *)menuForEvent: (NSEvent *)theEvent { return [self menu]; } /* * Tool Tips */ - (NSToolTipTag) addToolTipRect: (NSRect)aRect owner: (id)anObject userData: (void *)data { GSToolTips *tt = [GSToolTips tipsForView: self]; _rFlags.has_tooltips = 1; return [tt addToolTipRect: aRect owner: anObject userData: data]; } - (void) removeAllToolTips { if (_rFlags.has_tooltips == 1) { GSToolTips *tt = [GSToolTips tipsForView: self]; [tt removeAllToolTips]; } } - (void) removeToolTip: (NSToolTipTag)tag { if (_rFlags.has_tooltips == 1) { GSToolTips *tt = [GSToolTips tipsForView: self]; [tt removeToolTip: tag]; } } - (void) setToolTip: (NSString *)string { if (_rFlags.has_tooltips == 1 || [string length] > 0) { GSToolTips *tt = [GSToolTips tipsForView: self]; _rFlags.has_tooltips = 1; [tt setToolTip: string]; } } - (NSString *) toolTip { if (_rFlags.has_tooltips == 1) { GSToolTips *tt = [GSToolTips tipsForView: self]; return [tt toolTip]; } return nil; } - (void) rightMouseDown: (NSEvent *) theEvent { NSMenu *m; m = [self menuForEvent: theEvent]; if (m) { [NSMenu popUpContextMenu: m withEvent: theEvent forView: self]; } else { [super rightMouseDown: theEvent]; } } - (BOOL) shouldBeTreatedAsInkEvent: (NSEvent *)theEvent { return YES; } - (void) bind: (NSString *)binding toObject: (id)anObject withKeyPath: (NSString *)keyPath options: (NSDictionary *)options { if ([binding hasPrefix: NSHiddenBinding]) { GSKeyValueBinding *kvb; [self unbind: binding]; kvb = [[GSKeyValueOrBinding alloc] initWithBinding: NSHiddenBinding withName: binding toObject: anObject withKeyPath: keyPath options: options fromObject: self]; // The binding will be retained in the binding table RELEASE(kvb); } else { [super bind: binding toObject: anObject withKeyPath: keyPath options: options]; } } - (NSViewLayerContentsPlacement) layerContentsPlacement { // FIXME (when views have CALayer support) return NSViewLayerContentsPlacementScaleAxesIndependently; } - (void) setLayerContentsPlacement: (NSViewLayerContentsPlacement)placement { // FIXME (when views have CALayer support) static BOOL logged = NO; if (!logged) { NSLog(@"warning: stub no-op implementation of -[NSView setLayerContentsPlacement:]"); logged = YES; } } - (NSViewLayerContentsRedrawPolicy) layerContentsRedrawPolicy { // FIXME (when views have CALayer support) return NSViewLayerContentsRedrawNever; } - (void) setLayerContentsRedrawPolicy: (NSViewLayerContentsRedrawPolicy) pol { // FIXME (when views have CALayer support) static BOOL logged = NO; if (!logged) { NSLog(@"warning: stub no-op implementation of -[NSView setLayerContentsRedrawPolicy:]"); logged = YES; } } - (NSUserInterfaceLayoutDirection) userInterfaceLayoutDirection { // FIXME return NSUserInterfaceLayoutDirectionLeftToRight; } - (void) setUserInterfaceLayoutDirection: (NSUserInterfaceLayoutDirection)dir { // FIXME: implement this return; } /** * Layout */ - (void) layout { _needsLayout = NO; GSAutoLayoutEngine *engine = [self _layoutEngine]; if (!engine) { return; } NSArray *subviews = [self subviews]; FOR_IN (NSView *, subview, subviews) NSRect subviewAlignmentRect = [engine alignmentRectForView: subview]; [subview setFrame: subviewAlignmentRect]; END_FOR_IN (subviews); } - (void) layoutSubtreeIfNeeded { [self updateConstraintsForSubtreeIfNeeded]; [self _layoutViewAndSubViews]; } - (void) setNeedsLayout: (BOOL) needsLayout { if (!needsLayout) { return; } _needsLayout = needsLayout; } - (BOOL) needsLayout { return _needsLayout; } - (void) setNeedsUpdateConstraints: (BOOL)needsUpdateConstraints { // Calling setNeedsUpdateConstraints with NO should not have an effect if (!needsUpdateConstraints) { return; } _needsUpdateConstraints = YES; } - (BOOL) needsUpdateConstraints { return _needsUpdateConstraints; } - (void) setTranslatesAutoresizingMaskIntoConstraints: (BOOL)translate { _translatesAutoresizingMaskIntoConstraints = translate; } - (BOOL) translatesAutoresizingMaskIntoConstraints { return _translatesAutoresizingMaskIntoConstraints; } - (NSLayoutPriority) contentCompressionResistancePriority { return _contentCompressionResistancePriority; } - (void) setContentCompressionResistancePriority: (NSLayoutPriority)priority { _contentCompressionResistancePriority = priority; } - (NSSize) intrinsicContentSize { return NSMakeSize(NSViewNoIntrinsicMetric, NSViewNoIntrinsicMetric); } - (CGFloat) baselineOffsetFromBottom { return 0; } - (CGFloat) firstBaselineOffsetFromTop { return 0; } /* Implement NSAppearanceCustomization */ - (NSAppearance*) appearance { return _appearance; } - (void) setAppearance: (NSAppearance*) appearance { ASSIGNCOPY(_appearance, appearance); } - (NSAppearance*) effectiveAppearance { if (_appearance) { return _appearance; } else if ([self superview]) { return [[self superview] effectiveAppearance]; } else { return [NSAppearance currentAppearance]; } } - (void) setIdentifier: (NSUserInterfaceItemIdentifier) identifier { ASSIGN(_identifier, identifier); } - (NSUserInterfaceItemIdentifier) identifier { return _identifier; } @end #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) @implementation NSView (NSConstraintBasedLayoutCorePrivateMethods) // This private setter allows the updateConstraints method to toggle needsUpdateConstraints - (void) _setNeedsUpdateConstraints: (BOOL)needsUpdateConstraints { _needsUpdateConstraints = needsUpdateConstraints; } - (void) _layoutViewAndSubViews { if (_needsLayout) { [self layout]; } NSArray *subviews = [self subviews]; FOR_IN (NSView *, subview, subviews) [subview _layoutViewAndSubViews]; END_FOR_IN (subviews); } - (GSAutoLayoutEngine*) _layoutEngine { if (![self window]) { return nil; } return [[self window] _layoutEngine]; } - (void) _layoutEngineDidChangeAlignmentRect { [[self superview] setNeedsLayout: YES]; } - (GSAutoLayoutEngine*) _getOrCreateLayoutEngine { if (![self window]) { return nil; } if (![[self window] _layoutEngine]) { [[self window] _bootstrapAutoLayout]; } return [[self window] _layoutEngine]; } @end @implementation NSView (NSConstraintBasedLayoutCoreMethods) - (void) updateConstraintsForSubtreeIfNeeded { NSArray *subviews = [self subviews]; FOR_IN (NSView *, subview, subviews) [subview updateConstraintsForSubtreeIfNeeded]; END_FOR_IN (subviews); if ([self needsUpdateConstraints]) { [self updateConstraints]; } } - (void) updateConstraints { if ([self translatesAutoresizingMaskIntoConstraints] && [self superview] != nil) { NSArray *autoresizingConstraints = [NSAutoresizingMaskLayoutConstraint constraintsWithAutoresizingMask: [self autoresizingMask] subitem: self frame: [self frame] superitem: [self superview] bounds: [[self superview] bounds]]; [self addConstraints: autoresizingConstraints]; } [self _setNeedsUpdateConstraints: NO]; } - (NSLayoutPriority) contentCompressionResistancePriorityForOrientation: (NSLayoutConstraintOrientation)orientation { if (orientation == NSLayoutConstraintOrientationHorizontal) { return _compressionPriorities.horizontal; } else { return _compressionPriorities.vertical; } } - (void) setContentCompressionResistancePriority: (NSLayoutPriority)priority forOrientation: (NSLayoutConstraintOrientation)orientation { if (orientation == NSLayoutConstraintOrientationHorizontal) { _compressionPriorities.horizontal = priority; } else { _compressionPriorities.vertical = priority; } } - (NSLayoutPriority) contentHuggingPriorityForOrientation: (NSLayoutConstraintOrientation)orientation { if (orientation == NSLayoutConstraintOrientationHorizontal) { return _huggingPriorities.horizontal; } else { return _huggingPriorities.vertical; } } - (void) setContentHuggingPriority: (NSLayoutPriority)priority forOrientation: (NSLayoutConstraintOrientation)orientation { if (orientation == NSLayoutConstraintOrientationHorizontal) { _huggingPriorities.horizontal = priority; } else { _huggingPriorities.vertical = priority; } } @end @implementation NSView (NSConstraintBasedLayoutInstallingConstraints) - (void) addConstraint: (NSLayoutConstraint *)constraint { if (![self _getOrCreateLayoutEngine]) { return; } [[self _layoutEngine] addConstraint: constraint]; } - (void) addConstraints: (NSArray*)constraints { if (![self _getOrCreateLayoutEngine]) { return; } [[self _layoutEngine] addConstraints: constraints]; } - (void) removeConstraint: (NSLayoutConstraint *)constraint { if (![self _layoutEngine]) { return; } [[self _layoutEngine] removeConstraint: constraint]; } - (void) removeConstraints: (NSArray *)constraints { if (![self _layoutEngine]) { return; } [[self _layoutEngine] removeConstraints: constraints]; } - (NSArray*) constraints { GSAutoLayoutEngine *engine = [self _layoutEngine]; if (!engine) { return [NSArray array]; } return [engine constraintsForView: self]; } @end #endif @implementation NSView (__NSViewPrivateMethods__) /* * This method inserts a view at a given place in the view hierarchy. */ - (void) _insertSubview: (NSView *)sv atIndex: (NSUInteger)idx { [sv _viewWillMoveToWindow: _window]; [sv _viewWillMoveToSuperview: self]; [sv setNextResponder: self]; [_sub_views insertObject: sv atIndex: idx]; _rFlags.has_subviews = 1; [sv resetCursorRects]; [sv setNeedsDisplay: YES]; [sv _viewDidMoveToWindow]; [sv viewDidMoveToSuperview]; [self didAddSubview: sv]; } @end @implementation NSView(KeyViewLoop) static NSComparisonResult cmpFrame(id view1, id view2, void *context) { BOOL flippedSuperView = [(NSView *)context isFlipped]; NSRect frame1 = [view1 frame]; NSRect frame2 = [view2 frame]; if (NSMinY(frame1) < NSMinY(frame2)) return flippedSuperView ? NSOrderedAscending : NSOrderedDescending; if (NSMaxY(frame1) > NSMaxY(frame2)) return flippedSuperView ? NSOrderedDescending : NSOrderedAscending; // FIXME Should use NSMaxX in a Hebrew or Arabic locale if (NSMinX(frame1) < NSMinX(frame2)) return NSOrderedAscending; if (NSMinX(frame1) > NSMinX(frame2)) return NSOrderedDescending; return NSOrderedSame; } - (void) _setUpKeyViewLoopWithNextKeyView: (NSView *)nextKeyView { if (_rFlags.has_subviews) { [self _recursiveSetUpKeyViewLoopWithNextKeyView: nextKeyView]; } else { [self setNextKeyView: nextKeyView]; } } - (void) _recursiveSetUpKeyViewLoopWithNextKeyView: (NSView *)nextKeyView { NSArray *sortedViews; NSView *aView; NSEnumerator *e; sortedViews = [_sub_views sortedArrayUsingFunction: cmpFrame context: self]; e = [sortedViews reverseObjectEnumerator]; while ((aView = [e nextObject]) != nil) { [aView _setUpKeyViewLoopWithNextKeyView: nextKeyView]; nextKeyView = aView; } [self setNextKeyView: nextKeyView]; } @end @implementation NSView (CoreAnimationSupport) - (NSShadow *) shadow { return _shadow; } - (void) setShadow: (NSShadow *)shadow { ASSIGN(_shadow, shadow); } @end