Can I attach an NSTouchBar to an NSWindow after it's been created with no specific NSTouchBar support? - objective-c

I'm using SDL to create a window for use with OpenGL and the only information it gives back is the NSWindow object.
Can I use that to then subsequently associate an NSTouchBar with that window?
I've successfully done it by directly modifying the SDL code to do it in the ViewController, but as a user of the library API, that option isn't available to me.
I was previously thinking I could do so with a customer NSResponder, but am no longer convinced this is a valid option.
Thank you.

Creating an NSWindowController and attaching it to the existing window works.
#interface WindowController : NSWindowController <NSTouchBarDelegate>
and
- (id)init:(NSWindow *) nswindow
{
self = [super initWithWindow:nswindow];
return self;
}
- (NSTouchBar *)makeTouchBar
{
NSTouchBar *bar = [[NSTouchBar alloc] init];
bar.delegate = self;
bar.customizationIdentifier = PopoverCustomizationIdentifier;
bar.defaultItemIdentifiers = #[PopoverItemIdentifier, NSTouchBarItemIdentifierOtherItemsProxy];
bar.customizationAllowedItemIdentifiers = #[PopoverItemIdentifier];
bar.principalItemIdentifier = PopoverItemIdentifier;
return bar;
}
You can see https://developer.apple.com/library/content/samplecode/NSTouchBarCatalog/Listings/Objective_C_NSTouchBar_Catalog_TestViewControllers_PopoverViewController_m.html for a bunch more of the guts to put in these functions.

Related

Presenting modal dialogs from XIB in Cocoa: best/shortest pattern?

Below is my typical WindowController module for presenting a modal dialog (could be settings, asking username/password, etc) loaded from a XIB. It seems a bit too complex for something like this. Any ideas how this can be done better/with less code?
Never mind that it's asking for a password, it could be anything. What frustrates me most is that I repeat the same pattern in each and every of my XIB-based modal window modules. Which of course means I could define a custom window controller class, but before doing that I need to make sure this is really the best way of doing things.
#import "MyPasswordWindowController.h"
static MyPasswordWindowController* windowController;
#interface MyPasswordWindowController ()
#property (weak) IBOutlet NSSecureTextField *passwordField;
#end
#implementation MyPasswordWindowController
{
NSInteger _dialogCode;
}
- (id)init
{
return [super initWithWindowNibName:#"MyPassword"];
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self.window center];
}
- (void)windowWillClose:(NSNotification*)notification
{
[NSApp stopModalWithCode:_dialogCode];
_dialogCode = 0;
}
- (IBAction)okButtonAction:(NSButton *)sender
{
_dialogCode = 1;
[self.window close];
}
- (IBAction)cancelButtonAction:(NSButton *)sender
{
[self.window close];
}
+ (NSString*)run
{
if (!windowController)
windowController = [MyPasswordWindowController new];
[windowController loadWindow];
windowController.passwordField.stringValue = #"";
if ([NSApp runModalForWindow:windowController.window])
return windowController.passwordField.stringValue;
return nil;
}
The application calls [MyPasswordWindowController run], so from the point of view of the user of this module it looks simple, but not so much when you look inside.
Set tags on your buttons to distinguish them. Have them both target the same action method:
- (IBAction) buttonAction:(NSButton*)sender
{
[NSApp stopModalWithCode:[sender tag]];
[self.window close];
}
Get rid of your _dialogCode instance variable and -windowWillClose: method.
-[NSApplication runModalForWindow:] will already center the window, so you can get rid of your -awakeFromNib method.
Get rid of the invocation of -[NSWindowController loadWindow]. That's an override point. You're not supposed to call it. The documentation is clear on that point. It will be called automatically when you request the window controller's -window.
Get rid of the static instance of MyPasswordWindowController. Just allocate a new one each time. There's no point in keeping the old one around and it can be troublesome to reuse windows.

programmatically create initial window of cocoa app (OS X)

Usually I am making iOS app but now I am trying to make an OS X app, and I am lost at the very beginning. Say the style I make the iOS apps are totally programmatic, there's no xib files or whatsoever just because that I have a lot more control by typing than dragging. However in OS X programming, it starts with some xib files with the menu items and a default window. There are quite a lot of items in the menu items so that's probably not something I want to mess around, but I want to programmatically create my first window myself.
So I did this:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSUInteger windowStyleMask = NSTitledWindowMask|NSResizableWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask;
NSWindow* appWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(200, 200, 1280, 720) styleMask:windowStyleMask backing:NSBackingStoreBuffered defer:NO];
appWindow.backgroundColor = [NSColor lightGrayColor];
appWindow.minSize = NSMakeSize(1280, 720);
appWindow.title = #"Sample Window";
[appWindow makeKeyAndOrderFront:self];
_appWindowController = [[AppWindowController alloc] initWithWindow:appWindow];
[_appWindowController showWindow:self];
}
So here, I have created a window first, and use that windowController to init this window. The window does show up in this way, but I can only specify the inner elements, like buttons and labels here, but not in the windowController. It makes me feel bad so I tried another way.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
_appWindowController = [[AppWindowController alloc] init];
[_appWindowController showWindow:self];
}
and after this I want to set the other elements in the loadWindow: function in the windowController like this:
- (void)loadWindow
{
[self.window setFrame:NSMakeRect(200, 200, 1280, 720) display:YES];
self.window.title = #"Sample window";
self.window.backgroundColor = [NSColor lightGrayColor];
NSButton* sampleButton = [[NSButton alloc] initWithFrame:NSRectFromCGRect(CGRectMake(100, 100, 200, 23))];
sampleButton.title = #"Sample Button!";
[sampleButton setButtonType:NSMomentaryLightButton];
[sampleButton setBezelStyle:NSRoundedBezelStyle];
[self.window.contentView addSubview:sampleButton];
NSLog(#"Loaded window!");
[self.window makeKeyAndOrderFront:nil];
}
Unfortunately, this never works. the loadWindow: never gets called, nor windowDidLoad:. Where did they go?
And please don't ask why I don't use nibs. I wish to make some highly customized views inside, possibly OpenGL, so I don't think nibs can handle it. I am greatly appreciated if anyone could help. Thanks.
And also, who knows how to even start the menu items from scratch, programmatically?
I am using the latest Xcode.
I spent an entire Sunday digging into this problem myself. Like the person asking the question, I prefer coding iOS and OSX without nib files (mostly) or Interface Builder and to go bare metal. I DO use NSConstraints though. It is probably NOT WORTH avoiding IB if you're doing simpler UIs, however when you get into a more complex UI it gets harder.
It turns out to be fairly simple to do, and for the benefit of the "Community" I thought I'd post a concise up to date answer here. There ARE some older Blog Posts out there and the one I found most useful were the ones from Lap Cat Software. 'Tip O The Hat' to you sir!
This Assumes ARC. Modify your main() to look something like this:
#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"
int main(int argc, const char *argv[])
{
NSArray *tl;
NSApplication *application = [NSApplication sharedApplication];
[[NSBundle mainBundle] loadNibNamed:#"MainMenu" owner:application topLevelObjects:&tl];
AppDelegate *applicationDelegate = [[AppDelegate alloc] init]; // Instantiate App delegate
[application setDelegate:applicationDelegate]; // Assign delegate to the NSApplication
[application run]; // Call the Apps Run method
return 0; // App Never gets here.
}
You'll note that there is still a Nib (xib) in there. This is for the main menu only. As it turns out even today (2014) apparently no way to easily set the position 0 menu item. That's the one with the title = to your App name. You can set everything to the right of it using [NSApplication setMainMenu] but not that one. So I opted to keep the MainMenu Nib created by Xcode in new projects, and strip it down to just the position 0 item. I think that is a fair compromise and something I can live with. One brief plug for UI Sanity... when you're creating Menus please follow the same basic pattern as other Mac OSX Apps.
Next modify the AppDelegate to look something like this:
-(id)init
{
if(self = [super init]) {
NSRect contentSize = NSMakeRect(500.0, 500.0, 1000.0, 1000.0);
NSUInteger windowStyleMask = NSTitledWindowMask | NSResizableWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask;
window = [[NSWindow alloc] initWithContentRect:contentSize styleMask:windowStyleMask backing:NSBackingStoreBuffered defer:YES];
window.backgroundColor = [NSColor whiteColor];
window.title = #"MyBareMetalApp";
// Setup Preference Menu Action/Target on MainMenu
NSMenu *mm = [NSApp mainMenu];
NSMenuItem *myBareMetalAppItem = [mm itemAtIndex:0];
NSMenu *subMenu = [myBareMetalAppItem submenu];
NSMenuItem *prefMenu = [subMenu itemWithTag:100];
prefMenu.target = self;
prefMenu.action = #selector(showPreferencesMenu:);
// Create a view
view = [[NSTabView alloc] initWithFrame:CGRectMake(0, 0, 700, 700)];
}
return self;
}
-(IBAction)showPreferencesMenu:(id)sender
{
[NSApp runModalForWindow:[[PreferencesWindow alloc] initWithAppFrame:window.frame]];
}
-(void)applicationWillFinishLaunching:(NSNotification *)notification
{
[window setContentView:view]; // Hook the view up to the window
}
-(void)applicationDidFinishLaunching:(NSNotification *)notification
{
[window makeKeyAndOrderFront:self]; // Show the window
}
And Bingo... you're good to go! You can start working from there in the AppDelegate pretty much like you're familiar with. Hope that helps!
UPDATE: I don't create menus in code anymore as I've shown above. I've discovered you can edit MainMenu.xib source in Xcode 6.1. Works nice, very flexible and all it takes is a little experimentation to see how it works. Faster than messing around in code and easy to localize! See the picture to understand what I am on about:
See https://github.com/sindresorhus/touch-bar-simulator/blob/master/Touch%20Bar%20Simulator/main.swift
In main.swift
let app = NSApplication.shared()
let delegate = AppDelegate()
app.delegate = delegate
app.run()
Swift 4:
// File main.swift
autoreleasepool {
// Even if we loading application manually we need to setup `Info.plist` key:
// <key>NSPrincipalClass</key>
// <string>NSApplication</string>
// Otherwise Application will be loaded in `low resolution` mode.
let app = Application.shared
app.setActivationPolicy(.regular)
app.run()
}
// File Application.swift
public class Application: NSApplication {
private lazy var mainWindowController = MainWindowController()
private lazy var mainAppMenu = MainMenu()
override init() {
super.init()
delegate = self
mainMenu = mainAppMenu
}
public required init?(coder: NSCoder) {
super.init(coder: coder) // This will newer called.
}
}
extension Application: NSApplicationDelegate {
public func applicationDidFinishLaunching(_ aNotification: Notification) {
mainWindowController.showWindow(nil)
}
}
Override the -init method in your AppWindowController class to create the window and then call super's -initWithWindow: method (which is NSWindowController's designated initializer) with that window.
But I generally agree with the comments that there's little reason to avoid NIBs.

How to use NSWindowController to show a window in standard application?

I created a new blank standard application using Xcode template. Removed the window in MainMenu.xib and I created a new customized NSWindowController subclass with a xib.
They were named "WYSunFlowerWindowController.h" and "WYSunFlowerWindowController.m".
And I append then init function like below:
- (id)init
{
NSLog(#"init()");
return [super initWithWindowNibName:#"WYSunFlowerWindowController" owner:self];
}
And my WYAppDelegate.m file is like below:
static WYSunFlowerMainWindowController* windowController = nil;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
if (windowController == nil) {
windowController = [[WYSunFlowerMainWindowController alloc] init];
}
[[windowController window] makeKeyAndOrderFront:windowController];
}
And I have the problem, that the window can't show it self after I launch the app. Anyone can tell me why? Is anything wrong with my code?
I am a newbie in Objective-C and cocoa. So I think I maybe make a silly mistake that I can't figure it out by myself.
UPDATE:
Here is my project source. Pleas have a look and help me to figure out what is my mistake。
https://dl.dropbox.com/u/3193707/SunFlower.zip
In your init method, I think you have to set self to the super init first before you return self.
-(id)init
{
NSLog (#"init()");
self = [super initWithWindowNibName:#"WYSunFlowerWindowController" owners:self];
return self;
}
Edit:
Try replace makeKeyAndOrderFront: with [windowController showWindow:self]
Then if that still doesn't work, check your window controller xib, make sure the file owner is set to WYSunFlowerWindowController and that the IBOutlet Window (declared in NSWindowController) is connected to the window.
Edit 2:
Commenting out your #property and #synthesize window in your controller was the trick. Don't redeclare get and setters that were already predefined in a superclass.

Best design pattern for a window opening another window in cocoa application

I am learning how to create osx applications with Cocoa/Objective-C. I am writing a simple app which will link together two different tutorials I have been going through. On start up a choice window loads with 2 buttons, one button loads one window and the other loads the other window. When either button is clicked the choice window closes.
The choice window controller object was added to the MainMenu.xib file so it is created at launch. The window is then opened using the awakeFromNib message.
I want the result of one button to open up the 'track controller' tutorial application from the ADC website. The action looks like this:
- (IBAction)trackButton:(id)sender {
TMTrackController *trackController = [[TMTrackController alloc] init];
[self.window close];
}
I added an init method to the TMTrackController class which looks like this:
- (id) init {
if (self = [super init]) {
[self showWindow];
TMTrack *myTrack = [[TMTrack alloc] init];
myTrack.volume = 50;
self.track = myTrack;
[self updateUserInterface];
return self;
}
else {
return nil;
}
}
- (void) showWindow {
if(!self.window) {
[NSBundle loadNibNamed:#"trackWindow" owner:self];
}
[self.window makeKeyAndOrderFront:self];
}
I am not sure this is the best way to be doing this as I know that the choiceController class will be released when it is closed thus getting rid of the TMTrackController class too. However even when I untick the 'release when closed' box of the ChoiceWindow.xib it breaks too.
What is the correct way to do this?
With xib s in the same project use:
#interface
#property (strong) NSWindowController *test;
#implementation
#synthesize test;
test = [[NSWindowController alloc] initWithWindowNibName:#"XIB NAME HERE"];
[test showWindow:self];
[home close];
It is not completely the same but this is my solution for such problems: Stackoverflow
Just ignore my statement in this answer regarding showing the window as a modal window. Everything else is still valid. This way you could have your personal window controller and it controls everything there is within the xib. This is a huge advantage for maintaining the project afterwards (and you keep to the application logic).

How to inspect the responder chain?

I'm doing some crazy multiple documents inside a single window stuff with the document-based architecture and I'm 95% done.
I have this two-tier document architecture, where a parent document opens and configures the window, providing a list of "child" documents. When the user selects one of the children, that document is opened with the same window controller and it places a NSTextView in the window. The window controller's document association is changed so that the "edited dot" and the window title track the currently selected document. Think of an Xcode project and what happens when you edit different files in it.
To put the code in pseudo form, a method like this is invoked in the parent document when a child document is opened.
-(void)openChildDocumentWithURL:(NSURL *)documentURL {
// Don't open the same document multiple times
NSDocument *childDocument = [documentMapTable objectForKey:documentURL];
if (childDocument == nil) {
childDocument = [[[MyDocument alloc] init] autorelease];
// Use the same window controller
// (not as bad as it looks, AppKit swaps the window's document association for us)
[childDocument addWindowController:myWindowController];
[childDocument readFromURL:documentURL ofType:#"Whatever" error:NULL];
// Cache the document
[documentMapTable setObject:childDocument forKey:documentURL];
}
// Make sure the window controller gets the document-association swapped if the doc came from our cache
[myWindowController setDocument:childDocument];
// Swap the text views in
NSTextView *currentTextView = myCurrentTextView;
NSTextView *newTextView = [childDocument textView];
[newTextView setFrame:[currentTextView frame]]; // Don't flicker
[splitView replaceSubview:currentTextView with:newTextView];
if (currentTextView != newTextView) {
[currentTextView release];
currentTextView = [newTextView retain];
}
}
This works, and I know the window controller has the correct document association at any given time since the change dot and title follow whichever document I'm editing.
However, when I hit save, (CMD+S, or File -> Save/Save As) it wants to save the parent document, not the current document (as reported by [[NSDocumentController sharedDocumentController] currentDocument] and as indicated by the window title and change dot).
From reading the NSResponder documentation, it seems like the chain should be this:
Current View -> Superview (repeat) -> Window -> WindowController -> Document -> DocumentController -> Application.
I'm unsure how the document based architecture is setting up the responder chain (i.e. how it's placing NSDocument and NSDocumentController into the chain) so I'd like to debug it, but I'm not sure where to look. How do I access the responder chain at any given time?
You can iterate over the responder chain using the nextResponder method of NSResponder. For your example, you should be able to start with the current view, and then repeatedly print out the result of calling it in a loop like this:
NSResponder *responder = currentView;
while ((responder = [responder nextResponder])) {
NSLog(#"%#", responder);
}
Here is another version for Swift users:
func printResponderChain(_ responder: UIResponder?) {
guard let responder = responder else { return; }
print(responder)
printResponderChain(responder.next)
}
Simply call it with self to print out the responder chain starting from self.
printResponderChain(self)
I'll improve a bit on the Responder category answer, by using a class method which feels more "useable" when debugging (you don't need to break in a specific view or whatever).
Code is for Cocoa but should be easily portable to UIKit.
#interface NSResponder (Inspect)
+ (void)inspectResponderChain;
#end
#implementation NSResponder (Inspect)
+ (void)inspectResponderChain
{
NSWindow *mainWindow = [NSApplication sharedApplication].mainWindow;
NSLog(#"Responder chain:");
NSResponder *responder = mainWindow.firstResponder;
do
{
NSLog(#"\t%#", [responder debugDescription]);
}
while ((responder = [responder nextResponder]));
}
#end
You can also add a category to class UIResponder with appropriate method that is possible to be used by any subclass of UIResponder.
#interface UIResponder (Inspect)
- (void)inspectResponderChain; // show responder chain including self
#end
#implementation UIResponder (Inspect)
- (void)inspectResponderChain
{
UIResponder *x = self;
do {
NSLog(#"%#", x);
}while ((x = [x nextResponder]));
}
#end
Than you can use this method somewhere in code as the example below:
- (void)viewDidLoad {
...
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[self.view addSubview:myView];
[myView inspectResponderChain]; // UIView is a subclass of UIResponder
...
}
Swift:
extension UIResponder {
var responderChain: [UIResponder] {
var chain = [UIResponder]()
var nextResponder = next
while nextResponder != nil {
chain.append(nextResponder!)
nextResponder = nextResponder?.next
}
return chain
}
}
// ...
print(self.responderChain)
Here is the simplest one
extension UIResponder {
func responderChain() -> String {
guard let next = next else {
return String(describing: self)
}
return String(describing: self) + " -> " + next.responderChain()
}
}
// ...
print(self.responderChain())