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
use { Event, Input, Motion };

/// Stores the touch state.
#[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Debug)]
pub enum Touch {
    /// The start of touch, for example
    /// a finger pressed down on a touch screen.
    Start,
    /// The move of touch, for example
    /// a finger moving while touching a touch screen.
    Move,
    /// The end of touch, for example
    /// taking a finger away from a touch screen.
    End,
    /// The cancel of touch, for example
    /// the window loses focus.
    Cancel,
}

/// Touch arguments
///
/// The `id` might be reused for different touches that do not overlap in time.
///
/// - Coordinates are normalized to support both touch screens and trackpads
/// - Supports both 2D and 3D touch
/// - The pressure direction vector should have maximum length 1
///
/// For 2D touch the pressure is pointed the z direction.
/// Use `.pressure()` to get the pressure magnitude.
#[derive(Copy, Clone, RustcDecodable, RustcEncodable, PartialEq, Debug)]
pub struct TouchArgs {
    /// A unique identifier for touch device.
    pub device: i64,
    /// A unique identifier for touch event.
    pub id: i64,
    /// The x coordinate of the touch position, normalized 0..1.
    pub x: f64,
    /// The y coordinate of the touch position, normalized 0..1.
    pub y: f64,
    /// The z coordinate of the touch position, normalized 0..1.
    pub z: f64,
    /// The x coordinate of the touch pressure direction.
    pub px: f64,
    /// The y coordinate of the touch pressure direction.
    pub py: f64,
    /// The z coordinate of the touch pressure direction.
    pub pz: f64,
    /// Whether the touch is in 3D.
    pub is_3d: bool,
    /// The touch state.
    pub touch: Touch,
}

impl TouchArgs {
    /// Creates arguments for 2D touch.
    pub fn new(
        device: i64,
        id: i64,
        pos: [f64; 2],
        pressure: f64,
        touch: Touch
    ) -> TouchArgs {
        TouchArgs {
            device: device,
            id: id,
            x: pos[0],
            y: pos[1],
            z: 0.0,
            is_3d: false,
            px: 0.0,
            py: 0.0,
            pz: pressure,
            touch: touch,
        }
    }

    /// Creates arguments for 3D touch.
    ///
    /// The pressure direction vector should have maximum length 1.
    pub fn new_3d(
        device: i64,
        id: i64,
        pos: [f64; 3],
        pressure: [f64; 3],
        touch: Touch
    ) -> TouchArgs {
        TouchArgs {
            device: device,
            id: id,
            x: pos[0],
            y: pos[1],
            z: pos[2],
            is_3d: true,
            px: pressure[0],
            py: pressure[1],
            pz: pressure[2],
            touch: touch,
        }
    }

    /// The position of the touch in 2D.
    pub fn position(&self) -> [f64; 2] {
        [self.x, self.y]
    }

    /// The position of the touch in 3D.
    pub fn position_3d(&self) -> [f64; 3] {
        [self.x, self.y, self.z]
    }

    /// The pressure magnitude, normalized 0..1.
    pub fn pressure(&self) -> f64 {
        (self.px * self.px + self.py * self.py + self.pz * self.pz).sqrt()
    }

    /// The pressure vector in 3D.
    pub fn pressure_3d(&self) -> [f64; 3] {
        [self.px, self.py, self.pz]
    }
}

/// When a touch is started, moved, ended or cancelled.
pub trait TouchEvent: Sized {
    /// Creates a touch event.
    fn from_touch_args(args: &TouchArgs, old_event: &Self) -> Option<Self>;
    /// Calls closure if this is a touch event.
    fn touch<U, F>(&self, f: F) -> Option<U>
        where F: FnMut(&TouchArgs) -> U;
    /// Returns touch arguments.
    fn touch_args(&self) -> Option<TouchArgs> {
        self.touch(|args| args.clone())
    }
}

/* TODO: Enable when specialization gets stable.
impl<T> TouchEvent for T where T: GenericEvent {
    fn from_touch_args(args: &TouchArgs, old_event: &Self) -> Option<Self> {
        GenericEvent::from_args(TOUCH, args as &Any, old_event)
    }

    fn touch<U, F>(&self, mut f: F) -> Option<U>
        where F: FnMut(&TouchArgs) -> U
    {
        if self.event_id() != TOUCH {
            return None;
        }
        self.with_args(|any| {
            if let Some(args) = any.downcast_ref::<TouchArgs>() {
                Some(f(args))
            } else {
                panic!("Expected TouchArgs")
            }
        })
    }
}
*/

impl TouchEvent for Input {
    fn from_touch_args(args: &TouchArgs, _old_event: &Self) -> Option<Self> {
        Some(Input::Move(Motion::Touch(*args)))
    }

    fn touch<U, F>(&self, mut f: F) -> Option<U>
        where F: FnMut(&TouchArgs) -> U
    {
        match *self {
            Input::Move(Motion::Touch(ref args)) => Some(f(args)),
            _ => None
        }
    }
}

impl<I: TouchEvent> TouchEvent for Event<I> {
    fn from_touch_args(args: &TouchArgs, old_event: &Self) -> Option<Self> {
        if let &Event::Input(ref old_input) = old_event {
            <I as TouchEvent>::from_touch_args(args, old_input)
                .map(|x| Event::Input(x))
        } else {
            None
        }
    }

    fn touch<U, F>(&self, f: F) -> Option<U>
        where F: FnMut(&TouchArgs) -> U
    {
        match *self {
            Event::Input(ref x) => x.touch(f),
            _ => None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_input_touch() {
        use super::super::{ Input, Motion };

        let pos = [0.0; 2];
        let e = Input::Move(Motion::Touch(
            TouchArgs::new(0, 0, pos, 1.0, Touch::Start)));
        let a: Option<Input> = TouchEvent::from_touch_args(
            &TouchArgs::new(0, 0, pos, 1.0, Touch::Start), &e);
        let b: Option<Input> = a.clone().unwrap().touch(|t|
            TouchEvent::from_touch_args(
                &TouchArgs::new(t.device, t.id, t.position(), t.pressure(), Touch::Start),
                a.as_ref().unwrap())).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn test_event_touch() {
        use Event;
        use super::super::{ Input, Motion };

        let pos = [0.0; 2];
        let e = Event::Input(Input::Move(Motion::Touch(
            TouchArgs::new(0, 0, pos, 1.0, Touch::Start))));
        let a: Option<Event> = TouchEvent::from_touch_args(
            &TouchArgs::new(0, 0, pos, 1.0, Touch::Start), &e);
        let b: Option<Event> = a.clone().unwrap().touch(|t|
            TouchEvent::from_touch_args(
                &TouchArgs::new(t.device, t.id, t.position(), t.pressure(), Touch::Start),
                a.as_ref().unwrap())).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn test_input_touch_3d() {
        use super::super::{ Input, Motion };

        let pos = [0.0; 3];
        let pressure = [0.0, 0.0, 1.0];
        let e = Input::Move(Motion::Touch(
            TouchArgs::new_3d(0, 0, pos, pressure, Touch::Start)));
        let a: Option<Input> = TouchEvent::from_touch_args(
            &TouchArgs::new_3d(0, 0, pos, pressure, Touch::Start), &e);
        let b: Option<Input> = a.clone().unwrap().touch(|t|
            TouchEvent::from_touch_args(
                &TouchArgs::new_3d(t.device, t.id, t.position_3d(), t.pressure_3d(), Touch::Start),
                a.as_ref().unwrap())).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn test_event_touch_3d() {
        use Event;
        use super::super::{ Input, Motion };

        let pos = [0.0; 3];
        let pressure = [0.0, 0.0, 1.0];
        let e = Event::Input(Input::Move(Motion::Touch(
            TouchArgs::new_3d(0, 0, pos, pressure, Touch::Start))));
        let a: Option<Event> = TouchEvent::from_touch_args(
            &TouchArgs::new_3d(0, 0, pos, pressure, Touch::Start), &e);
        let b: Option<Event> = a.clone().unwrap().touch(|t|
            TouchEvent::from_touch_args(
                &TouchArgs::new_3d(t.device, t.id, t.position_3d(), t.pressure_3d(), Touch::Start),
                a.as_ref().unwrap())).unwrap();
        assert_eq!(a, b);
    }
}