// SPDX-FileCopyrightText: Copyright 2026 Gloria Goertz, Mireille Meyer // SPDX-License-Identifier: BSD-2-Clause #include #include #include namespace atom::IO { Result> HIDDevice::Open(const u16 vendorId, const u16 productId) { IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDManagerOptionIndependentDevices); ATOM_ASSERT(manager != nullptr, "IOHIDManagerCreate failed"); IOReturn result = IOHIDManagerOpen(manager, kIOHIDManagerOptionIndependentDevices); switch (result) { case kIOReturnSuccess: { break; } // TODO(Gloria): implement more errors default: { ATOM_PANIC("IOHIDManagerOpen failed with {}", result); } } CFMutableDictionaryRef infoDict = CFDictionaryCreateMutable(kCFAllocatorDefault, kIOHIDOptionsTypeNone, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFNumberRef vendor = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &vendorId); CFNumberRef product = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &productId); CFDictionarySetValue(infoDict, CFSTR(kIOHIDVendorIDKey), vendor); CFDictionarySetValue(infoDict, CFSTR(kIOHIDProductIDKey), product); IOHIDManagerSetDeviceMatching(manager, infoDict); IOHIDManagerSetDispatchQueue(manager, dispatch_get_main_queue()); IOHIDManagerActivate(manager); Implementation::MacOSHIDDevice::UpdateLoop(); CFRelease(vendor); CFRelease(product); CFRelease(infoDict); CFSetRef deviceSet = IOHIDManagerCopyDevices(manager); if (deviceSet == nullptr) { return Status::NotFound; } const usize deviceCount = CFSetGetCount(deviceSet); std::vector devices {deviceCount}; CFSetGetValues(deviceSet, const_cast(reinterpret_cast(devices.data()))); // I love Apple. CFRelease(deviceSet); IOHIDDeviceRef deviceRef = devices[0]; result = IOHIDDeviceOpen(deviceRef, 0); switch (result) { case kIOReturnSuccess: { break; } // TODO(Gloria): implement more errors default: { ATOM_PANIC("IOHIDDeviceOpen failed with {}", result); } } IOHIDDeviceSetDispatchQueue(deviceRef, dispatch_get_main_queue()); auto transport = static_cast(IOHIDDeviceGetProperty(deviceRef, CFSTR(kIOHIDTransportKey))); ConnectionType type = ConnectionType::USB; if (CFStringCompare(transport, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) { // ... } else if (CFStringCompare(transport, CFSTR(kIOHIDTransportBluetoothValue), 0) == kCFCompareEqualTo || CFStringCompare(transport, CFSTR(kIOHIDTransportBluetoothLowEnergyValue), 0) == kCFCompareEqualTo) { type = ConnectionType::Bluetooth; } else { // TODO(Gloria): dispatch warning } auto device = new Implementation::MacOSHIDDevice(type, Implementation::MacOSHIDDevice::GetCapabilitiesImpl(deviceRef), deviceRef); IOHIDDeviceRegisterRemovalCallback(device->m_device, Implementation::MacOSHIDDevice::DeviceRemovedCallback, device); IOHIDDeviceRegisterInputReportCallback(device->m_device, device->m_inputData.get(), device->m_capabilities.InputReportSize, Implementation::MacOSHIDDevice::InputReportCallback, device); IOHIDDeviceActivate(device->m_device); Implementation::MacOSHIDDevice::UpdateLoop(); result = IOHIDManagerClose(manager, 0); switch (result) { case kIOReturnSuccess: { break; } // TODO(Gloria): implement more errors default: { ATOM_PANIC("IOHIDManagerClose failed"); } } return std::unique_ptr(device); } namespace Implementation { MacOSHIDDevice::~MacOSHIDDevice() { IOHIDDeviceCancel(m_device); UpdateLoop(); IOHIDDeviceClose(m_device, 0); } // TODO(Gloria): Check if we got too few/many bytes Status MacOSHIDDevice::Read(std::span data, const u32 milliseconds) { if (!m_stillValid) { return Status::Expired; } if (data.size_bytes() == 0 || data.size_bytes() > m_capabilities.InputReportSize) { return Status::InvalidParameters; } const bool acquired = m_inputArrived.try_acquire_for(std::chrono::milliseconds(milliseconds)); if (!acquired) { return Status::Timeout; } { std::lock_guard guard { m_inputMutex }; std::memcpy(data.data(), m_inputData.get(), data.size_bytes()); } return Status::Success; } Status MacOSHIDDevice::ReadFeature(std::span data, const u32 milliseconds) { if (!m_stillValid) { return Status::Expired; } if (data.size_bytes() == 0 || data.size_bytes() > m_capabilities.FeatureReportSize) { return Status::InvalidParameters; } CFIndex reportSize = data.size_bytes(); const IOReturn result = IOHIDDeviceGetReportWithCallback(m_device, kIOHIDReportTypeFeature, data.data()[0], data.data(), &reportSize, milliseconds, FeatureReportCallback, this); switch (result) { case kIOReturnSuccess: { break; } // TODO(Gloria): implement more errors default: { ATOM_PANIC("IOHIDDeviceGetReportWithCallback failed"); } } const bool acquired = m_featureArrived.try_acquire_for(std::chrono::milliseconds(milliseconds)); if (!acquired) { return Status::Timeout; } return Status::Success; } Status MacOSHIDDevice::Write(std::span data, const u32 milliseconds) { if (!m_stillValid) { return Status::Expired; } if (data.size_bytes() == 0 || data.size_bytes() > m_capabilities.OutputReportSize || milliseconds == 0) { return Status::InvalidParameters; } const IOReturn result = IOHIDDeviceSetReportWithCallback(m_device, kIOHIDReportTypeOutput, data.data()[0], data.data(), data.size_bytes(), milliseconds, nullptr, nullptr); switch (result) { case kIOReturnSuccess: { break; } // TODO(Gloria): implement more errors default: { ATOM_PANIC("IOHIDDeviceSetReportWithCallback failed"); } } return Status::Success; } MacOSHIDDevice::MacOSHIDDevice(ConnectionType t, Capabilities c, IOHIDDeviceRef d) : HIDDevice{t, c}, m_device{d}, m_stillValid{true}, m_inputArrived{0}, m_featureArrived{0} { m_inputData = std::make_unique(m_capabilities.InputReportSize); } HIDDevice::Capabilities MacOSHIDDevice::GetCapabilitiesImpl(IOHIDDeviceRef device) { auto inputSizeNumber = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDMaxInputReportSizeKey))); auto outputSizeNumber = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDMaxOutputReportSizeKey))); auto featureSizeNumber = static_cast(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDMaxFeatureReportSizeKey))); ATOM_ASSERT(inputSizeNumber != nullptr, "IOHIDDeviceGetProperty(kIOHIDMaxInputReportSizeKey) failed"); ATOM_ASSERT(outputSizeNumber != nullptr, "IOHIDDeviceGetProperty(kIOHIDMaxOutputReportSizeKey) failed"); ATOM_ASSERT(featureSizeNumber != nullptr, "IOHIDDeviceGetProperty(kIOHIDMaxFeatureReportSizeKey) failed"); u16 inputSize = 0; Boolean result = CFNumberGetValue(inputSizeNumber, kCFNumberShortType, &inputSize); ATOM_ASSERT(result == TRUE, "CFNumberGetValue(kIOHIDMaxInputReportSizeKey) failed"); u16 outputSize = 0; result = CFNumberGetValue(outputSizeNumber, kCFNumberShortType, &outputSize); ATOM_ASSERT(result == TRUE, "CFNumberGetValue(kIOHIDMaxInputReportSizeKey) failed"); u16 featureSize = 0; result = CFNumberGetValue(featureSizeNumber, kCFNumberShortType, &featureSize); ATOM_ASSERT(result == TRUE, "CFNumberGetValue(kIOHIDMaxInputReportSizeKey) failed"); return Capabilities { .InputReportSize = inputSize, .OutputReportSize = outputSize, .FeatureReportSize = featureSize }; } void MacOSHIDDevice::DeviceRemovedCallback(void* context, IOReturn result, void* sender) { (void)sender; ATOM_ASSERT(result == kIOReturnSuccess, "result != kIOReturnSuccess (is {})", result); auto device = static_cast(context); device->m_stillValid = false; } void MacOSHIDDevice::InputReportCallback(void* context, IOReturn result, void* sender, IOHIDReportType type, u32 id, u8* data, CFIndex length) { (void)sender; (void)id; ATOM_ASSERT(context != nullptr, "context is nullptr"); ATOM_ASSERT(type == kIOHIDReportTypeInput, "type != kIOHIDReportTypeInput (is {})", static_cast(type)); ATOM_ASSERT(result == kIOReturnSuccess, "result != kIOReturnSuccess (is {})", result); auto device = static_cast(context); ATOM_ASSERT(length <= device->m_capabilities.InputReportSize, "length !<= {} (is {})", device->m_capabilities.InputReportSize, length); { std::lock_guard guard { device->m_inputMutex }; std::memcpy(device->m_inputData.get(), data, length); } device->m_inputArrived.release(); } void MacOSHIDDevice::FeatureReportCallback(void* context, IOReturn result, void* sender, IOHIDReportType type, u32 id, u8* data, CFIndex length) { (void)sender; (void)type; (void)id; ATOM_ASSERT(context != nullptr, "context is nullptr"); ATOM_ASSERT(type == kIOHIDReportTypeFeature, "type != kIOHIDReportTypeFeature (is {})", static_cast(type)); ATOM_ASSERT(result == kIOReturnSuccess, "result != kIOReturnSuccess (is {})", result); auto device = static_cast(context); ATOM_ASSERT(length <= device->m_capabilities.FeatureReportSize, "length !<= {} (is {})", device->m_capabilities.FeatureReportSize, length); device->m_featureArrived.release(); // Data is copied by IOHIDDeviceGetReportWithCallback } void MacOSHIDDevice::UpdateLoop() { while (true) { const CFRunLoopRunResult runResult = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1 * MSEC_PER_SEC, FALSE); if (runResult == kCFRunLoopRunFinished || runResult == kCFRunLoopRunTimedOut) { break; } } } } }