coop-deluxe / sm64coopdx

An official continuation of https://github.com/djoslin0/sm64ex-coop on sm64coopdx for the enhancements and progress it already has.
https://sm64coopdx.com
403 stars 71 forks source link

Fixed clipboard (text copy & paste) implementation #380

Closed Flower35 closed 1 month ago

Flower35 commented 1 month ago

This pull request addresses the following issues:


1. "SDL_GetClipboardText" memory leak

In case of failure, SDL_GetClipboardText() returns a SDL_strdup("") value, so that the result is never NULL and must always be freed by user application. This memory leak is hardly noticeable in-game, unless one would simulate it with the following code to watch the memory usage:

static char* gfx_sdl_get_clipboard_text(void) {
    while (!0) { SDL_GetClipboardText(); }
    return "";
}

reference: https://wiki.libsdl.org/SDL2/SDL_GetClipboardText


2. "gfx_dxgi_get_clipboard_text" returning a NULL pointer

In cases where clipboard data cannot be converted to text on Windows - for example, when user copies some image and the clipboard is filled with bitmap data - the GetClipboardData(CF_TEXT) call returns NULL, which is later passed to functions like djui_interactable_on_text_input() and strlen().


3. "SetClipboardData" and "GetClipboardData" assuming wrong text encoding.

The sm64coopdx engine assumes UTF-8 encoding for most textual data, same with the SDL2 API. However, to ensure no data is lost while copying text in the DirectX version, the values must be converted from UTF-8 to UTF-16LE encoding. The CF_TEXT type assumes an ANSI encoding, and some text copied this way could be broken when trying to paste it to other application, like chat or notepad.

Additionally, the game should not access the clipboard memory once CloseClipboard() has been called, so I added static clipboard text buffers with sufficient size to hold UTF-8 text.

references: https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclipboarddata