#[repr(C)]pub struct GCController { /* private fields */ }
GCController
only.Expand description
Controllers are available to an application that links to GameController.framework. There are 2 ways to access controllers paired to the system, adopt both to ensure the best user experience:
1: Querying for the the current array or controllers using [GCController controllers]. 2: Registering for Connection/Disconnection notifications from NSNotificationCenter.
Only controllers that support one of the allowed profiles, such as GCExtendedGamepad, will be enumerated. Check for the profile supported before using a controller in your application. Ignore a controller that doesn’t support a profile that suits your application, as the user will expect their controller to either be fully supported or not supported at all.
See also Apple’s documentation
Implementations§
Source§impl GCController
impl GCController
Sourcepub unsafe fn controllers() -> Retained<NSArray<GCController>>
pub unsafe fn controllers() -> Retained<NSArray<GCController>>
Get a list of controllers currently attached to the system.
See: GCControllerDidConnectNotification
See: GCControllerDidDisconnectNotification
Sourcepub unsafe fn current() -> Option<Retained<GCController>>
pub unsafe fn current() -> Option<Retained<GCController>>
The most recently used game controller. If a user actuates a game controller input, that controller will become the current one.
Note: This is useful for single player games where you only care about whether an input is pressed, and not where it came from. You will still need to register for changes to GCController.current so that your UI can remain up-to-date with the current controller.
Sourcepub unsafe fn controllerPausedHandler(
&self,
) -> *mut DynBlock<dyn Fn(NonNull<GCController>)>
👎Deprecated: Use the Menu button found on the controller’s input profile, if it exists.Available on crate feature block2
only.
pub unsafe fn controllerPausedHandler( &self, ) -> *mut DynBlock<dyn Fn(NonNull<GCController>)>
block2
only.Set this block to be notified when a user intends to suspend or resume the current game state. A controller will have a button dedicated to suspending and resuming play and invoking context sensitive actions. During event handling the system will notify the application using this block such that the application can handle the suspension and resumption from the given controller.
Use this to implement your canonical transition to a pause menu for example if that is your application’s desired handling of suspension in play. You may pause and resume based on game state as well so the event is only called each time the pause/resume button is pressed.
Note: This handler has been deprecated in favor of the Menu button found on GCMicroGamepad and GCExtendedGamepad.
See: microGamepad
See: extendedGamepad
Sourcepub unsafe fn setControllerPausedHandler(
&self,
controller_paused_handler: Option<&DynBlock<dyn Fn(NonNull<GCController>)>>,
)
👎Deprecated: Use the Menu button found on the controller’s input profile, if it exists.Available on crate feature block2
only.
pub unsafe fn setControllerPausedHandler( &self, controller_paused_handler: Option<&DynBlock<dyn Fn(NonNull<GCController>)>>, )
block2
only.Setter for controllerPausedHandler
.
Sourcepub unsafe fn shouldMonitorBackgroundEvents() -> bool
pub unsafe fn shouldMonitorBackgroundEvents() -> bool
Whether the current application should monitor and respond to game controller events when it is not the frontmost application.
not be forwarded to the application. Once the application becomes the frontmost application, game controller events will be forwarded.
Note: Starting with macOS Big Sur 11.3, shouldMonitorBackgroundEvents will be NO by default. For applications built prior to macOS Big Sur 11.3, (or running on devices with an earlier version of macOS), shouldMonitorBackgroundEvents will be YES by default. On iOS and tvOS, this property is ignored.
Sourcepub unsafe fn setShouldMonitorBackgroundEvents(
should_monitor_background_events: bool,
)
pub unsafe fn setShouldMonitorBackgroundEvents( should_monitor_background_events: bool, )
Setter for shouldMonitorBackgroundEvents
.
Sourcepub unsafe fn isAttachedToDevice(&self) -> bool
pub unsafe fn isAttachedToDevice(&self) -> bool
A controller may be form fitting or otherwise closely attached to the device. This closeness to other inputs on the device may suggest that interaction with the device may use other inputs easily. This is presented to developers to allow them to make informed decisions about UI and interactions to choose for their game in this situation.
Sourcepub unsafe fn playerIndex(&self) -> GCControllerPlayerIndex
pub unsafe fn playerIndex(&self) -> GCControllerPlayerIndex
A player index for the controller, defaults to GCControllerPlayerIndexUnset.
This can be set both for the application to keep track of controllers and as a signal to make a controller display a player index on a set of LEDs or some other mechanism.
A controller is not guaranteed to have a visual display of the playerIndex, playerIndex does not persist for a controller with regards to a system.
Negative values less than GCControllerPlayerIndexUnset will just map back to GCControllerPlayerIndexUnset when read back.
Sourcepub unsafe fn setPlayerIndex(&self, player_index: GCControllerPlayerIndex)
pub unsafe fn setPlayerIndex(&self, player_index: GCControllerPlayerIndex)
Setter for playerIndex
.
Sourcepub unsafe fn input(&self) -> Retained<GCControllerLiveInput>
Available on crate feature GCControllerInput
only.
pub unsafe fn input(&self) -> Retained<GCControllerLiveInput>
GCControllerInput
only.Gets the input profile for the controller.
Sourcepub unsafe fn battery(&self) -> Option<Retained<GCDeviceBattery>>
Available on crate feature GCDeviceBattery
only.
pub unsafe fn battery(&self) -> Option<Retained<GCDeviceBattery>>
GCDeviceBattery
only.Gets the battery information if controller supports one
This property is useful when you try to notify your user to change or charge controller before it runs out of battery life or simply display the current battery level and status.
Sourcepub unsafe fn physicalInputProfile(&self) -> Retained<GCPhysicalInputProfile>
Available on crate feature GCPhysicalInputProfile
only.
pub unsafe fn physicalInputProfile(&self) -> Retained<GCPhysicalInputProfile>
GCPhysicalInputProfile
only.Gets the physical input profile for the controller.
Note: This is equivalent to the controller’s microGamepad, or extendedGamepad instance.
See: microGamepad
See: extendedGamepad
Sourcepub unsafe fn gamepad(&self) -> Option<Retained<GCGamepad>>
👎DeprecatedAvailable on crate features GCGamepad
and GCPhysicalInputProfile
only.
pub unsafe fn gamepad(&self) -> Option<Retained<GCGamepad>>
GCGamepad
and GCPhysicalInputProfile
only.Gets the profile for the controller that suits current application.
There are several supported profiles, with an additional optional profile for motion as well. Each controller may be able to map its inputs into all profiles or just one kind of profile. Query for the controller profile that suits your game, the simplest kind will be supported by the broadest variety of controllers. A controller supporting the Extended Gamepad profile for example supports the Gamepad profile and more. As such it can always be used just in the Gamepad profile if that suits the game.
A physical controller that supports a profile must support it completely. That means that all buttons and axis inputs must be valid inputs that a developer can utilize.
If a controller does not support the given profile the returned value will be nil. Use this to filter controllers if the application requires a specific kind of profile.
See: motion
pub unsafe fn microGamepad(&self) -> Option<Retained<GCMicroGamepad>>
GCMicroGamepad
and GCPhysicalInputProfile
only.pub unsafe fn extendedGamepad(&self) -> Option<Retained<GCExtendedGamepad>>
GCExtendedGamepad
and GCPhysicalInputProfile
only.Sourcepub unsafe fn motion(&self) -> Option<Retained<GCMotion>>
Available on crate feature GCMotion
only.
pub unsafe fn motion(&self) -> Option<Retained<GCMotion>>
GCMotion
only.Gets the motion input profile. This profile is optional and may be available if the controller is attached to a device that supports motion. If this is nil the controller does not support motion input and only the gamepad & extendedGamepad profiles are available.
See: gamepad
See: extendedGamepad
Sourcepub unsafe fn light(&self) -> Option<Retained<GCDeviceLight>>
Available on crate feature GCDeviceLight
only.
pub unsafe fn light(&self) -> Option<Retained<GCDeviceLight>>
GCDeviceLight
only.Gets the light for the controller, if one exists.
A controller’s light can be used to signal information to the player, such as using different light colors based on the player index. It can also be used to react to in-game events and enhance user immersion.
Sourcepub unsafe fn haptics(&self) -> Option<Retained<GCDeviceHaptics>>
Available on crate feature GCDeviceHaptics
only.
pub unsafe fn haptics(&self) -> Option<Retained<GCDeviceHaptics>>
GCDeviceHaptics
only.Gets the haptics for the controller, if one exists.
Use this property to create CHHapticEngine instances according to your needs.
Note: Haptics are a drain on the controller’s battery, and can be distracting when used excessively.
Source§impl GCController
Methods declared on superclass NSObject
.
impl GCController
Methods declared on superclass NSObject
.
Source§impl GCController
Snapshot.
impl GCController
Snapshot.
Sourcepub unsafe fn isSnapshot(&self) -> bool
pub unsafe fn isSnapshot(&self) -> bool
A controller may represent a real device managed by the operating system, or a virtual snapshot created by the developer. If a controller is created by the developer, it is considered to be a snapshot, allowing direct writes to any GCControllerElement of its profiles. If the controller is not snapshot, the system will reject any write requests to GCControllerElement.
See: controllerWithMicroGamepad
See: controllerWithExtendedGamepad
See: capture
Sourcepub unsafe fn capture(&self) -> Retained<GCController>
pub unsafe fn capture(&self) -> Retained<GCController>
Polls the state vector of the controller and saves it to a new and writable instance of GCController.
If your application is heavily multithreaded this may also be useful to guarantee atomicity of input handling as a snapshot will not change based on user input once it is taken.
See: snapshot
Returns: A new controller with the duplicated state vector of the current controller.
Sourcepub unsafe fn controllerWithMicroGamepad() -> Retained<GCController>
pub unsafe fn controllerWithMicroGamepad() -> Retained<GCController>
Creates a controller with a micro gamepad profile.
This controller will be considered a snapshot, allowing developers to write to any GCControllerElement of its profiles.
See: snapshot
Returns: A new controller with a micro gamepad profile
Sourcepub unsafe fn controllerWithExtendedGamepad() -> Retained<GCController>
pub unsafe fn controllerWithExtendedGamepad() -> Retained<GCController>
Creates a controller with an extended gamepad profile.
This controller will be considered a snapshot, allowing developers to write to any GCControllerElement of its profiles.
See: snapshot
Returns: A new controller with an extended gamepad profile
Source§impl GCController
Discovery.
impl GCController
Discovery.
Sourcepub unsafe fn startWirelessControllerDiscoveryWithCompletionHandler(
completion_handler: Option<&DynBlock<dyn Fn()>>,
)
Available on crate feature block2
only.
pub unsafe fn startWirelessControllerDiscoveryWithCompletionHandler( completion_handler: Option<&DynBlock<dyn Fn()>>, )
block2
only.Start discovery of new wireless controllers that are discoverable. This is an asynchronous and the supplied completionHandler will get called once no more devices can be found. If there are already multiple controllers available for use, there may be little reason to automatically start discovery of new wireless controllers. In this situation it may be best to allow the user to start discovery manually via in-game UI.
Once discovery has started new controllers will notify themselves as connected via GCControllerDidConnectNotification. As the notification arrives the controller is also available in the controllers array.
The completionHandler could be used to update UI and/or game state to indicate that no more controllers will be found and the current set of controllers is what is available for use in the game.
If a completionHandler was provided, it will be called once when discovery stops. Either from an explicit call to stopWirelessControllerDiscovery or from timing out or stopping in its natural course of operation. Thus the completionHandler will at most be called once per call to startWirelessControllerDiscoveryWithCompletionHandler:.
The completionHandler may also not get called at all, if for example startWirelessControllerDiscoveryWithCompletionHandler: is called multiple times during dicovery. For this case the net effect is that the completionHandler is replaced with each call and only the last one set before discovery stops will be called.
Parameter completionHandler
: an optional handler that is called when discovery stops. (may be nil, in which case you will not be notified when discovery stops)
See: stopWirelessControllerDiscovery
See: controllers
Sourcepub unsafe fn stopWirelessControllerDiscovery()
pub unsafe fn stopWirelessControllerDiscovery()
If no more controllers are needed, depending on game state or number of controllers supported by a game, the discovery process can be stopped. Calling stopWirelessControllerDiscovery when no discovery is currently in progress will return immediately without any effect, thus it is safe to call even if the completionHandler of startWirelessControllerDiscoveryWithCompletionHandler: has been called.
See: startWirelessControllerDiscoveryWithCompletionHandler:
Methods from Deref<Target = NSObject>§
Sourcepub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
Handle messages the object doesn’t recognize.
See Apple’s documentation for details.
Methods from Deref<Target = AnyObject>§
Sourcepub fn class(&self) -> &'static AnyClass
pub fn class(&self) -> &'static AnyClass
Dynamically find the class of this object.
§Panics
May panic if the object is invalid (which may be the case for objects
returned from unavailable init
/new
methods).
§Example
Check that an instance of NSObject
has the precise class NSObject
.
use objc2::ClassType;
use objc2::runtime::NSObject;
let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());
Sourcepub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
👎Deprecated: this is difficult to use correctly, use Ivar::load
instead.
pub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
Ivar::load
instead.Use Ivar::load
instead.
§Safety
The object must have an instance variable with the given name, and it
must be of type T
.
See Ivar::load_ptr
for details surrounding this.
Sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
pub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
Attempt to downcast the object to a class of type T
.
This is the reference-variant. Use Retained::downcast
if you want
to convert a retained object to another type.
§Mutable classes
Some classes have immutable and mutable variants, such as NSString
and NSMutableString
.
When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable “under the hood”.
So using this method to convert a NSString
to a NSMutableString
,
while not unsound, is generally frowned upon unless you created the
string yourself, or the API explicitly documents the string to be
mutable.
See Apple’s documentation on mutability and on
isKindOfClass:
for more details.
§Generic classes
Objective-C generics are called “lightweight generics”, and that’s because they aren’t exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.
You can, however, safely downcast to generic collections where all the
type-parameters are AnyObject
.
§Panics
This works internally by calling isKindOfClass:
. That means that the
object must have the instance method of that name, and an exception
will be thrown (if CoreFoundation is linked) or the process will abort
if that is not the case. In the vast majority of cases, you don’t need
to worry about this, since both root objects NSObject
and
NSProxy
implement this method.
§Examples
Cast an NSString
back and forth from NSObject
.
use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};
let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();
Try (and fail) to cast an NSObject
to an NSString
.
use objc2_foundation::{NSObject, NSString};
let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());
Try to cast to an array of strings.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();
This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.
Downcast when processing each element instead.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
for elem in arr {
if let Some(data) = elem.downcast_ref::<NSString>() {
// handle `data`
}
}
Trait Implementations§
Source§impl AsRef<AnyObject> for GCController
impl AsRef<AnyObject> for GCController
Source§impl AsRef<GCController> for GCController
impl AsRef<GCController> for GCController
Source§impl AsRef<NSObject> for GCController
impl AsRef<NSObject> for GCController
Source§impl Borrow<AnyObject> for GCController
impl Borrow<AnyObject> for GCController
Source§impl Borrow<NSObject> for GCController
impl Borrow<NSObject> for GCController
Source§impl ClassType for GCController
impl ClassType for GCController
Source§const NAME: &'static str = "GCController"
const NAME: &'static str = "GCController"
Source§type ThreadKind = <<GCController as ClassType>::Super as ClassType>::ThreadKind
type ThreadKind = <<GCController as ClassType>::Super as ClassType>::ThreadKind
Source§impl Debug for GCController
impl Debug for GCController
Source§impl Deref for GCController
impl Deref for GCController
Source§impl GCDevice for GCController
impl GCDevice for GCController
Source§unsafe fn handlerQueue(&self) -> Retained<DispatchQueue>
unsafe fn handlerQueue(&self) -> Retained<DispatchQueue>
GCDevice
and dispatch2
only.Source§unsafe fn setHandlerQueue(&self, handler_queue: &DispatchQueue)
unsafe fn setHandlerQueue(&self, handler_queue: &DispatchQueue)
GCDevice
and dispatch2
only.handlerQueue
.Source§unsafe fn vendorName(&self) -> Option<Retained<NSString>>
unsafe fn vendorName(&self) -> Option<Retained<NSString>>
GCDevice
only.Source§unsafe fn productCategory(&self) -> Retained<NSString>
unsafe fn productCategory(&self) -> Retained<NSString>
GCDevice
only.Source§unsafe fn physicalInputProfile(&self) -> Retained<GCPhysicalInputProfile>
unsafe fn physicalInputProfile(&self) -> Retained<GCPhysicalInputProfile>
GCDevice
and GCPhysicalInputProfile
only.Source§impl Hash for GCController
impl Hash for GCController
Source§impl Message for GCController
impl Message for GCController
Source§impl NSObjectProtocol for GCController
impl NSObjectProtocol for GCController
Source§fn isEqual(&self, other: Option<&AnyObject>) -> bool
fn isEqual(&self, other: Option<&AnyObject>) -> bool
Source§fn hash(&self) -> usize
fn hash(&self) -> usize
Source§fn isKindOfClass(&self, cls: &AnyClass) -> bool
fn isKindOfClass(&self, cls: &AnyClass) -> bool
Source§fn is_kind_of<T>(&self) -> bool
fn is_kind_of<T>(&self) -> bool
isKindOfClass
directly, or cast your objects with AnyObject::downcast_ref