NSColorWell subclass not getting mouseMoved events - cocoa

I'm trying to implement a color picker in my Cocoa app. (Yes, I know about NSColorPanel. I don't like it very much. The point of rolling my own is that I think I can do better.)
Here's a picture of the current state of my picker.
(source: ryanballantyne.name)
The wells surrounding the color wheel are NSColorWell subclasses. They are instantiated programmatically and added to the color wheel view (an NSView subclass) by calling addSubView on the color wheel class.
I want to make it so that you can drag the color wells around by their grab handles. The start of that journey is making the cursor change to an open hand when the mouse hovers over the handles. Sadly, I can't use a cursor rect for this because most of my views are rotated. I must therefore use mouseMoved events and do the hit detection myself.
Here's the mouse event code I'm trying to make work:
- (void)mouseMoved:(NSEvent*)event
{
NSLog(#"I am over here!\n");
[super mouseMoved:event];
NSPoint eventPoint = [self convertPoint:[event locationInWindow] fromView:nil];
BOOL isInHandle = [grabHandle containsPoint:eventPoint];
if (isInHandle && [NSCursor currentCursor] != [NSCursor openHandCursor]) {
[[NSCursor openHandCursor] push];
}
else if (!isInHandle) [NSCursor pop];
}
- (void)mouseEntered:(NSEvent*)event
{
[[self window] setAcceptsMouseMovedEvents:YES];
}
- (void)mouseExited:(NSEvent*)event
{
[[self window] setAcceptsMouseMovedEvents:NO];
[NSCursor pop];
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (BOOL)resignFirstResponder
{
return YES;
}
I find that my mouseMoved method is never called. Ditto for entered and exited. However, when I implement mouseDown, that one does get called, so at least some events are getting to me, just not the ones I want.
Any ideas? Thanks!

mouseEntered: and mouseExited: don't track entering/exiting your view directly; they track entering/exiting any tracking areas you've established in your view. The relevant methods are -addTrackingRect:owner:userData:assumeInside: and -removeTrackingRect:. Just pass [self bounds] for the first parameter if you want your whole view to be tracked. If your app is 10.5+ only, you should probably use NSTrackingArea instead as it directly supports getting mouse-moved events only inside the tracking area.
Keep in mind that 1) tracking rects have the same somewhat odd behavior as cursor rects w/r/t rotated views, and 2) if your bounds change (not merely your frame) you'll probably need to re-establish your tracking rect, so save the tracking rect's tag to remove it later.

Related

NSTextField Drawing on Top of Sub View

I have created a secondary NSViewController to create a progress indicator "popup". The reason for this is that the software has to interact with some hardware and some of the functions take the device a few seconds to respond. So being thoughtful of the end user I have a NSViewController that has a NSView (that is black and semi-transparent) and then a message/progress bar on top. This is added to the window using addSubView.
Everything works great except when the screen has a NSTextField in it. The popup shows but the NSTextField is drawn on top. What is this?
The view code I used for drawing semi-transparent:
#implementation ConnectingView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
// Drawing code here.
CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}
#end
The code I use to show the progress view
-(void) showProgressWithMessage:(NSString *) message andIsIndet:(BOOL) indet
{
connectingView = [[ConnectingViewController alloc] init];
[self.view.window.contentView addSubview:connectingView.view];
connectingView.view.frame = ((NSView*)self.view.window.contentView).bounds;
[connectingView changeProgressLabel:message];
if (indet)
[connectingView makeProgressBar:NO];
}
Is there a better way to add the subview or to tell the NSTextFields I don't want them to be drawn on top?
Thanks!
So Setting [self setWantsLayer] to my custom NSViews sort of worked however there are a lot of redraw issues (white borders, and backgrounds). A NSPopover may be better in some instances however I was going for "locked down" approach where the interface is unreachable until it finishes (or times out).
What worked for me was to go to the instance of my NSView, select the window in Interface Builder, then go to layers (far right on properties view) and select my view under "Core Animation Layer".

Subview of subclassed NSView re-positioned incorrectly after drawing a focus ring

I wanted to create a focus ring outside a subclassed NSView to identify selection. My reference comes from here: Link.
I followed the reference, overwrote the -drawRect method as:
#property (nonatomic) BOOL shouldDisplayFocus;
...
- (void)drawRect:(NSRect)dirtyRect
{
// Drawing code here.
if (_shouldDisplayFocus)
{
[self setKeyboardFocusRingNeedsDisplayInRect:[self bounds]];
}
[super drawRect:dirtyRect];
[[NSColor blackColor] set];
NSRectFill(dirtyRect);
if (_shouldDisplayFocus)
{
NSSetFocusRingStyle(NSFocusRingTypeExterior);
NSBezierPath *path = [NSBezierPath bezierPathWithRect:NSInsetRect([self bounds], -1.0, -1.0)];
[[NSColor blackColor] set];
[path stroke];
[NSGraphicsContext restoreGraphicsState];
}
}
And its -mouseDown: method also overwritten:
- (void)mouseDown:(NSEvent *)theEvent
{
[super mouseDown:theEvent];
if (_delegate && [_delegate respondsToSelector:#selector(mouseDownAtView:withEvent:)])
{
[_delegate mouseDownAtView:self withEvent:theEvent];
}
}
And after the view is clicked, its delegate would set/un-set the focus ring and which would make its -drawRect: called again.
It worked and generated the focus ring outside the view correctly. However, one problem occurred soon:
I had an image view inside the subclassed view. As the image view rectangle was auto-layout with NSLayoutConstraint objects, I create four NSLayoutConstraint outlets to adjust their values. I do not frequently change the layout constraints. Actually, as the image size remained unchanged, I would not set them.
Here is the situation when the subclassed view not clicked (seemed fine):
Then click on the image (the focus ring generated, but...):
And I tried resize the window, things got even more sadly "FUNNY":
I could not understand why the problem is or how to solve that. Could anyone help me with that? I have uploaded my sample code here: Download
Quite sad that no one answer this question.
I noticed that the subviews also layouted incorrectly when they were add to this view by -addSubview: and -setFrame method.
Really late answer, but here it is anyway: you didn't call [NSGraphicsContext saveGraphicsState] at the start of the if (_shouldDisplayFocus) { block.
You call [NSGraphicsContext restoreGraphicsState] to pop the graphics state off the stack, but you never put anything on the stack. Cocoa is using the graphics state stack to draw everything so you are popping off some unknown state that has something to do with the position of the image. If you want to add the focus ring style and be able to remove the focus ring style you need to first save the graphics state, set the focus ring style to whatever you want, and then restore the graphics state back to what it was.

NSOutlineView scroll animation is not working

I want to remove the NSOutlineView's show/hide button.So,I override the NSOutlineView and get the mouseDown event.The follow is the code.
-(void)mouseDown:(NSEvent *)theEvent
{
NSLog(#"LeftFolderListOutlineView mouseDown");
[super mouseDown:theEvent];
NSPoint localPoint = [self convertPoint:theEvent.locationInWindow
fromView:nil];
NSInteger row = [self rowAtPoint:localPoint];
id clickedItem = [self itemAtRow:row];
if (![clickedItem isKindOfClass:[NSDictionary class]]) {
return;
}
if ([self isItemExpanded:clickedItem]) {
[[self animator] collapseItem:clickedItem];
}else{
[[self animator] expandItem:clickedItem];
}
}
It should be a scroll animation when the NSOutlineView collapse or expand.But in this case it's not working.Anyone tell me why and how can I improve this?
To remove 'show/hide button' (outline cell) you could implement - (NSRect)frameOfOutlineCellAtRow:(NSInteger)row method in the NSOutliveView subclass and return NSZeroRect.
NSOutlineView collapse/expand animation is not animatable via animator.
Only OS 10.7 or above provide collapse/expand animation effects. So it you planed to support older OS versions you need to provide separate implementation.
If you want to provide collapse/expand animation on OS 10.6 or below, you definitely needed to override 'drawRect' of NSOutlineView.
-- Update --
Sorry, I think I neglected the main point. 10.7 expand/collapse animation is automatically kick in only when users clicked the outline cell. If we want to show the animation without default outline cells, there is no other way but manually implementing animation effects, I think.
I made a sample project that implement expand/collapse animation effects with image drawing.
Check the source codes in here: https://github.com/roh0sun/ovanimation

cursorUpdate called, but cursor not updated

I have been working on this for hours, have no idea what went wrong. I want a custom cursor for a button which is a subview of NSTextView, I add a tracking area and send the cursorUpdate message when mouse entered button.
The cursorUpdate method is indeed called every time the mouse entered the tracking area. But the cursor stays the IBeamCursor.
Any ideas?
Reference of the Apple Docs: managing cursor-update event
- (void)cursorUpdate:(NSEvent *)event {
[[NSCursor arrowCursor] set];
}
- (void)myAddTrackingArea {
[self myRemoveTrackingArea];
NSTrackingAreaOptions trackingOptions = NSTrackingCursorUpdate | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
_trackingArea = [[NSTrackingArea alloc] initWithRect: [self bounds] options: trackingOptions owner: self userInfo: nil];
[self addTrackingArea: _trackingArea];
}
- (void)myRemoveTrackingArea {
if (_trackingArea)
{
[self removeTrackingArea: _trackingArea];
_trackingArea = nil;
}
}
I ran into the same problem.
The issue is, that NSTextView updates its cursor every time it receives a mouseMoved: event. The event is triggered by a self updating NSTrackingArea of the NSTextView, which always tracks the visible part of the NSTextView inside the NSScrollView. So there are maybe 2 solutions I can think of.
Override updateTrackingAreas remove the tracking area that is provided by Cocoa and make sure you always create a new one instead that excludes the button. (I would not do this!)
Override mouseMoved: and make sure it doesn't call super when the cursor is over the button.
- (void)mouseMoved:(NSEvent *)theEvent {
NSPoint windowPt = [theEvent locationInWindow];
NSPoint superViewPt = [[self superview]
convertPoint: windowPt fromView: nil];
if ([self hitTest: superViewPt] == self) {
[super mouseMoved:theEvent];
}
}
I had the same issue but using a simple NSView subclass that was a child of the window's contentView and did not reside within an NScrollView.
The documentation for the cursorUpdate flag of NSTrackingArea makes it sound like you only need to handle the mouse entering the tracking area rect. However, I had to manually check the mouse location as the cursorUpdate(event:) method is called both when the mouse enters the tracking area's rect and when it leaves the tracking rect. So if the cursorUpdate(event:) implementation only sets the cursor without checking whether it lies within the tracking area rect, it is set both when it enters and leaves the rect.
The documentation for cursorUpdate(event:) states:
Override this method to set the cursor image. The default
implementation uses cursor rectangles, if cursor rectangles are
currently valid. If they are not, it calls super to send the message
up the responder chain.
If the responder implements this method, but decides not to handle a
particular event, it should invoke the superclass implementation of
this method.
override func cursorUpdate(with event: NSEvent) {
// Convert mouse location to the view coordinates
let mouseLocation = convert(event.locationInWindow, from: nil)
// Check if the mouse location lies within the rect being tracked
if trackingRect.contains(mouseLocation) {
// Set the custom cursor
NSCursor.openHand.set()
} else {
// Reset the cursor
super.cursorUpdate(with: event)
}
}
I just ran across this through a Google search, so I thought I'd post my solution.
Subclass the NSTextView/NSTextField.
Follow the steps in the docs to create an NSTrackingArea. Should look something like the following. Put this code in the subclass's init method (also add the updateTrackingAreas method):
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:(NSTrackingMouseMoved | NSTrackingActiveInKeyWindow) owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
self.trackingArea = trackingArea;
Now you need to add the mouseMoved: method to the subclass:
- (void)mouseMoved:(NSEvent *)theEvent {
NSPoint point = [self convertPoint:theEvent.locationInWindow fromView:nil];
if (NSPointInRect(point, self.popUpButton.frame)) {
[[NSCursor arrowCursor] set];
} else {
[[NSCursor IBeamCursor] set];
}
}
Note: the self.popUpButton is the button that is a subview of the NSTextView/NSTextField.
That's it! Not too hard it ends up--just had to used mouseMoved: instead of cursorUpdate:. Took me a few hours to figure this out, hopefully someone can use it.

CALayer only painting on input events

I have a Mac app that's using IKImageBrowserView. I've subclassed IKImageBrowserView and I'm returning a custom cell type from newCellForRepresentedItem.
In my cell, I'm creating and returning a layer from layerForType:
// When asked for a foreground layer, return a new layer that we'll render the icon decorations into
- (CALayer *)layerForType:(NSString *)type {
if ([type isEqualToString:IKImageBrowserCellForegroundLayer]) {
#synchronized(self) {
if (!self.foregroundLayer) {
self.foregroundLayer = [[CALayer alloc] init];
self.foregroundLayer.delegate = self;
self.foregroundLayer.needsDisplayOnBoundsChange = YES;
[self.foregroundLayer setNeedsDisplay];
}
}
return self.foregroundLayer;
} else {
return [super layerForType:type];
}
}
I have my cell observing an object, and calling setNeedsDisplay on my custom layer when it changes.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.percentDone = (float)self.bytesSoFar/self.bytesTotal;
NSLog(#"Update");
[self.foregroundLayer setNeedsDisplay];
}];
}
Here's the problem I'm having: The download proceeds, the object being observed fires the observer (so observeValueForKeyPath is called) and setNeedsDisplay is called. I verified this by logging with NSLog messages.
But the drawing method:
- (void)drawLayer:(CALayer *)theLayer
inContext:(CGContextRef)theContext
{
NSLog(#"Drawing");
// Drawing happens here
}
What I'm seeing is that the drawing starts out okay - printing "Update" and "Drawing" interleaved - but after a short time, the "Drawing" stops and just the "Update" messages continue.
If I click in the image browser, or tap a key on the keyboard, the "Drawing" resumes for a short while, and then stops, back to just "Update".
It's like I need to trigger a repaint using the keyboard or mouse - the setNeedsDisplay isn't doing it - but I don't understand why. It does work for a short time, stops working, then only works while I'm providing mouse input.
This has me baffled. I'd appreciate any suggestions.
I didn't find the problem here, but I did find a solution.
Invalidating IKImageBrowserView cells doesn't cause them to be repainted because IKImageBrowserView, probably for performance, doesn't redraw cells unless their version changes.
Instead of invalidating the cell, I now increment the imageVersion returned by my IKImageBrowserItem, and then invalidate the IKImageBrowserView. This reliably redraws the item.

Resources