I'm trying to get the following code to work as a macOS command line tool. It is important that this not be a Cocoa app, so that is not an option.
This same code works perfectly in the same project with a Cocoa App target and detects a compatible controller, but when run as a Command Line Tool target, nothing happens and the API shows no controllers connected.
Obviously, some of it is contrived... it's just the simplest I could boil it down to and have some indication of things happening when it actually works.
#import <Cocoa/Cocoa.h>
#import <GameController/GameController.h>
int main( int argc, const char * argv[] )
{
@autoreleasepool
{
NSApplication * application = [NSApplication sharedApplication];
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
[center addObserverForName: GCControllerDidConnectNotification
object: nil
queue: nil
usingBlock: ^(NSNotification * note) {
GCController * controller = note.object;
printf( "ATTACHED: %s\n", controller.vendorName.UTF8String );
}
];
[application finishLaunching];
bool shouldKeepRunning = true;
while (shouldKeepRunning)
{
printf( "." );
while (true)
{
NSEvent * event = [application
nextEventMatchingMask: NSEventMaskAny
untilDate: nil
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (event == NULL)
{
break;
}
else
{
[application sendEvent: event];
}
}
usleep( 100 * 1000 );
}
}
return 0;
}
I'm guessing it's got something to do with how the Cocoa application sets up or the event loops are handled. Or maybe there's some internal trigger that initializes the GameController framework. The API doesn't appear to have any explicit way to initialize it.
https://developer.apple.com/documentation/gamecontroller?language=objc
Can anyone shed some light on how I might get this working?
Ultimately, this code really needs to work inside a Core Foundation bundle, so if it could actually work with a Core Foundation runloop that would be ideal.
-- EDIT --
I have made a test project to illustrate the problem more clearly. There are two build targets. The Cocoa app build target works and receives the controller connected event. The other build target, just a simple CLI app, does not work. They both use the same source file. It also includes two code paths, one of which is the traditional [NSApp run], the second is the manual event loop above. The result is the same.
https://www.dropbox.com/s/a6fw3nuegq7bg8x/ControllerTest.zip?dl=0