NSTextView Weird Selection Behavior with NSTextAttachmentCells

I have an NSTextView that displays several NSTextAttachmentCells. I notice this weird behavior.

Sometimes if I just click in an empty area of the text view the entire text content selects.

So I implemented the delegate method to catch it:

- (NSRange)textView:(NSTextView *)textView willChangeSelectionFromCharacterRange:(NSRange)oldSelectedCharRange toCharacterRange:(NSRange)newSelectedCharRange
		{
			if (newSelectedCharRange.length > 1
				&& newSelectedCharRange.length > oldSelectedCharRange.length)
				{
					NSEvent *currentEvent = NSApp.currentEvent;
					NSLog(@"Selection expanded from %@ to %@. Event type: %ld, click count: %ld, modifier flags: %lu, current selected ranges: %@",
						NSStringFromRange(oldSelectedCharRange),
						NSStringFromRange(newSelectedCharRange),
						(long)currentEvent.type,
						(long)currentEvent.clickCount,
						(unsigned long)currentEvent.modifierFlags,
						self.selectedRanges);
					// put a break point here.
				}
			
			return newSelectedCharRange;
		}

And I reproduced the issue and this logs out:

Selection expanded from {0, 0} to {0, 6}. Event type: 2, click count: 1, modifier flags: 0, current selected ranges: ( "NSRange: {0, 6}

Click count is only 1 so I didn't accidentally triple click. I know on Golden Gate use of NSEvent.currentEvent isn't the way (but I'm not there yet). A simple workaround would be to block the selection right here in the delegate method when clickCount != 3 (but again I know NSEvent.currentEvent in Golden Gate won't be reliable).

Anyone run into this and have any ideas? It seems to happen after I did a triple click in the text view at some point previously (but not this click). So I got the feeling that maybe the text view isn't resetting some private properties and is treating this single click as a triple click. But I really don't know.

Edit: Hmm maybe it has nothing to do with a previous triple click. May have to do with text selection not accounting for the geometry of the NSTextAttachmentCells. Not sure. But I still have to figure out a way to workaround this because a random select all is really annoying!

Call stack looks like:

** -[MyTextView textView:willChangeSelectionFromCharacterRange:toCharacterRange:] at MyTextView.m

-[NSTextView(NSSharing) setSelectedRanges:affinity:stillSelecting:] ()

-[MyTextView setSelectedRanges:affinity:stillSelecting:] MyTextView.m

+[NSInputAnalytics(TrackedActionsManager) allowActionTrackingAnalyticsWithName:forAction:] () n -[NSTextView mouseDown:] ()

-[MyTextView mouseDown:] **

If you're wondering what my -mouseDown: override does it just calls super. I realize this is not a whole lot to go on but any help would be appreciated.

NSTextView Weird Selection Behavior with NSTextAttachmentCells
 
 
Q