SDL: pen: Added Cocoa backend.

From b4ca15b654c6eaaa41657d6a2ad7ceed09000e0a Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Fri, 9 Aug 2024 02:27:37 -0400
Subject: [PATCH] pen: Added Cocoa backend.

---
 Xcode/SDL/SDL.xcodeproj/project.pbxproj |   7 +
 src/video/cocoa/SDL_cocoapen.h          |  32 +++++
 src/video/cocoa/SDL_cocoapen.m          | 177 ++++++++++++++++++++++++
 src/video/cocoa/SDL_cocoavideo.h        |   1 +
 src/video/cocoa/SDL_cocoavideo.m        |   3 +
 src/video/cocoa/SDL_cocoawindow.h       |   4 +
 src/video/cocoa/SDL_cocoawindow.m       |  22 +++
 test/testpen.c                          |   4 +-
 8 files changed, 248 insertions(+), 2 deletions(-)
 create mode 100644 src/video/cocoa/SDL_cocoapen.h
 create mode 100644 src/video/cocoa/SDL_cocoapen.m

diff --git a/Xcode/SDL/SDL.xcodeproj/project.pbxproj b/Xcode/SDL/SDL.xcodeproj/project.pbxproj
index e93e7d67e5e4f..3fa652201da23 100644
--- a/Xcode/SDL/SDL.xcodeproj/project.pbxproj
+++ b/Xcode/SDL/SDL.xcodeproj/project.pbxproj
@@ -524,6 +524,8 @@
 		F3FA5A242B59ACE000FEAD97 /* yuv_rgb_lsx.h in Headers */ = {isa = PBXBuildFile; fileRef = F3FA5A1B2B59ACE000FEAD97 /* yuv_rgb_lsx.h */; };
 		F3FA5A252B59ACE000FEAD97 /* yuv_rgb_common.h in Headers */ = {isa = PBXBuildFile; fileRef = F3FA5A1C2B59ACE000FEAD97 /* yuv_rgb_common.h */; };
 		FA73671D19A540EF004122E4 /* CoreVideo.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FA73671C19A540EF004122E4 /* CoreVideo.framework */; platformFilters = (ios, maccatalyst, macos, tvos, watchos, ); };
+		0000E5D7110DFF81FF660000 /* SDL_cocoapen.h in Headers */ = {isa = PBXBuildFile; fileRef = 00002F2F5496FA184A0F0000 /* SDL_cocoapen.h */; };
+		0000D5B526B85DE7AB1C0000 /* SDL_cocoapen.m in Sources */ = {isa = PBXBuildFile; fileRef = 0000CCA310B73A7B59910000 /* SDL_cocoapen.m */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXContainerItemProxy section */
@@ -1076,6 +1078,8 @@
 		F59C710600D5CB5801000001 /* SDL.info */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = SDL.info; sourceTree = "<group>"; };
 		F5A2EF3900C6A39A01000001 /* BUGS.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = BUGS.txt; path = ../../BUGS.txt; sourceTree = SOURCE_ROOT; };
 		FA73671C19A540EF004122E4 /* CoreVideo.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreVideo.framework; path = System/Library/Frameworks/CoreVideo.framework; sourceTree = SDKROOT; };
+		00002F2F5496FA184A0F0000 /* SDL_cocoapen.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SDL_cocoapen.h; path = SDL_cocoapen.h; sourceTree = "<group>"; };
+		0000CCA310B73A7B59910000 /* SDL_cocoapen.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SDL_cocoapen.m; path = SDL_cocoapen.m; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
 /* Begin PBXFrameworksBuildPhase section */
@@ -1676,6 +1680,8 @@
 				A7D8A68323E2513E00DCD162 /* SDL_cocoavulkan.m */,
 				A7D8A69223E2513E00DCD162 /* SDL_cocoawindow.h */,
 				A7D8A68423E2513E00DCD162 /* SDL_cocoawindow.m */,
+				00002F2F5496FA184A0F0000 /* SDL_cocoapen.h */,
+				0000CCA310B73A7B59910000 /* SDL_cocoapen.m */,
 			);
 			path = cocoa;
 			sourceTree = "<group>";
@@ -2908,6 +2914,7 @@
 				0000494CC93F3E624D3C0000 /* SDL_systime.c in Sources */,
 				000095FA1BDE436CF3AF0000 /* SDL_time.c in Sources */,
 				0000140640E77F73F1DF0000 /* SDL_dialog_utils.c in Sources */,
+				0000D5B526B85DE7AB1C0000 /* SDL_cocoapen.m in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
diff --git a/src/video/cocoa/SDL_cocoapen.h b/src/video/cocoa/SDL_cocoapen.h
new file mode 100644
index 0000000000000..61d8496f7d4df
--- /dev/null
+++ b/src/video/cocoa/SDL_cocoapen.h
@@ -0,0 +1,32 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "SDL_internal.h"
+
+#ifndef SDL_cocoapen_h_
+#define SDL_cocoapenm_h_
+
+#include "SDL_cocoavideo.h"
+
+extern int Cocoa_InitPen(SDL_VideoDevice *_this);
+extern SDL_bool Cocoa_HandlePenEvent(SDL_CocoaWindowData *_data, NSEvent *event);  // return SDL_FALSE if we didn't handle this event.
+extern void Cocoa_QuitPen(SDL_VideoDevice *_this);
+
+#endif /* SDL_cocoapen_h_ */
diff --git a/src/video/cocoa/SDL_cocoapen.m b/src/video/cocoa/SDL_cocoapen.m
new file mode 100644
index 0000000000000..24f5f5104bbda
--- /dev/null
+++ b/src/video/cocoa/SDL_cocoapen.m
@@ -0,0 +1,177 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "SDL_internal.h"
+
+#ifdef SDL_VIDEO_DRIVER_COCOA
+
+#include "SDL_cocoapen.h"
+#include "SDL_cocoavideo.h"
+
+#include "../../events/SDL_pen_c.h"
+
+int Cocoa_InitPen(SDL_VideoDevice *_this)
+{
+    return 0;
+}
+
+typedef struct Cocoa_PenHandle
+{
+    NSUInteger deviceid;
+    NSUInteger toolid;
+    SDL_PenID pen;
+    SDL_bool is_eraser;
+} Cocoa_PenHandle;
+
+typedef struct FindPenByDeviceAndToolIDData
+{
+    NSUInteger deviceid;
+    NSUInteger toolid;
+    void *handle;
+} FindPenByDeviceAndToolIDData;
+
+static SDL_bool FindPenByDeviceAndToolID(void *handle, void *userdata)
+{
+    const Cocoa_PenHandle *cocoa_handle = (const Cocoa_PenHandle *) handle;
+    FindPenByDeviceAndToolIDData *data = (FindPenByDeviceAndToolIDData *) userdata;
+
+    if (cocoa_handle->deviceid != data->deviceid) {
+        return SDL_FALSE;
+    } else if (cocoa_handle->toolid != data->toolid) {
+        return SDL_FALSE;
+    }
+    data->handle = handle;
+    return SDL_TRUE;
+}
+
+static Cocoa_PenHandle *Cocoa_FindPenByDeviceID(NSUInteger deviceid, NSUInteger toolid)
+{
+    FindPenByDeviceAndToolIDData data;
+    data.deviceid = deviceid;
+    data.toolid = toolid;
+    data.handle = NULL;
+    SDL_FindPenByCallback(FindPenByDeviceAndToolID, &data);
+    return (Cocoa_PenHandle *) data.handle;
+}
+
+static void Cocoa_HandlePenProximityEvent(SDL_CocoaWindowData *_data, NSEvent *event)
+{
+    const NSUInteger devid = [event deviceID];
+    const NSUInteger toolid = [event pointingDeviceID];
+
+    if (event.enteringProximity) {  // new pen coming!
+        const NSPointingDeviceType devtype = [event pointingDeviceType];
+        const SDL_bool is_eraser = (devtype == NSPointingDeviceTypeEraser);
+        const SDL_bool is_pen = (devtype == NSPointingDeviceTypePen);
+        if (!is_eraser && !is_pen) {
+            return;  // we ignore other things, which hopefully is right.
+        }
+
+        Cocoa_PenHandle *handle = (Cocoa_PenHandle *) SDL_calloc(1, sizeof (*handle));
+        if (!handle) {
+            return;  // oh well.
+        }
+
+        // Cocoa offers almost none of this information.
+        SDL_PenInfo peninfo;
+        SDL_zero(peninfo);
+        peninfo.capabilities = SDL_PEN_CAPABILITY_PRESSURE | SDL_PEN_CAPABILITY_ROTATION | SDL_PEN_CAPABILITY_XTILT | SDL_PEN_CAPABILITY_YTILT | (is_eraser ? SDL_PEN_CAPABILITY_ERASER : 0);
+        peninfo.max_tilt = 90.0f;
+        peninfo.num_buttons = 2;
+        peninfo.subtype = is_eraser ? SDL_PEN_TYPE_ERASER : SDL_PEN_TYPE_PEN;
+
+        handle->deviceid = devid;
+        handle->toolid = toolid;
+        handle->is_eraser = is_eraser;
+        handle->pen = SDL_AddPenDevice(Cocoa_GetEventTimestamp([event timestamp]), NULL, &peninfo, handle);
+        if (!handle->pen) {
+            SDL_free(handle);  // oh well.
+        }
+    } else {  // old pen leaving!
+        Cocoa_PenHandle *handle = Cocoa_FindPenByDeviceID(devid, toolid);
+        if (handle) {
+            SDL_RemovePenDevice(Cocoa_GetEventTimestamp([event timestamp]), handle->pen);
+            SDL_free(handle);
+        }
+    }
+}
+
+static void Cocoa_HandlePenPointEvent(SDL_CocoaWindowData *_data, NSEvent *event)
+{
+    const Uint32 timestamp = Cocoa_GetEventTimestamp([event timestamp]);
+    Cocoa_PenHandle *handle = Cocoa_FindPenByDeviceID([event deviceID], [event pointingDeviceID]);
+    if (!handle) {
+        return;
+    }
+
+    const SDL_PenID pen = handle->pen;
+    const NSEventButtonMask buttons = [event buttonMask];
+    const NSPoint tilt = [event tilt];
+    const NSPoint point = [event locationInWindow];
+    const SDL_bool is_touching = (buttons & NSEventButtonMaskPenTip) != 0;
+    SDL_Window *window = _data.window;
+
+    SDL_SendPenTouch(timestamp, pen, window, is_touching, handle->is_eraser ? 1 : 0);
+    SDL_SendPenMotion(timestamp, pen, window, (float) point.x, (float) (window->h - point.y));
+    SDL_SendPenButton(timestamp, pen, window, (buttons & NSEventButtonMaskPenLowerSide) ? SDL_PRESSED : SDL_RELEASED, 1);
+    SDL_SendPenButton(timestamp, pen, window, (buttons & NSEventButtonMaskPenUpperSide) ? SDL_PRESSED : SDL_RELEASED, 2);
+    SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_PRESSURE, [event pressure]);
+    SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_ROTATION, [event rotation]);
+    SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_XTILT, ((float) tilt.x) * 90.0f);
+    SDL_SendPenAxis(timestamp, pen, window, SDL_PEN_AXIS_YTILT, ((float) tilt.y) * 90.0f);
+}
+
+SDL_bool Cocoa_HandlePenEvent(SDL_CocoaWindowData *_data, NSEvent *event)
+{
+    NSEventType type = [event type];
+
+    if ((type != NSEventTypeTabletPoint) && (type != NSEventTypeTabletProximity)) {
+        const NSEventSubtype subtype = [event subtype];
+        if (subtype == NSEventSubtypeTabletPoint) {
+            type = NSEventTypeTabletPoint;
+        } else if (subtype == NSEventSubtypeTabletProximity) {
+            type = NSEventTypeTabletProximity;
+        } else {
+            return SDL_FALSE;  // not a tablet event.
+        }
+    }
+
+    if (type == NSEventTypeTabletPoint) {
+        Cocoa_HandlePenPointEvent(_data, event);
+    } else if (type == NSEventTypeTabletProximity) {
+        Cocoa_HandlePenProximityEvent(_data, event);
+    } else {
+        return SDL_FALSE;  // not a tablet event.
+    }
+
+    return SDL_TRUE;
+}
+
+static void Cocoa_FreePenHandle(SDL_PenID instance_id, void *handle, void *userdata)
+{
+    SDL_free(handle);
+}
+
+void Cocoa_QuitPen(SDL_VideoDevice *_this)
+{
+    SDL_RemoveAllPenDevices(Cocoa_FreePenHandle, NULL);
+}
+
+#endif /* SDL_VIDEO_DRIVER_COCOA */
diff --git a/src/video/cocoa/SDL_cocoavideo.h b/src/video/cocoa/SDL_cocoavideo.h
index df7fb382d2683..a3c1df6263c05 100644
--- a/src/video/cocoa/SDL_cocoavideo.h
+++ b/src/video/cocoa/SDL_cocoavideo.h
@@ -38,6 +38,7 @@
 #include "SDL_cocoamouse.h"
 #include "SDL_cocoaopengl.h"
 #include "SDL_cocoawindow.h"
+#include "SDL_cocoapen.h"
 
 #ifndef MAC_OS_X_VERSION_10_12
 #define DECLARE_EVENT(name) static const NSEventType NSEventType##name = NS##name
diff --git a/src/video/cocoa/SDL_cocoavideo.m b/src/video/cocoa/SDL_cocoavideo.m
index 7bc315805a83c..677c24a08babe 100644
--- a/src/video/cocoa/SDL_cocoavideo.m
+++ b/src/video/cocoa/SDL_cocoavideo.m
@@ -201,6 +201,8 @@ int Cocoa_VideoInit(SDL_VideoDevice *_this)
         Cocoa_InitKeyboard(_this);
         if (Cocoa_InitMouse(_this) < 0) {
             return -1;
+        } else if (Cocoa_InitPen(_this) < 0) {
+            return -1;
         }
 
         // Assume we have a mouse and keyboard
@@ -227,6 +229,7 @@ void Cocoa_VideoQuit(SDL_VideoDevice *_this)
         Cocoa_QuitModes(_this);
         Cocoa_QuitKeyboard(_this);
         Cocoa_QuitMouse(_this);
+        Cocoa_QuitPen(_this);
         SDL_DestroyMutex(data.swaplock);
         data.swaplock = NULL;
     }
diff --git a/src/video/cocoa/SDL_cocoawindow.h b/src/video/cocoa/SDL_cocoawindow.h
index ce8cf3117cee1..9dfffac6dc23d 100644
--- a/src/video/cocoa/SDL_cocoawindow.h
+++ b/src/video/cocoa/SDL_cocoawindow.h
@@ -121,6 +121,10 @@ typedef enum
 /* Touch event handling */
 - (void)handleTouches:(NSTouchPhase)phase withEvent:(NSEvent *)theEvent;
 
+/* Tablet event handling (but these also come through on mouse events sometimes!) */
+- (void)tabletProximity:(NSEvent *)theEvent;
+- (void)tabletPoint:(NSEvent *)theEvent;
+
 @end
 /* *INDENT-ON* */
 
diff --git a/src/video/cocoa/SDL_cocoawindow.m b/src/video/cocoa/SDL_cocoawindow.m
index a457a5a53f200..a353981191c30 100644
--- a/src/video/cocoa/SDL_cocoawindow.m
+++ b/src/video/cocoa/SDL_cocoawindow.m
@@ -1568,6 +1568,10 @@ static int Cocoa_SendMouseButtonClicks(SDL_Mouse *mouse, NSEvent *theEvent, SDL_
 
 - (void)mouseDown:(NSEvent *)theEvent
 {
+    if (Cocoa_HandlePenEvent(_data, theEvent)) {
+        return;  // pen code handled it.
+    }
+
     SDL_Mouse *mouse = SDL_GetMouse();
     int button;
 
@@ -1625,6 +1629,10 @@ - (void)otherMouseDown:(NSEvent *)theEvent
 
 - (void)mouseUp:(NSEvent *)theEvent
 {
+    if (Cocoa_HandlePenEvent(_data, theEvent)) {
+        return;  // pen code handled it.
+    }
+
     SDL_Mouse *mouse = SDL_GetMouse();
     int button;
 
@@ -1672,6 +1680,10 @@ - (void)otherMouseUp:(NSEvent *)theEvent
 
 - (void)mouseMoved:(NSEvent *)theEvent
 {
+    if (Cocoa_HandlePenEvent(_data, theEvent)) {
+        return;  // pen code handled it.
+    }
+
     SDL_MouseID mouseID = SDL_DEFAULT_MOUSE_ID;
     SDL_Mouse *mouse = SDL_GetMouse();
     NSPoint point;
@@ -1887,6 +1899,16 @@ - (void)handleTouches:(NSTouchPhase)phase withEvent:(NSEvent *)theEvent
     }
 }
 
+- (void)tabletProximity:(NSEvent *)theEvent
+{
+    Cocoa_HandlePenEvent(_data, theEvent);
+}
+
+- (void)tabletPoint:(NSEvent *)theEvent
+{
+    Cocoa_HandlePenEvent(_data, theEvent);
+}
+
 @end
 
 @interface SDL3View : NSView
diff --git a/test/testpen.c b/test/testpen.c
index ace0fd656b4b5..1dfef50076d19 100644
--- a/test/testpen.c
+++ b/test/testpen.c
@@ -171,7 +171,7 @@ int SDL_AppEvent(void *appstate, const SDL_Event *event)
             /*SDL_Log("Pen %" SDL_PRIu32 " button %d down!", event->pbutton.which, (int) event->pbutton.button);*/
             pen = FindPen(event->ptouch.which);
             if (pen) {
-                pen->buttons |= (1 << event->pbutton.button);
+                pen->buttons |= (1 << (event->pbutton.button-1));
             }
             return SDL_APP_CONTINUE;
 
@@ -179,7 +179,7 @@ int SDL_AppEvent(void *appstate, const SDL_Event *event)
             /*SDL_Log("Pen %" SDL_PRIu32 " button %d up!", event->pbutton.which, (int) event->pbutton.button);*/
             pen = FindPen(event->ptouch.which);
             if (pen) {
-                pen->buttons &= ~(1 << event->pbutton.button);
+                pen->buttons &= ~(1 << (event->pbutton.button-1));
             }
             return SDL_APP_CONTINUE;