SDL: Added support for displaying XIM composition strings

https://github.com/libsdl-org/SDL/commit/715897aea778144d2bcd242c298d1b220f27934d

From 715897aea778144d2bcd242c298d1b220f27934d Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 10 Jan 2025 03:10:45 -0800
Subject: [PATCH] Added support for displaying XIM composition strings

Fixes https://github.com/libsdl-org/SDL/issues/6437
---
 src/video/x11/SDL_x11dyn.c      |  10 ++
 src/video/x11/SDL_x11dyn.h      |   4 +
 src/video/x11/SDL_x11events.c   |   1 +
 src/video/x11/SDL_x11keyboard.c | 240 +++++++++++++++++++++++++++++++-
 src/video/x11/SDL_x11keyboard.h |   2 +
 src/video/x11/SDL_x11sym.h      |   2 +
 src/video/x11/SDL_x11window.c   |  13 +-
 src/video/x11/SDL_x11window.h   |   7 +
 8 files changed, 269 insertions(+), 10 deletions(-)

diff --git a/src/video/x11/SDL_x11dyn.c b/src/video/x11/SDL_x11dyn.c
index a9669edd2f8d4..7c48ed5ce6158 100644
--- a/src/video/x11/SDL_x11dyn.c
+++ b/src/video/x11/SDL_x11dyn.c
@@ -104,6 +104,8 @@ static void *X11_GetSym(const char *fnname, int *pHasModule)
 #ifdef X_HAVE_UTF8_STRING
 SDL_DYNX11FN_XCreateIC X11_XCreateIC = NULL;
 SDL_DYNX11FN_XGetICValues X11_XGetICValues = NULL;
+SDL_DYNX11FN_XSetICValues X11_XSetICValues = NULL;
+SDL_DYNX11FN_XVaCreateNestedList X11_XVaCreateNestedList = NULL;
 #endif
 
 /* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */
@@ -129,6 +131,8 @@ void SDL_X11_UnloadSymbols(void)
 #ifdef X_HAVE_UTF8_STRING
             X11_XCreateIC = NULL;
             X11_XGetICValues = NULL;
+            X11_XSetICValues = NULL;
+            X11_XVaCreateNestedList = NULL;
 #endif
 
 #ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
@@ -171,6 +175,10 @@ bool SDL_X11_LoadSymbols(void)
             X11_GetSym("XCreateIC", &SDL_X11_HAVE_UTF8);
         X11_XGetICValues = (SDL_DYNX11FN_XGetICValues)
             X11_GetSym("XGetICValues", &SDL_X11_HAVE_UTF8);
+        X11_XSetICValues = (SDL_DYNX11FN_XSetICValues)
+            X11_GetSym("XSetICValues", &SDL_X11_HAVE_UTF8);
+        X11_XVaCreateNestedList = (SDL_DYNX11FN_XVaCreateNestedList)
+            X11_GetSym("XVaCreateNestedList", &SDL_X11_HAVE_UTF8);
 #endif
 
         if (SDL_X11_HAVE_BASEXLIB) {
@@ -191,6 +199,8 @@ bool SDL_X11_LoadSymbols(void)
 #ifdef X_HAVE_UTF8_STRING
         X11_XCreateIC = XCreateIC;
         X11_XGetICValues = XGetICValues;
+        X11_XSetICValues = XSetICValues;
+        X11_XVaCreateNestedList = XVaCreateNestedList;
 #endif
 #endif
     }
diff --git a/src/video/x11/SDL_x11dyn.h b/src/video/x11/SDL_x11dyn.h
index 1f23ca4f20790..e9831fcd608f5 100644
--- a/src/video/x11/SDL_x11dyn.h
+++ b/src/video/x11/SDL_x11dyn.h
@@ -94,8 +94,12 @@ extern void SDL_X11_UnloadSymbols(void);
 #ifdef X_HAVE_UTF8_STRING
 typedef XIC (*SDL_DYNX11FN_XCreateIC)(XIM, ...);
 typedef char *(*SDL_DYNX11FN_XGetICValues)(XIC, ...);
+typedef char *(*SDL_DYNX11FN_XSetICValues)(XIC, ...);
+typedef XVaNestedList (*SDL_DYNX11FN_XVaCreateNestedList)(int, ...);
 extern SDL_DYNX11FN_XCreateIC X11_XCreateIC;
 extern SDL_DYNX11FN_XGetICValues X11_XGetICValues;
+extern SDL_DYNX11FN_XSetICValues X11_XSetICValues;
+extern SDL_DYNX11FN_XVaCreateNestedList X11_XVaCreateNestedList;
 #endif
 
 /* These SDL_X11_HAVE_* flags are here whether you have dynamic X11 or not. */
diff --git a/src/video/x11/SDL_x11events.c b/src/video/x11/SDL_x11events.c
index 95f2dc21970f8..90ce95c584ca0 100644
--- a/src/video/x11/SDL_x11events.c
+++ b/src/video/x11/SDL_x11events.c
@@ -939,6 +939,7 @@ void X11_HandleKeyEvent(SDL_VideoDevice *_this, SDL_WindowData *windowdata, SDL_
 
             if (*text) {
                 text[text_length] = '\0';
+                X11_ClearComposition(windowdata);
                 SDL_SendKeyboardText(text);
             }
         } else {
diff --git a/src/video/x11/SDL_x11keyboard.c b/src/video/x11/SDL_x11keyboard.c
index 2d25ec2de51c8..336f906e2ebc7 100644
--- a/src/video/x11/SDL_x11keyboard.c
+++ b/src/video/x11/SDL_x11keyboard.c
@@ -451,6 +451,227 @@ void X11_QuitKeyboard(SDL_VideoDevice *_this)
 #endif
 }
 
+void X11_ClearComposition(SDL_WindowData *data)
+{
+    if (data->preedit_length > 0) {
+        data->preedit_text[0] = '\0';
+        data->preedit_length = 0;
+    }
+
+    if (data->ime_needs_clear_composition) {
+        SDL_SendEditingText("", 0, 0);
+        data->ime_needs_clear_composition = false;
+    }
+}
+
+static void X11_SendEditingEvent(SDL_WindowData *data)
+{
+    if (data->preedit_length == 0) {
+        X11_ClearComposition(data);
+        return;
+    }
+
+    bool in_highlight = false;
+    int start = -1, length = 0, i;
+    for (i = 0; i < data->preedit_length; ++i) {
+        if (data->preedit_feedback[i] & (XIMReverse | XIMHighlight)) {
+            if (start < 0) {
+                start = i;
+                in_highlight = true;
+            }
+        } else if (in_highlight) {
+            // Found the end of the highlight
+            break;
+        }
+    }
+    if (in_highlight) {
+        length = (i - start);
+    } else {
+        start = SDL_clamp(data->preedit_cursor, 0, data->preedit_length);
+    }
+    SDL_SendEditingText(data->preedit_text, start, length);
+
+    data->ime_needs_clear_composition = true;
+}
+
+static int preedit_start_callback(XIC xic, XPointer client_data, XPointer call_data)
+{
+    // No limit on preedit text length
+    return -1;
+}
+
+static void preedit_done_callback(XIC xic, XPointer client_data, XPointer call_data)
+{
+}
+
+static void preedit_draw_callback(XIC xic, XPointer client_data, XIMPreeditDrawCallbackStruct *call_data)
+{
+    SDL_WindowData *data = (SDL_WindowData *)client_data;
+    int chg_first = SDL_clamp(call_data->chg_first, 0, data->preedit_length);
+    int chg_length = SDL_clamp(call_data->chg_length, 0, data->preedit_length - chg_first);
+
+    const char *start = data->preedit_text;
+    if (chg_length > 0) {
+        // Delete text in range
+        for (int i = 0; start && *start && i < chg_first; ++i) {
+            SDL_StepUTF8(&start, NULL);
+        }
+
+        const char *end = start;
+        for (int i = 0; end && *end && i < chg_length; ++i) {
+            SDL_StepUTF8(&end, NULL);
+        }
+
+        if (end > start) {
+            SDL_memmove((char *)start, end, SDL_strlen(end) + 1);
+            if ((chg_first + chg_length) > data->preedit_length) {
+                SDL_memmove(&data->preedit_feedback[chg_first], &data->preedit_feedback[chg_first + chg_length], (data->preedit_length - chg_first - chg_length) * sizeof(*data->preedit_feedback));
+            }
+        }
+        data->preedit_length -= chg_length;
+    }
+
+    XIMText *text = call_data->text;
+    if (text) {
+        // Insert text in range
+        SDL_assert(!text->encoding_is_wchar);
+
+        // The text length isn't calculated as directed by the spec, recalculate it now
+        if (text->string.multi_byte) {
+            text->length = SDL_utf8strlen(text->string.multi_byte);
+        }
+
+        size_t string_size = SDL_strlen(text->string.multi_byte);
+        size_t size = string_size + 1;
+        if (data->preedit_text) {
+            size += SDL_strlen(data->preedit_text);
+        }
+        char *preedit_text = (char *)SDL_malloc(size * sizeof(*preedit_text));
+        if (preedit_text) {
+            size_t pre_size = (start - data->preedit_text);
+            size_t post_size = start ? SDL_strlen(start) : 0;
+            if (pre_size > 0) {
+                SDL_memcpy(&preedit_text[0], data->preedit_text, pre_size);
+            }
+            SDL_memcpy(&preedit_text[pre_size], text->string.multi_byte, string_size);
+            if (post_size > 0) {
+                SDL_memcpy(&preedit_text[pre_size + string_size], start, post_size);
+            }
+            preedit_text[size - 1] = '\0';
+        }
+
+        size_t feedback_size = data->preedit_length + text->length;
+        XIMFeedback *feedback = (XIMFeedback *)SDL_malloc(feedback_size * sizeof(*feedback));
+        if (feedback) {
+            size_t pre_size = (size_t)chg_first;
+            size_t post_size = (size_t)data->preedit_length - pre_size;
+            if (pre_size > 0) {
+                SDL_memcpy(&feedback[0], data->preedit_feedback, pre_size * sizeof(*feedback));
+            }
+            SDL_memcpy(&feedback[pre_size], text->feedback, text->length * sizeof(*feedback));
+            if (post_size > 0) {
+                SDL_memcpy(&feedback[pre_size + text->length], &data->preedit_feedback[pre_size], post_size * sizeof(*feedback));
+            }
+        }
+
+        if (preedit_text && feedback) {
+            SDL_free(data->preedit_text);
+            data->preedit_text = preedit_text;
+
+            SDL_free(data->preedit_feedback);
+            data->preedit_feedback = feedback;
+
+            data->preedit_length += text->length;
+        } else {
+            SDL_free(preedit_text);
+            SDL_free(feedback);
+        }
+    }
+
+    data->preedit_cursor = call_data->caret;
+
+#ifdef DEBUG_XIM
+    if (call_data->chg_length > 0) {
+        SDL_Log("Draw callback deleted %d characters at %d\n", call_data->chg_length, call_data->chg_first);
+    }
+    if (text) {
+        SDL_Log("Draw callback inserted %s at %d, caret: %d\n", text->string.multi_byte, call_data->chg_first, call_data->caret);
+    }
+    SDL_Log("Pre-edit text: %s\n", data->preedit_text);
+#endif
+
+    X11_SendEditingEvent(data);
+}
+
+static void preedit_caret_callback(XIC xic, XPointer client_data, XIMPreeditCaretCallbackStruct *call_data)
+{
+    SDL_WindowData *data = (SDL_WindowData *)client_data;
+
+    switch (call_data->direction) {
+    case XIMAbsolutePosition:
+        if (call_data->position != data->preedit_cursor) {
+            data->preedit_cursor = call_data->position;
+            X11_SendEditingEvent(data);
+        }
+        break;
+    case XIMDontChange:
+        break;
+    default:
+        // Not currently supported
+        break;
+    }
+}
+
+void X11_CreateInputContext(SDL_WindowData *data)
+{
+#ifdef X_HAVE_UTF8_STRING
+    SDL_VideoData *videodata = data->videodata;
+
+    if (SDL_X11_HAVE_UTF8 && videodata->im) {
+        const char *hint = SDL_GetHint(SDL_HINT_IME_IMPLEMENTED_UI);
+        if (hint && SDL_strstr(hint, "composition")) {
+            XIMCallback draw_callback;
+            draw_callback.client_data = (XPointer)data;
+            draw_callback.callback = (XIMProc)preedit_draw_callback;
+
+            XIMCallback start_callback;
+            start_callback.client_data = (XPointer)data;
+            start_callback.callback = (XIMProc)preedit_start_callback;
+
+            XIMCallback done_callback;
+            done_callback.client_data = (XPointer)data;
+            done_callback.callback = (XIMProc)preedit_done_callback;
+
+            XIMCallback caret_callback;
+            caret_callback.client_data = (XPointer)data;
+            caret_callback.callback = (XIMProc)preedit_caret_callback;
+
+            XVaNestedList attr = X11_XVaCreateNestedList(0,
+                                                         XNPreeditStartCallback, &start_callback,
+                                                         XNPreeditDoneCallback, &done_callback,
+                                                         XNPreeditDrawCallback, &draw_callback,
+                                                         XNPreeditCaretCallback, &caret_callback,
+                                                         NULL);
+            if (attr) {
+                data->ic = X11_XCreateIC(videodata->im,
+                                         XNInputStyle, XIMPreeditCallbacks | XIMStatusCallbacks,
+                                         XNPreeditAttributes, attr,
+                                         XNClientWindow, data->xwindow,
+                                         NULL);
+                X11_XFree(attr);
+            }
+        } else {
+            data->ic = X11_XCreateIC(videodata->im,
+                                     XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
+                                     XNClientWindow, data->xwindow,
+                                     NULL);
+        }
+        data->xim_spot.x = -1;
+        data->xim_spot.y = -1;
+    }
+#endif // X_HAVE_UTF8_STRING
+}
+
 static void X11_ResetXIM(SDL_VideoDevice *_this, SDL_Window *window)
 {
 #ifdef X_HAVE_UTF8_STRING
@@ -463,7 +684,7 @@ static void X11_ResetXIM(SDL_VideoDevice *_this, SDL_Window *window)
             X11_XFree(contents);
         }
     }
-#endif
+#endif // X_HAVE_UTF8_STRING
 }
 
 bool X11_StartTextInput(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID props)
@@ -481,6 +702,23 @@ bool X11_StopTextInput(SDL_VideoDevice *_this, SDL_Window *window)
 
 bool X11_UpdateTextInputArea(SDL_VideoDevice *_this, SDL_Window *window)
 {
+#ifdef X_HAVE_UTF8_STRING
+    SDL_WindowData *data = window->internal;
+
+    if (data && data->ic) {
+        XPoint spot;
+        spot.x = window->text_input_rect.x + window->text_input_cursor;
+        spot.y = window->text_input_rect.y + window->text_input_rect.h;
+        if (spot.x != data->xim_spot.x || spot.y != data->xim_spot.y) {
+            XVaNestedList attr = X11_XVaCreateNestedList(0, XNSpotLocation, &spot, NULL);
+            if (attr) {
+                X11_XSetICValues(data->ic, XNPreeditAttributes, attr, NULL);
+                X11_XFree(attr);
+            }
+            SDL_copyp(&data->xim_spot, &spot);
+        }
+    }
+#endif
     return true;
 }
 
diff --git a/src/video/x11/SDL_x11keyboard.h b/src/video/x11/SDL_x11keyboard.h
index fbc5265f6fbf9..a6cd2f7e9714c 100644
--- a/src/video/x11/SDL_x11keyboard.h
+++ b/src/video/x11/SDL_x11keyboard.h
@@ -26,6 +26,8 @@
 extern bool X11_InitKeyboard(SDL_VideoDevice *_this);
 extern void X11_UpdateKeymap(SDL_VideoDevice *_this, bool send_event);
 extern void X11_QuitKeyboard(SDL_VideoDevice *_this);
+extern void X11_CreateInputContext(SDL_WindowData *data);
+extern void X11_ClearComposition(SDL_WindowData *data);
 extern bool X11_StartTextInput(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID props);
 extern bool X11_StopTextInput(SDL_VideoDevice *_this, SDL_Window *window);
 extern bool X11_UpdateTextInputArea(SDL_VideoDevice *_this, SDL_Window *window);
diff --git a/src/video/x11/SDL_x11sym.h b/src/video/x11/SDL_x11sym.h
index c35fc94e67ea2..68d70cd27a91d 100644
--- a/src/video/x11/SDL_x11sym.h
+++ b/src/video/x11/SDL_x11sym.h
@@ -223,6 +223,8 @@ SDL_X11_SYM(int,Xutf8LookupString,(XIC a,XKeyPressedEvent* b,char* c,int d,KeySy
 // SDL_X11_SYM(XIC,XCreateIC,(XIM, ...),return)  !!! ARGH!
 SDL_X11_SYM(void,XDestroyIC,(XIC a),(a),)
 /* SDL_X11_SYM(char*,XGetICValues,(XIC, ...),return)  !!! ARGH! */
+/* SDL_X11_SYM(char*,XSetICValues,(XIC, ...),return)  !!! ARGH! */
+/* SDL_X11_SYM(XVaNestedList,XVaCreateNestedList,(int, ...),return)  !!! ARGH! */
 SDL_X11_SYM(void,XSetICFocus,(XIC a),(a),)
 SDL_X11_SYM(void,XUnsetICFocus,(XIC a),(a),)
 SDL_X11_SYM(XIM,XOpenIM,(Display* a,struct _XrmHashBucketRec* b,char* c,char* d),(a,b,c,d),return)
diff --git a/src/video/x11/SDL_x11window.c b/src/video/x11/SDL_x11window.c
index 81b8434a265e4..0ecabec6752dc 100644
--- a/src/video/x11/SDL_x11window.c
+++ b/src/video/x11/SDL_x11window.c
@@ -356,19 +356,12 @@ static bool SetupWindowData(SDL_VideoDevice *_this, SDL_Window *window, Window w
     if (!data) {
         return false;
     }
+    data->videodata = videodata;
     data->window = window;
     data->xwindow = w;
     data->hit_test_result = SDL_HITTEST_NORMAL;
 
-#ifdef X_HAVE_UTF8_STRING
-    if (SDL_X11_HAVE_UTF8 && videodata->im) {
-        data->ic =
-            X11_XCreateIC(videodata->im, XNClientWindow, w, XNFocusWindow, w,
-                          XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
-                          NULL);
-    }
-#endif
-    data->videodata = videodata;
+    X11_CreateInputContext(data);
 
     // Associate the data with the window
 
@@ -2044,6 +2037,8 @@ void X11_DestroyWindow(SDL_VideoDevice *_this, SDL_Window *window)
 #ifdef X_HAVE_UTF8_STRING
         if (data->ic) {
             X11_XDestroyIC(data->ic);
+            SDL_free(data->preedit_text);
+            SDL_free(data->preedit_feedback);
         }
 #endif
 
diff --git a/src/video/x11/SDL_x11window.h b/src/video/x11/SDL_x11window.h
index 97cb7f6658263..16936033596f2 100644
--- a/src/video/x11/SDL_x11window.h
+++ b/src/video/x11/SDL_x11window.h
@@ -111,6 +111,13 @@ struct SDL_WindowData
     bool toggle_borders;
     bool fullscreen_borders_forced_on;
     SDL_HitTestResult hit_test_result;
+
+    XPoint xim_spot;
+    char *preedit_text;
+    XIMFeedback *preedit_feedback;
+    int preedit_length;
+    int preedit_cursor;
+    bool ime_needs_clear_composition;
 };
 
 extern void X11_SetNetWMState(SDL_VideoDevice *_this, Window xwindow, SDL_WindowFlags flags);