SDL: Don't enumerate HID devices on macOS if we don't have input monitoring permissions

From 172865ff137532123ec06177119be163ba1811f5 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 16 Sep 2022 09:16:18 -0700
Subject: [PATCH] Don't enumerate HID devices on macOS if we don't have input
 monitoring permissions

Unfortunately the only way to detect this is to actually try opening a device, so we wait until the application tries, and then stop enumerating afterwards.

Fixes https://github.com/libsdl-org/SDL/issues/5781
---
 src/hidapi/mac/hid.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/src/hidapi/mac/hid.c b/src/hidapi/mac/hid.c
index 35ca3803745..445de68231b 100644
--- a/src/hidapi/mac/hid.c
+++ b/src/hidapi/mac/hid.c
@@ -130,6 +130,7 @@ struct hid_device_list_node
 
 static 	IOHIDManagerRef hid_mgr = 0x0;
 static 	struct hid_device_list_node *device_list = 0x0;
+static	int hid_input_monitoring_denied = 0;
 
 static hid_device *new_hid_device(void)
 {
@@ -521,7 +522,11 @@ struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
 	/* Set up the HID Manager if it hasn't been done */
 	if (hid_init() < 0)
 		return NULL;
-	
+
+	/* If we don't have permission do open devices, don't enumerate them */
+	if (hid_input_monitoring_denied)
+		return NULL;
+
 	/* give the IOHIDManager a chance to update itself */
 	process_pending_events();
 	
@@ -862,6 +867,11 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path, int bExclusive)
 				
 				return dev;
 			}
+			else if (ret == kIOReturnNotPermitted) {
+				/* This application doesn't have input monitoring permissions */
+				hid_input_monitoring_denied = 1;
+				goto return_error;
+			}
 			else {
 				goto return_error;
 			}