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
#![allow(clippy::unnecessary_cast)]

use core_foundation::base::{OSStatus, TCFType};
use core_foundation::string::{CFString, CFStringRef};

use coremidi_sys::{
    MIDIIOErrorNotification, MIDINotification, MIDIObjectAddRemoveNotification,
    MIDIObjectPropertyChangeNotification,
};

use crate::any_object::AnyObject;
use crate::device::Device;
use crate::object::Object;

#[derive(Debug, PartialEq)]
pub struct AddedRemovedInfo {
    pub parent: AnyObject,
    pub child: AnyObject,
}

#[derive(Debug, PartialEq)]
pub struct PropertyChangedInfo {
    pub object: AnyObject,
    pub property_name: String,
}

#[derive(Debug, PartialEq)]
pub struct IoErrorInfo {
    pub driver_device: Device,
    pub error_code: OSStatus,
}

/// A message describing a system state change.
/// See [MIDINotification](https://developer.apple.com/documentation/coremidi/midinotification).
///
#[derive(Debug, PartialEq)]
pub enum Notification {
    SetupChanged,
    ObjectAdded(AddedRemovedInfo),
    ObjectRemoved(AddedRemovedInfo),
    PropertyChanged(PropertyChangedInfo),
    ThruConnectionsChanged,
    SerialPortOwnerChanged,
    IoError(IoErrorInfo),
}

impl Notification {
    fn try_from_object_added_removed(
        notification: &MIDINotification,
    ) -> Result<Notification, OSStatus> {
        let add_remove_notification =
            unsafe { &*(notification as *const _ as *const MIDIObjectAddRemoveNotification) };
        let parent = AnyObject::create(
            add_remove_notification.parentType,
            add_remove_notification.parent,
        );
        let child = AnyObject::create(
            add_remove_notification.childType,
            add_remove_notification.child,
        );
        if let Some((parent, child)) = parent.zip(child) {
            let info = AddedRemovedInfo { parent, child };
            match notification.messageID as ::std::os::raw::c_uint {
                coremidi_sys::kMIDIMsgObjectAdded => Ok(Notification::ObjectAdded(info)),
                coremidi_sys::kMIDIMsgObjectRemoved => Ok(Notification::ObjectRemoved(info)),
                _ => unreachable!(),
            }
        } else {
            Err(notification.messageID as OSStatus)
        }
    }

    fn try_from_property_changed(notification: &MIDINotification) -> Result<Notification, i32> {
        let property_changed_notification =
            unsafe { &*(notification as *const _ as *const MIDIObjectPropertyChangeNotification) };
        let maybe_object = AnyObject::create(
            property_changed_notification.objectType,
            property_changed_notification.object,
        );
        if let Some(object) = maybe_object {
            let property_name = {
                let name_ref: CFStringRef = property_changed_notification.propertyName;
                let name: CFString = unsafe { TCFType::wrap_under_get_rule(name_ref) };
                name.to_string()
            };
            let property_changed_info = PropertyChangedInfo {
                object,
                property_name,
            };
            Ok(Notification::PropertyChanged(property_changed_info))
        } else {
            Err(notification.messageID as i32)
        }
    }

    fn from_io_error(notification: &MIDINotification) -> Notification {
        let io_error_notification =
            unsafe { &*(notification as *const _ as *const MIDIIOErrorNotification) };
        let io_error_info = IoErrorInfo {
            driver_device: Device {
                object: Object(io_error_notification.driverDevice),
            },
            error_code: io_error_notification.errorCode,
        };
        Notification::IoError(io_error_info)
    }
}

impl TryFrom<&MIDINotification> for Notification {
    type Error = OSStatus;

    fn try_from(notification: &MIDINotification) -> Result<Self, Self::Error> {
        match notification.messageID as ::std::os::raw::c_uint {
            coremidi_sys::kMIDIMsgSetupChanged => Ok(Notification::SetupChanged),
            coremidi_sys::kMIDIMsgObjectAdded | coremidi_sys::kMIDIMsgObjectRemoved => {
                Self::try_from_object_added_removed(notification)
            }
            coremidi_sys::kMIDIMsgPropertyChanged => Self::try_from_property_changed(notification),
            coremidi_sys::kMIDIMsgThruConnectionsChanged => {
                Ok(Notification::ThruConnectionsChanged)
            }
            coremidi_sys::kMIDIMsgSerialPortOwnerChanged => {
                Ok(Notification::SerialPortOwnerChanged)
            }
            coremidi_sys::kMIDIMsgIOError => Ok(Self::from_io_error(notification)),
            unknown => Err(unknown as OSStatus),
        }
    }
}

#[cfg(test)]
mod tests {

    use core_foundation::base::{OSStatus, TCFType};
    use core_foundation::string::CFString;

    use coremidi_sys::{
        MIDIIOErrorNotification, MIDINotification, MIDINotificationMessageID,
        MIDIObjectAddRemoveNotification, MIDIObjectPropertyChangeNotification, MIDIObjectRef,
    };

    use crate::any_object::AnyObject;
    use crate::device::Device;
    use crate::notifications::{AddedRemovedInfo, IoErrorInfo, Notification, PropertyChangedInfo};
    use crate::object::Object;

    #[test]
    fn notification_from_error() {
        let notification_raw = MIDINotification {
            messageID: 0xffff as MIDINotificationMessageID,
            messageSize: 8,
        };

        let notification = Notification::try_from(&notification_raw);

        assert!(notification.is_err());
        assert_eq!(notification.err().unwrap(), 0xffff as i32);
    }

    #[test]
    fn notification_from_setup_changed() {
        let notification_raw = MIDINotification {
            messageID: coremidi_sys::kMIDIMsgSetupChanged as MIDINotificationMessageID,
            messageSize: 8,
        };

        let notification = Notification::try_from(&notification_raw);

        assert!(notification.is_ok());
        assert_eq!(notification.unwrap(), Notification::SetupChanged);
    }

    #[test]
    fn notification_from_object_added() {
        let notification_raw = MIDIObjectAddRemoveNotification {
            messageID: coremidi_sys::kMIDIMsgObjectAdded as MIDINotificationMessageID,
            messageSize: 24,
            parent: 1 as MIDIObjectRef,
            parentType: coremidi_sys::kMIDIObjectType_Device,
            child: 2 as MIDIObjectRef,
            childType: coremidi_sys::kMIDIObjectType_Other,
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_ok());

        let info = AddedRemovedInfo {
            parent: AnyObject::Device(Device::new(1)),
            child: AnyObject::Other(Object(2)),
        };

        assert_eq!(notification.unwrap(), Notification::ObjectAdded(info));
    }

    #[test]
    fn notification_from_object_removed() {
        let notification_raw = MIDIObjectAddRemoveNotification {
            messageID: coremidi_sys::kMIDIMsgObjectRemoved as MIDINotificationMessageID,
            messageSize: 24,
            parent: 1 as MIDIObjectRef,
            parentType: coremidi_sys::kMIDIObjectType_Device,
            child: 2 as MIDIObjectRef,
            childType: coremidi_sys::kMIDIObjectType_Other,
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_ok());

        let info = AddedRemovedInfo {
            parent: AnyObject::Device(Device::new(1)),
            child: AnyObject::Other(Object(2)),
        };

        assert_eq!(notification.unwrap(), Notification::ObjectRemoved(info));
    }

    #[test]
    fn notification_from_object_added_removed_err() {
        let notification_raw = MIDIObjectAddRemoveNotification {
            messageID: coremidi_sys::kMIDIMsgObjectAdded as MIDINotificationMessageID,
            messageSize: 24,
            parent: 1 as MIDIObjectRef,
            parentType: coremidi_sys::kMIDIObjectType_Device,
            child: 2 as MIDIObjectRef,
            childType: 0xffff,
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_err());
        assert_eq!(
            notification.err().unwrap(),
            coremidi_sys::kMIDIMsgObjectAdded as i32
        );

        let notification_raw = MIDIObjectAddRemoveNotification {
            messageID: coremidi_sys::kMIDIMsgObjectRemoved as MIDINotificationMessageID,
            messageSize: 24,
            parent: 1 as MIDIObjectRef,
            parentType: 0xffff,
            child: 2 as MIDIObjectRef,
            childType: coremidi_sys::kMIDIObjectType_Device,
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_err());
        assert_eq!(
            notification.err().unwrap(),
            coremidi_sys::kMIDIMsgObjectRemoved as i32
        );
    }

    #[test]
    fn notification_from_property_changed() {
        let name = CFString::new("name");
        let notification_raw = MIDIObjectPropertyChangeNotification {
            messageID: coremidi_sys::kMIDIMsgPropertyChanged as MIDINotificationMessageID,
            messageSize: 24,
            object: 1 as MIDIObjectRef,
            objectType: coremidi_sys::kMIDIObjectType_Device,
            propertyName: name.as_concrete_TypeRef(),
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_ok());

        let info = PropertyChangedInfo {
            object: AnyObject::Device(Device::new(1)),
            property_name: "name".to_string(),
        };

        assert_eq!(notification.unwrap(), Notification::PropertyChanged(info));
    }

    #[test]
    fn notification_from_property_changed_error() {
        let name = CFString::new("name");
        let notification_raw = MIDIObjectPropertyChangeNotification {
            messageID: coremidi_sys::kMIDIMsgPropertyChanged as MIDINotificationMessageID,
            messageSize: 24,
            object: 1 as MIDIObjectRef,
            objectType: 0xffff,
            propertyName: name.as_concrete_TypeRef(),
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_err());
        assert_eq!(
            notification.err().unwrap(),
            coremidi_sys::kMIDIMsgPropertyChanged as i32
        );
    }

    #[test]
    fn notification_from_thru_connections_changed() {
        let notification_raw = MIDINotification {
            messageID: coremidi_sys::kMIDIMsgThruConnectionsChanged as MIDINotificationMessageID,
            messageSize: 8,
        };

        let notification = Notification::try_from(&notification_raw);

        assert!(notification.is_ok());
        assert_eq!(notification.unwrap(), Notification::ThruConnectionsChanged);
    }

    #[test]
    fn notification_from_serial_port_owner_changed() {
        let notification_raw = MIDINotification {
            messageID: coremidi_sys::kMIDIMsgSerialPortOwnerChanged as MIDINotificationMessageID,
            messageSize: 8,
        };

        let notification = Notification::try_from(&notification_raw);

        assert!(notification.is_ok());
        assert_eq!(notification.unwrap(), Notification::SerialPortOwnerChanged);
    }

    #[test]
    fn notification_from_io_error() {
        let notification_raw = MIDIIOErrorNotification {
            messageID: coremidi_sys::kMIDIMsgIOError as MIDINotificationMessageID,
            messageSize: 16,
            driverDevice: 1 as MIDIObjectRef,
            errorCode: 123 as OSStatus,
        };

        let notification = Notification::try_from(unsafe {
            &*(&notification_raw as *const _ as *const MIDINotification)
        });

        assert!(notification.is_ok());

        let info = IoErrorInfo {
            driver_device: Device { object: Object(1) },
            error_code: 123 as OSStatus,
        };

        assert_eq!(notification.unwrap(), Notification::IoError(info));
    }
}