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
//! Playing the effect on the haptic device.

use crate::{bind, Result, Sdl, SdlError};

use super::{effect::HapticEffect, Haptic};

/// An haptic effect but pending to play.
#[derive(Debug)]
pub struct PendingEffect<'haptic> {
    id: i32,
    haptic: &'haptic Haptic,
}

impl<'haptic> PendingEffect<'haptic> {
    pub(super) fn new(id: i32, haptic: &'haptic Haptic) -> Self {
        Self { id, haptic }
    }

    /// Updates the effect with a new effect.
    ///
    /// # Errors
    ///
    /// Returns `Err` if failed to update the properties.
    pub fn update(&self, effect: &HapticEffect) -> Result<()> {
        let mut raw = effect.clone().into_raw();
        let ret =
            unsafe { bind::SDL_HapticUpdateEffect(self.haptic.ptr.as_ptr(), self.id, &mut raw) };
        if ret < 0 {
            Err(SdlError::Others { msg: Sdl::error() })
        } else {
            Ok(())
        }
    }

    /// Starts to run the effect. If `iterations` is `None`, the effect repeats over and over indefinitely.
    ///
    /// # Errors
    ///
    /// Returns `Err` if failed to run the effect on the device.
    pub fn run(self, iterations: Option<u32>) -> Result<PlayingEffect<'haptic>> {
        let ret = unsafe {
            bind::SDL_HapticRunEffect(
                self.haptic.ptr.as_ptr(),
                self.id,
                iterations.unwrap_or(bind::SDL_HAPTIC_INFINITY),
            )
        };
        if ret < 0 {
            Err(SdlError::Others { msg: Sdl::error() })
        } else {
            Ok(PlayingEffect {
                id: self.id,
                haptic: self.haptic,
            })
        }
    }

    /// Drops the effect manually.
    pub fn destroy(self) {
        unsafe { bind::SDL_HapticDestroyEffect(self.haptic.ptr.as_ptr(), self.id) }
    }
}

/// A playing haptic effect.
#[derive(Debug)]
pub struct PlayingEffect<'haptic> {
    id: i32,
    haptic: &'haptic Haptic,
}

impl<'haptic> PlayingEffect<'haptic> {
    /// Stops playing the effect.
    ///
    /// # Errors
    ///
    /// Returns `Err` if failed to stop the effect on the device.
    pub fn stop(self) -> Result<PendingEffect<'haptic>> {
        let ret = unsafe { bind::SDL_HapticStopEffect(self.haptic.ptr.as_ptr(), self.id) };
        if ret < 0 {
            Err(SdlError::Others { msg: Sdl::error() })
        } else {
            Ok(PendingEffect {
                id: self.id,
                haptic: self.haptic,
            })
        }
    }

    /// Drops the effect manually.
    pub fn destroy(self) {
        unsafe { bind::SDL_HapticDestroyEffect(self.haptic.ptr.as_ptr(), self.id) }
    }
}