Capturing Window Events in NSDocument - cocoa

I have an document-based Cocoa application with a TextView and I would like to capture clicks on it, so I'm trying to intercept Window events like mouseDown, mouseUp, etc. then relate them to my TextView.
I've tried a two things:
1.) I made the TextView the initial first responder for the Window of my document, and overrode the mouseDown event on my document class, but it's not hitting.
2.) I subclassed NSWindow and override mouseDown, and set that subclass to my Window's class in my document xib. That event didn't hit either.
I noticed that the Window's delegate is already set to my File's Owner which is my NSDocument subclass. Why don't the events fire on my NSDocument if my document subclass is the delegate for my Window?

It's not clear why you would expect NSDocument to handle -mouseDown: events for a view in a window. NSDocument doesn't respond to -mouseDown:. NSTextView (as its name suggests) is a subclass of NSView, which is a subclass of NSResponder, which does respond to -mouseDown:.
You should give the Cocoa Event-Handling Guide a good read.
It's also not clear why you want to handle the events and pass them on to views yourself. Cocoa takes care of all of this stuff for you and will likely do a far better job of it. You should clarify your overall goal (as in "why do you want to intercept clicks and forward them to views yourself?") - there may be a far better (and likely easier) way to accomplish it.

Related

How to get notified when NSWindow opens?

How to take notice when an NSWindow is about to be opened or have just opened? That is, the opposite of windowWillClose: delegate method (likewise the opposite of NSWindowWillCloseNotification.)
This is related to this question, but from the other direction.
The background is, I'm looking to couple a window with a tickmark on the main menu (among other things). When the window is shown, the corresponding ̨ menu item should be checked and vice-versa.
It should not normally be a mystery when or how a window is made visible. It should only happen in response to something that your own code is doing. If the window is in a NIB and is marked Visible At Launch, then it shows when your code loads that NIB. Otherwise, it should only show if you call one of the -order... methods other than -orderOut: (e.g. -orderFront:) or -makeKeyAndOrderFront:. If the window is controlled by a window controller, then it would show if you invoke -[NSWindowController showWindow:]. Etc.
If you really feel the need to be notified, you can subclass NSWindow and override -orderWindow:relativeTo: and, if orderingMode is not NSWindowOut and the window was not already visible, post a notification of your own.
By macOS 10.10, this is somewhat solved by the call to NSViewController's viewWillAppear or viewDidAppear. Have an NSViewController subclass and set it as the contentViewController of the window. Then its viewWillAppear/ viewDidAppear implementation can post a notification that the window will (or did) open.
You can bind your NSMenuItem value to the NSWindows visible binding Zero lines of code if you do it in IB.
visible:
A Boolean value that specifies if the NSWindow is visible.
If visible evaluates to YES, the NSWindow is visible.
Availability:
Available in OS X v10.3 and later.
See the NSWindow Binding Documentation for more info.
You can either bind the NSMenuItem value binding to an existing NSWindow property on one of your existing classes, or add an NSObjectController to your nib and set its content to the NSWindow instance then bind to the controller.
Tested and confirmed on Mac OS 10.9. Works for window minimization and restoration too.

NSWindow tracking

I would like to track each time a certain window appears (becomes visible to the user) in a OS X app. Where would be the most adequate place to call the tracker?
windowWillLoad, maybe?
I expected to find something like windowWillAppear but it seems I'm thinking too much iOS.
How about getting notification such as NSWindowDidBecomeMainNotification, By main I guess the one which is top most on screen directly visible by user.
see : Apple Documentation
Yes, one would expect that a window would notify its delegate or its controller with a windowWillAppear or windowDidAppear message, or post a documented notification like NSWindowDidAppearNotification. But alas, none of those exist. I filed a bug report with Apple and was given the advice to use a storyboard and a view controller instead. This is unhelpful in legacy apps that already use a bunch of window controllers and xibs.
You could subclass NSWindow and override orderWindow:relativeTo: to send a notification. Most, but not quite all, of the messages that make a window show itself ultimately go through this method, including orderBack:, orderFront:, makeKeyAndOrderFront:, and -[NSWindowController showWindow:]. But orderFrontRegardless does not go through orderWindow:relativeTo:, so you would also want to override that for completeness.
Another way to be notified is to make a subclass of NSViewController that controls some view that's always visible in the window. The view controller will receive viewWillAppear and viewDidAppear.
If you're subclassing NSWindow or NSViewController already for some other reason, either of these is a reasonable solution.
If you're not subclassing NSWindow already, and don't have an NSViewController subclass for a view that's always visible in the window, then another way is to use Cocoa bindings to connect the window's visible binding to a property one of your objects. For example, I have a custom NSWindowController subclass. I gave it a windowIsVisible property:
#interface MyWindowController ()
#property (nonatomic) BOOL windowIsVisible;
#end
and I implemented the accessors like this:
- (BOOL)windowIsVisible { return self.window.visible; }
- (void)setWindowIsVisible:(BOOL)windowIsVisible {
NSLog(#"window %# became %s", self.window, windowIsVisible ? "visible" : "hidden");
}
and in awakeFromNib, I bind the window's visible binding to the property like this:
- (void)awakeFromNib {
[super awakeFromNib];
[self.window bind:NSVisibleBinding toObject:self withKeyPath:NSStringFromSelector(#selector(windowIsVisible)) options:nil];
}
When the window becomes visible, the setWindowIsVisible: setter is called with an argument of YES. Note that if the whole app is hidden and reappears, the setter is called again, even though it wasn't called with argument NO when the app was hidden. So be careful not to assume the window was previously hidden.
Also, the binding might create a retain cycle, so you should probably unbind it when the window is closed, unless you want to keep the window and controller around. Note that the window does post NSWindowWillCloseNotification when it's closing, so you don't need any special magic to detect that.

When an NSWindow object has a delegate that is a NSWindow subclass, who is responsible to act on received events?

So I'm building a program that features the use of the IKImageBrowserView component as a subview in an NSWindow. As a side note, I have a controller object called ImageBrowserController which subclasses NSWindow and is set as the delegate of the NSWindow object of my app.
I have sent IKImageBrowserView the message setCanControlQuickLookPanel:YES to enable it to automatically use the QuickLook functionality to preview image files when the IKImageBrowserView is a first responder to receive key events. Then it took me a while to figure out how to make the IKImageBrowserView a first responder which I finally got working by overriding acceptsFirstResponder inside my ImageBrowserController.
Now I understand that as the delegate to the NSWindow, ImageBrowserController has a place in the responder chain after the event gets triggered on NSWindow. And I understand that as a subview of NSWindow, IKImageBrowserView is in line to be passed events for event handling. What I don't get is where the connection is between the ImageBrowserController being a first responder and the event somehow making it to the IKImageBrowserView. I didn't set NSWindow or IKImageBrowserView as first responders explicitly. So why isn't it necessary for me to implement event handling inside my ImageBrowserController?
EDIT: So after reading the accepted answer and going back to my code I tried removing the acceptsFirstResponder override in my ImageBrowserController and the QuickLook functionality still triggered just like the accepted answer said it would. Commenting out the setCanControlQuickLookPanel:YES made the app beep at me when I tried to invoke QuickLook functionality via the spacebar. I'm getting the feeling that my troubles were caused by user error of XCode in hitting the RUN button instead of the BUILD button after making changes to my code (sigh).
Some of what you are saying regarding the interactions between your objects does not make sense, and it is hard to address your stated question without some background.
As you say, your window delegate has a place at the end of the responder chain, after the window itself. The key point I think you are missing is that GUI elements, such as your IKImageBrowserView, will be at the beginning of the chain, and any one of them in a given window could be the current firstResponder.
When your application gets an event, it passes it off to the key window (which is just the window which currently accepts "key" (i.e., "keystroke") events). That window begins by asking its firstResponder to handle the event. If that object refuses, it passes the event to its own nextResponder, usually its superview, which either handles it or passes it on, until the event has either been handled or passed all the way up to the window object itself. Only then will the window (if it does not handle the event itself) ask its delegate to handle the event.
This means that the connection between the window delegate and the IKImageBrowserView is only through the Responder Chain, and its nature is simply that if the view declines to handle any given event, the delegate may eventually be asked to handle it, if no other object in between them handles it first.
Your window delegate does not need to be a firstResponder. Nor does overriding acceptsFirstResponder on the window delegate have any effect on one of the window's subviews.*
Your window delegate also does not need to (and, indeed should not) be a subclass of NSWindow. All it needs is to be a subclass of NSObject which implements whatever methods from the NSWindowDelegate Protocol you are interested in, and methods to handle any events you might want to catch if they are not handled by other objects.
So, the answer to your explicit question at the end is (and I do not mean this sarcastically): you only need to implement event handling in your window delegate if you want it to handle events itself.
*: IKImageBrowserView already responds YES to acceptsFirstResponder. If there are no other subviews in your window, it will automatically be the firstResponder when your application starts. You can set this initialFirstResponder explicitly in Interface Builder by connecting that outlet on the window to whatever object you want.

How to make a view controller first responder for an NSView in Cocoa

I'm trying to implement a view controller for a custom NSOpenGLView based view (this is Cocoa, not Cocoa Touch).
The view is contained within a NIB loaded window but it does not have its own NIB. In fact the window contains multiple instances of the view.
I want to route mouse events to the controller instead of to the view. I would like for this to happen as soon as the user clicks within the corresponding view.
So how can this be done ?
I've tried having the view's becomeFirstResponder method call makeFirstResponder with the controller as argument. However that doesn't seem to work, the view still receives the mouse events instead of the controller if NSView::becomeFirstResponder returns YES. If it returns NO then neither of my classes receive the mouse events.
Of course I could implement the mouse event handling methods in the view and explicitly forward them to the controller but it seems like there should be a better way to handle this.
For general "first responder" status, I recommend Charles Parnot's MTViewController, an NSViewController subclass that uses KVO to make certain the controller is in the responder chain with no extra effort on your part.
However, in your case, you want mouse events too. There's really no way around this - your view will need to translate mouse events into controller interactions.

KeyDown and Cocoa Sample

I'm learning how to build programs with Cocoa. I'm using a sample Apple application that records video from a webcam. I'd like to start and stop the video by capturing the key press. I've tried to override the keydown event but I've read that it's not possible in an NSObject. How can I handle this kind of event?
The class of application extends a NSObject class.
This is the code:
- (void)keyDown:(NSEvent *)event {
NSLog(#"Hi there");
NSString *characters = [event characters];
if ([characters length]) {
switch ([characters characterAtIndex:0]) {
case NSUpArrowFunctionKey:
NSLog(#"Key UP");
break;
}
}
}
I've tried to override Keydown event but I've read that It's not possible in an NSObject.
Correct. Only a responder can respond to events.
How can I handle this kind of event?
Implement a responder. Subclassing NSWindow or NSWindowController will work. Make sure you make your actual window or window controller an instance of your subclass.
The Cocoa documentation explains further.
The class of application extends a NSObject class.
Why? Normally, the principal class of the application bundle is NSApplication or a subclass of that—and there aren't many good reasons to subclass NSApplication.
PS: What's a very good book to start learn MacOS Programming?
I didn't learn by the Hillegass book, myself (I stuck to Apple's docs), but it's a very popular recommendation and I have read it and can tell you it's good.
From the Cocoa Event-Handling Guide - The Responder Chain:
The responder chain is a linked series of responder objects to which an event or action message is applied. When a given responder object doesn’t handle a particular message, the object passes the message to its successor in the chain (that is, its next responder).
When you press a key the window receives the keyDown event. Then it dispatches the event to the first responder, that usually is the control with a blue bezel around its border (try to click on the address field in Safari or Firefox, when it's blue-bezeled then it has first-responder status).
If the first responder does not eat the keypress (the Safari address field does eat it when it displays a character) then it passes it down the responder chain to the next responder in the view hierarchy, then to the window and to the window controller as you can see in the Guide. (Take care that the action responder is another story.)
So you have to implement the keyDown: on a view of your window or in the window itself, if it has no views that eat events. The simplest way to test is to override the keyDown: method of an empty window
To put your hands into the inner workings you can even try overriding the sendEvent: method of a window. sendEvent: dispatches the events to the views of the window, and from there you can for example log all the events managed by the window.
Subclassing NSWindow or
NSWindowController will work.
Similarly, you can subclass NSView and override its event-handling methods.
What's a very good book to start learn
MacOS Programming?
Learn Objective-C on the Mac by Dalrymple is really straightforward, covers enough basics and moves fast enough to get you off the ground in a short bit. It touches on everything from Xcode and Interface Builder to OOP and Objective-C practices. Particularly helpful to beginners (IMHO) are the source file organization and Foundation kit chapters.
Best of luck!

Resources