SDL: cocoa: Attempt to convert incoming clipboard UTF-16 strings to UTF-8.

From e0232c5b9d972ad394d597ce858185cd15a0f1a7 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Thu, 29 Oct 2026 16:31:39 -0400
Subject: [PATCH] cocoa: Attempt to convert incoming clipboard UTF-16 strings
 to UTF-8.

Do this only if the app didn't ask for a specific encoding.

Fixes #16438.
---
 src/video/cocoa/SDL_cocoaclipboard.m | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/src/video/cocoa/SDL_cocoaclipboard.m b/src/video/cocoa/SDL_cocoaclipboard.m
index dd0836a1903a1..535ea049d4b8c 100644
--- a/src/video/cocoa/SDL_cocoaclipboard.m
+++ b/src/video/cocoa/SDL_cocoaclipboard.m
@@ -322,7 +322,6 @@ static CFStringRef GetUTIType(const char *tag)
             CFStringRef utiType = GetUTIType(mime_type);
             NSString *availableType = [pasteboard availableTypeFromArray:@[(__bridge NSString *) utiType]];
             itemData = [item dataForType: availableType];
-            CFRelease(utiType);
             if (itemData != nil) {
                 NSUInteger length = [itemData length];
                 *size = (size_t)length;
@@ -330,9 +329,23 @@ static CFStringRef GetUTIType(const char *tag)
                 if (data) {
                     [itemData getBytes: data length: length];
                     SDL_memset((Uint8 *)data + length, 0, sizeof(Uint32));
+                    // if the app asked for, generically, "plain text" and we see a UTF-16 byte-order-mark, convert it to UTF-8.
+                    // almost all plain text comes through as UTF-8 on the Mac, but some things, like "copying" a file's icon to the clipboard from the Finder,
+                    // will still give you UTF-16. Other than the BOM, there's no indication of the encoding for the "public.plain-text" UTI,
+                    // so if the app didn't ask for something more specific, this is the best we can do.
+                    if ((*((const Uint16 *) data) == 0xFEFF) && (CFStringCompare(utiType, CFSTR("public.plain-text"), 0) == kCFCompareEqualTo)) {
+                        char *utf8 = SDL_iconv_string("UTF-8", "UTF-16", ((char *) data) + 2, length + sizeof (Uint32) - 2);
+                        if (utf8) {
+                            *size = (size_t) SDL_strlen(utf8);
+                            SDL_free(data);
+                            data = utf8;
+                        }
+                    }
                 }
+                CFRelease(utiType);
                 break;
             }
+            CFRelease(utiType);
         }
 
         if (!data && SDL_strcmp(mime_type, "text/uri-list") == 0) {