Struct GCController

Source
#[repr(C)]
pub struct GCController { /* private fields */ }
Available on crate feature 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

Source

pub unsafe fn controllers() -> Retained<NSArray<GCController>>

Get a list of controllers currently attached to the system.

See: GCControllerDidConnectNotification

See: GCControllerDidDisconnectNotification

Source

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.

Source

pub 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.

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

Source

pub 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.
Source

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.

Source

pub unsafe fn setShouldMonitorBackgroundEvents( should_monitor_background_events: bool, )

Source

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.

Source

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.

Source

pub unsafe fn setPlayerIndex(&self, player_index: GCControllerPlayerIndex)

Setter for playerIndex.

Source

pub unsafe fn input(&self) -> Retained<GCControllerLiveInput>

Available on crate feature GCControllerInput only.

Gets the input profile for the controller.

Source

pub unsafe fn battery(&self) -> Option<Retained<GCDeviceBattery>>

Available on crate feature 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.

Source

pub unsafe fn physicalInputProfile(&self) -> Retained<GCPhysicalInputProfile>

Available on crate feature 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

Source

pub unsafe fn gamepad(&self) -> Option<Retained<GCGamepad>>

👎Deprecated
Available on crate features 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

Source

pub unsafe fn microGamepad(&self) -> Option<Retained<GCMicroGamepad>>

Available on crate features GCMicroGamepad and GCPhysicalInputProfile only.
Source

pub unsafe fn extendedGamepad(&self) -> Option<Retained<GCExtendedGamepad>>

Available on crate features GCExtendedGamepad and GCPhysicalInputProfile only.
Source

pub unsafe fn motion(&self) -> Option<Retained<GCMotion>>

Available on crate feature 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

Source

pub unsafe fn light(&self) -> Option<Retained<GCDeviceLight>>

Available on crate feature 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.

Source

pub unsafe fn haptics(&self) -> Option<Retained<GCDeviceHaptics>>

Available on crate feature 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.

Source

pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>

Source

pub unsafe fn new() -> Retained<Self>

Source§

impl GCController

Snapshot.

Source

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

Source

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.

Source

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

Source

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.

Source

pub unsafe fn startWirelessControllerDiscoveryWithCompletionHandler( completion_handler: Option<&DynBlock<dyn Fn()>>, )

Available on crate feature 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

Source

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>§

Source

pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !

Handle messages the object doesn’t recognize.

See Apple’s documentation for details.

Methods from Deref<Target = AnyObject>§

Source

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());
Source

pub unsafe fn get_ivar<T>(&self, name: &str) -> &T
where T: Encode,

👎Deprecated: this is difficult to use correctly, use 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.

Source

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

Source§

fn as_ref(&self) -> &AnyObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<GCController> for GCController

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSObject> for GCController

Source§

fn as_ref(&self) -> &NSObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<AnyObject> for GCController

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for GCController

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for GCController

Source§

const NAME: &'static str = "GCController"

The name of the Objective-C class that this type represents. Read more
Source§

type Super = NSObject

The superclass of this class. Read more
Source§

type ThreadKind = <<GCController as ClassType>::Super as ClassType>::ThreadKind

Whether the type can be used from any thread, or from only the main thread. Read more
Source§

fn class() -> &'static AnyClass

Get a reference to the Objective-C class that this type represents. Read more
Source§

fn as_super(&self) -> &Self::Super

Get an immutable reference to the superclass.
Source§

impl Debug for GCController

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for GCController

Source§

type Target = NSObject

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl GCDevice for GCController

Source§

unsafe fn handlerQueue(&self) -> Retained<DispatchQueue>
where Self: Sized + Message,

Available on crate features GCDevice and dispatch2 only.
The dispatch queue that element value change handlers are submitted on. The default queue is main, and setting this to any other queue will make value change handlers dispatch async on the given queue. This is useful if the main game loop of the application is not on main, or if input logic is handled on another thread from the main game loop. Read more
Source§

unsafe fn setHandlerQueue(&self, handler_queue: &DispatchQueue)
where Self: Sized + Message,

Available on crate features GCDevice and dispatch2 only.
Setter for handlerQueue.
Source§

unsafe fn vendorName(&self) -> Option<Retained<NSString>>
where Self: Sized + Message,

Available on crate feature GCDevice only.
A vendor supplied name. May be nil, and is not guaranteed to be unique. This should not be used as a key in a dictionary, but simply as a way to present some basic information about the device in testing or to the user.
Source§

unsafe fn productCategory(&self) -> Retained<NSString>
where Self: Sized + Message,

Available on crate feature GCDevice only.
The product category the device belongs to. This is useful for setting appropriate UI elements based on what type of device is connected. Read more
Source§

unsafe fn physicalInputProfile(&self) -> Retained<GCPhysicalInputProfile>
where Self: Sized + Message,

👎Deprecated: Use the physicalInputProfile property on GCController instead. For GCKeyboard, use the keyboardInput property. For GCMouse, use the mouseInput property.
Available on crate features GCDevice and GCPhysicalInputProfile only.
Gets the physical input profile for the device. Read more
Source§

impl Hash for GCController

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Message for GCController

Source§

fn retain(&self) -> Retained<Self>
where Self: Sized,

Increment the reference count of the receiver. Read more
Source§

impl NSObjectProtocol for GCController

Source§

fn isEqual(&self, other: Option<&AnyObject>) -> bool
where Self: Sized + Message,

Check whether the object is equal to an arbitrary other object. Read more
Source§

fn hash(&self) -> usize
where Self: Sized + Message,

An integer that can be used as a table address in a hash table structure. Read more
Source§

fn isKindOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of the class, or one of its subclasses. Read more
Source§

fn is_kind_of<T>(&self) -> bool
where T: ClassType, Self: Sized + Message,

👎Deprecated: use isKindOfClass directly, or cast your objects with AnyObject::downcast_ref
Check if the object is an instance of the class type, or one of its subclasses. Read more
Source§

fn isMemberOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of a specific class, without checking subclasses. Read more
Source§

fn respondsToSelector(&self, aSelector: Sel) -> bool
where Self: Sized + Message,

Check whether the object implements or inherits a method with the given selector. Read more
Source§

fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
where Self: Sized + Message,

Check whether the object conforms to a given protocol. Read more
Source§

fn description(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object. Read more
Source§

fn debugDescription(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object to use when debugging. Read more
Source§

fn isProxy(&self) -> bool
where Self: Sized + Message,

Check whether the receiver is a subclass of the NSProxy root class instead of the usual NSObject. Read more
Source§

fn retainCount(&self) -> usize
where Self: Sized + Message,

The reference count of the object. Read more
Source§

impl PartialEq for GCController

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RefEncode for GCController

Source§

const ENCODING_REF: Encoding = <NSObject as ::objc2::RefEncode>::ENCODING_REF

The Objective-C type-encoding for a reference of this type. Read more
Source§

impl DowncastTarget for GCController

Source§

impl Eq for GCController

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T> AnyThread for T
where T: ClassType<ThreadKind = dyn AnyThread + 'a> + ?Sized,

Source§

fn alloc() -> Allocated<Self>
where Self: Sized + ClassType,

Allocate a new instance of the class. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,