objc2-core-haptics 0.3.2

Bindings to the CoreHaptics framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! This file has been automatically generated by `objc2`'s `header-translator`.
//! DO NOT EDIT
use core::ffi::*;
use core::ptr::NonNull;
use objc2::__framework_prelude::*;
#[cfg(feature = "objc2-avf-audio")]
use objc2_avf_audio::*;
use objc2_foundation::*;

use crate::*;

/// [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhaptictimeimmediate?language=objc)
pub const CHHapticTimeImmediate: NSTimeInterval = 0.0;
/// A block which is called asynchronously when a call to start or stop the haptic engine completes.
///
/// Parameter `error`: If the call fails, this is set to a valid NSError describing the error.
///
/// All callbacks are delivered on an internal queue which guarantees proper delivery order and allows reentrant calls to the API.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticcompletionhandler?language=objc)
#[cfg(feature = "block2")]
pub type CHHapticCompletionHandler = *mut block2::DynBlock<dyn Fn(*mut NSError)>;

/// Constants indicating what the engine should do in response to the finished handler being called.
///
///
/// Stop the engine.  This is useful if the client knows that the client is about to go inactive.
///
///
/// Do not stop the engine.  This is useful if the client expects more activity.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticenginefinishedaction?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CHHapticEngineFinishedAction(pub NSInteger);
impl CHHapticEngineFinishedAction {
    #[doc(alias = "CHHapticEngineFinishedActionStopEngine")]
    pub const StopEngine: Self = Self(1);
    #[doc(alias = "CHHapticEngineFinishedActionLeaveEngineRunning")]
    pub const LeaveEngineRunning: Self = Self(2);
}

unsafe impl Encode for CHHapticEngineFinishedAction {
    const ENCODING: Encoding = NSInteger::ENCODING;
}

unsafe impl RefEncode for CHHapticEngineFinishedAction {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}

/// A block which is called asynchronously when the engine detects that all active pattern players have finished.  The
/// return value tells the system what action to take as a result of this (see `CHHapticEngineFinishedAction`).
///
/// Parameter `error`: If the engine detects the players have stopped due to an error, this is set to a valid NSError describing the error.
///
/// All callbacks are delivered on an internal queue which guarantees proper delivery order and allows reentrant calls to the API.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticenginefinishedhandler?language=objc)
#[cfg(feature = "block2")]
pub type CHHapticEngineFinishedHandler =
    *mut block2::DynBlock<dyn Fn(*mut NSError) -> CHHapticEngineFinishedAction>;

/// Constants indicating the reason why the CHHapticEngine has stopped.
///
///
/// The AVAudioSession bound to this engine has been interrupted.
///
///
/// The application owning this engine has been suspended (i.e., put into the background).
///
///
/// The engine has stopped due to an idle timeout when the engine's `autoShutdownEnabled` property was set to YES.
///
///
/// The engine has stopped due to a call to a `CHHapticEngineFinishedHandler` returning `CHHapticEngineFinishedActionStopEngine`.
///
///
/// The engine has stopped because the CHHapticEngine instance was destroyed.
///
///
/// The engine has stopped because the Game Controller associated with this engine disconnected.
///
///
/// An error has occurred.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticenginestoppedreason?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CHHapticEngineStoppedReason(pub NSInteger);
impl CHHapticEngineStoppedReason {
    #[doc(alias = "CHHapticEngineStoppedReasonAudioSessionInterrupt")]
    pub const AudioSessionInterrupt: Self = Self(1);
    #[doc(alias = "CHHapticEngineStoppedReasonApplicationSuspended")]
    pub const ApplicationSuspended: Self = Self(2);
    #[doc(alias = "CHHapticEngineStoppedReasonIdleTimeout")]
    pub const IdleTimeout: Self = Self(3);
    #[doc(alias = "CHHapticEngineStoppedReasonNotifyWhenFinished")]
    pub const NotifyWhenFinished: Self = Self(4);
    #[doc(alias = "CHHapticEngineStoppedReasonEngineDestroyed")]
    pub const EngineDestroyed: Self = Self(5);
    #[doc(alias = "CHHapticEngineStoppedReasonGameControllerDisconnect")]
    pub const GameControllerDisconnect: Self = Self(6);
    #[doc(alias = "CHHapticEngineStoppedReasonSystemError")]
    pub const SystemError: Self = Self(-1);
}

unsafe impl Encode for CHHapticEngineStoppedReason {
    const ENCODING: Encoding = NSInteger::ENCODING;
}

unsafe impl RefEncode for CHHapticEngineStoppedReason {
    const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}

/// A block which is called asynchronously when the engine has stopped due to external causes such as
/// an audio session interruption or autoShutdown.
///
/// Parameter `stoppedReason`: This constant indicates the reason why the engine stopped.
///
/// This handler is NOT called if the client directly calls stopWithCompletionHandler:.
/// All callbacks are delivered on an internal queue which guarantees proper delivery order and allows reentrant calls to the API.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticenginestoppedhandler?language=objc)
#[cfg(feature = "block2")]
pub type CHHapticEngineStoppedHandler = *mut block2::DynBlock<dyn Fn(CHHapticEngineStoppedReason)>;

/// A block which is called asynchronously if the haptic engine has reset itself due a server failure.
///
/// In response to this handler, the app must reload all custom audio resources and recreate all necessary
/// pattern players.  The engine must of course be restarted.  CHHapticPatterns do not need to be re-created.
/// All callbacks are delivered on an internal queue which guarantees proper delivery order and allows reentrant calls to the API.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticengineresethandler?language=objc)
#[cfg(feature = "block2")]
pub type CHHapticEngineResetHandler = *mut block2::DynBlock<dyn Fn()>;

/// [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticaudioresourcekey?language=objc)
pub type CHHapticAudioResourceKey = NSString;

extern "C" {
    /// Keys used to configure the playback behavior of a custom waveform.
    ///
    /// Indicates whether the audio file playback should be ramped in and out with an envelope.  This can be useful for preventing clicks during playback,
    /// or for cases where the application wants to modulate this envelope to use different attack and release times.
    /// Value type: boolean.  Default is
    /// .
    ///
    /// Indicates whether the audio file will be looped when played back.  The default loop range is the entire file.
    /// Value type: boolean.  Default is
    /// .
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticaudioresourcekeyusevolumeenvelope?language=objc)
    pub static CHHapticAudioResourceKeyUseVolumeEnvelope: &'static CHHapticAudioResourceKey;
}

extern "C" {
    /// [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticaudioresourcekeyloopenabled?language=objc)
    pub static CHHapticAudioResourceKeyLoopEnabled: &'static CHHapticAudioResourceKey;
}

extern_class!(
    /// Represents the connection with the haptic server.
    ///
    /// See also [Apple's documentation](https://developer.apple.com/documentation/corehaptics/chhapticengine?language=objc)
    #[unsafe(super(NSObject))]
    #[derive(Debug, PartialEq, Eq, Hash)]
    pub struct CHHapticEngine;
);

extern_conformance!(
    unsafe impl NSObjectProtocol for CHHapticEngine {}
);

impl CHHapticEngine {
    extern_methods!(
        #[cfg(feature = "CHHapticDeviceCapability")]
        /// Get the protocol that describes haptic and audio capabilities on this device.
        ///
        /// Detailed description on the capability protocol is in CHHapticDeviceCapability.h.
        #[unsafe(method(capabilitiesForHardware))]
        #[unsafe(method_family = none)]
        pub unsafe fn capabilitiesForHardware(
        ) -> Retained<ProtocolObject<dyn CHHapticDeviceCapability>>;

        /// The absolute time from which all current and future event times may be calculated.
        /// The units are seconds.
        #[unsafe(method(currentTime))]
        #[unsafe(method_family = none)]
        pub unsafe fn currentTime(&self) -> NSTimeInterval;

        #[cfg(feature = "block2")]
        /// The engine will call this block when it has stopped due to external causes (such as
        /// an audio session interruption or the app going into the background).  It will NOT be called
        /// if the client calls stopWithCompletionHandler:.
        ///
        /// In general, callbacks arrive on a non-main thread and it is the client's responsibility to handle
        /// it in a thread-safe manner.
        #[unsafe(method(stoppedHandler))]
        #[unsafe(method_family = none)]
        pub unsafe fn stoppedHandler(&self) -> CHHapticEngineStoppedHandler;

        #[cfg(feature = "block2")]
        /// Setter for [`stoppedHandler`][Self::stoppedHandler].
        ///
        /// # Safety
        ///
        /// `stopped_handler` must be a valid pointer.
        #[unsafe(method(setStoppedHandler:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setStoppedHandler(&self, stopped_handler: CHHapticEngineStoppedHandler);

        #[cfg(feature = "block2")]
        /// This block will called asynchronously if the haptic engine has to reset itself after a server failure.
        ///
        /// In response to this handler being called, the client must release all haptic pattern players
        /// and recreate them.  All CHHapticPattern objects and CHHapticEngine properties will have been preserved.
        /// In general, callbacks arrive on a non-main thread and it is the client's responsibility to handle
        /// it in a thread-safe manner.
        #[unsafe(method(resetHandler))]
        #[unsafe(method_family = none)]
        pub unsafe fn resetHandler(&self) -> CHHapticEngineResetHandler;

        #[cfg(feature = "block2")]
        /// Setter for [`resetHandler`][Self::resetHandler].
        ///
        /// # Safety
        ///
        /// `reset_handler` must be a valid pointer.
        #[unsafe(method(setResetHandler:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setResetHandler(&self, reset_handler: CHHapticEngineResetHandler);

        /// If set to YES, the CHHapticEngine will ignore all events of type CHHapticEventTypeAudio and play only haptic events.
        ///
        /// This behavior change will only take effect after the engine is stopped and restarted.
        /// The default is NO.
        #[unsafe(method(playsHapticsOnly))]
        #[unsafe(method_family = none)]
        pub unsafe fn playsHapticsOnly(&self) -> bool;

        /// Setter for [`playsHapticsOnly`][Self::playsHapticsOnly].
        #[unsafe(method(setPlaysHapticsOnly:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setPlaysHapticsOnly(&self, plays_haptics_only: bool);

        /// If set to YES, the CHHapticEngine will ignore all events of type CHHapticEventTypeHaptic and play only audio events.
        ///
        /// This behavior change will only take effect after the engine is stopped and restarted.
        /// The default is NO.
        #[unsafe(method(playsAudioOnly))]
        #[unsafe(method_family = none)]
        pub unsafe fn playsAudioOnly(&self) -> bool;

        /// Setter for [`playsAudioOnly`][Self::playsAudioOnly].
        #[unsafe(method(setPlaysAudioOnly:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setPlaysAudioOnly(&self, plays_audio_only: bool);

        /// When set to YES, the CHHapticEngine mutes audio playback from its players.
        ///
        /// Default is NO.
        #[unsafe(method(isMutedForAudio))]
        #[unsafe(method_family = none)]
        pub unsafe fn isMutedForAudio(&self) -> bool;

        /// Setter for [`isMutedForAudio`][Self::isMutedForAudio].
        #[unsafe(method(setIsMutedForAudio:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setIsMutedForAudio(&self, is_muted_for_audio: bool);

        /// When set to YES, the CHHapticEngine mutes haptic playback from its players.
        ///
        /// Default is NO.
        #[unsafe(method(isMutedForHaptics))]
        #[unsafe(method_family = none)]
        pub unsafe fn isMutedForHaptics(&self) -> bool;

        /// Setter for [`isMutedForHaptics`][Self::isMutedForHaptics].
        #[unsafe(method(setIsMutedForHaptics:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setIsMutedForHaptics(&self, is_muted_for_haptics: bool);

        /// When auto shutdown is enabled, the haptic engine can start and stop the hardware dynamically,
        /// to conserve power.
        ///
        /// To conserve power, it is advised that the client stop the haptic engine when not in use.
        /// But when auto shutdown is enabled, the haptic engine will stop the hardware if it was running
        /// idle for a certain duration, and restart it later when required.
        /// Note that, because this operation is dynamic, it may affect the start times of the pattern players
        /// (e.g. `CHHapticPatternplayer`), if the engine has to resume from its shutdown state.
        ///
        /// This feature is disabled by default, but the client can enable it if needed.
        #[unsafe(method(isAutoShutdownEnabled))]
        #[unsafe(method_family = none)]
        pub unsafe fn isAutoShutdownEnabled(&self) -> bool;

        /// Setter for [`isAutoShutdownEnabled`][Self::isAutoShutdownEnabled].
        #[unsafe(method(setAutoShutdownEnabled:))]
        #[unsafe(method_family = none)]
        pub unsafe fn setAutoShutdownEnabled(&self, auto_shutdown_enabled: bool);

        #[unsafe(method(init))]
        #[unsafe(method_family = init)]
        pub unsafe fn init(this: Allocated<Self>) -> Option<Retained<Self>>;

        /// Create an instance of the CHHapticEngine.
        ///
        /// More than one instance may exist within a process.  Each will function independently of the others.
        /// CHHapticEngines created using this method will be associated with the device's internal haptics hardware system,
        /// if one exists.  For systems without internal haptics, this method will fail with the error `CHHapticErrorCodeNotSupported`.
        /// To access engine instances associated with external game controllers, see the GameController framework documentation
        /// for the `hapticEngines` property on the GCController class.
        #[unsafe(method(initAndReturnError:_))]
        #[unsafe(method_family = init)]
        pub unsafe fn initAndReturnError(
            this: Allocated<Self>,
        ) -> Result<Retained<Self>, Retained<NSError>>;

        #[cfg(feature = "objc2-avf-audio")]
        /// Create an instance of an CHHapticEngine and associate it with an audio session.  If 'audioSession' is nil,
        /// the engine will create its own.
        ///
        /// More than one instance may exist within a process.  Each will function independently of the others, but all
        /// CHHapticEngines which share an audio session will have identical audio behavior with regard to interruptions, etc.
        /// CHHapticEngines created using this method will be associated with the device's internal haptics hardware system,
        /// if one exists.  For systems without internal haptics, this method will fail with the error `CHHapticErrorCodeNotSupported`.
        /// To access engine instances associated with external game controllers, see the GameController framework documentation
        /// for the `hapticEngines` property on the GCController class.
        #[unsafe(method(initWithAudioSession:error:_))]
        #[unsafe(method_family = init)]
        pub unsafe fn initWithAudioSession_error(
            this: Allocated<Self>,
            audio_session: Option<&AVAudioSession>,
        ) -> Result<Retained<Self>, Retained<NSError>>;

        #[cfg(feature = "block2")]
        /// Asynchronously start the engine. The handler will be called when the operation completes.
        ///
        /// The handler is guaranteed to be called on either success or failure.
        ///
        /// # Safety
        ///
        /// `completion_handler` must be a valid pointer or null.
        #[unsafe(method(startWithCompletionHandler:))]
        #[unsafe(method_family = none)]
        pub unsafe fn startWithCompletionHandler(
            &self,
            completion_handler: CHHapticCompletionHandler,
        );

        /// Start the engine and block until the engine has started.
        ///
        /// This method will return NO upon failure, and outError will be set to a valid NSError describing the error.
        #[unsafe(method(startAndReturnError:_))]
        #[unsafe(method_family = none)]
        pub unsafe fn startAndReturnError(&self) -> Result<(), Retained<NSError>>;

        #[cfg(feature = "block2")]
        /// Asynchronously stop the engine.  The handler will be called when the operation completes.
        ///
        /// The handler is guaranteed to be called on either success or failure.
        ///
        /// # Safety
        ///
        /// `completion_handler` must be a valid pointer or null.
        #[unsafe(method(stopWithCompletionHandler:))]
        #[unsafe(method_family = none)]
        pub unsafe fn stopWithCompletionHandler(
            &self,
            completion_handler: CHHapticCompletionHandler,
        );

        #[cfg(feature = "block2")]
        /// Tell the engine to asynchronously call the passed-in handler when all active pattern players associated
        /// with this engine have stopped.
        ///
        /// Parameter `finishedHandler`: The block that will be called asynchronously.  The return value of this block determines the action the
        /// engine will take when the block finishes (see `CHHapticEngineFinishedHandler`).
        ///
        /// If additional players are started after this call is made, they will delay the callback.
        /// If no players are active or the engine is stopped, the callback will happen immediately.
        ///
        /// # Safety
        ///
        /// `finished_handler` must be a valid pointer.
        #[unsafe(method(notifyWhenPlayersFinished:))]
        #[unsafe(method_family = none)]
        pub unsafe fn notifyWhenPlayersFinished(
            &self,
            finished_handler: CHHapticEngineFinishedHandler,
        );

        #[cfg(all(feature = "CHHapticPattern", feature = "CHHapticPatternPlayer"))]
        /// Factory method for creating a CHHapticPatternPlayer from a CHHapticPattern.
        ///
        /// Parameter `pattern`: The pattern to be played.
        #[unsafe(method(createPlayerWithPattern:error:_))]
        #[unsafe(method_family = none)]
        pub unsafe fn createPlayerWithPattern_error(
            &self,
            pattern: &CHHapticPattern,
        ) -> Result<Retained<ProtocolObject<dyn CHHapticPatternPlayer>>, Retained<NSError>>;

        #[cfg(all(feature = "CHHapticPattern", feature = "CHHapticPatternPlayer"))]
        /// Factory method for creating a CHHapticAdvancedPatternPlayer from a CHHapticPattern.
        ///
        /// Parameter `pattern`: The pattern to be played.
        #[unsafe(method(createAdvancedPlayerWithPattern:error:_))]
        #[unsafe(method_family = none)]
        pub unsafe fn createAdvancedPlayerWithPattern_error(
            &self,
            pattern: &CHHapticPattern,
        ) -> Result<Retained<ProtocolObject<dyn CHHapticAdvancedPatternPlayer>>, Retained<NSError>>;

        #[cfg(feature = "CHHapticEvent")]
        /// Unregister and remove a previously-registered audio resource.
        ///
        /// Parameter `resourceID`: The resource ID that was returned when the resource was registered.
        ///
        /// Parameter `outError`: If the unregister operation fails, this will be set to a valid NSError describing the error.
        #[unsafe(method(unregisterAudioResource:error:_))]
        #[unsafe(method_family = none)]
        pub unsafe fn unregisterAudioResource_error(
            &self,
            resource_id: CHHapticAudioResourceID,
        ) -> Result<(), Retained<NSError>>;

        /// Simple one-shot call to play a pattern specified by a URL.
        ///
        /// Parameter `fileURL`: The URL of the file containing a haptic/audio pattern dictionary.
        ///
        /// Parameter `outError`: If the operation fails, this will be set to a valid NSError describing the error.
        ///
        /// The engine should be started prior to calling this method if low latency is desired. If this is not done,
        /// this method will start it, which can cause a significant delay.
        #[unsafe(method(playPatternFromURL:error:_))]
        #[unsafe(method_family = none)]
        pub unsafe fn playPatternFromURL_error(
            &self,
            file_url: &NSURL,
        ) -> Result<(), Retained<NSError>>;

        /// Simple one-shot call to play a pattern specified by NSData.
        ///
        /// Parameter `data`: The NSData containing a haptic/audio pattern dictionary.
        ///
        /// Parameter `outError`: If the operation fails, this will be set to a valid NSError describing the error.
        ///
        /// The engine should be started prior to calling this method if low latency is desired. If this is not done,
        /// this method will start it, which can cause a significant delay.
        #[unsafe(method(playPatternFromData:error:_))]
        #[unsafe(method_family = none)]
        pub unsafe fn playPatternFromData_error(
            &self,
            data: &NSData,
        ) -> Result<(), Retained<NSError>>;
    );
}

/// Methods declared on superclass `NSObject`.
impl CHHapticEngine {
    extern_methods!(
        #[unsafe(method(new))]
        #[unsafe(method_family = new)]
        pub unsafe fn new() -> Retained<Self>;
    );
}