Search code examples
objective-ccocoanscursor

Unhiding cursor lags


I have a part of a popup-window in which I draw a custom cursor with lines. Hence I don't want the standard cursor to be shown within a certain area (isInDiagram).

This is my code:

- (void)mouseMoved:(NSEvent *)theEvent {
   position = [self convertPoint:[theEvent locationInWindow] fromView:nil];
   if(![self isInDiagram:position]) {
       [NSCursor unhide];
   }
   else{
       [NSCursor hide];
   }
   [self setNeedsDisplay: YES];
}

- (bool) isInDiagram: (NSPoint) p {
   return (p.x >= bborder.x + inset) && (p.y >= bborder.y + inset) &&
   (p.x <= self.window.frame.size.width - bborder.x - inset) &&
   (p.y <= self.window.frame.size.height - bborder.y - inset);
}

Now hiding the cursor works perfectly fine but unhiding always lags. I could not figure out what eventually triggers the cursor to be shown again. However, if I loop the unhide command unhiding works:

for (int i = 0; i<100; i++) {
     [NSCursor unhide];
}

Any ideas how I can solve this problem without using this ugly loop?


Solution

  • From Docs:

    Each invocation of unhide must be balanced by an invocation of hide in order for the cursor display to be correct.

    When you moving mouse it is hiding multiple times. You need flag if cursor is not already hidden than only hide. It should hide only once.

    - (void)mouseMoved:(NSEvent *)theEvent {
       position = [self convertPoint:[theEvent locationInWindow] fromView:nil];
       BOOL isInDiagram = [self isInDiagram:position]
       if(!isInDiagram && !CGCursorIsVisible()) {
           [NSCursor unhide];
       }
       else if (isInDiagram && CGCursorIsVisible()){ // cursor is not hidden
           [NSCursor hide];
       }
       [self setNeedsDisplay: YES];
    }
    

    Note: CGCursorIsVisible is deprecated you can maintain your own flag to track the cursor hidden state.