Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): the desktop host is the text-editing surface it had none of

esengine047206dacecd
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index a439d53ab..e2d9c201c 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -29,6 +29,7 @@ env:
test_registry_ondestroy test_view_api_matrix
test_shader_device test_draw_params test_texture_fb test_buffer_device
test_compressed_format test_batch_builder test_boundary_span test_webgpu_device
+ test_text_edit
jobs:
build-emscripten:
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index b92115597..78c853c69 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -411,6 +411,24 @@ export const settingsMessages = defineMessages({
zh: 'depot id 由 Valve 分配;留 0 则使用 App ID + 1、+2…,'
+ '生成的 STEAM.md 会提示你去 SteamPipe → Depots 核对。',
},
+ 'set.group.achievements': { en: 'Achievements', zh: '成就' },
+ 'set.project.packaging.achievements': { en: 'Achievement IDs', zh: '成就 ID' },
+ 'set.project.packaging.achievements.desc': {
+ en: 'The ids this game unlocks, matching the API names in the store backend. Declaring them '
+ + 'lets an unlock of an id no backend has be refused where it happens — a store accepts '
+ + 'it, does nothing, and reports nothing. Platform-neutral: every store keeps this same '
+ + 'list under a different name.',
+ zh: '本游戏会解锁的 id,与商店后台的 API 名一一对应。声明它们,越界的 unlock 才能在发生处被拒绝——'
+ + '商店会接受它、什么也不做、也什么都不报。平台中立:每个商店都有这份同样的清单,只是名字不同。',
+ },
+ 'set.achievement.id': { en: 'ID', zh: 'ID' },
+ 'set.achievement.add': { en: 'Add achievement', zh: '添加成就' },
+ 'set.achievement.empty': {
+ en: 'No achievements declared — an unlock of any id is then forwarded unchecked.',
+ zh: '尚未声明任何成就——此时任何 id 的 unlock 都会被不加检查地转发。',
+ },
+ 'set.achievement.errId': { en: 'An id is required.', zh: '必须填写 id。' },
+ 'set.achievement.errDup': { en: 'Already declared.', zh: '已经声明过了。' },
'set.project.packaging.desktop.steam.sdkPath': { en: 'Steamworks SDK', zh: 'Steamworks SDK' },
'set.project.packaging.desktop.steam.sdkPath.desc': {
en: 'The Steamworks SDK you downloaded, on this machine. The package takes its '
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index cda6686bc..c142a73ea 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -481,6 +481,38 @@ settingsRegistry.register({
},
});
+// The ids this game unlocks. Platform-NEUTRAL and therefore not under Steam: every
+// store keeps this same list under a different name. Declared so that an unlock of
+// an id no backend has is refused here rather than accepted and dropped there.
+settingsRegistry.register({
+ id: 'project.packaging.achievements',
+ type: 'objectList', scope: 'project', section: 'packaging', group: t('set.group.achievements'),
+ label: t('set.project.packaging.achievements'),
+ description: t('set.project.packaging.achievements.desc'),
+ layout: 'block',
+ default: [],
+ columns: [
+ { key: 'id', label: t('set.achievement.id'), type: 'text', width: '1fr', placeholder: 'FIRST_BLOOD' },
+ ],
+ addLabel: t('set.achievement.add'),
+ emptyHint: t('set.achievement.empty'),
+ newRow: () => ({ id: '' }),
+ rowError: (row, all) => {
+ const id = String(row.id ?? '').trim();
+ if (!id) return t('set.achievement.errId');
+ // A store keys achievements by this exact string, so two rows differing only
+ // in whitespace are one achievement and one that never fires.
+ if (all.filter((r) => String(r.id ?? '').trim() === id).length > 1) return t('set.achievement.errDup');
+ return null;
+ },
+ bind: {
+ get: () => (ProjectStore.packagingSettings().achievements ?? []).map((id) => ({ id })),
+ set: (v) => void ProjectStore.setPackaging({
+ achievements: v.map((r) => String(r.id ?? '').trim()).filter(Boolean),
+ }),
+ },
+});
+
// Where Steam's own library comes from. A path rather than a checkbox because the
// engine has no copy to switch on: the SDK is the developer's download, and the
// assembler takes exactly one file out of it.
diff --git a/desktop/tests/steam-settings.test.ts b/desktop/tests/steam-settings.test.ts
index 51289e9c8..afed48100 100644
--- a/desktop/tests/steam-settings.test.ts
+++ b/desktop/tests/steam-settings.test.ts
@@ -8,7 +8,7 @@
* the depot ids the project had. That is the whole reason these setters exist.
*/
import { describe, it, expect } from 'vitest';
-import type { SteamPackaging } from '@/project/format';
+import { parseManifest, type SteamPackaging } from '@/project/format';
/** The merge, as the store performs it, over a plain object. */
function mergeSteam(prev: SteamPackaging | undefined, patch: Partial<SteamPackaging>): SteamPackaging | undefined {
@@ -55,3 +55,22 @@ describe('the Steam packaging settings', () => {
expect(mergeSteam(undefined, { appId: undefined })).toBeUndefined();
});
});
+
+describe('the declared achievement ids', () => {
+ const parsed = (achievements: unknown) =>
+ parseManifest({ name: 'p', packaging: { achievements } }).packaging?.achievements;
+
+ it('are trimmed and deduplicated, because a store keys on the exact string', () => {
+ // Two rows differing only in whitespace are one achievement and one that
+ // never fires — and the settings table cannot tell them apart on screen.
+ expect(parsed(['FIRST_BLOOD', ' FIRST_BLOOD ', 'ALL_LEVELS'])).toEqual(['FIRST_BLOOD', 'ALL_LEVELS']);
+ });
+
+ it('are absent rather than empty when a project declares none', () => {
+ // Absence means "check nothing", which is what an older project gets; an
+ // empty list would have to mean the same thing in a second way.
+ expect(parsed([])).toBeUndefined();
+ expect(parsed([' '])).toBeUndefined();
+ expect(parsed(undefined)).toBeUndefined();
+ });
+});
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 58ba579e3..6fa30fb5f 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -300,6 +300,9 @@ if(ESTELLA_QUICKJS_DIR)
host/bindings/InputBindings.cpp
$<$<BOOL:${ESTELLA_DESKTOP}>:host/steam/SteamApi.cpp>
$<$<BOOL:${ESTELLA_DESKTOP}>:host/bindings/SteamBindings.cpp>
+ # Desktop-only because it is the editing surface no desktop OS supplies;
+ # a phone's keyboard IS one, so there is nothing here for it to be.
+ $<$<BOOL:${ESTELLA_DESKTOP}>:host/media/text_edit.cpp>
host/bindings/NetBindings.cpp
host/bindings/TextEditorBindings.cpp
host/media/native_audio.cpp
diff --git a/native/host/media/text_edit.cpp b/native/host/media/text_edit.cpp
new file mode 100644
index 000000000..1ad6ea309
--- /dev/null
+++ b/native/host/media/text_edit.cpp
@@ -0,0 +1,266 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file text_edit.cpp
+ * @brief The desktop editing model — see text_edit.hpp for why it exists.
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "media/text_edit.hpp"
+
+#include <algorithm>
+
+namespace eshost {
+namespace {
+
+constexpr char16_t kReplacement = 0xFFFD;
+
+bool isHighSurrogate(char16_t c) { return c >= 0xD800 && c <= 0xDBFF; }
+bool isLowSurrogate(char16_t c) { return c >= 0xDC00 && c <= 0xDFFF; }
+
+void appendUtf8(std::string& out, char32_t cp) {
+ if (cp < 0x80) {
+ out.push_back(static_cast<char>(cp));
+ } else if (cp < 0x800) {
+ out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
+ } else if (cp < 0x10000) {
+ out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
+ } else {
+ out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
+ out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
+ }
+}
+
+/** A word boundary as every text field draws it: runs of non-space, so one
+ * Ctrl+Left crosses one word however it is punctuated. */
+bool isWordChar(char16_t c) {
+ return c != u' ' && c != u'\t' && c != u'\n' && c != u'\r';
+}
+
+} // namespace
+
+std::string utf16ToUtf8(const std::u16string& text) {
+ std::string out;
+ out.reserve(text.size());
+ for (size_t i = 0; i < text.size(); ++i) {
+ char32_t cp = text[i];
+ if (isHighSurrogate(text[i]) && i + 1 < text.size() && isLowSurrogate(text[i + 1])) {
+ cp = 0x10000 + ((static_cast<char32_t>(text[i]) - 0xD800) << 10)
+ + (static_cast<char32_t>(text[i + 1]) - 0xDC00);
+ ++i;
+ } else if (isHighSurrogate(text[i]) || isLowSurrogate(text[i])) {
+ cp = kReplacement; // a half of a pair that lost its other half
+ }
+ appendUtf8(out, cp);
+ }
+ return out;
+}
+
+std::u16string utf8ToUtf16(const std::string& text) {
+ std::u16string out;
+ out.reserve(text.size());
+ size_t i = 0;
+ while (i < text.size()) {
+ const unsigned char lead = static_cast<unsigned char>(text[i]);
+ int extra = 0;
+ char32_t cp = 0;
+ if (lead < 0x80) { cp = lead; extra = 0; }
+ else if ((lead & 0xE0) == 0xC0) { cp = lead & 0x1F; extra = 1; }
+ else if ((lead & 0xF0) == 0xE0) { cp = lead & 0x0F; extra = 2; }
+ else if ((lead & 0xF8) == 0xF0) { cp = lead & 0x07; extra = 3; }
+ else { out.push_back(kReplacement); ++i; continue; }
+
+ if (i + static_cast<size_t>(extra) >= text.size()) { out.push_back(kReplacement); break; }
+ bool ok = true;
+ for (int n = 1; n <= extra; ++n) {
+ const unsigned char cont = static_cast<unsigned char>(text[i + static_cast<size_t>(n)]);
+ if ((cont & 0xC0) != 0x80) { ok = false; break; }
+ cp = (cp << 6) | (cont & 0x3F);
+ }
+ if (!ok) { out.push_back(kReplacement); ++i; continue; }
+ i += static_cast<size_t>(extra) + 1;
+
+ if (cp > 0x10FFFF) cp = kReplacement;
+ if (cp >= 0x10000) {
+ cp -= 0x10000;
+ out.push_back(static_cast<char16_t>(0xD800 + (cp >> 10)));
+ out.push_back(static_cast<char16_t>(0xDC00 + (cp & 0x3FF)));
+ } else {
+ out.push_back(static_cast<char16_t>(cp));
+ }
+ }
+ return out;
+}
+
+void TextEditModel::focus(const std::string& value, int selectionStart, int selectionEnd,
+ bool multiline, int maxLength, bool password) {
+ focused_ = true;
+ multiline_ = multiline;
+ password_ = password;
+ maxLength_ = maxLength > 0 ? maxLength : 0;
+ write(value, selectionStart, selectionEnd);
+}
+
+void TextEditModel::blur() {
+ focused_ = false;
+ composition_.clear();
+}
+
+void TextEditModel::write(const std::string& value, int selectionStart, int selectionEnd) {
+ text_ = utf8ToUtf16(value);
+ composition_.clear();
+ const int size = static_cast<int>(text_.size());
+ anchor_ = std::clamp(selectionStart, 0, size);
+ caret_ = std::clamp(selectionEnd, 0, size);
+}
+
+int TextEditModel::low() const { return std::min(anchor_, caret_); }
+int TextEditModel::high() const { return std::max(anchor_, caret_); }
+
+void TextEditModel::insert(const std::string& utf8) {
+ composition_.clear();
+ replaceSelection(utf8ToUtf16(utf8));
+}
+
+void TextEditModel::setComposition(const std::string& utf8) {
+ // The caret before the preedit is where it goes, and it is captured only when
+ // a composition STARTS: an IME edits its preedit in place, and re-reading the
+ // caret each time would walk it across the text.
+ if (composition_.empty()) compositionAt_ = low();
+ composition_ = utf8ToUtf16(utf8);
+}
+
+void TextEditModel::replaceSelection(const std::u16string& with) {
+ const int at = low();
+ text_.erase(static_cast<size_t>(at), static_cast<size_t>(high() - at));
+ std::u16string insert = with;
+ if (maxLength_ > 0) {
+ const int room = maxLength_ - static_cast<int>(text_.size());
+ if (room <= 0) insert.clear();
+ else if (static_cast<int>(insert.size()) > room) {
+ // Truncated at a code-unit boundary would split a surrogate pair into
+ // two lone halves, which is a character no font has.
+ int keep = room;
+ if (keep > 0 && isHighSurrogate(insert[static_cast<size_t>(keep) - 1])) --keep;
+ insert.resize(static_cast<size_t>(keep));
+ }
+ }
+ text_.insert(static_cast<size_t>(at), insert);
+ anchor_ = caret_ = at + static_cast<int>(insert.size());
+}
+
+void TextEditModel::moveCaret(int to, bool select) {
+ caret_ = std::clamp(to, 0, static_cast<int>(text_.size()));
+ if (!select) anchor_ = caret_;
+}
+
+int TextEditModel::wordLeft() const {
+ int at = caret_;
+ while (at > 0 && !isWordChar(text_[static_cast<size_t>(at) - 1])) --at;
+ while (at > 0 && isWordChar(text_[static_cast<size_t>(at) - 1])) --at;
+ return at;
+}
+
+int TextEditModel::wordRight() const {
+ const int size = static_cast<int>(text_.size());
+ int at = caret_;
+ while (at < size && !isWordChar(text_[static_cast<size_t>(at)])) ++at;
+ while (at < size && isWordChar(text_[static_cast<size_t>(at)])) ++at;
+ return at;
+}
+
+void TextEditModel::backspace() {
+ if (composing()) { composition_.clear(); return; }
+ if (anchor_ == caret_) {
+ if (caret_ == 0) return;
+ int to = caret_ - 1;
+ // One character, not one code unit: deleting half a surrogate pair leaves
+ // a lone half behind.
+ if (to > 0 && isLowSurrogate(text_[static_cast<size_t>(to)])
+ && isHighSurrogate(text_[static_cast<size_t>(to) - 1])) --to;
+ anchor_ = to;
+ }
+ replaceSelection({});
+}
+
+void TextEditModel::deleteForward() {
+ if (composing()) { composition_.clear(); return; }
+ const int size = static_cast<int>(text_.size());
+ if (anchor_ == caret_) {
+ if (caret_ >= size) return;
+ int to = caret_ + 1;
+ if (to < size && isHighSurrogate(text_[static_cast<size_t>(caret_)])
+ && isLowSurrogate(text_[static_cast<size_t>(to)])) ++to;
+ anchor_ = to;
+ }
+ replaceSelection({});
+}
+
+void TextEditModel::moveLeft(bool select, bool word) {
+ if (word) { moveCaret(wordLeft(), select); return; }
+ // Without shift, a selection COLLAPSES to its near edge rather than stepping
+ // one further — what every text field does, and what makes Left after a
+ // select-all put the caret at 0 instead of at -1.
+ if (!select && anchor_ != caret_) { moveCaret(low(), false); return; }
+ int to = caret_ - 1;
+ if (to > 0 && isLowSurrogate(text_[static_cast<size_t>(to)])
+ && isHighSurrogate(text_[static_cast<size_t>(to) - 1])) --to;
+ moveCaret(to, select);
+}
+
+void TextEditModel::moveRight(bool select, bool word) {
+ if (word) { moveCaret(wordRight(), select); return; }
+ if (!select && anchor_ != caret_) { moveCaret(high(), false); return; }
+ const int size = static_cast<int>(text_.size());
+ int to = caret_ + 1;
+ if (to < size && isHighSurrogate(text_[static_cast<size_t>(caret_)])
+ && isLowSurrogate(text_[static_cast<size_t>(to)])) ++to;
+ moveCaret(to, select);
+}
+
+void TextEditModel::moveToStart(bool select) { moveCaret(0, select); }
+void TextEditModel::moveToEnd(bool select) { moveCaret(static_cast<int>(text_.size()), select); }
+
+void TextEditModel::selectAll() {
+ anchor_ = 0;
+ caret_ = static_cast<int>(text_.size());
+}
+
+std::string TextEditModel::selectedText() const {
+ if (anchor_ == caret_) return {};
+ return utf16ToUtf8(text_.substr(static_cast<size_t>(low()), static_cast<size_t>(high() - low())));
+}
+
+void TextEditModel::deleteSelection() {
+ if (anchor_ == caret_) return;
+ replaceSelection({});
+}
+
+std::string TextEditModel::value() const {
+ if (composition_.empty()) return utf16ToUtf8(text_);
+ std::u16string shown = text_;
+ shown.insert(static_cast<size_t>(std::clamp(compositionAt_, 0, static_cast<int>(shown.size()))),
+ composition_);
+ return utf16ToUtf8(shown);
+}
+
+int TextEditModel::selectionStart() const {
+ // While an IME is up the caret sits after the preedit, which is where the
+ // user is typing — a caret left behind it would draw in the middle of the
+ // characters being composed.
+ return composition_.empty() ? low() : compositionAt_ + static_cast<int>(composition_.size());
+}
+
+int TextEditModel::selectionEnd() const {
+ return composition_.empty() ? high() : selectionStart();
+}
+
+} // namespace eshost
diff --git a/native/host/media/text_edit.hpp b/native/host/media/text_edit.hpp
new file mode 100644
index 000000000..888d36386
--- /dev/null
+++ b/native/host/media/text_edit.hpp
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file text_edit.hpp
+ * @brief The editing surface a desktop host has to BE, because no desktop OS
+ * supplies one.
+ * @details The platform seam (Host.hpp) hands the value and the selection to an
+ * OS editing surface: a UITextView on iOS, an EditText on Android, a
+ * hidden textarea on the web. Desktop has no such thing — the OS gives
+ * committed text and an IME's preedit, and every native app owns the
+ * caret, the selection and the editing keys itself. So this is that
+ * model, and it is the only implementation of it anywhere in the engine.
+ *
+ * Deliberately free of SDL and of the host: the clipboard and the events
+ * are the caller's, so the rules below can be tested as what they are —
+ * a pure function of keystrokes.
+ *
+ * Text is held as UTF-16 because that is the unit the seam's selection
+ * indices are in (a textarea's, an EditText's, an NSString's), and UTF-8
+ * only at the boundary where the value crosses into JS. Storing UTF-8 and
+ * converting indices would put a conversion in every operation instead of
+ * one at each edge.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include <string>
+
+namespace eshost {
+
+/** UTF-8 ⇄ UTF-16 at the boundary. Lone surrogates and truncated sequences are
+ * replaced rather than dropped, so a round trip never changes a string's length
+ * in a way the caller's indices did not account for. */
+std::string utf16ToUtf8(const std::u16string& text);
+std::u16string utf8ToUtf16(const std::string& text);
+
+/**
+ * One text field being edited: its content, its selection, and an IME's preedit.
+ *
+ * The reported selection is [start, end) in UTF-16 code units, ordered: no
+ * platform seam reports a selection's direction, so neither does this.
+ */
+class TextEditModel {
+ public:
+ /** Begin editing @p value. Options that outlive one keystroke are held here
+ * because every key has to be judged against them. */
+ void focus(const std::string& value, int selectionStart, int selectionEnd,
+ bool multiline, int maxLength, bool password);
+ void blur();
+ bool focused() const { return focused_; }
+ bool multiline() const { return multiline_; }
+ bool password() const { return password_; }
+
+ /** The app's own edit, which replaces everything — the seam's `write`. */
+ void write(const std::string& value, int selectionStart, int selectionEnd);
+
+ /** Committed text from the OS (SDL_EVENT_TEXT_INPUT): replaces the selection.
+ * Ends any composition, since the OS commits before it sends this. */
+ void insert(const std::string& utf8);
+
+ /**
+ * The IME's in-progress text (SDL_EVENT_TEXT_EDITING), not committed.
+ *
+ * Reported inside {@link value}, as the seam declares: a field that hid it
+ * would show nothing while a CJK user types. Empty ends the composition.
+ */
+ void setComposition(const std::string& utf8);
+ bool composing() const { return !composition_.empty(); }
+
+ // Editing keys. `select` extends the selection instead of collapsing it;
+ // `word` moves by word rather than by code unit.
+ void backspace();
+ void deleteForward();
+ void moveLeft(bool select, bool word);
+ void moveRight(bool select, bool word);
+ void moveToStart(bool select);
+ void moveToEnd(bool select);
+ void selectAll();
+
+ /** The selected text, for a copy or a cut. Empty when nothing is selected. */
+ std::string selectedText() const;
+ /** Drop the selection's contents, for a cut. */
+ void deleteSelection();
+
+ /** What the seam reports: the value WITH any preedit in it, and where the
+ * caret sits inside that. */
+ std::string value() const;
+ int selectionStart() const;
+ int selectionEnd() const;
+
+ private:
+ void replaceSelection(const std::u16string& with);
+ void moveCaret(int to, bool select);
+ int low() const;
+ int high() const;
+ int wordLeft() const;
+ int wordRight() const;
+
+ std::u16string text_;
+ std::u16string composition_;
+ /**
+ * Anchor and caret, NOT start and end.
+ *
+ * Which end MOVES is state shift+arrow cannot do without: after extending
+ * rightwards, shrinking walks the right end back, and a model holding only
+ * {start, end} walks the left one instead.
+ */
+ int anchor_ = 0;
+ int caret_ = 0;
+ /** Where the preedit sits — the caret at the moment composition began, kept
+ * because the caret is reported AFTER the preedit while it is up. */
+ int compositionAt_ = 0;
+ bool focused_ = false;
+ bool multiline_ = false;
+ bool password_ = false;
+ /** 0 = no limit, matching the seam's `maxLength`. */
+ int maxLength_ = 0;
+};
+
+} // namespace eshost
diff --git a/native/host/platform/desktop.cpp b/native/host/platform/desktop.cpp
index 800ea54fa..c193b3960 100644
--- a/native/host/platform/desktop.cpp
+++ b/native/host/platform/desktop.cpp
@@ -32,6 +32,7 @@
#include "Host.hpp"
+#include "media/text_edit.hpp"
#include "platform/desktop_keymap.hpp"
#if defined(__APPLE__)
@@ -130,6 +131,40 @@ struct DesktopPlatform final : eshost::Platform {
std::string executableDir() override { return exeDir; }
+ // The editing surface, which on desktop is US: a phone hands its keyboard the
+ // value and gets edits back, and SDL supplies only committed text and an IME
+ // preedit. The model in media/text_edit.hpp is the rest.
+ bool hasTextEditor() const override { return true; }
+
+ void textEditorFocus(const std::string& value, int selectionStart, int selectionEnd,
+ bool multiline, int maxLength, bool password) override {
+ editor.focus(value, selectionStart, selectionEnd, multiline, maxLength, password);
+ // Without this SDL delivers no SDL_EVENT_TEXT_INPUT at all, and on the
+ // platforms with a compositor-side IME it is also what opens it.
+ if (window) SDL_StartTextInput(window);
+ reportEditor();
+ }
+
+ void textEditorBlur() override {
+ editor.blur();
+ if (window) SDL_StopTextInput(window);
+ }
+
+ void textEditorWrite(const std::string& value, int selectionStart, int selectionEnd) override {
+ editor.write(value, selectionStart, selectionEnd);
+ // NOT reported back: this edit came FROM the app, and echoing it would be
+ // a second truth racing the one it already has.
+ }
+
+ /** Push the model's state across the seam — after every change, because the
+ * SDK's mirror is what a field reads while it renders. */
+ void reportEditor() {
+ eshost::deliverTextEditorState(editor.value(), editor.selectionStart(),
+ editor.selectionEnd(), editor.composing());
+ }
+
+ eshost::TextEditModel editor;
+
/** The same directory: on desktop the player can open it, which is the whole
* reason the mobile platforms distinguish a log dir from a private one. */
std::string logDir() override { return prefPath; }
@@ -263,6 +298,85 @@ std::string resolveContentRoot(int argc, char** argv) {
return readFileBytes(content + "game.config.json").empty() ? std::string(base) : content;
}
+/**
+ * A key that edits the focused field, if there is one.
+ *
+ * Only the keys a field OWNS: printable ones arrive as SDL_EVENT_TEXT_INPUT,
+ * already through the layout and the IME. While an IME composes, nothing but
+ * cancel — stealing its arrows is how a candidate list stops working.
+ */
+void editKey(const SDL_KeyboardEvent& key) {
+ eshost::TextEditModel& editor = g_platform.editor;
+ if (!editor.focused()) return;
+
+ const bool shift = (key.mod & SDL_KMOD_SHIFT) != 0;
+ // The word-jump chord: Alt on macOS, Ctrl elsewhere — as every text field on
+ // each platform does it.
+#if defined(__APPLE__)
+ const bool word = (key.mod & SDL_KMOD_ALT) != 0;
+ const bool command = (key.mod & SDL_KMOD_GUI) != 0;
+#else
+ const bool word = (key.mod & SDL_KMOD_CTRL) != 0;
+ const bool command = (key.mod & SDL_KMOD_CTRL) != 0;
+#endif
+
+ if (editor.composing() && key.scancode != SDL_SCANCODE_ESCAPE) return;
+
+ switch (key.scancode) {
+ case SDL_SCANCODE_BACKSPACE: editor.backspace(); break;
+ case SDL_SCANCODE_DELETE: editor.deleteForward(); break;
+ case SDL_SCANCODE_LEFT: editor.moveLeft(shift, word); break;
+ case SDL_SCANCODE_RIGHT: editor.moveRight(shift, word); break;
+ // A single-line field has one line, so Up/Down are its ends — which is
+ // where a caret goes when there is nowhere else to go.
+ case SDL_SCANCODE_UP:
+ case SDL_SCANCODE_HOME: editor.moveToStart(shift); break;
+ case SDL_SCANCODE_DOWN:
+ case SDL_SCANCODE_END: editor.moveToEnd(shift); break;
+ case SDL_SCANCODE_RETURN:
+ case SDL_SCANCODE_KP_ENTER:
+ if (editor.multiline()) editor.insert("\n");
+ else { eshost::deliverTextEditorSubmit(); return; }
+ break;
+ case SDL_SCANCODE_ESCAPE:
+ if (editor.composing()) editor.setComposition("");
+ else { eshost::deliverTextEditorCancel(); return; }
+ break;
+ case SDL_SCANCODE_A:
+ if (!command) return;
+ editor.selectAll();
+ break;
+ case SDL_SCANCODE_C:
+ case SDL_SCANCODE_X: {
+ if (!command) return;
+ const std::string selected = editor.selectedText();
+ if (selected.empty()) return;
+ SDL_SetClipboardText(selected.c_str());
+ if (key.scancode == SDL_SCANCODE_X) editor.deleteSelection();
+ break;
+ }
+ case SDL_SCANCODE_V: {
+ if (!command) return;
+ char* text = SDL_GetClipboardText();
+ if (!text) return;
+ // Newlines in a single-line field are what a paste from a document
+ // brings; a field that took them would render one line and hold two.
+ std::string paste = text;
+ SDL_free(text);
+ if (!editor.multiline()) {
+ std::string flat;
+ flat.reserve(paste.size());
+ for (const char c : paste) flat.push_back(c == '\n' || c == '\r' ? ' ' : c);
+ paste.swap(flat);
+ }
+ editor.insert(paste);
+ break;
+ }
+ default: return;
+ }
+ g_platform.reportEditor();
+}
+
/**
* The directory this binary is in, with a trailing separator.
*
@@ -413,6 +527,24 @@ int main(int argc, char** argv) {
if (const char* code = domCode(e.key.scancode)) {
eshost::key(e.type == SDL_EVENT_KEY_DOWN, code);
}
+ // AND to the field, if one is focused — not instead. A browser
+ // does the same: the hidden textarea takes the key and it still
+ // bubbles to the game's own listener, so play == ship.
+ if (e.type == SDL_EVENT_KEY_DOWN) editKey(e.key);
+ break;
+ case SDL_EVENT_TEXT_INPUT:
+ if (g_platform.editor.focused()) {
+ g_platform.editor.insert(e.text.text ? e.text.text : "");
+ g_platform.reportEditor();
+ }
+ break;
+ // The IME's preedit. It is NOT in the value yet, and a field that
+ // ignored it would show nothing at all while a CJK user types.
+ case SDL_EVENT_TEXT_EDITING:
+ if (g_platform.editor.focused()) {
+ g_platform.editor.setComposition(e.edit.text ? e.edit.text : "");
+ g_platform.reportEditor();
+ }
break;
// A pad appears as a joystick first; opening it is what makes SDL
// report it as a gamepad, and pollGamepads only sees opened ones.
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index f5b491dab..550bf50df 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -289,3 +289,14 @@ if(ES_ENABLE_BOX2D)
)
add_test(NAME test_physics_interpolation COMMAND test_physics_interpolation)
endif()
+
+# The desktop text-editing model. It lives in the native host rather than in the
+# engine, and it is compiled in directly (not linked) because the host is not a
+# library — which is fine, since the model is pure by construction: no SDL, no
+# host state, so the rules are testable as what they are.
+add_executable(test_text_edit
+ text/test_text_edit.cpp
+ ${CMAKE_SOURCE_DIR}/native/host/media/text_edit.cpp
+)
+target_include_directories(test_text_edit PRIVATE ${CMAKE_SOURCE_DIR}/native/host)
+add_test(NAME test_text_edit COMMAND test_text_edit)
diff --git a/tests/text/test_text_edit.cpp b/tests/text/test_text_edit.cpp
new file mode 100644
index 000000000..af08c7057
--- /dev/null
+++ b/tests/text/test_text_edit.cpp
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file test_text_edit.cpp
+ * @brief The desktop text-editing model.
+ *
+ * It is the engine's ONLY implementation of caret and selection behaviour — the
+ * web has a textarea, the phones have the OS keyboard — so nothing else can catch
+ * a rule that is wrong here, and a wrong rule reads as "typing does something
+ * odd", never as an error. Pure by construction (no SDL, no host), which is what
+ * makes this a unit test rather than something you check by typing into a window.
+ */
+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
+#include "doctest.h"
+
+#include "media/text_edit.hpp"
+
+using eshost::TextEditModel;
+using eshost::utf16ToUtf8;
+using eshost::utf8ToUtf16;
+
+namespace {
+
+TextEditModel field(const char* value = "", int start = 0, int end = -1) {
+ TextEditModel m;
+ const int at = end < 0 ? start : end;
+ m.focus(value, start, at, false, 0, false);
+ return m;
+}
+
+/** value + caret, the two things every case is about. */
+std::string shown(const TextEditModel& m) {
+ std::string out = m.value();
+ out += "|";
+ out += std::to_string(m.selectionStart());
+ out += ",";
+ out += std::to_string(m.selectionEnd());
+ return out;
+}
+
+} // namespace
+
+TEST_CASE("UTF-8 and UTF-16 round trip, including what is outside the BMP") {
+ for (const char* s : {"", "abc", u8"héllo", u8"日本語", u8"🎮 game", u8"a🎮b"}) {
+ CHECK(utf16ToUtf8(utf8ToUtf16(s)) == std::string(s));
+ }
+ // An emoji is ONE character and TWO code units — which is exactly the case
+ // every index rule below has to get right.
+ CHECK(utf8ToUtf16(u8"🎮").size() == 2);
+ CHECK(utf8ToUtf16("abc").size() == 3);
+}
+
+TEST_CASE("malformed input is replaced, not dropped") {
+ // Dropping would shorten the string under indices the caller already holds.
+ CHECK(utf8ToUtf16("\xC3").size() == 1); // truncated sequence
+ CHECK(utf8ToUtf16("a\x80\x62").size() == 3); // a stray continuation byte
+ std::u16string lone;
+ lone.push_back(0xD800);
+ CHECK(utf16ToUtf8(lone) == u8"�");
+}
+
+TEST_CASE("typing replaces the selection") {
+ TextEditModel m = field("hello", 1, 4);
+ m.insert("i");
+ CHECK(shown(m) == "hio|2,2");
+}
+
+TEST_CASE("backspace deletes a character, not a code unit") {
+ TextEditModel m = field(u8"a🎮");
+ m.moveToEnd(false);
+ m.backspace();
+ // Deleting one code unit would leave half a surrogate pair — a character no
+ // font has, and a string that no longer round-trips.
+ CHECK(shown(m) == "a|1,1");
+}
+
+TEST_CASE("delete forward mirrors it") {
+ TextEditModel m = field(u8"🎮b", 0);
+ m.deleteForward();
+ CHECK(shown(m) == "b|0,0");
+}
+
+TEST_CASE("backspace with a selection deletes the selection, not one more") {
+ TextEditModel m = field("hello", 1, 3);
+ m.backspace();
+ CHECK(shown(m) == "hlo|1,1");
+}
+
+TEST_CASE("arrows collapse a selection rather than moving from its edge") {
+ TextEditModel m = field("hello", 1, 4);
+ m.moveLeft(false, false);
+ CHECK(shown(m) == "hello|1,1");
+ m = field("hello", 1, 4);
+ m.moveRight(false, false);
+ CHECK(shown(m) == "hello|4,4");
+}
+
+TEST_CASE("shift+arrow extends from the anchor, in both directions") {
+ TextEditModel m = field("hello", 2);
+ m.moveRight(true, false);
+ m.moveRight(true, false);
+ CHECK(shown(m) == "hello|2,4");
+ // And back: the anchor stays put while the moving end walks over it.
+ m.moveLeft(true, false);
+ CHECK(shown(m) == "hello|2,3");
+}
+
+TEST_CASE("word movement crosses one word however it is punctuated") {
+ TextEditModel m = field("one two three");
+ m.moveToEnd(false);
+ m.moveLeft(false, true);
+ CHECK(shown(m) == "one two three|9,9");
+ m.moveLeft(false, true);
+ CHECK(shown(m) == "one two three|5,5");
+ m.moveRight(false, true);
+ CHECK(shown(m) == "one two three|8,8");
+}
+
+TEST_CASE("an IME's preedit is shown but not committed") {
+ TextEditModel m = field("ab", 1);
+ m.setComposition(u8"に");
+ // Inside the value, which is the seam's contract: a field that hid it would
+ // show nothing at all while a CJK user types.
+ CHECK(m.value() == u8"aにb");
+ CHECK(m.composing());
+ // The caret sits AFTER the preedit — where the typing is going.
+ CHECK(m.selectionStart() == 2);
+ CHECK(m.selectionEnd() == 2);
+
+ // The IME rewrites its preedit in place; the anchor must not walk.
+ m.setComposition(u8"にほん");
+ CHECK(m.value() == std::string(u8"aにほんb"));
+ CHECK(m.selectionStart() == 4);
+ m.insert(u8"日本");
+ CHECK(shown(m) == std::string(u8"a日本b") + "|3,3");
+ CHECK_FALSE(m.composing());
+}
+
+TEST_CASE("escape from a composition drops the preedit, not the text") {
+ TextEditModel m = field("ab", 1);
+ m.setComposition(u8"に");
+ m.backspace();
+ CHECK(shown(m) == "ab|1,1");
+ CHECK_FALSE(m.composing());
+}
+
+TEST_CASE("maxLength truncates the insertion, never mid-character") {
+ TextEditModel m;
+ m.focus("ab", 2, 2, false, 4, false);
+ m.insert(u8"c🎮d");
+ // Two code units of room: 'c' takes one, the emoji needs two, so neither the
+ // emoji nor 'd' fits — and half an emoji must not be what fits instead.
+ CHECK(m.value() == "abc");
+ // And with one unit of room the emoji is refused rather than halved.
+ TextEditModel n;
+ n.focus("abc", 3, 3, false, 4, false);
+ n.insert(u8"🎮");
+ CHECK(n.value() == "abc");
+}
+
+TEST_CASE("select all, copy and cut work on characters") {
+ TextEditModel m = field(u8"a🎮b");
+ m.selectAll();
+ CHECK(m.selectedText() == u8"a🎮b");
+ m.deleteSelection();
+ CHECK(shown(m) == "|0,0");
+}
+
+TEST_CASE("the app's own write replaces everything, including a preedit") {
+ TextEditModel m = field("abc", 1);
+ m.setComposition(u8"に");
+ m.write("xyz", 3, 3);
+ CHECK(shown(m) == "xyz|3,3");
+ CHECK_FALSE(m.composing());
+}
+
+TEST_CASE("a selection given backwards is the same selection") {
+ // No platform seam reports a selection's direction, so carrying one would be
+ // a state that can never be refreshed.
+ TextEditModel m = field("hello", 4, 1);
+ CHECK(shown(m) == "hello|1,4");
+}
+
+TEST_CASE("indices outside the value are clamped rather than trusted") {
+ TextEditModel m = field("hi", 99, 99);
+ CHECK(shown(m) == "hi|2,2");
+ m.write("hi", -5, 1);
+ CHECK(shown(m) == "hi|0,1");
+}