Compare commits

...
33 Commits
Author SHA1 Message Date
github-actions[bot] 43714e9270 Update CHANGELOG for v0.1.89 2026-09-08 14:01:45 +00:00
github-actions[bot] 488c351dcb release: bump version to v0.1.89 2026-09-08 13:59:24 +00:00
waozi c02966d54c Isolate native tab state per render host 2026-09-08 10:48:01 -03:00
github-actions[bot] 7f4ad51b71 Update CHANGELOG for v0.1.88 2026-09-08 13:46:36 +00:00
github-actions[bot] 7c923f347b release: bump version to v0.1.88 2026-09-08 13:44:06 +00:00
waozi 58734882d0 Keep dropdown keys within popup ownership 2026-09-08 10:33:22 -03:00
github-actions[bot] 262cb2d4e2 Update CHANGELOG for v0.1.87 2026-09-08 13:32:29 +00:00
github-actions[bot] 78f44046d9 release: bump version to v0.1.87 2026-09-08 13:30:19 +00:00
waozi 913e901a88 Keep popup menu Escape within its owner 2026-09-08 10:19:28 -03:00
github-actions[bot] 36857c5a5c Update CHANGELOG for v0.1.86 2026-09-08 13:17:58 +00:00
github-actions[bot] 11d496a362 release: bump version to v0.1.86 2026-09-08 13:15:11 +00:00
waozi d1d9346a62 Focus native sliders from pointer presses 2026-09-08 10:04:57 -03:00
github-actions[bot] 359fdb1452 Update CHANGELOG for v0.1.85 2026-09-08 12:54:16 +00:00
github-actions[bot] bd10a0d344 release: bump version to v0.1.85 2026-09-08 12:51:52 +00:00
waozi a169c824fb Add native Linux IBus text composition 2026-09-08 09:41:24 -03:00
github-actions[bot] cf5a8c1eb7 Update CHANGELOG for v0.1.84 2026-09-08 05:49:27 +00:00
github-actions[bot] eb8779cfba release: bump version to v0.1.84 2026-09-08 05:47:39 +00:00
waozi 644e0bd381 Remove legacy UIForm aliases 2026-09-08 02:37:01 -03:00
github-actions[bot] e4867b53a7 Update CHANGELOG for v0.1.83 2026-09-08 04:20:59 +00:00
github-actions[bot] 6af3207f0c release: bump version to v0.1.83 2026-09-08 04:18:47 +00:00
waozi d2877a70a0 Unify C text composition handling 2026-09-08 01:08:36 -03:00
github-actions[bot] fb788ac372 Update CHANGELOG for v0.1.82 2026-09-08 03:33:25 +00:00
github-actions[bot] 9b461dfda0 release: bump version to v0.1.82 2026-09-08 03:31:15 +00:00
waozi 4c17e487f0 Render native IME preedit accurately 2026-09-08 00:21:03 -03:00
github-actions[bot] 612de4e381 Update CHANGELOG for v0.1.81 2026-09-08 02:36:13 +00:00
github-actions[bot] 9136eeb6f1 release: bump version to v0.1.81 2026-09-08 02:33:45 +00:00
waozi 58714e5072 Add native word text editing 2026-09-07 23:23:21 -03:00
github-actions[bot] 0c0a5e88cf Update CHANGELOG for v0.1.80 2026-09-08 00:06:11 +00:00
github-actions[bot] 987ab0ef84 release: bump version to v0.1.80 2026-09-08 00:03:13 +00:00
waozi 415ce2ee6b Centralize C text navigation 2026-09-07 20:52:53 -03:00
github-actions[bot] d2aef861f2 Update CHANGELOG for v0.1.79 2026-09-07 23:32:59 +00:00
github-actions[bot] 8b83b40a9f release: bump version to v0.1.79 2026-09-07 23:30:45 +00:00
waozi 6a4e356f46 Unify text selection navigation 2026-09-07 20:19:42 -03:00
45 changed files with 3324 additions and 645 deletions

No files matched your search

+77
View File
@@ -1,4 +1,81 @@
# Changelog
## v0.1.89 - 2026-09-08
### Changed
- Release: bump version to v0.1.89
- Isolate native tab state per render host
## v0.1.88 - 2026-09-08
### Changed
- Release: bump version to v0.1.88
- Keep dropdown keys within popup ownership
## v0.1.87 - 2026-09-08
### Changed
- Release: bump version to v0.1.87
- Keep popup menu Escape within its owner
## v0.1.86 - 2026-09-08
### Changed
- Release: bump version to v0.1.86
- Focus native sliders from pointer presses
## v0.1.85 - 2026-09-08
### Changed
- Release: bump version to v0.1.85
- Add native Linux IBus text composition
## v0.1.84 - 2026-09-08
### Changed
- Release: bump version to v0.1.84
- Remove legacy UIForm aliases
## v0.1.83 - 2026-09-08
### Changed
- Release: bump version to v0.1.83
- Unify C text composition handling
## v0.1.82 - 2026-09-08
### Changed
- Release: bump version to v0.1.82
- Render native IME preedit accurately
## v0.1.81 - 2026-09-08
### Changed
- Release: bump version to v0.1.81
- Add native word text editing
## v0.1.80 - 2026-09-08
### Changed
- Release: bump version to v0.1.80
- Centralize C text navigation
## v0.1.79 - 2026-09-07
### Changed
- Release: bump version to v0.1.79
- Unify text selection navigation
## v0.1.78 - 2026-09-07
### Changed
+11 -10
View File
@@ -1850,19 +1850,20 @@ typedef struct {
Rectangle last_bounds;
int focused_rect_valid;
Rectangle focused_rect;
} UIForm;
} Form;
UIForm UIFormBegin(int x, int y, int width);
int UIFormY(const UIForm *form);
Rectangle UIFormTakeRect(UIForm *form, int height);
int UIFormLabelTextField(UIForm *form, LabelTextFieldProps row);
int UIFormCheckboxRow(UIForm *form, CheckboxRowProps row);
int UIFormSpinboxRow(UIForm *form, SpinboxRowProps row);
int UIFormButtonRow(UIForm *form, ButtonRowProps row);
int UIFormEnsureFocusedVisible(UIForm *form, UIScrollArea area, int margin);
Form FormBegin(int x, int y, int width);
int FormY(const Form *form);
Rectangle FormTakeRect(Form *form, int height);
int FormSection(Form *form, SectionLabelProps row);
int FormTextField(Form *form, LabelTextFieldProps row);
int FormCheckbox(Form *form, CheckboxRowProps row);
int FormSpinbox(Form *form, SpinboxRowProps row);
int FormButtons(Form *form, ButtonRowProps row);
int FormEnsureFocusedVisible(Form *form, UIScrollArea area, int margin);
```
`UIForm` is a small immediate-mode cursor for settings and data-entry pages.
`Form` is a small immediate-mode cursor for settings and data-entry pages.
It centralizes row advancement, default row heights, and focused-field
scrolling so apps do not need parallel `draw_*` and `content_height_*`
arithmetic for simple forms.
+9 -5
View File
@@ -296,8 +296,9 @@ events expire at frame end alongside other unhandled text, preventing delayed
commit after dismissal. Commits cannot mutate read-only TextField/TextArea
buffers. Preedit is cancelled when the retained editor loses focus, becomes
read-only or is blocked by popup keyboard ownership; tests check cancellation
events and no revival after re-enabling. Immediate C composition and device-level
IME delivery remain unfinished.
events and no revival after re-enabling. Immediate and retained C editors now
share the same composition session and commit operation. Device-level Android
IME delivery remains unverified.
Native Go now has runtime-local composition queues and per-editor preedit state.
TextField/TextArea display preedit without mutating caller buffers, and commits
@@ -305,9 +306,12 @@ use UTF-8 insertion/cursor handling. Tests cover queue isolation and limits,
multi-frame preedit, commits, cancellation, removed/disabled/unfocused editors,
and popup dismissal without replay. The native generated `composition.kry`
fixture verifies non-mutating preedit, UTF-8 commit and cancellation through C
and Go; the JavaScript runner does not execute it. Go OS-window event delivery,
detailed preedit cursor/selection rendering and C TextArea preedit rendering
are still incomplete.
and Go; the JavaScript runner does not execute it. The pure-Go Linux/X11 window
backend now routes native IBus key/focus events and preedit/commit signals into
that same composition queue, including UTF-8 cursor conversion and focused
caret placement. Detailed preedit rendering is shared by TextField and TextArea
in both native runtimes. Other Linux input-method protocols and device-level
Android/Win32 delivery remain unverified.
Read-only editing now has matching native generated coverage. The composition
fixture declares read-only TextField and TextArea in C and Go, checks copying,
+1 -1
View File
@@ -115,7 +115,7 @@ li{margin:.25rem 0}
<tr><td class="">PanedView (splitter)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>PanedView</code></td><td class="no">✗</td></tr>
<tr><td class="">Collapsible</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Collapsible</code></td><td class="no">✗</td></tr>
<tr><td class="">Tk pack/grid helpers (<code>FramePack</code>, <code>GridCell</code>, <code>Place</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td></tr>
<tr><td class="">UIForm cursor (<code>UIForm*</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Form cursor (<code>Form*</code>)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="no">✗</td><td class="no">✗</td><td class="no">✗</td></tr>
<tr><td class="">Canvas (pan/zoom, hit-test, grid)</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅</td><td class="ok">✅ <code>Begin/EndCanvas</code></td><td class="ok">✅ <code>Begin/EndCanvas</code>+hit-test</td><td class="no">✗</td></tr>
</table>
<h3>UI/Collections</h3>
+1 -1
View File
@@ -149,7 +149,7 @@ declaration pass (`src/ui/ui_tree.c`).
| PanedView (splitter) | ✅ | ✅ | ✅ | ✅ | ✅ `PanedView` | ✗ |
| Collapsible | ✅ | ✅ | ✅ | ✅ | ✅ `Collapsible` | ✗ |
| Tk pack/grid helpers (`FramePack`, `GridCell`, `Place`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✗ |
| UIForm cursor (`UIForm*`) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Form cursor (`Form*`) | ✅ | ✅ | ✅ | ✗ | ✗ | ✗ |
| Canvas (pan/zoom, hit-test, grid) | ✅ | ✅ | ✅ | ✅ `Begin/EndCanvas` | ✅ `Begin/EndCanvas`+hit-test | ✗ |
### UI/Collections
+56 -15
View File
@@ -77,8 +77,8 @@ select the range limits, Alt slows adjustment, and Shift accelerates it. Pointer
presses focus the exact component, disabled sliders reject keys, popup ownership
gates keyboard input, and the focused component receives the ordinary focus
presentation. Matching native tests cover component Tab traversal and the
generated `plots.kry` fixture verifies horizontal float and vertical integer
adjustment through k2c and k2go.
pointer-to-keyboard transition; the generated `plots.kry` fixture verifies
horizontal float and vertical integer adjustment through k2c and k2go.
Ctrl-clicking or double-clicking a drag or slider component temporarily
replaces that component with the canonical text editor in native C and Go. Valid edits update live,
Enter returns to the numeric control, and typed values remain unclamped like
@@ -138,6 +138,11 @@ the surrounding layout cursor.
C layer disabled scopes now inherit the parent's state without allowing child
scope endings to unwind the parent. Headless nested-scope tests and the real
layer test cover restoration, with invalid-scope checks for an unclosed child.
C tab-bar owned scroll and its bar-local click, reorder, and pane-drag
bookkeeping now belong to that same render-host context instead of
process-global statics. Interleaved graphical hosts use the same tab ID without
sharing omitted scroll state, and restoring the outer host restores its state
immediately. The broader C focus and pointer state is still shared.
C layers also isolate input clips and scroll depth from the owner. Ordinary
button tests verify escaped clipping without bypassing modal capture, and real
pixels verify mixed content outside a 1x1 scrolling owner. Popup-to-background
@@ -194,7 +199,13 @@ Generic native accelerators now have matching C and Go APIs and top-popup
ownership. Generated k2c/k2cpp/k2go coverage proves Ctrl+C dispatch inside the
active popup, suppression of the same background chord, and restoration after
the popup is explicitly closed. Widget-specific shortcut paths still require
their own ownership coverage.
their own ownership coverage. Popup menus apply that ownership to Escape as
well as navigation and activation, so an obscured menu cannot clear focus
belonging to the active popup branch.
Dropdown/Combobox stores the declaration's popup-owner snapshot for its
deferred overlay pass. Escape, arrows, Home/End, and Enter are ignored while a
newer child branch owns the keyboard, then work again as soon as that branch
closes.
Collapsible/tree-header arrows now have matching native and generated popup
ownership coverage, including background restoration after close.
Selectable-text copy is likewise ownership-gated in C and Go; native Go tests
@@ -239,19 +250,38 @@ reject captured text, remain unchanged on the next frame without input, and
accept fresh text later. C covers both injected and platform-queued characters,
same-frame dismissal, and queued Backspace/Enter for TextField. Popup-captured
leftovers now expire at frame end. Go's existing frame cleanup passes the matching
text test. IME composition and device-level Android delivery remain unverified.
C retained IME now has separate regressions: blocked commits do not replay,
text test. Device-level Android IME delivery remains unverified.
C IME now has separate regressions: blocked commits do not replay,
read-only TextField/TextArea reject commits, and TextField preedit cancels on
focus loss, a read-only transition or popup capture without revival. This does
not establish immediate C editor composition, native Go composition events or
device-level IME delivery.
focus loss, a read-only transition or popup capture without revival.
Native Go now implements runtime-local composition events and per-editor
preedit for TextField/TextArea. Tests cover queue isolation/limits, preedit
persistence without buffer mutation, UTF-8 commit, cancellation, editor removal,
focus loss, disabling and popup dismissal. `composition.kry` is executed through
generated C and Go to verify preedit/commit/cancel behavior; it is not executed
by the JavaScript runner. OS-window Go IME delivery and detailed preedit
cursor/selection rendering remain unfinished.
by the JavaScript runner. Retained C and native Go now build the visible preedit
through one UTF-8 composition-view primitive per runtime: it visually replaces
the committed selection without mutating the caller buffer, positions the caret
at the IME cursor, highlights the IME-selected subrange, and underlines the full
composition in both TextField and TextArea. C previously omitted TextArea
preedit entirely. The DOM and Android adapters now normalize the composition
cursor to the runtime's documented UTF-8 byte-offset contract, and retained C
editors preserve their declaration-time Kryon font through deferred painting.
Immediate and retained C editors now share one private composition session and
one commit operation; retained widget state no longer duplicates preedit text,
cursor or selection fields. Immediate TextField/TextArea tests cover UTF-8
preedit without caller-buffer mutation, commits, selection replacement and
read-only cancellation.
The pure-Go Linux/X11 window backend now connects directly to the desktop's
IBus daemon without cgo. Each window owns one input context; X11 press/release
and focus events pass through it before the ordinary keysym fallback, and
CommitText/UpdatePreeditText signals feed the existing runtime-local
composition queue. Cursor positions are converted from IBus codepoints to the
runtime's UTF-8 byte offsets, and candidate placement follows the focused
TextField/TextArea caret. A fake-daemon protocol test covers context setup,
key forwarding and Unicode preedit/commit, while an opt-in test verifies the
real desktop daemon. Other Linux input-method protocols and device-level
Android/Win32 IME delivery remain unverified.
Read-only TextField/TextArea behavior is now covered by the native generated
composition fixture: selection/copy remains usable while text, cut/paste,
deletion and IME commits cannot mutate buffers. C retained mutation paths now
@@ -260,11 +290,22 @@ while suppressing the insertion caret. Go tests cover preedit cancellation,
buffer preservation, rejected-input expiry and fresh editing after re-enabling.
Multiline TextArea navigation now handles Up/Down and PageUp/PageDown in native
C and Go, with page movement derived from the visible editor height. The C
immediate and retained paths share the same internal line/page movement helpers,
so generated code no longer loses vertical navigation when submitted through
the retained tree. Enter inserts a newline in Go TextArea instead of following
the single-line commit path. Direct runtime tests and the generated composition
fixture exercise these behaviors through k2c and k2go.
immediate and retained paths route every navigation key through one internal
selection-navigation routine, including the shared line/page movement helpers,
so generated code cannot drift from the direct widget behavior. Enter inserts
a newline in Go TextArea instead of following the single-line commit path.
Direct runtime tests and the generated composition fixture exercise these
behaviors through k2c and k2go. Shift extends selections across horizontal,
vertical, page and Home/End navigation; an unmodified arrow collapses an active
selection toward that edge. Multiline Home/End target the current line, while
the platform modifier plus Home/End targets the whole buffer. Modifier plus
Left/Right now uses Dear ImGui-compatible UTF-8 word boundaries, including
punctuation separators and full-width blanks, and Shift extends those word
selections. Modifier plus Backspace/Delete uses the same boundary helpers and
the same selection-first deletion primitive in immediate C, retained C, and
Go. The generated composition fixture covers word movement, selection, and
deletion through k2c and k2go. Native Go's X11 input path also preserves Shift
on special keys and routes Ctrl+Arrow/Backspace/Delete as modifier shortcuts.
Native C and Go list boxes now register with ordinary Tab focus, expose a
visible focus presentation, and move selection with Up/Down/Home/End while
+11 -21
View File
@@ -1707,30 +1707,20 @@ include/ui_profile.h function GetUIProfilePictureIconType
include/ui_profile.h function GetUIProfilePictureIconTypeForSyncID
include/ui_profile.h function GetUISyncIDForProfilePictureIconType
include/ui_reorder.h function UpdateUIReorderList
include/ui_rows.h function FormAdvance
include/ui_rows.h function FormBegin
include/ui_rows.h function FormButtons
include/ui_rows.h function FormCheckbox
include/ui_rows.h function FormEnsureFocusedVisible
include/ui_rows.h function FormNoteFocus
include/ui_rows.h function FormSection
include/ui_rows.h function FormSpinbox
include/ui_rows.h function FormTakeRect
include/ui_rows.h function FormTextField
include/ui_rows.h function FormY
include/ui_rows.h function GetUIButtonRowHeight
include/ui_rows.h function GetUILabelTextFieldHeight
include/ui_rows.h function GetUISpinboxRowHeight
include/ui_rows.h function UIFormAdvance
include/ui_rows.h function UIFormBegin
include/ui_rows.h function UIFormButtonRow
include/ui_rows.h function UIFormButtons
include/ui_rows.h function UIFormButtonsEx
include/ui_rows.h function UIFormCheckbox
include/ui_rows.h function UIFormCheckboxEx
include/ui_rows.h function UIFormCheckboxRow
include/ui_rows.h function UIFormEnsureFocusedVisible
include/ui_rows.h function UIFormLabelTextField
include/ui_rows.h function UIFormNoteFocus
include/ui_rows.h function UIFormSection
include/ui_rows.h function UIFormSectionEx
include/ui_rows.h function UIFormSectionLabel
include/ui_rows.h function UIFormSpinbox
include/ui_rows.h function UIFormSpinboxEx
include/ui_rows.h function UIFormSpinboxRow
include/ui_rows.h function UIFormTakeRect
include/ui_rows.h function UIFormTextField
include/ui_rows.h function UIFormTextFieldEx
include/ui_rows.h function UIFormY
include/ui_scaling.h function ClampUIPx
include/ui_scaling.h function GetUIScale
include/ui_scaling.h function Scale
+4
View File
@@ -47,6 +47,10 @@ type inputController interface {
QueueShortcut(int32)
}
type modifiedInputController interface {
queueModifiedKey(int32, bool, bool)
}
type clipboardController interface {
SetClipboardText(string)
ClipboardText() string
+40 -3
View File
@@ -1,6 +1,9 @@
package kryon
import "strings"
import (
"strings"
"unicode/utf8"
)
// These phases and queue limits match the native C input front-end.
type KryTextCompositionPhase int32
@@ -14,8 +17,9 @@ const (
)
type KryTextCompositionEvent struct {
Phase KryTextCompositionPhase
Text string
Phase KryTextCompositionPhase
Text string
// Cursor and SelectionLength are UTF-8 byte offsets within Text.
Cursor int32
SelectionLength int32
}
@@ -30,6 +34,9 @@ func (r *runtime) SubmitTextComposition(phase KryTextCompositionPhase, text stri
if len(text) >= KRY_TEXT_COMPOSITION_MAX {
text = text[:KRY_TEXT_COMPOSITION_MAX-1]
}
for !utf8.ValidString(text) {
text = text[:len(text)-1]
}
r.compositionEvents = append(r.compositionEvents, KryTextCompositionEvent{phase, text, max(cursor, 0), max(selectionLength, 0)})
return 1
}
@@ -60,6 +67,36 @@ func PollTextComposition(event *KryTextCompositionEvent) int32 {
func ClearTextComposition() { active().ClearTextComposition() }
type textCompositionView struct {
text string
cursor int
selectionStart int
selectionEnd int
compositionStart int
compositionEnd int
}
func makeTextCompositionView(text string, selectionStart, selectionEnd int, preedit KryTextCompositionEvent) (textCompositionView, bool) {
if preedit.Text == "" {
return textCompositionView{}, false
}
selectionStart = clampCursor(text, selectionStart)
selectionEnd = clampCursor(text, selectionEnd)
if selectionStart > selectionEnd {
selectionStart, selectionEnd = selectionEnd, selectionStart
}
preeditCursor := clampCursor(preedit.Text, int(preedit.Cursor))
preeditSelectionEnd := clampCursor(preedit.Text, preeditCursor+int(preedit.SelectionLength))
return textCompositionView{
text: text[:selectionStart] + preedit.Text + text[selectionEnd:],
cursor: selectionStart + preeditCursor,
selectionStart: selectionStart + preeditCursor,
selectionEnd: selectionStart + preeditSelectionEnd,
compositionStart: selectionStart,
compositionEnd: selectionStart + len(preedit.Text),
}, true
}
func (r *runtime) editComposition(id int32, text string, pos int, sel selection, limit int) (string, int, selection, bool) {
changed := false
var event KryTextCompositionEvent
+51 -1
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"strings"
"testing"
"unicode/utf8"
)
func TestCompositionQueueOwnership(t *testing.T) {
@@ -31,6 +32,11 @@ func TestCompositionQueueOwnership(t *testing.T) {
if r.PollTextComposition(&event) != 0 {
t.Fatal("clear retained events")
}
truncated := strings.Repeat("x", 254) + "日"
if r.SubmitTextComposition(KRY_TEXT_COMPOSITION_UPDATE, truncated, 254, 0) != 1 ||
r.PollTextComposition(&event) != 1 || len(event.Text) != 254 || !utf8.ValidString(event.Text) {
t.Fatalf("composition queue retained partial UTF-8: %q", event.Text)
}
}
func compositionEditor(r *runtime, area bool, text []byte, cursor *int32) {
@@ -63,6 +69,7 @@ func TestCompositionPreeditCommitAndCancel(t *testing.T) {
r.BeginFrame()
compositionEditor(r, area, text, &cursor)
r.EndFrame()
op := r.FrameOps()[0]
want, display := "a", "ani"
if frame >= 2 {
want, display = "a日", "a日"
@@ -70,10 +77,14 @@ func TestCompositionPreeditCommitAndCancel(t *testing.T) {
if got := string(text[:zeroIndex(text)]); got != want {
t.Fatalf("area=%v frame=%d buffer=%q want=%q", area, frame, got, want)
}
if got := r.FrameOps()[0].Text; got != display {
if got := op.Text; got != display {
t.Fatalf("area=%v frame=%d display=%q want=%q", area, frame, got, display)
}
if frame == 0 {
if op.Cursor != 3 || op.SelectionStart != 3 || op.SelectionEnd != 3 ||
op.CompositionStart != 1 || op.CompositionEnd != 3 {
t.Fatalf("area=%v: bad preedit paint metadata: %+v", area, op)
}
withPreedit := RenderFrame(160, 120, r.FrameOps())
plain := append([]FrameOp(nil), r.FrameOps()...)
plain[0].Text = want
@@ -89,6 +100,45 @@ func TestCompositionPreeditCommitAndCancel(t *testing.T) {
}
}
func TestCompositionPaintReplacesSelectionAndUsesUTF8Offsets(t *testing.T) {
for _, area := range []bool{false, true} {
r := New(AppConfig{}).(*runtime)
text := make([]byte, 32)
copy(text, "aXYZz")
cursor := int32(4)
r.setFocus(26100)
r.selection[26100] = selection{Anchor: 1, Cursor: 4}
r.SubmitTextComposition(KRY_TEXT_COMPOSITION_UPDATE, "日ab", 3, 1)
r.BeginFrame()
compositionEditor(r, area, text, &cursor)
r.EndFrame()
if got := string(text[:zeroIndex(text)]); got != "aXYZz" {
t.Fatalf("area=%v: preedit mutated committed text: %q", area, got)
}
op := r.FrameOps()[0]
if op.Text != "a日abz" || op.Cursor != 4 ||
op.SelectionStart != 4 || op.SelectionEnd != 5 ||
op.CompositionStart != 1 || op.CompositionEnd != 6 {
t.Fatalf("area=%v: bad selected preedit paint metadata: %+v", area, op)
}
withUnderline := RenderFrame(180, 120, r.FrameOps())
withoutUnderlineOps := append([]FrameOp(nil), r.FrameOps()...)
withoutUnderlineOps[0].CompositionStart = 0
withoutUnderlineOps[0].CompositionEnd = 0
withoutUnderline := RenderFrame(180, 120, withoutUnderlineOps)
if bytes.Equal(withUnderline.Pix, withoutUnderline.Pix) {
t.Fatalf("area=%v: renderer omitted composition underline", area)
}
}
view, ok := makeTextCompositionView("ab", 1, 1,
KryTextCompositionEvent{Text: "日", Cursor: 2, SelectionLength: 8})
if !ok || view.cursor != 1 || view.selectionEnd != 4 {
t.Fatalf("composition view did not clamp UTF-8 offsets: %+v", view)
}
}
func TestPopupCompositionDismissalDoesNotReplay(t *testing.T) {
for _, area := range []bool{false, true} {
r := New(AppConfig{}).(*runtime)
+28
View File
@@ -87,6 +87,34 @@ func dbusSession() (*dbusConn, error) {
if addr == "" {
return nil, errors.New("dbus: no session bus address")
}
return dbusOpen(addr)
}
// dbusOpen connects to a D-Bus address and completes the standard bus
// handshake. Desktop services such as IBus publish their own private bus
// address rather than living on DBUS_SESSION_BUS_ADDRESS.
func dbusOpen(addr string) (*dbusConn, error) {
// An address may contain fallbacks separated by semicolons. Keep this
// client deliberately small, but try every advertised Unix transport.
var lastErr error
for _, candidate := range strings.Split(addr, ";") {
candidate = strings.TrimSpace(candidate)
if candidate == "" {
continue
}
conn, err := dbusOpenOne(candidate)
if err == nil {
return conn, nil
}
lastErr = err
}
if lastErr == nil {
lastErr = errors.New("dbus: empty address")
}
return nil, lastErr
}
func dbusOpenOne(addr string) (*dbusConn, error) {
transport, rest, ok := strings.Cut(addr, ":")
if !ok {
return nil, fmt.Errorf("dbus: bad address %q", addr)
+2
View File
@@ -46,6 +46,8 @@ type FrameOp struct {
Cursor int32
SelectionStart int32
SelectionEnd int32
CompositionStart int32
CompositionEnd int32
Focused bool
Pressed bool
Disabled bool
+396
View File
@@ -0,0 +1,396 @@
//go:build linux
package kryon
// Native IBus input-method bridge for the pure-Go X11 window backend. IBus
// feeds the same composition queue as every other platform; text editing and
// rendering remain owned by TextField/TextArea.
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
const (
ibusService = "org.freedesktop.IBus"
ibusRootPath = "/org/freedesktop/IBus"
ibusContextIface = "org.freedesktop.IBus.InputContext"
ibusCapPreedit = uint32(1 << 0)
ibusCapFocus = uint32(1 << 3)
ibusCallTimeout = 750 * time.Millisecond
ibusCloseTimeout = 100 * time.Millisecond
ibusPendingLimit = 16
)
type ibusInputMethod struct {
conn *dbusConn
path string
mu sync.Mutex
pending []KryTextCompositionEvent
forwarded []ibusForwardedKey
preedit bool
focused bool
cursor [4]int32
hasCursor bool
}
type ibusForwardedKey struct {
keyval uint32
state uint32
}
func openIBusInputMethod() (*ibusInputMethod, error) {
if !ibusRequested() {
return nil, errors.New("ibus: not selected by desktop environment")
}
addr, err := ibusAddress()
if err != nil {
return nil, err
}
conn, err := dbusOpen(addr)
if err != nil {
return nil, err
}
fail := func(err error) (*ibusInputMethod, error) {
conn.close()
return nil, err
}
reply, err := conn.call(ibusService, ibusRootPath, ibusService,
"CreateInputContext", "s", []any{"kryon"}, ibusCallTimeout)
if err != nil {
return fail(err)
}
values, err := dbusDecodeAll("o", reply.body)
if err != nil {
return fail(fmt.Errorf("ibus: invalid input context reply: %w", err))
}
if len(values) != 1 {
return fail(errors.New("ibus: invalid input context reply"))
}
path, ok := values[0].(string)
if !ok || path == "" {
return fail(errors.New("ibus: empty input context path"))
}
im := &ibusInputMethod{conn: conn, path: path}
rule := "type='signal',path='" + path + "',interface='" + ibusContextIface + "'"
if err := conn.onSignal(rule, im.handleSignal); err != nil {
return fail(err)
}
if _, err := conn.call(ibusService, path, ibusContextIface,
"SetCapabilities", "u", []any{ibusCapPreedit | ibusCapFocus}, ibusCallTimeout); err != nil {
return fail(err)
}
return im, nil
}
func ibusRequested() bool {
if os.Getenv("IBUS_ADDRESS") != "" {
return true
}
for _, name := range []string{"GTK_IM_MODULE", "QT_IM_MODULE"} {
if strings.EqualFold(strings.TrimSpace(os.Getenv(name)), "ibus") {
return true
}
}
return strings.Contains(strings.ToLower(os.Getenv("XMODIFIERS")), "@im=ibus")
}
func ibusAddress() (string, error) {
if addr := strings.TrimSpace(os.Getenv("IBUS_ADDRESS")); addr != "" {
return addr, nil
}
config, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("ibus: config directory: %w", err)
}
dir := filepath.Join(config, "ibus", "bus")
entries, err := os.ReadDir(dir)
if err != nil {
return "", fmt.Errorf("ibus: address directory: %w", err)
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
suffix := ibusDisplaySuffix(os.Getenv("DISPLAY"))
var fallback string
for _, entry := range entries {
if entry.IsDir() {
continue
}
path := filepath.Join(dir, entry.Name())
data, readErr := os.ReadFile(path)
if readErr != nil || len(data) > 4096 {
continue
}
addr := ibusAddressFromFile(string(data))
if addr == "" {
continue
}
if suffix != "" && strings.HasSuffix(entry.Name(), suffix) {
return addr, nil
}
if fallback == "" {
fallback = addr
}
}
if fallback != "" {
return fallback, nil
}
return "", errors.New("ibus: no address found")
}
func ibusDisplaySuffix(display string) string {
display = strings.TrimSpace(display)
colon := strings.LastIndexByte(display, ':')
if colon < 0 {
return ""
}
host := display[:colon]
number := display[colon+1:]
if dot := strings.IndexByte(number, '.'); dot >= 0 {
number = number[:dot]
}
if _, err := strconv.Atoi(number); err != nil {
return ""
}
if host == "" || host == "unix" || host == "localhost" {
host = "unix"
}
return "-" + host + "-" + number
}
func ibusAddressFromFile(contents string) string {
for _, line := range strings.Split(contents, "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "IBUS_ADDRESS=") {
continue
}
return strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "IBUS_ADDRESS=")), "\"'")
}
return ""
}
func (im *ibusInputMethod) focusIn() {
im.mu.Lock()
if im.focused {
im.mu.Unlock()
return
}
im.mu.Unlock()
if _, err := im.conn.call(ibusService, im.path, ibusContextIface, "FocusIn", "", nil, ibusCallTimeout); err != nil {
return
}
im.mu.Lock()
im.focused = true
im.mu.Unlock()
}
func (im *ibusInputMethod) focusOut() {
im.mu.Lock()
if !im.focused {
im.mu.Unlock()
return
}
im.focused = false
im.hasCursor = false
im.mu.Unlock()
_, _ = im.conn.call(ibusService, im.path, ibusContextIface, "Reset", "", nil, ibusCloseTimeout)
_, _ = im.conn.call(ibusService, im.path, ibusContextIface, "FocusOut", "", nil, ibusCloseTimeout)
}
func (im *ibusInputMethod) close() {
if im == nil || im.conn == nil {
return
}
im.focusOut()
im.conn.close()
}
func (im *ibusInputMethod) processKey(keyval uint32, keycode uint8, state uint32) bool {
if im == nil || keyval == 0 {
return false
}
im.focusIn()
im.mu.Lock()
focused := im.focused
im.mu.Unlock()
if !focused {
return false
}
xkbCode := uint32(0)
if keycode >= 8 {
xkbCode = uint32(keycode - 8)
}
reply, err := im.conn.call(ibusService, im.path, ibusContextIface,
"ProcessKeyEvent", "uuu", []any{keyval, xkbCode, state}, ibusCallTimeout)
if err != nil {
return false
}
values, err := dbusDecodeAll("b", reply.body)
return err == nil && len(values) == 1 && values[0] == true
}
func (im *ibusInputMethod) setCursor(x, y, width, height int32) {
if im == nil {
return
}
next := [4]int32{x, y, width, height}
im.mu.Lock()
if !im.focused || im.hasCursor && im.cursor == next {
im.mu.Unlock()
return
}
im.cursor = next
im.hasCursor = true
im.mu.Unlock()
_, _ = im.conn.call(ibusService, im.path, ibusContextIface,
"SetCursorLocationRelative", "iiii", []any{x, y, width, height}, ibusCallTimeout)
}
func (im *ibusInputMethod) handleSignal(message *dbusMessage) {
if message.path != im.path || message.iface != ibusContextIface {
return
}
switch message.member {
case "CommitText":
values, err := dbusDecodeAll("v", message.body)
if err == nil && len(values) == 1 {
if text, ok := ibusText(values[0]); ok {
im.enqueue(KryTextCompositionEvent{Phase: KRY_TEXT_COMPOSITION_COMMIT, Text: text})
im.mu.Lock()
im.preedit = false
im.mu.Unlock()
}
}
case "UpdatePreeditText", "UpdatePreeditTextWithMode":
sig := "vub"
if message.member == "UpdatePreeditTextWithMode" {
sig = "vubu"
}
values, err := dbusDecodeAll(sig, message.body)
if err != nil || len(values) < 3 {
return
}
text, ok := ibusText(values[0])
cursor, cursorOK := values[1].(uint32)
visible, visibleOK := values[2].(bool)
if !ok || !cursorOK || !visibleOK {
return
}
if !visible || text == "" {
im.cancelPreedit()
return
}
im.mu.Lock()
phase := KRY_TEXT_COMPOSITION_UPDATE
if !im.preedit {
phase = KRY_TEXT_COMPOSITION_START
im.preedit = true
}
im.enqueueLocked(KryTextCompositionEvent{
Phase: phase, Text: text, Cursor: ibusCursorByteOffset(text, cursor),
})
im.mu.Unlock()
case "HidePreeditText":
im.cancelPreedit()
case "ForwardKeyEvent":
values, err := dbusDecodeAll("uuu", message.body)
if err != nil || len(values) != 3 {
return
}
keyval, keyOK := values[0].(uint32)
state, stateOK := values[2].(uint32)
if !keyOK || !stateOK {
return
}
im.mu.Lock()
if len(im.forwarded) == ibusPendingLimit {
copy(im.forwarded, im.forwarded[1:])
im.forwarded = im.forwarded[:len(im.forwarded)-1]
}
im.forwarded = append(im.forwarded, ibusForwardedKey{keyval: keyval, state: state})
im.mu.Unlock()
}
}
func ibusText(value any) (string, bool) {
variant, ok := value.(dbusVariant)
if !ok {
return "", false
}
object, ok := variant.Val.(dbusStruct)
if !ok || len(object.Val) < 3 {
return "", false
}
typeName, typeOK := object.Val[0].(string)
text, textOK := object.Val[2].(string)
return text, typeOK && typeName == "IBusText" && textOK && utf8.ValidString(text)
}
func ibusCursorByteOffset(text string, runeOffset uint32) int32 {
if runeOffset == 0 {
return 0
}
count := uint32(0)
for offset := range text {
if count == runeOffset {
return int32(offset)
}
count++
}
return int32(len(text))
}
func (im *ibusInputMethod) cancelPreedit() {
im.mu.Lock()
defer im.mu.Unlock()
if !im.preedit {
return
}
im.preedit = false
im.enqueueLocked(KryTextCompositionEvent{Phase: KRY_TEXT_COMPOSITION_CANCEL})
}
func (im *ibusInputMethod) enqueue(event KryTextCompositionEvent) {
im.mu.Lock()
im.enqueueLocked(event)
im.mu.Unlock()
}
func (im *ibusInputMethod) enqueueLocked(event KryTextCompositionEvent) {
if event.Phase == KRY_TEXT_COMPOSITION_UPDATE && len(im.pending) > 0 &&
im.pending[len(im.pending)-1].Phase == KRY_TEXT_COMPOSITION_UPDATE {
im.pending[len(im.pending)-1] = event
return
}
if len(im.pending) == ibusPendingLimit {
copy(im.pending, im.pending[1:])
im.pending = im.pending[:len(im.pending)-1]
}
im.pending = append(im.pending, event)
}
func (im *ibusInputMethod) drain() []KryTextCompositionEvent {
im.mu.Lock()
defer im.mu.Unlock()
events := append([]KryTextCompositionEvent(nil), im.pending...)
clear(im.pending)
im.pending = im.pending[:0]
return events
}
func (im *ibusInputMethod) drainForwarded() []ibusForwardedKey {
im.mu.Lock()
defer im.mu.Unlock()
keys := append([]ibusForwardedKey(nil), im.forwarded...)
clear(im.forwarded)
im.forwarded = im.forwarded[:0]
return keys
}
+155
View File
@@ -0,0 +1,155 @@
//go:build linux
package kryon
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestIBusAddressUsesCurrentDisplay(t *testing.T) {
config := t.TempDir()
dir := filepath.Join(config, "ibus", "bus")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "machine-unix-1"),
[]byte("IBUS_ADDRESS=unix:path=/wrong\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "machine-unix-2"),
[]byte("# generated\nIBUS_ADDRESS='unix:path=/right,guid=abc'\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("IBUS_ADDRESS", "")
t.Setenv("XDG_CONFIG_HOME", config)
t.Setenv("DISPLAY", ":2.0")
address, err := ibusAddress()
if err != nil {
t.Fatal(err)
}
if address != "unix:path=/right,guid=abc" {
t.Fatalf("address = %q", address)
}
}
func TestIBusInputMethodKeyAndCompositionProtocol(t *testing.T) {
fb := newFakeBus(t)
defer fb.close()
t.Setenv("IBUS_ADDRESS", os.Getenv("DBUS_SESSION_BUS_ADDRESS"))
seen := make(chan *dbusMessage, 32)
go fb.run(seen)
const contextPath = "/org/freedesktop/IBus/InputContext_7"
fb.handler = func(message *dbusMessage, reply func(string, []any)) {
switch message.member {
case "CreateInputContext":
reply("o", []any{contextPath})
case "ProcessKeyEvent":
reply("b", []any{true})
default:
reply("", nil)
}
}
im, err := openIBusInputMethod()
if err != nil {
t.Fatal(err)
}
defer im.close()
if !im.processKey(uint32('a'), 38, x11ShiftMask) {
t.Fatal("ProcessKeyEvent was not handled")
}
deadline := time.After(3 * time.Second)
for {
select {
case message := <-seen:
if message.member != "ProcessKeyEvent" {
continue
}
values, decodeErr := dbusDecodeAll("uuu", message.body)
if decodeErr != nil {
t.Fatal(decodeErr)
}
if values[0] != uint32('a') || values[1] != uint32(30) || values[2] != uint32(x11ShiftMask) {
t.Fatalf("ProcessKeyEvent args = %#v", values)
}
goto keySeen
case <-deadline:
t.Fatal("ProcessKeyEvent did not reach IBus")
}
}
keySeen:
serialized := dbusVariant{
Sig: "(sa{sv}sv)",
Val: dbusStruct{Sig: "(sa{sv}sv)", Val: []any{
"IBusText", map[string]any{}, "é文", dbusVariant{Sig: "s", Val: ""},
}},
}
fb.sendSignal(contextPath, ibusContextIface, "UpdatePreeditText", "vub",
[]any{serialized, uint32(1), true})
events := waitIBusEvents(t, im, 1)
if events[0].Phase != KRY_TEXT_COMPOSITION_START || events[0].Text != "é文" || events[0].Cursor != 2 {
t.Fatalf("preedit event = %+v", events[0])
}
fb.sendSignal(contextPath, ibusContextIface, "CommitText", "v", []any{serialized})
events = waitIBusEvents(t, im, 1)
if events[0].Phase != KRY_TEXT_COMPOSITION_COMMIT || events[0].Text != "é文" {
t.Fatalf("commit event = %+v", events[0])
}
fb.sendSignal(contextPath, ibusContextIface, "ForwardKeyEvent", "uuu",
[]any{uint32(0xff51), uint32(105), uint32(x11ShiftMask)})
forwarded := waitIBusForwarded(t, im)
if forwarded.keyval != 0xff51 || forwarded.state != x11ShiftMask {
t.Fatalf("forwarded key = %+v", forwarded)
}
}
func TestIBusLiveConnection(t *testing.T) {
if os.Getenv("KRYON_LIVE_IBUS_TEST") == "" {
t.Skip("set KRYON_LIVE_IBUS_TEST=1 to exercise the desktop IBus daemon")
}
im, err := openIBusInputMethod()
if err != nil {
t.Fatal(err)
}
im.focusIn()
im.mu.Lock()
focused := im.focused
im.mu.Unlock()
if !focused {
t.Fatal("IBus input context did not accept FocusIn")
}
im.close()
}
func waitIBusEvents(t *testing.T, im *ibusInputMethod, count int) []KryTextCompositionEvent {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if events := im.drain(); len(events) >= count {
return events
}
time.Sleep(time.Millisecond)
}
t.Fatalf("timed out waiting for %d IBus event(s)", count)
return nil
}
func waitIBusForwarded(t *testing.T, im *ibusInputMethod) ibusForwardedKey {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if keys := im.drainForwarded(); len(keys) > 0 {
return keys[0]
}
time.Sleep(time.Millisecond)
}
t.Fatal("timed out waiting for IBus forwarded key")
return ibusForwardedKey{}
}
+11 -1
View File
@@ -1239,7 +1239,17 @@ func TestNativeSliderKeyboardNavigation(t *testing.T) {
r.BeginFrame()
r.SliderFloat(floatProps)
r.EndFrame()
r.SetFocus(600)
r.QueueMouseButtonDown(MouseButtonLeft, 35, 20)
r.BeginFrame()
r.SliderFloat(floatProps)
r.EndFrame()
if r.Focus() != 600 {
t.Fatalf("clicked slider focus=%d, want 600", r.Focus())
}
r.QueueMouseButtonUp(MouseButtonLeft, 35, 20)
r.BeginFrame()
r.SliderFloat(floatProps)
r.EndFrame()
r.QueueKey(KeyRight)
r.BeginFrame()
if !r.SliderFloat(floatProps) || floats[0] < 0.2599 || floats[0] > 0.2601 {
+49
View File
@@ -43,6 +43,30 @@ func TestPopupComboKeyboardOwnership(t *testing.T) {
}
r.EndFrame()
}
for _, inside := range []bool{false, true} {
r := New(AppConfig{}).(*runtime)
r.openDropdowns[25400] = true
r.QueueKey(KeyEscape)
r.BeginFrame()
parent := r.beginPopupInput(0, NewRectangle(180, 180, 40, 40))
child := r.beginPopupInput(1, NewRectangle(190, 190, 20, 20))
if !inside {
r.endPopupInput(child)
}
r.setFocus(25400)
var selected int32
r.Combobox(ComboboxProps{Bounds: NewRectangle(10, 10, 100, 28), ID: 25400,
Options: []string{"One", "Two"}, SelectedIndex: &selected})
if r.openDropdowns[25400] == inside {
t.Fatalf("inside=%v: obscured combo handled Escape", inside)
}
r.closeDropdown(25400)
if inside {
r.endPopupInput(child)
}
r.endPopupInput(parent)
r.EndFrame()
}
}
func TestPopupTextKeyboardOwnership(t *testing.T) {
@@ -314,6 +338,31 @@ func TestPopupMenuKeyboardOwnership(t *testing.T) {
r.endPopupInput(parent)
r.EndFrame()
}
for _, inside := range []bool{false, true} {
r := New(AppConfig{}).(*runtime)
r.QueueKey(KeyEscape)
r.BeginFrame()
parent := r.beginPopupInput(0, NewRectangle(180, 180, 40, 40))
child := r.beginPopupInput(1, NewRectangle(190, 190, 20, 20))
if !inside {
r.endPopupInput(child)
}
r.setFocus(25711)
r.PopupMenu(25711, 10, 10, items, 1)
wantFocus := int32(25711)
if inside {
wantFocus = 0
}
if r.Focus() != wantFocus {
t.Fatalf("inside=%v: popup menu Escape focus=%d want=%d",
inside, r.Focus(), wantFocus)
}
if inside {
r.endPopupInput(child)
}
r.endPopupInput(parent)
r.EndFrame()
}
}
func TestPopupAcceleratorKeyboardOwnership(t *testing.T) {
+11
View File
@@ -334,6 +334,17 @@ func renderTextInput(img *image.RGBA, op FrameOp) {
}
drawText(img, sliceTextByByteCursor(op.Text, start, end), sx, y, op.FontSize, selected, op.FontID)
}
if op.CompositionStart != op.CompositionEnd {
start, end := orderedInt32(op.CompositionStart, op.CompositionEnd)
sx := x + textAdvance(op.Text, start, op.FontSize, op.FontID)
ex := x + textAdvance(op.Text, end, op.FontSize, op.FontID)
composition := border
if op.CursorColor.A != 0 {
composition = op.CursorColor
}
fillRectPixels(img, sx, y+int(textHeight(op.FontSize, op.FontID))-2,
maxInt(2, ex-sx), 2, composition)
}
if op.Focused && !op.ReadOnly {
cursorX := x + textAdvance(op.Text, op.Cursor, op.FontSize, op.FontID)
top := int(round(op.Bounds.Y)) + 5
+219 -52
View File
@@ -1709,9 +1709,18 @@ func (r *runtime) QueueShiftKey(key int32) {
r.keyDown[key] = true
}
func (r *runtime) QueueShortcut(key int32) {
r.inputEvents = append(r.inputEvents, inputEvent{key: key, shortcut: true})
r.queueModifiedKey(key, false, true)
}
func (r *runtime) queueModifiedKey(key int32, shift, shortcut bool) {
r.inputEvents = append(r.inputEvents, inputEvent{
key: key,
shift: shift,
shortcut: shortcut,
})
r.keyDown[key] = true
}
func (r *runtime) QueueTap(x, y float32) {
r.QueueMouseButton(MouseButtonLeft, x, y)
}
@@ -4047,6 +4056,14 @@ func (r *runtime) Dropdown(id, x, y, w, h int32, options any, rest ...any) bool
bounds := r.layoutRect(Rectangle{X: float32(x), Y: float32(y), Width: float32(w), Height: float32(h)})
return r.dropdownAt(id, bounds, labels, selected)
}
func (r *runtime) dropdownKeyboardAvailable(id int32) bool {
if _, openPopup := r.popupPanels[id]; openPopup {
return !r.popupKeyboardCapturesOwner(id, true)
}
return !r.popupFocusCaptures(id)
}
func (r *runtime) dropdownAt(id int32, bounds Rectangle, labels []string, selected *int32) bool {
if r.dropdownsSeen == nil {
r.dropdownsSeen = make(map[int32]bool)
@@ -4088,6 +4105,7 @@ func (r *runtime) dropdownAt(id int32, bounds Rectangle, labels []string, select
}
}
open := r.openDropdowns[id]
keyboardAvailable := r.dropdownKeyboardAvailable(id)
panel := r.dropdownPanel(bounds, len(labels))
if open && !pressed {
if r.mousePressed[MouseButtonLeft] && !pointInRect(r.mousePos.X, r.mousePos.Y, bounds) && !pointInRect(r.mousePos.X, r.mousePos.Y, panel) {
@@ -4099,11 +4117,12 @@ func (r *runtime) dropdownAt(id int32, bounds Rectangle, labels []string, select
}
}
}
if len(labels) == 0 || bounds.Height <= 0 || r.keyDown[KeyEscape] {
if len(labels) == 0 || bounds.Height <= 0 ||
keyboardAvailable && r.keyDown[KeyEscape] {
open = false
}
changed := false
if open && !pressed {
if open && !pressed && keyboardAvailable {
highlight := clamp32(r.dropdownHighlight[id], 0, int32(len(labels)-1))
if r.keyDown[KeyUp] {
highlight = max32(0, highlight-1)
@@ -4158,7 +4177,9 @@ func (r *runtime) dropdownAt(id int32, bounds Rectangle, labels []string, select
viewport := panel
viewport.Y += 4
viewport.Height = max(float32(0), viewport.Height-8)
if pressed || r.keyDown[KeyUp] || r.keyDown[KeyDown] || r.keyDown[KeyHome] || r.keyDown[KeyEnd] {
if pressed || keyboardAvailable &&
(r.keyDown[KeyUp] || r.keyDown[KeyDown] ||
r.keyDown[KeyHome] || r.keyDown[KeyEnd]) {
top := float32(r.dropdownHighlight[id]) * itemH
if top < float32(*offset) {
*offset = int32(top)
@@ -5161,7 +5182,7 @@ func (r *runtime) PopupMenu(id, x, y int32, items []MenuItem, itemCount int32) i
r.registerField(id)
}
state := r.menuNav(id)
if r.focusID == id && r.keyDown[KeyEscape] {
if r.focusID == id && !r.popupFocusCaptures(id) && r.keyDown[KeyEscape] {
state.Path = state.Path[:0]
r.setFocus(0)
return 0
@@ -6433,12 +6454,24 @@ func intersectRectangles(a, b Rectangle) Rectangle {
func (r *runtime) recordTextInput(kind FrameOpKind, bounds Rectangle, buf []byte, cursor *int32, focused *bool, focusID, font int32, secure, readOnly bool) {
text := string(buf[:zeroIndex(buf)])
pos := len(text)
if cursor != nil {
pos = clampCursor(text, int(*cursor))
}
selectionStart, selectionEnd := pos, pos
if sel, ok := r.selection[focusID]; ok {
selectionStart, selectionEnd = selectionRange(sel)
}
compositionStart, compositionEnd := 0, 0
if preedit, ok := r.preedit[focusID]; ok && r.focusID == focusID && !secure {
pos := len(text)
if cursor != nil {
pos = clampCursor(text, int(*cursor))
if view, visible := makeTextCompositionView(text, selectionStart, selectionEnd, preedit); visible {
text = view.text
pos = view.cursor
selectionStart = view.selectionStart
selectionEnd = view.selectionEnd
compositionStart = view.compositionStart
compositionEnd = view.compositionEnd
}
text = text[:pos] + preedit.Text + text[pos:]
}
if secure {
text = strings.Repeat("*", utf8.RuneCountInString(text))
@@ -6460,21 +6493,18 @@ func (r *runtime) recordTextInput(kind FrameOpKind, bounds Rectangle, buf []byte
CursorColor: theme.focus,
FontSize: font,
FocusID: focusID,
Cursor: int32(pos),
SelectionStart: int32(selectionStart),
SelectionEnd: int32(selectionEnd),
CompositionStart: int32(compositionStart),
CompositionEnd: int32(compositionEnd),
Focused: r.focusID == focusID,
Secure: secure,
ReadOnly: readOnly,
}
if cursor != nil {
op.Cursor = *cursor
}
if focused != nil {
op.Focused = *focused
}
if sel, ok := r.selection[focusID]; ok {
start, end := selectionRange(sel)
op.SelectionStart = int32(start)
op.SelectionEnd = int32(end)
}
r.record(op)
}
@@ -6672,6 +6702,7 @@ func (r *runtime) editText(bounds Rectangle, buf []byte, cursor *int32, focused
}
continue
}
textSelection := event.shift || r.keyDown[KeyLeftShift] || r.keyDown[KeyRightShift]
if event.shortcut {
switch event.key {
case KeyA:
@@ -6703,6 +6734,37 @@ func (r *runtime) editText(bounds Rectangle, buf []byte, cursor *int32, focused
changed = true
sel = selection{Anchor: pos, Cursor: pos}
}
case KeyHome:
pos, sel = textMoveSelection(sel, pos, 0, textSelection)
case KeyEnd:
pos, sel = textMoveSelection(sel, pos, len(text), textSelection)
case KeyLeft:
target := 0
if !options.secure {
target = textWordLeft(text, pos)
}
if !textSelection && sel.Anchor != sel.Cursor {
target, _ = selectionRange(sel)
}
pos, sel = textMoveSelection(sel, pos, target, textSelection)
case KeyRight:
target := len(text)
if !options.secure {
target = textWordRight(text, pos)
}
if !textSelection && sel.Anchor != sel.Cursor {
_, target = selectionRange(sel)
}
pos, sel = textMoveSelection(sel, pos, target, textSelection)
case KeyBackspace, KeyDelete:
if options.readOnly {
continue
}
var deleted bool
text, pos, sel, deleted = textDeleteKey(
text, pos, sel, event.key, true, options.secure,
)
changed = changed || deleted
}
continue
}
@@ -6711,17 +6773,29 @@ func (r *runtime) editText(bounds Rectangle, buf []byte, cursor *int32, focused
r.setFocus(r.nextFocus(focusID, event.shift))
sel = selection{Anchor: pos, Cursor: pos}
case KeyLeft:
pos = prevRune(text, pos)
sel = selection{Anchor: pos, Cursor: pos}
target := prevRune(text, pos)
if !textSelection && sel.Anchor != sel.Cursor {
target, _ = selectionRange(sel)
}
pos, sel = textMoveSelection(sel, pos, target, textSelection)
case KeyRight:
pos = nextRune(text, pos)
sel = selection{Anchor: pos, Cursor: pos}
target := nextRune(text, pos)
if !textSelection && sel.Anchor != sel.Cursor {
_, target = selectionRange(sel)
}
pos, sel = textMoveSelection(sel, pos, target, textSelection)
case KeyHome:
pos = 0
sel = selection{Anchor: pos, Cursor: pos}
target := 0
if options.multiline {
target = textLineStart(text, pos)
}
pos, sel = textMoveSelection(sel, pos, target, textSelection)
case KeyEnd:
pos = len(text)
sel = selection{Anchor: pos, Cursor: pos}
target := len(text)
if options.multiline {
target = textLineEnd(text, pos)
}
pos, sel = textMoveSelection(sel, pos, target, textSelection)
case KeyUp, KeyDown, KeyPageUp, KeyPageDown:
if options.multiline {
direction, rows := -1, 1
@@ -6731,42 +6805,27 @@ func (r *runtime) editText(bounds Rectangle, buf []byte, cursor *int32, focused
if event.key == KeyPageUp || event.key == KeyPageDown {
rows = max(1, options.pageRows)
}
pos = textMoveVertical(text, pos, direction, rows)
sel = selection{Anchor: pos, Cursor: pos}
target := textMoveVertical(text, pos, direction, rows)
pos, sel = textMoveSelection(sel, pos, target, textSelection)
}
case KeyBackspace:
if options.readOnly {
continue
}
if sel.Anchor != sel.Cursor {
var deleted bool
text, pos, deleted = deleteSelection(text, sel)
if deleted {
changed = true
}
} else if pos > 0 {
prev := prevRune(text, pos)
text = text[:prev] + text[pos:]
pos = prev
changed = true
}
sel = selection{Anchor: pos, Cursor: pos}
var deleted bool
text, pos, sel, deleted = textDeleteKey(
text, pos, sel, KeyBackspace, false, options.secure,
)
changed = changed || deleted
case KeyDelete:
if options.readOnly {
continue
}
if sel.Anchor != sel.Cursor {
var deleted bool
text, pos, deleted = deleteSelection(text, sel)
if deleted {
changed = true
}
} else if pos < len(text) {
next := nextRune(text, pos)
text = text[:pos] + text[next:]
changed = true
}
sel = selection{Anchor: pos, Cursor: pos}
var deleted bool
text, pos, sel, deleted = textDeleteKey(
text, pos, sel, KeyDelete, false, options.secure,
)
changed = changed || deleted
case KeyEnter:
if options.multiline && !options.readOnly {
var inserted bool
@@ -7177,6 +7236,103 @@ func nextRune(text string, pos int) int {
return pos + size
}
func textCodepointAt(text string, pos int) rune {
pos = clampCursor(text, pos)
if pos >= len(text) {
return 0
}
codepoint, _ := utf8.DecodeRuneInString(text[pos:])
return codepoint
}
func textIsBlank(codepoint rune) bool {
return codepoint == ' ' || codepoint == '\t' || codepoint == '\u3000'
}
func textIsSeparator(codepoint rune) bool {
switch codepoint {
case ',', '\u3001', '.', '\u3002', ';', '\uff1b',
'(', '\uff08', ')', '\uff09', '{', '\uff5b', '}', '\uff5d',
'[', '\u300c', ']', '\u300d', '|', '\uff5c', '!', '\uff01',
'\\', '\uffe5', '/', '\u30fb', '\uff0f', '\n', '\r':
return true
default:
return false
}
}
func textIsWordBoundary(text string, pos int) bool {
if pos <= 0 {
return false
}
previous := textCodepointAt(text, prevRune(text, pos))
current := textCodepointAt(text, pos)
previousBlank := textIsBlank(previous)
previousSeparator := textIsSeparator(previous)
currentBlank := textIsBlank(current)
currentSeparator := textIsSeparator(current)
return ((previousBlank || previousSeparator) &&
!(currentSeparator || currentBlank)) ||
(currentSeparator && !previousSeparator)
}
func textWordLeft(text string, pos int) int {
pos = prevRune(text, pos)
for pos > 0 && !textIsWordBoundary(text, pos) {
pos = prevRune(text, pos)
}
return pos
}
func textWordRight(text string, pos int) int {
pos = nextRune(text, pos)
for pos < len(text) && !textIsWordBoundary(text, pos) {
pos = nextRune(text, pos)
}
return pos
}
func textDeleteKey(
text string,
pos int,
current selection,
key int32,
word bool,
secure bool,
) (string, int, selection, bool) {
start, end := selectionRange(current)
if start == end {
switch key {
case KeyBackspace:
if word && secure {
start = 0
} else if word {
start = textWordLeft(text, pos)
} else {
start = prevRune(text, pos)
}
end = pos
case KeyDelete:
start = pos
if word && secure {
end = len(text)
} else if word {
end = textWordRight(text, pos)
} else {
end = nextRune(text, pos)
}
default:
return text, pos, current, false
}
}
if end <= start {
return text, pos, current, false
}
text = text[:start] + text[end:]
current = selection{Anchor: start, Cursor: start}
return text, start, current, true
}
func textLineStart(text string, pos int) int {
pos = clampCursor(text, pos)
if start := strings.LastIndexByte(text[:pos], '\n'); start >= 0 {
@@ -7220,6 +7376,17 @@ func textMoveVertical(text string, pos, direction, rows int) int {
return pos
}
func textMoveSelection(current selection, cursor, target int, extend bool) (int, selection) {
if extend {
if current.Anchor == current.Cursor {
current.Anchor = cursor
}
current.Cursor = target
return target, current
}
return target, selection{Anchor: target, Cursor: target}
}
func cellW(grid Grid) float32 {
return (grid.Bounds.Width - float32(grid.PadX*2) - float32(max32(0, grid.Cols-1)*grid.GapX)) / float32(grid.Cols)
}
+93
View File
@@ -34,8 +34,101 @@ func TestTextAreaMultilineNavigation(t *testing.T) {
if cursor != 7 {
t.Fatalf("PageUp cursor = %d, want 7", cursor)
}
r.QueueShiftKey(KeyPageDown)
draw(0)
if cursor != 13 {
t.Fatalf("Shift+PageDown cursor = %d, want 13", cursor)
}
if selected := r.selection[props.FocusID]; selected.Anchor != 7 || selected.Cursor != 13 {
t.Fatalf("Shift+PageDown selection = %+v, want {Anchor:7 Cursor:13}", selected)
}
draw(KeyLeft)
if cursor != 7 {
t.Fatalf("Left after selection cursor = %d, want collapsed start 7", cursor)
}
draw(KeyHome)
if cursor != 6 {
t.Fatalf("multiline Home cursor = %d, want line start 6", cursor)
}
r.QueueShortcut(KeyEnd)
draw(0)
if cursor != int32(len("a0\nb1\nc2\nd3\ne4\nf5")) {
t.Fatalf("Ctrl+End cursor = %d, want buffer end", cursor)
}
cursor = 7
delete(r.selection, props.FocusID)
draw(KeyEnter)
if got := CString(text); got != "a0\nb1\nc\n2\nd3\ne4\nf5" {
t.Fatalf("multiline Enter text = %q", got)
}
}
func TestTextFieldWordNavigationAndDeletion(t *testing.T) {
r := New(AppConfig{Width: 240, Height: 100}).(*runtime)
text := make([]byte, 64)
copy(text, "alpha beta.gamma")
cursor := int32(len("alpha beta.gamma"))
focused := true
props := TextFieldProps{
Bounds: NewRectangle(10, 10, 180, 32), Text: text,
CursorPosition: &cursor, Focused: &focused, FocusID: 32101,
}
draw := func() {
r.BeginFrame()
r.TextField(props)
r.EndFrame()
}
r.SetFocus(props.FocusID)
r.QueueShortcut(KeyLeft)
draw()
if cursor != 11 {
t.Fatalf("Ctrl+Left cursor = %d, want 11", cursor)
}
r.queueModifiedKey(KeyLeft, true, true)
draw()
if selected := r.selection[props.FocusID]; selected.Anchor != 11 || selected.Cursor != 10 {
t.Fatalf("Ctrl+Shift+Left selection = %+v, want {Anchor:11 Cursor:10}", selected)
}
cursor = int32(len("alpha beta.gamma"))
delete(r.selection, props.FocusID)
r.QueueShortcut(KeyBackspace)
draw()
if got := CString(text); got != "alpha beta." || cursor != 11 {
t.Fatalf("Ctrl+Backspace = %q cursor %d, want %q cursor 11", got, cursor, "alpha beta.")
}
r.QueueShortcut(KeyBackspace)
draw()
if got := CString(text); got != "alpha beta" || cursor != 10 {
t.Fatalf("second Ctrl+Backspace = %q cursor %d, want %q cursor 10", got, cursor, "alpha beta")
}
cursor = 6
delete(r.selection, props.FocusID)
r.QueueShortcut(KeyDelete)
draw()
if got := CString(text); got != "alpha " || cursor != 6 {
t.Fatalf("Ctrl+Delete = %q cursor %d, want %q cursor 6", got, cursor, "alpha ")
}
clear(text)
copy(text, "alpha beta")
props.Secure = true
cursor = 5
delete(r.selection, props.FocusID)
r.QueueShortcut(KeyLeft)
draw()
if cursor != 0 {
t.Fatalf("secure Ctrl+Left cursor = %d, want 0", cursor)
}
r.QueueShortcut(KeyRight)
draw()
if cursor != int32(len("alpha beta")) {
t.Fatalf("secure Ctrl+Right cursor = %d, want buffer end", cursor)
}
r.QueueShortcut(KeyBackspace)
draw()
if got := CString(text); got != "" || cursor != 0 {
t.Fatalf("secure Ctrl+Backspace = %q cursor %d, want empty at 0", got, cursor)
}
}
+182 -46
View File
@@ -20,10 +20,12 @@ import (
type windowRuntime struct {
Runtime
window *x11Window
fps int
last time.Time
closed bool
window *x11Window
ime *ibusInputMethod
fps int
last time.Time
closed bool
focused bool
// frame *image.RGBA reused target image (reallocation only on resize)
// prevOps/nextOps double buffer for change detection
@@ -55,11 +57,21 @@ func openWindowRuntime(config AppConfig) (Runtime, error) {
if err != nil {
return nil, err
}
return &windowRuntime{Runtime: base, window: win, fps: config.FPS}, nil
wr := &windowRuntime{Runtime: base, window: win, fps: config.FPS}
if im, imErr := openIBusInputMethod(); imErr == nil {
wr.ime = im
} else if os.Getenv("KRYON_WINDOW_DEBUG") != "" {
fmt.Fprintf(os.Stderr, "kryon: native input method unavailable: %v\n", imErr)
}
return wr, nil
}
func (r *windowRuntime) Close() {
r.closed = true
if r.ime != nil {
r.ime.close()
r.ime = nil
}
if r.window != nil {
r.window.close()
}
@@ -83,6 +95,7 @@ func (r *windowRuntime) EndFrame() {
if fr, ok := r.Runtime.(frameOpController); ok {
ops = fr.FrameOps()
}
r.updateInputMethod(ops)
if os.Getenv("KRYON_OPS_DEBUG") != "" {
n := len(ops)
if n > 80 {
@@ -164,6 +177,13 @@ func (r *windowRuntime) pumpEvents() {
case x11EventExposeKind:
r.dirty = true // server asks for a repaint after occlusion
case x11EventFocusIn:
r.focused = true
case x11EventFocusOut:
r.focused = false
if r.ime != nil {
r.ime.focusOut()
}
case x11EventTap:
if c, ok := r.Runtime.(mouseController); ok {
c.QueueMouseButtonDown(ev.button, float32(ev.x), float32(ev.y))
@@ -186,17 +206,98 @@ func (r *windowRuntime) pumpEvents() {
c.QueueMouseWheel(ev.wheel)
}
case x11EventKey:
if c, ok := r.Runtime.(inputController); ok {
if ev.shortcut != 0 {
c.QueueShortcut(ev.shortcut)
} else if ev.key != 0 {
c.QueueKey(ev.key)
} else if ev.text != "" {
c.QueueText(ev.text)
}
if r.ime != nil && r.hasFocusedTextInput() &&
r.ime.processKey(ev.keysym, ev.keycode, ev.state) {
continue
}
r.queueDecodedKey(ev)
case x11EventKeyRelease:
if r.ime != nil && r.hasFocusedTextInput() {
_ = r.ime.processKey(ev.keysym, ev.keycode, ev.state|ibusReleaseMask)
}
}
}
if r.ime != nil {
if c, ok := r.Runtime.(interface {
SubmitTextComposition(KryTextCompositionPhase, string, int32, int32) int32
}); ok {
for _, event := range r.ime.drain() {
c.SubmitTextComposition(event.Phase, event.Text, event.Cursor, event.SelectionLength)
}
}
for _, key := range r.ime.drainForwarded() {
if key.state&ibusReleaseMask == 0 {
r.queueDecodedKey(x11EventFromKeysym(key.keyval, key.state))
}
}
}
}
func (r *windowRuntime) queueDecodedKey(event x11Event) {
c, ok := r.Runtime.(inputController)
if !ok {
return
}
if event.shortcut != 0 {
if modified, ok := r.Runtime.(modifiedInputController); ok {
modified.queueModifiedKey(event.shortcut, event.shift, true)
} else {
c.QueueShortcut(event.shortcut)
}
} else if event.shift && event.key != 0 {
c.QueueShiftKey(event.key)
} else if event.key != 0 {
c.QueueKey(event.key)
} else if event.text != "" {
c.QueueText(event.text)
}
}
func (r *windowRuntime) hasFocusedTextInput() bool {
if !r.focused {
return false
}
for _, op := range r.FrameOps() {
if editableTextInput(op) {
return true
}
}
return false
}
func (r *windowRuntime) updateInputMethod(ops []FrameOp) {
if r.ime == nil {
return
}
if !r.focused {
r.ime.focusOut()
return
}
for _, op := range ops {
if !editableTextInput(op) {
continue
}
r.ime.focusIn()
cursor := clampCursor(op.Text, int(op.Cursor))
prefix := op.Text[:cursor]
line := strings.Count(prefix, "\n")
if newline := strings.LastIndexByte(prefix, '\n'); newline >= 0 {
prefix = prefix[newline+1:]
}
x := op.Bounds.X + 6 + float32(runtimeTextWidth(prefix, op.FontSize))
y := op.Bounds.Y + float32(line+1)*float32(max(op.FontSize+4, int32(1)))
if y > op.Bounds.Y+op.Bounds.Height {
y = op.Bounds.Y + op.Bounds.Height
}
r.ime.setCursor(int32(x), int32(y), 1, max(op.FontSize, int32(1)))
return
}
r.ime.focusOut()
}
func editableTextInput(op FrameOp) bool {
return op.Focused && !op.ReadOnly && !op.Secure &&
(op.Kind == FrameOpTextField || op.Kind == FrameOpTextArea)
}
func (r *windowRuntime) QueueTap(x, y float32) {
@@ -309,31 +410,37 @@ func (r *windowRuntime) CharPressed() int32 {
}
const (
x11EventKeyPress = 2
x11EventButtonPress = 4
x11EventButtonRelease = 5
x11EventMotionNotify = 6
x11EventExpose = 12
x11EventConfigureNotify = 22
x11EventClientMessage = 33
x11EventKeyPress = 2
x11EventKeyReleaseNotify = 3
x11EventButtonPress = 4
x11EventButtonRelease = 5
x11EventMotionNotify = 6
x11EventFocusInNotify = 9
x11EventFocusOutNotify = 10
x11EventExpose = 12
x11EventConfigureNotify = 22
x11EventClientMessage = 33
x11InputOutput = 1
x11ZPixmap = 2
x11EventMaskKeyPress = 1 << 0
x11EventMaskKeyRelease = 1 << 1
x11EventMaskButtonPress = 1 << 2
x11EventMaskButtonRelease = 1 << 3
x11EventMaskPointerMotion = 1 << 6
x11EventMaskExposure = 1 << 15
x11EventMaskStructureNotify = 1 << 17
x11EventMaskFocusChange = 1 << 21
x11CWBackPixel = 1 << 1
x11CWEventMask = 1 << 11
x11AtomAtom = 4
x11ShiftMask = 1
x11ControlMask = 4
x11ShiftMask = 1
x11ControlMask = 4
ibusReleaseMask = uint32(1 << 30)
)
type x11Window struct {
@@ -382,7 +489,10 @@ const (
x11EventRelease
x11EventWheel
x11EventKey
x11EventKeyRelease
x11EventExposeKind
x11EventFocusIn
x11EventFocusOut
)
type x11Event struct {
@@ -392,7 +502,11 @@ type x11Event struct {
wheel float32
key int32
shortcut int32
shift bool
text string
keysym uint32
keycode uint8
state uint32
}
func openX11Window(config AppConfig) (*x11Window, error) {
@@ -615,7 +729,7 @@ func (w *x11Window) create(config AppConfig) error {
values := []uint32{
0xffffff,
x11EventMaskKeyPress | x11EventMaskButtonPress | x11EventMaskButtonRelease | x11EventMaskPointerMotion | x11EventMaskExposure | x11EventMaskStructureNotify,
x11EventMaskKeyPress | x11EventMaskKeyRelease | x11EventMaskButtonPress | x11EventMaskButtonRelease | x11EventMaskPointerMotion | x11EventMaskExposure | x11EventMaskStructureNotify | x11EventMaskFocusChange,
}
req := make([]byte, 32+len(values)*4)
req[0] = 1
@@ -991,6 +1105,16 @@ func (w *x11Window) decodeEvent(buf []byte) (x11Event, bool) {
if ev, ok := w.decodeKey(buf[1], get16(buf[28:])); ok {
return ev, true
}
case x11EventKeyReleaseNotify:
if ev, ok := w.decodeKey(buf[1], get16(buf[28:])); ok {
ev.kind = x11EventKeyRelease
ev.key, ev.shortcut, ev.text = 0, 0, ""
return ev, true
}
case x11EventFocusInNotify:
return x11Event{kind: x11EventFocusIn}, true
case x11EventFocusOutNotify:
return x11Event{kind: x11EventFocusOut}, true
case x11EventExpose:
return x11Event{}, false
}
@@ -1006,35 +1130,35 @@ func (w *x11Window) decodeKey(keycode uint8, state uint16) (x11Event, bool) {
return x11Event{}, false
}
shift := state&x11ShiftMask != 0
ctrl := state&x11ControlMask != 0
ks := syms[0]
if shift && len(syms) > 1 && syms[1] != 0 {
ks = syms[1]
}
if ctrl {
if k := shortcutKey(ks); k != 0 {
if os.Getenv("KRYON_WINDOW_DEBUG") != "" {
fmt.Fprintf(os.Stderr, "kryon: x11 key keycode=%d state=%#x keysym=%#x shortcut=%d\n", keycode, state, ks, k)
}
return x11Event{kind: x11EventKey, shortcut: k}, true
}
}
if key := specialKey(ks); key != 0 {
if os.Getenv("KRYON_WINDOW_DEBUG") != "" {
fmt.Fprintf(os.Stderr, "kryon: x11 key keycode=%d state=%#x keysym=%#x special=%d\n", keycode, state, ks, key)
}
return x11Event{kind: x11EventKey, key: key}, true
}
if text := keysymText(ks); text != "" {
if os.Getenv("KRYON_WINDOW_DEBUG") != "" {
fmt.Fprintf(os.Stderr, "kryon: x11 key keycode=%d state=%#x keysym=%#x text=%q\n", keycode, state, ks, text)
}
return x11Event{kind: x11EventKey, text: text}, true
}
event := x11EventFromKeysym(ks, uint32(state))
event.keycode = keycode
if os.Getenv("KRYON_WINDOW_DEBUG") != "" {
fmt.Fprintf(os.Stderr, "kryon: x11 key keycode=%d state=%#x keysym=%#x ignored\n", keycode, state, ks)
fmt.Fprintf(os.Stderr, "kryon: x11 key keycode=%d state=%#x keysym=%#x key=%d shortcut=%d text=%q\n",
keycode, state, ks, event.key, event.shortcut, event.text)
}
return x11Event{}, false
return event, true
}
func x11EventFromKeysym(keysym, state uint32) x11Event {
event := x11Event{
kind: x11EventKey, keysym: keysym, state: state,
shift: state&x11ShiftMask != 0,
}
if state&x11ControlMask != 0 {
event.shortcut = shortcutKey(keysym)
if event.shortcut != 0 {
return event
}
}
if event.key = specialKey(keysym); event.key != 0 {
return event
}
event.text = keysymText(keysym)
return event
}
func (w *x11Window) close() {
@@ -1084,6 +1208,18 @@ func shortcutKey(ks uint32) int32 {
return KeyV
case 'x', 'X':
return KeyX
case 0xff08:
return KeyBackspace
case 0xffff:
return KeyDelete
case 0xff50:
return KeyHome
case 0xff51:
return KeyLeft
case 0xff53:
return KeyRight
case 0xff57:
return KeyEnd
}
return 0
}
+45
View File
@@ -96,6 +96,7 @@ func TestX11DecodeKeyEvents(t *testing.T) {
36: {0xff0d, 0},
38: {'a', 'A'},
54: {'c', 'C'},
55: {0xff51, 0},
}}
ev, ok := win.decodeKey(38, 0)
@@ -128,6 +129,10 @@ func TestX11DecodeKeyEvents(t *testing.T) {
if !ok || ev.kind != x11EventKey || ev.key != KeyUp {
t.Fatalf("decode up = %#v ok=%v, want KeyUp", ev, ok)
}
ev, ok = win.decodeKey(111, x11ShiftMask)
if !ok || ev.key != KeyUp || !ev.shift {
t.Fatalf("decode shift-up = %#v", ev)
}
win.keysyms[113] = []uint32{0xffbf, 0}
ev, ok = win.decodeKey(113, 0)
@@ -139,6 +144,46 @@ func TestX11DecodeKeyEvents(t *testing.T) {
if !ok || ev.kind != x11EventKey || ev.shortcut != KeyC {
t.Fatalf("decode ctrl-c = %#v ok=%v, want shortcut KeyC", ev, ok)
}
ev, ok = win.decodeKey(55, x11ControlMask|x11ShiftMask)
if !ok || ev.kind != x11EventKey || ev.shortcut != KeyLeft || !ev.shift {
t.Fatalf("decode ctrl-shift-left = %#v ok=%v, want shifted shortcut KeyLeft", ev, ok)
}
}
func TestX11DecodeKeyboardCarriesNativeIMEData(t *testing.T) {
win := &x11Window{keysyms: map[uint8][]uint32{38: {'a', 'A'}}}
event, ok := win.decodeKey(38, x11ShiftMask)
if !ok {
t.Fatal("shifted key was not decoded")
}
if event.keysym != uint32('A') || event.keycode != 38 || event.state != x11ShiftMask {
t.Fatalf("native key data = %+v", event)
}
buf := make([]byte, 32)
buf[0] = x11EventKeyReleaseNotify
buf[1] = 38
put16(buf[28:], x11ShiftMask)
event, ok = win.decodeEvent(buf)
if !ok || event.kind != x11EventKeyRelease || event.keysym != uint32('A') {
t.Fatalf("release event = %+v, ok=%v", event, ok)
}
}
func TestX11DecodeWindowFocusEvents(t *testing.T) {
win := &x11Window{}
for raw, want := range map[byte]x11EventKind{
x11EventFocusInNotify: x11EventFocusIn,
x11EventFocusOutNotify: x11EventFocusOut,
} {
buf := make([]byte, 32)
buf[0] = raw
event, ok := win.decodeEvent(buf)
if !ok || event.kind != want {
t.Fatalf("focus event %d = %+v, ok=%v", raw, event, ok)
}
}
}
func TestX11LoadKeyboardMappingRequestAndDecode(t *testing.T) {
+5 -3
View File
@@ -37,9 +37,11 @@ typedef struct KryTextCompositionEvent {
char text[KRY_TEXT_COMPOSITION_MAX];
} KryTextCompositionEvent;
/* Platform adapters submit UTF-8 composition events here. Focused text
* controls consume them during input routing. Events are copied, so callers
* do not need to retain `text`. Returns zero only when the queue is full. */
/* Platform adapters submit UTF-8 composition events here. Cursor and selection
* length are UTF-8 byte offsets within `text`; controls clamp them to codepoint
* boundaries before painting. Focused text controls consume events during
* input routing. Events are copied, so callers do not need to retain `text`.
* Returns zero only when the queue is full. */
int SubmitTextComposition(KryTextCompositionPhase phase, const char *text,
int cursor, int selection_length);
int PollTextComposition(KryTextCompositionEvent *event);
+2 -2
View File
@@ -3,7 +3,7 @@
#define KRYON_VERSION_MAJOR 0
#define KRYON_VERSION_MINOR 1
#define KRYON_VERSION_PATCH 78
#define KRYON_VERSION_STRING "v0.1.78"
#define KRYON_VERSION_PATCH 89
#define KRYON_VERSION_STRING "v0.1.89"
#endif /* KRYON_VERSION_H */
+12 -25
View File
@@ -89,7 +89,7 @@ typedef struct {
Rectangle last_bounds;
int focused_rect_valid;
Rectangle focused_rect;
} UIForm;
} Form;
typedef struct {
const char *label;
@@ -105,29 +105,16 @@ int GetUILabelTextFieldHeight(LabelTextFieldProps row);
int GetUIButtonRowHeight(ButtonRowProps row);
int GetUISpinboxRowHeight(SpinboxRowProps row);
UIForm UIFormBegin(int x, int y, int width);
int UIFormY(const UIForm *form);
int UIFormAdvance(UIForm *form, int height);
Rectangle UIFormTakeRect(UIForm *form, int height);
void UIFormNoteFocus(UIForm *form, int focus_id, Rectangle bounds);
int UIFormEnsureFocusedVisible(UIForm *form, UIScrollArea area, int margin);
int UIFormSectionLabel(UIForm *form, SectionLabelProps label);
int UIFormLabelTextField(UIForm *form, LabelTextFieldProps row);
int UIFormCheckboxRow(UIForm *form, CheckboxRowProps row);
int UIFormSpinboxRow(UIForm *form, SpinboxRowProps row);
int UIFormButtonRow(UIForm *form, ButtonRowProps row);
int UIFormSection(UIForm *form, const char *label);
int UIFormSectionEx(UIForm *form, SectionLabelProps label);
int UIFormTextField(UIForm *form, const char *label, char *text,
size_t text_size, int *cursor_position, int *focused,
int focus_id);
int UIFormTextFieldEx(UIForm *form, LabelTextFieldProps row);
int UIFormCheckbox(UIForm *form, const char *label, int *value);
int UIFormCheckboxEx(UIForm *form, CheckboxRowProps row);
int UIFormSpinbox(UIForm *form, const char *label, int id, int min, int max,
int step, int *value);
int UIFormSpinboxEx(UIForm *form, SpinboxRowProps row);
int UIFormButtons(UIForm *form, const UIButtonRowItem *items, int count);
int UIFormButtonsEx(UIForm *form, ButtonRowProps row);
Form FormBegin(int x, int y, int width);
int FormY(const Form *form);
int FormAdvance(Form *form, int height);
Rectangle FormTakeRect(Form *form, int height);
void FormNoteFocus(Form *form, int focus_id, Rectangle bounds);
int FormEnsureFocusedVisible(Form *form, UIScrollArea area, int margin);
int FormSection(Form *form, SectionLabelProps row);
int FormTextField(Form *form, LabelTextFieldProps row);
int FormCheckbox(Form *form, CheckboxRowProps row);
int FormSpinbox(Form *form, SpinboxRowProps row);
int FormButtons(Form *form, ButtonRowProps row);
#endif
+4
View File
@@ -97,6 +97,8 @@ typedef struct UIWidgetTextInputPaint {
int font_token;
int selection_start;
int selection_end;
int composition_start;
int composition_end;
int scroll_x;
} UIWidgetTextInputPaint;
@@ -194,6 +196,8 @@ typedef struct UIWidgetNode {
unsigned paint_capture;
/* Internal declaration snapshot for deferred popup hit testing. */
unsigned popup_input_capture;
/* Internal declaration-time font snapshot for deferred text painting. */
int font_token;
int parent;
int first_child;
int next_sibling;
+2 -2
View File
@@ -397,14 +397,14 @@ EM_JS(void, js_dom_boot, (int w, int h, const char *title), {
if (!claimEvent(e, 'compositionupdate')) return;
var text = e.data || "";
K.compositions.push({phase: 2, text: text,
cursor: Array.from(text).length,
cursor: lengthBytesUTF8(text),
selectionLength: 0});
});
target.addEventListener('compositionend', function (e) {
if (!claimEvent(e, 'compositionend')) return;
var text = e.data || "";
K.compositions.push({phase: text ? 3 : 4, text: text,
cursor: Array.from(text).length,
cursor: lengthBytesUTF8(text),
selectionLength: 0});
});
target.addEventListener('touchstart', function (e) {
+26
View File
@@ -36,6 +36,31 @@ static KryTextCompositionEvent
static int g_text_composition_head;
static int g_text_composition_count;
static void
kry_text_composition_trim_utf8(char *text)
{
size_t len;
size_t start;
int expected = 1;
unsigned char lead;
if(text == NULL || text[0] == '\0')
return;
len = strlen(text);
start = len - 1;
while(start > 0 && (((unsigned char)text[start] & 0xc0) == 0x80))
start--;
lead = (unsigned char)text[start];
if((lead & 0xe0) == 0xc0)
expected = 2;
else if((lead & 0xf0) == 0xe0)
expected = 3;
else if((lead & 0xf8) == 0xf0)
expected = 4;
if(start + (size_t)expected > len)
text[start] = '\0';
}
int
SubmitTextComposition(KryTextCompositionPhase phase, const char *text,
int cursor, int selection_length)
@@ -57,6 +82,7 @@ SubmitTextComposition(KryTextCompositionPhase phase, const char *text,
if(text != NULL) {
strncpy(event->text, text, sizeof(event->text) - 1);
event->text[sizeof(event->text) - 1] = '\0';
kry_text_composition_trim_utf8(event->text);
}
g_text_composition_count++;
return 1;
@@ -33,6 +33,15 @@ public final class TextInputBridge {
}
};
private static int compositionCursor(String value, int relativePosition) {
int utf16Cursor = relativePosition > 0
? value.length() + relativePosition - 1
: relativePosition;
utf16Cursor = Math.max(0, Math.min(value.length(), utf16Cursor));
return value.substring(0, utf16Cursor)
.getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
}
public TextInputBridge(Context context, Callbacks callbacks) {
this.callbacks = callbacks;
this.view = new BridgeView(context);
@@ -184,7 +193,7 @@ public final class TextInputBridge {
int newCursorPosition) {
String value = text == null ? "" : text.toString();
callbacks.composition(composing ? 2 : 1, value,
Math.max(0, newCursorPosition - 1), 0);
compositionCursor(value, newCursorPosition), 0);
composing = true;
return true;
}
@@ -201,8 +210,9 @@ public final class TextInputBridge {
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
if (composing) {
callbacks.composition(3, text == null ? "" : text.toString(),
Math.max(0, newCursorPosition - 1), 0);
String value = text == null ? "" : text.toString();
callbacks.composition(3, value,
compositionCursor(value, newCursorPosition), 0);
composing = false;
} else {
TextInputBridge.this.commitText(text);
+17 -6
View File
@@ -27,6 +27,7 @@ typedef struct DropdownState {
int scrollbar_pressed;
int clip_top;
int clip_bottom;
UIPopupInputToken input_snapshot;
unsigned long frame_seen;
unsigned long opened_frame;
} DropdownState;
@@ -360,6 +361,7 @@ draw_dropdown_options(int id, int x, int y, int w, int h,
int can_draw = IsWindowReady();
state->frame_seen = g_ui_frame_serial;
state->input_snapshot = ui_popup_input_snapshot();
if(UIContentDisabled()) {
close_dropdown_state(state);
state->pending_changed = 0;
@@ -503,6 +505,7 @@ draw_dropdown_menu(int id)
{
DropdownState *state = get_or_create_dropdown_state(id);
int changed = 0;
int keyboard_available;
if(!state->open)
return 0;
@@ -510,6 +513,8 @@ draw_dropdown_menu(int id)
close_dropdown_state(state);
return 0;
}
keyboard_available =
!ui_popup_input_snapshot_keyboard_captures(state->input_snapshot);
int font = GetFontSize();
int x = state->x;
@@ -607,13 +612,13 @@ draw_dropdown_menu(int id)
int navigating = 1;
if(state->opened_frame == g_ui_frame_serial)
navigating = 0;
else if(IsKeyPressed(KEY_UP))
else if(keyboard_available && IsKeyPressed(KEY_UP))
state->highlight_index = ui_clampi(state->highlight_index - 1, 0, option_count - 1);
else if(IsKeyPressed(KEY_DOWN))
else if(keyboard_available && IsKeyPressed(KEY_DOWN))
state->highlight_index = ui_clampi(state->highlight_index + 1, 0, option_count - 1);
else if(IsKeyPressed(KEY_HOME))
else if(keyboard_available && IsKeyPressed(KEY_HOME))
state->highlight_index = 0;
else if(IsKeyPressed(KEY_END))
else if(keyboard_available && IsKeyPressed(KEY_END))
state->highlight_index = option_count - 1;
else
navigating = 0;
@@ -628,7 +633,7 @@ draw_dropdown_menu(int id)
if(scroll > max_scroll) scroll = max_scroll;
state->scroll_offset = (int)scroll;
}
if(state->opened_frame != g_ui_frame_serial &&
if(keyboard_available && state->opened_frame != g_ui_frame_serial &&
(IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER))) {
state->pending_index = state->highlight_index;
state->pending_changed = state->selected_index != state->highlight_index;
@@ -815,8 +820,14 @@ draw_dropdown_overlays(void)
dropdown_store->previous_focused = focused;
if(lost_focus || escape_pressed) {
for(DropdownState *state = dropdown_store->states; state != NULL; state = state->next)
for(DropdownState *state = dropdown_store->states;
state != NULL; state = state->next) {
if(escape_pressed && !lost_focus &&
ui_popup_input_snapshot_keyboard_captures(
state->input_snapshot))
continue;
close_dropdown_state(state);
}
}
DropdownState **link = &dropdown_store->states;
while(*link != NULL) {
+20 -115
View File
@@ -200,10 +200,10 @@ GetUISpinboxRowHeight(SpinboxRowProps row)
return row.row_height > 0 ? row.row_height : Scale(54);
}
UIForm
UIFormBegin(int x, int y, int width)
Form
FormBegin(int x, int y, int width)
{
UIForm form;
Form form;
memset(&form, 0, sizeof(form));
form.x = x;
@@ -215,13 +215,13 @@ UIFormBegin(int x, int y, int width)
}
int
UIFormY(const UIForm *form)
FormY(const Form *form)
{
return form != NULL ? form->cursor_y : 0;
}
int
UIFormAdvance(UIForm *form, int height)
FormAdvance(Form *form, int height)
{
int y;
@@ -236,7 +236,7 @@ UIFormAdvance(UIForm *form, int height)
}
Rectangle
UIFormTakeRect(UIForm *form, int height)
FormTakeRect(Form *form, int height)
{
Rectangle bounds = {0};
@@ -245,12 +245,12 @@ UIFormTakeRect(UIForm *form, int height)
bounds = (Rectangle){(float)form->x, (float)form->cursor_y,
(float)form->width, (float)(height > 0 ? height : 0)};
form->last_bounds = bounds;
UIFormAdvance(form, height);
FormAdvance(form, height);
return bounds;
}
void
UIFormNoteFocus(UIForm *form, int focus_id, Rectangle bounds)
FormNoteFocus(Form *form, int focus_id, Rectangle bounds)
{
if(form == NULL || focus_id <= 0)
return;
@@ -261,7 +261,7 @@ UIFormNoteFocus(UIForm *form, int focus_id, Rectangle bounds)
}
int
UIFormEnsureFocusedVisible(UIForm *form, UIScrollArea area, int margin)
FormEnsureFocusedVisible(Form *form, UIScrollArea area, int margin)
{
if(form == NULL || !form->focused_rect_valid)
return 0;
@@ -271,7 +271,7 @@ UIFormEnsureFocusedVisible(UIForm *form, UIScrollArea area, int margin)
}
int
UIFormSectionLabel(UIForm *form, SectionLabelProps label)
FormSection(Form *form, SectionLabelProps label)
{
int y;
int height;
@@ -280,12 +280,12 @@ UIFormSectionLabel(UIForm *form, SectionLabelProps label)
return 0;
y = form->cursor_y;
height = ui_section_label_height(label);
UIFormTakeRect(form, height);
FormTakeRect(form, height);
return SectionLabel(label, form->x, y);
}
int
UIFormLabelTextField(UIForm *form, LabelTextFieldProps row)
FormTextField(Form *form, LabelTextFieldProps row)
{
int y;
int height;
@@ -296,7 +296,7 @@ UIFormLabelTextField(UIForm *form, LabelTextFieldProps row)
return 0;
y = form->cursor_y;
height = ui_label_text_field_height(row);
UIFormTakeRect(form, height);
FormTakeRect(form, height);
result = LabelTextField(row, form->x, y, form->width);
field_bounds = row.field.bounds;
@@ -309,12 +309,12 @@ UIFormLabelTextField(UIForm *form, LabelTextFieldProps row)
(float)form->width,
(float)field_h};
}
UIFormNoteFocus(form, row.field.focus_id, field_bounds);
FormNoteFocus(form, row.field.focus_id, field_bounds);
return result;
}
int
UIFormCheckboxRow(UIForm *form, CheckboxRowProps row)
FormCheckbox(Form *form, CheckboxRowProps row)
{
int y;
int height;
@@ -323,12 +323,12 @@ UIFormCheckboxRow(UIForm *form, CheckboxRowProps row)
return 0;
y = form->cursor_y;
height = ui_checkbox_row_height(row);
UIFormTakeRect(form, height);
FormTakeRect(form, height);
return CheckboxRow(row, form->x, y);
}
int
UIFormSpinboxRow(UIForm *form, SpinboxRowProps row)
FormSpinbox(Form *form, SpinboxRowProps row)
{
int y;
int height;
@@ -342,7 +342,7 @@ UIFormSpinboxRow(UIForm *form, SpinboxRowProps row)
return 0;
y = form->cursor_y;
height = GetUISpinboxRowHeight(row);
UIFormTakeRect(form, height);
FormTakeRect(form, height);
label_font = row.label_font > 0 ? row.label_font : GetFontSize();
control_w = row.control_width > 0 ? row.control_width : Scale(156);
@@ -370,7 +370,7 @@ UIFormSpinboxRow(UIForm *form, SpinboxRowProps row)
}
int
UIFormButtonRow(UIForm *form, ButtonRowProps row)
FormButtons(Form *form, ButtonRowProps row)
{
int height;
@@ -380,105 +380,10 @@ UIFormButtonRow(UIForm *form, ButtonRowProps row)
row.y = form->cursor_y;
row.width = form->width;
height = GetUIButtonRowHeight(row);
UIFormTakeRect(form, height);
FormTakeRect(form, height);
return ButtonRow(row);
}
int
UIFormSection(UIForm *form, const char *label)
{
SectionLabelProps section;
memset(&section, 0, sizeof(section));
section.label = label;
return UIFormSectionLabel(form, section);
}
int
UIFormSectionEx(UIForm *form, SectionLabelProps label)
{
return UIFormSectionLabel(form, label);
}
int
UIFormTextField(UIForm *form, const char *label, char *text,
size_t text_size, int *cursor_position, int *focused,
int focus_id)
{
LabelTextFieldProps row;
memset(&row, 0, sizeof(row));
row.label = label;
row.field.text = text;
row.field.text_size = text_size;
row.field.cursor_position = cursor_position;
row.field.focused = focused;
row.field.focus_id = focus_id;
return UIFormLabelTextField(form, row);
}
int
UIFormTextFieldEx(UIForm *form, LabelTextFieldProps row)
{
return UIFormLabelTextField(form, row);
}
int
UIFormCheckbox(UIForm *form, const char *label, int *value)
{
CheckboxRowProps row;
memset(&row, 0, sizeof(row));
row.label = label;
row.value = value;
return UIFormCheckboxRow(form, row);
}
int
UIFormCheckboxEx(UIForm *form, CheckboxRowProps row)
{
return UIFormCheckboxRow(form, row);
}
int
UIFormSpinbox(UIForm *form, const char *label, int id, int min, int max,
int step, int *value)
{
SpinboxRowProps row;
memset(&row, 0, sizeof(row));
row.label = label;
row.spinbox.id = id;
row.spinbox.min = min;
row.spinbox.max = max;
row.spinbox.step = step;
row.spinbox.value = value;
return UIFormSpinboxRow(form, row);
}
int
UIFormSpinboxEx(UIForm *form, SpinboxRowProps row)
{
return UIFormSpinboxRow(form, row);
}
int
UIFormButtons(UIForm *form, const UIButtonRowItem *items, int count)
{
ButtonRowProps row;
memset(&row, 0, sizeof(row));
row.items = items;
row.count = count;
return UIFormButtonRow(form, row);
}
int
UIFormButtonsEx(UIForm *form, ButtonRowProps row)
{
return UIFormButtonRow(form, row);
}
int
DrawUIButtonRow(ButtonRowProps row)
{
+154 -84
View File
@@ -1,5 +1,6 @@
#include "ui_internal.h"
#include "ui_popup_input_internal.h"
#include "tab_bar_store.h"
/* zero constants: the native Plan 9 compiler rejects short
* compound literals like (Type){0}, and a copy of a zero
@@ -13,7 +14,79 @@ typedef struct UITabBarState {
unsigned long frame_seen;
} UITabBarState;
static UITabBarState *tab_bar_states;
struct TabBarStore {
UITabBarState *states;
Vector2 last_drag_position;
int dragging_scroll;
int scroll_drag_bar_id;
Rectangle scroll_drag_bar_bounds;
int last_clicked_tab;
int last_clicked_bar_id;
Rectangle last_clicked_bar_bounds;
double last_click_time;
Vector2 press_position;
int press_index;
int press_bar_id;
Rectangle press_bar_bounds;
int reorder_drag_active;
Vector2 pane_press_position;
int pane_press_index;
int pane_drag_reported;
};
static TabBarStore fallback_store = {
.last_clicked_tab = -1,
.press_index = -1,
.pane_press_index = -1
};
static TabBarStore *tab_bar_store = &fallback_store;
TabBarStore *
tab_bar_store_new(void)
{
TabBarStore *store = calloc(1, sizeof(*store));
if(store == NULL)
abort();
store->last_clicked_tab = -1;
store->press_index = -1;
store->pane_press_index = -1;
return store;
}
void
tab_bar_store_free(TabBarStore *store)
{
UITabBarState *state;
if(store == NULL)
return;
if(store == tab_bar_store || store == &fallback_store)
abort();
state = store->states;
while(state != NULL) {
UITabBarState *next = state->next;
free(state);
state = next;
}
free(store);
}
TabBarStore *
tab_bar_store_swap(TabBarStore *store)
{
TabBarStore *previous = tab_bar_store;
tab_bar_store = store != NULL ? store : &fallback_store;
return previous;
}
TabBarStore *
tab_bar_store_current(void)
{
return tab_bar_store;
}
static int
ui_tab_bar_same_identity(int id, Rectangle bounds, int other_id,
@@ -33,7 +106,7 @@ ui_tab_bar_owned_scroll(int id, int *fallback)
if(id <= 0)
return fallback;
for(state = tab_bar_states; state != NULL; state = state->next) {
for(state = tab_bar_store->states; state != NULL; state = state->next) {
if(state->id == id) {
state->frame_seen = g_ui_frame_serial;
return &state->scroll;
@@ -44,15 +117,15 @@ ui_tab_bar_owned_scroll(int id, int *fallback)
abort();
state->id = id;
state->frame_seen = g_ui_frame_serial;
state->next = tab_bar_states;
tab_bar_states = state;
state->next = tab_bar_store->states;
tab_bar_store->states = state;
return &state->scroll;
}
void
ui_tab_bar_finish_frame(void)
{
UITabBarState **link = &tab_bar_states;
UITabBarState **link = &tab_bar_store->states;
ui_tab_scope_finish_frame();
while(*link != NULL) {
@@ -282,19 +355,6 @@ DrawUITabBar(TabBarProps bar)
int disabled = bar.disabled || UIContentDisabled();
int focused = 0;
int default_scroll_offset = 0;
static Vector2 last_drag_pos = {0};
static int is_dragging = 0;
static int scroll_drag_bar_id = 0;
static Rectangle scroll_drag_bar_bounds = {0};
static int last_clicked_tab = -1;
static int last_clicked_bar_id = 0;
static Rectangle last_clicked_bar_bounds = {0};
static double last_click_time = 0.0;
static Vector2 press_pos = {0};
static int press_index = -1;
static int press_bar_id = 0;
static Rectangle press_bar_bounds = {0};
static int drag_active = 0;
int *scroll_offset = bar.scroll_offset != NULL
? bar.scroll_offset
: ui_tab_bar_owned_scroll(bar.id,
@@ -381,24 +441,28 @@ DrawUITabBar(TabBarProps bar)
int drag_target = -1;
int owns_press = ui_tab_bar_same_identity(bar.id,bar.bounds,
press_bar_id,press_bar_bounds);
int owns_drag = drag_active && owns_press;
tab_bar_store->press_bar_id,
tab_bar_store->press_bar_bounds);
int owns_drag = tab_bar_store->reorder_drag_active && owns_press;
if(!disabled && reorder_enabled && owns_press &&
press_index >= 0 && press_index < bar.count &&
tab_bar_store->press_index >= 0 &&
tab_bar_store->press_index < bar.count &&
IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
int dx = (int)(mouse_world.x - press_pos.x);
int dy = (int)(mouse_world.y - press_pos.y);
int dx = (int)(mouse_world.x - tab_bar_store->press_position.x);
int dy = (int)(mouse_world.y - tab_bar_store->press_position.y);
int abs_dx = dx < 0 ? -dx : dx;
int abs_dy = dy < 0 ? -dy : dy;
int threshold = Scale(6);
if(!drag_active && abs_dx >= threshold && abs_dx >= abs_dy) {
drag_active = 1;
if(!tab_bar_store->reorder_drag_active &&
abs_dx >= threshold && abs_dx >= abs_dy) {
tab_bar_store->reorder_drag_active = 1;
g_ui_pointer_owner = UI_POINTER_OWNER_REORDER;
}
if(drag_active) {
if(tab_bar_store->reorder_drag_active) {
drag_target = ui_tab_bar_reorder_target(
bar, press_index, min_tab_w, max_tab_w, icon_tab_w, tab_gap,
bar, tab_bar_store->press_index, min_tab_w, max_tab_w,
icon_tab_w, tab_gap,
*scroll_offset, equal_tabs, (int)mouse_world.x);
PushUIInputCapture((Rectangle){0.0f, 0.0f,
(float)ui_view_width,
@@ -482,7 +546,7 @@ DrawUITabBar(TabBarProps bar)
if(!ui_material_style() && owns_drag && drag_target == i) {
int marker_x = tab_x;
if(drag_target > press_index)
if(drag_target > tab_bar_store->press_index)
marker_x = tab_x + tab_w;
DrawRectangle(marker_x - Scale(1), bar_y + Scale(4),
Scale(2), bar_h - Scale(8), c_link);
@@ -608,42 +672,42 @@ DrawUITabBar(TabBarProps bar)
if(!is_disabled && !close_active &&
IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
press_index = i;
press_bar_id = bar.id;
press_bar_bounds = bar.bounds;
press_pos = mouse_world;
drag_active = 0;
tab_bar_store->press_index = i;
tab_bar_store->press_bar_id = bar.id;
tab_bar_store->press_bar_bounds = bar.bounds;
tab_bar_store->press_position = mouse_world;
tab_bar_store->reorder_drag_active = 0;
}
if(close_active && released && !owns_drag) {
clicked_tab = -1;
if(bar.closed_index != NULL)
*bar.closed_index = i;
last_clicked_tab = -1;
last_clicked_bar_id = 0;
last_clicked_bar_bounds =
tab_bar_store->last_clicked_tab = -1;
tab_bar_store->last_clicked_bar_id = 0;
tab_bar_store->last_clicked_bar_bounds =
(Rectangle){0.0f, 0.0f, 0.0f, 0.0f};
last_click_time = 0.0;
tab_bar_store->last_click_time = 0.0;
UIConsumeRelease();
} else if(!close_active && released && !owns_drag &&
(press_index < 0 ||
(tab_bar_store->press_index < 0 ||
(ui_tab_bar_same_identity(bar.id,bar.bounds,
press_bar_id,
press_bar_bounds) &&
press_index == i))) {
tab_bar_store->press_bar_id,
tab_bar_store->press_bar_bounds) &&
tab_bar_store->press_index == i))) {
double now = GetTime();
if(bar.double_clicked_index != NULL &&
ui_tab_bar_same_identity(bar.id,bar.bounds,
last_clicked_bar_id,
last_clicked_bar_bounds) &&
last_clicked_tab == i &&
now - last_click_time <= 0.45)
tab_bar_store->last_clicked_bar_id,
tab_bar_store->last_clicked_bar_bounds) &&
tab_bar_store->last_clicked_tab == i &&
now - tab_bar_store->last_click_time <= 0.45)
*bar.double_clicked_index = i;
last_clicked_tab = i;
last_clicked_bar_id = bar.id;
last_clicked_bar_bounds = bar.bounds;
last_click_time = now;
tab_bar_store->last_clicked_tab = i;
tab_bar_store->last_clicked_bar_id = bar.id;
tab_bar_store->last_clicked_bar_bounds = bar.bounds;
tab_bar_store->last_click_time = now;
clicked_tab = i;
if(bar.id > 0) {
SetUIFocus(bar.id);
@@ -662,28 +726,33 @@ DrawUITabBar(TabBarProps bar)
EndUIClip();
owns_press = ui_tab_bar_same_identity(bar.id,bar.bounds,
press_bar_id,press_bar_bounds);
owns_drag = drag_active && owns_press;
tab_bar_store->press_bar_id,
tab_bar_store->press_bar_bounds);
owns_drag = tab_bar_store->reorder_drag_active && owns_press;
if(!disabled && reorder_enabled && owns_drag && released &&
press_index >= 0 && press_index < bar.count) {
tab_bar_store->press_index >= 0 &&
tab_bar_store->press_index < bar.count) {
int target = drag_target;
if(target < 0)
target = ui_tab_bar_reorder_target(
bar, press_index, min_tab_w, max_tab_w, icon_tab_w, tab_gap,
bar, tab_bar_store->press_index, min_tab_w, max_tab_w,
icon_tab_w, tab_gap,
*scroll_offset, equal_tabs, (int)mouse_world.x);
if(target >= 0 && target < bar.count && target != press_index) {
*bar.reordered_from_index = press_index;
if(target >= 0 && target < bar.count &&
target != tab_bar_store->press_index) {
*bar.reordered_from_index = tab_bar_store->press_index;
*bar.reordered_to_index = target;
}
clicked_tab = -1;
UIConsumeRelease();
}
if((released || !IsMouseButtonDown(MOUSE_BUTTON_LEFT)) && owns_press) {
press_index = -1;
press_bar_id = 0;
press_bar_bounds = (Rectangle){0.0f, 0.0f, 0.0f, 0.0f};
drag_active = 0;
tab_bar_store->press_index = -1;
tab_bar_store->press_bar_id = 0;
tab_bar_store->press_bar_bounds =
(Rectangle){0.0f, 0.0f, 0.0f, 0.0f};
tab_bar_store->reorder_drag_active = 0;
if(g_ui_pointer_owner == UI_POINTER_OWNER_REORDER)
g_ui_pointer_owner = UI_POINTER_OWNER_NONE;
}
@@ -698,19 +767,21 @@ DrawUITabBar(TabBarProps bar)
int is_over_bar = CheckCollisionPointRec(current_pos, scroll_area);
int owns_scroll_drag = ui_tab_bar_same_identity(
bar.id,bar.bounds,scroll_drag_bar_id,scroll_drag_bar_bounds);
bar.id,bar.bounds,tab_bar_store->scroll_drag_bar_id,
tab_bar_store->scroll_drag_bar_bounds);
if(is_mouse_down && is_over_bar && !is_dragging) {
is_dragging = 1;
scroll_drag_bar_id = bar.id;
scroll_drag_bar_bounds = bar.bounds;
last_drag_pos = current_pos;
if(is_mouse_down && is_over_bar && !tab_bar_store->dragging_scroll) {
tab_bar_store->dragging_scroll = 1;
tab_bar_store->scroll_drag_bar_id = bar.id;
tab_bar_store->scroll_drag_bar_bounds = bar.bounds;
tab_bar_store->last_drag_position = current_pos;
owns_scroll_drag = 1;
}
if(is_dragging && owns_scroll_drag) {
if(tab_bar_store->dragging_scroll && owns_scroll_drag) {
if(is_mouse_down) {
float dx = current_pos.x - last_drag_pos.x;
float dx = current_pos.x -
tab_bar_store->last_drag_position.x;
*scroll_offset -= (int)dx;
// Clamp scroll offset
@@ -719,11 +790,11 @@ DrawUITabBar(TabBarProps bar)
if(*scroll_offset > max_scroll)
*scroll_offset = max_scroll;
last_drag_pos = current_pos;
tab_bar_store->last_drag_position = current_pos;
} else {
is_dragging = 0;
scroll_drag_bar_id = 0;
scroll_drag_bar_bounds =
tab_bar_store->dragging_scroll = 0;
tab_bar_store->scroll_drag_bar_id = 0;
tab_bar_store->scroll_drag_bar_bounds =
(Rectangle){0.0f, 0.0f, 0.0f, 0.0f};
}
}
@@ -755,9 +826,6 @@ DrawUIPaneTabBar(PaneTabBar bar)
int equal_tabs;
int tab_x;
int drag_threshold = Scale(6);
static Vector2 press_pos = {0};
static int press_index = -1;
static int drag_reported = 0;
if(bar.dragged_index != NULL)
*bar.dragged_index = -1;
@@ -807,14 +875,16 @@ DrawUIPaneTabBar(PaneTabBar bar)
if(CheckCollisionPointRec(mouse, tab_rect) &&
!UIInputCapturesClick(mouse)) {
if(IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) {
press_index = i;
press_pos = mouse;
drag_reported = 0;
tab_bar_store->pane_press_index = i;
tab_bar_store->pane_press_position = mouse;
tab_bar_store->pane_drag_reported = 0;
} else if(IsMouseButtonDown(MOUSE_BUTTON_LEFT) &&
press_index == i &&
!drag_reported) {
int dx = (int)(mouse.x - press_pos.x);
int dy = (int)(mouse.y - press_pos.y);
tab_bar_store->pane_press_index == i &&
!tab_bar_store->pane_drag_reported) {
int dx = (int)(mouse.x -
tab_bar_store->pane_press_position.x);
int dy = (int)(mouse.y -
tab_bar_store->pane_press_position.y);
if(dx < 0)
dx = -dx;
if(dy < 0)
@@ -823,7 +893,7 @@ DrawUIPaneTabBar(PaneTabBar bar)
result.dragged_index = i;
if(bar.dragged_index != NULL)
*bar.dragged_index = i;
drag_reported = 1;
tab_bar_store->pane_drag_reported = 1;
}
}
MarkUIClickable();
@@ -831,8 +901,8 @@ DrawUIPaneTabBar(PaneTabBar bar)
tab_x += tab_w + tab_gap;
}
if(!IsMouseButtonDown(MOUSE_BUTTON_LEFT)) {
press_index = -1;
drag_reported = 0;
tab_bar_store->pane_press_index = -1;
tab_bar_store->pane_drag_reported = 0;
}
return result;
+11
View File
@@ -0,0 +1,11 @@
#ifndef KRYON_TAB_BAR_STORE_H
#define KRYON_TAB_BAR_STORE_H
typedef struct TabBarStore TabBarStore;
TabBarStore *tab_bar_store_new(void);
void tab_bar_store_free(TabBarStore *store);
TabBarStore *tab_bar_store_swap(TabBarStore *store);
TabBarStore *tab_bar_store_current(void);
#endif
+464 -73
View File
@@ -1590,8 +1590,10 @@ ClaimUITextFocus(int *focused)
* disappears immediately this frame even though it has not re-run yet. */
if(g_ui_text_focus_owner != NULL && g_ui_text_focus_owner != focused)
*g_ui_text_focus_owner = 0;
if(g_ui_text_focus_owner != focused)
if(g_ui_text_focus_owner != focused) {
ui_text_composition_cancel(g_ui_text_focus_owner);
ui_text_context_close();
}
g_ui_text_focus_owner = focused;
g_ui_text_focus_owner_this_frame = focused;
g_ui_text_focus_owner_frame = g_ui_text_focus_frame;
@@ -1623,8 +1625,10 @@ ReleaseUITextFocus(int *focused, int focus_id)
{
if(focused == NULL)
return;
if(g_ui_text_focus_owner == focused)
if(g_ui_text_focus_owner == focused) {
ui_text_composition_cancel(focused);
g_ui_text_focus_owner = NULL;
}
if(g_ui_text_focus_owner_this_frame == focused)
g_ui_text_focus_owner_this_frame = NULL;
if(focus_id > 0 && g_ui_focus_active_id == focus_id)
@@ -1654,6 +1658,8 @@ ClearTextInputFocus(void)
g_ui_focus_text_input_active = 0;
g_ui_text_input_requested = 0;
g_ui_text_input_show_requested = 0;
ui_text_composition_cancel(NULL);
ClearTextComposition();
ui_text_context_close();
ui_clear_text_field_selection();
ui_clear_text_area_selection();
@@ -1812,11 +1818,15 @@ ui_resolve_text_input_style(TextInputStyle style)
return style;
}
static int ui_text_width_before_cursor(const char *text, int font,
int cursor_position);
static void
DrawUITextInputEx(Rectangle bounds, const char *text, int cursor_position,
int focused, int text_input_active, int cursor_visible, int font,
TextInputStyle style, int selection_start,
int selection_end, int scroll_x)
int selection_end, int composition_start,
int composition_end, int scroll_x)
{
style = ui_resolve_text_input_style(style);
const char *value = text ? text : "";
@@ -1892,6 +1902,31 @@ DrawUITextInputEx(Rectangle bounds, const char *text, int cursor_position,
}
DrawUIText(value, text_x, text_y, font, text_color);
if(composition_end > composition_start) {
char composition[1024];
int len = (int)strlen(value);
int composition_len;
int composition_x;
int composition_w;
composition_start = ui_clampi(composition_start, 0, len);
composition_end = ui_clampi(composition_end, 0, len);
composition_len = composition_end - composition_start;
if(composition_len >= (int)sizeof(composition))
composition_len = (int)sizeof(composition) - 1;
memcpy(composition, value + composition_start,
(size_t)composition_len);
composition[composition_len] = '\0';
composition_x = text_x +
ui_text_width_before_cursor(value, font, composition_start);
composition_w = TextWidth(composition, font);
if(composition_w < Scale(2))
composition_w = Scale(2);
DrawRectangle(composition_x,
text_y + TextLineHeight(font) - Scale(2),
composition_w, Scale(2), cursor_color);
}
if(focused && cursor_visible) {
char before_cursor[1024];
int len = (int)strlen(value);
@@ -1915,7 +1950,7 @@ DrawTextInput(Rectangle bounds, const char *text, int cursor_position,
TextInputStyle style)
{
DrawUITextInputEx(bounds, text, cursor_position, focused, 1,
cursor_visible, font, style, 0, 0, 0);
cursor_visible, font, style, 0, 0, 0, 0, 0);
}
static int
@@ -1974,7 +2009,7 @@ ui_draw_text_input_selection(Rectangle bounds, const char *text, int cursor,
int selection_start, int selection_end)
{
DrawUITextInputEx(bounds, text, cursor, focused, 1, 1, font, style,
selection_start, selection_end, 0);
selection_start, selection_end, 0, 0, 0);
}
int
@@ -1983,6 +2018,7 @@ EditText(TextEdit edit)
int changed = 0;
int len;
int codepoint;
int anchor;
if(edit.commit_pressed != NULL)
*edit.commit_pressed = 0;
@@ -1994,17 +2030,15 @@ EditText(TextEdit edit)
if(!UIKeyboardInputEnabled())
return 0;
if(IsKeyPressed(KEY_LEFT)) {
*edit.cursor_position = ui_utf8_prev_offset(edit.text, *edit.cursor_position);
}
if(IsKeyPressed(KEY_RIGHT)) {
*edit.cursor_position = ui_utf8_next_offset(edit.text, *edit.cursor_position);
}
if(IsKeyPressed(KEY_HOME)) {
*edit.cursor_position = 0;
}
if(IsKeyPressed(KEY_END)) {
*edit.cursor_position = (int)strlen(edit.text);
{
TextNavigationInput navigation = {
.text = edit.text,
.key = ui_text_navigation_key(0),
.modifier = ui_mod_key_down()
};
anchor = *edit.cursor_position;
(void)ui_text_navigate(navigation, &anchor, edit.cursor_position);
}
if(ui_mod_key_down() && IsKeyPressed(KEY_C)) {
@@ -2022,20 +2056,20 @@ EditText(TextEdit edit)
{
int repeat = g_ui_text_input_backspace_count + ui_backspace_repeat_count();
for(int i = 0; i < repeat; i++) {
int start = ui_utf8_prev_offset(edit.text, *edit.cursor_position);
changed |= ui_text_delete_range(edit.text, edit.text_size,
edit.cursor_position, start,
*edit.cursor_position);
}
anchor = *edit.cursor_position;
for(int i = 0; i < repeat; i++)
changed |= ui_text_delete_key(
edit.text, edit.text_size, &anchor, edit.cursor_position,
KEY_BACKSPACE, ui_mod_key_down(), 0);
g_ui_text_input_backspace_count = 0;
}
if(IsKeyPressed(KEY_DELETE)) {
int end = ui_utf8_next_offset(edit.text, *edit.cursor_position);
changed |= ui_text_delete_range(edit.text, edit.text_size,
edit.cursor_position,
*edit.cursor_position, end);
anchor = *edit.cursor_position;
changed |= ui_text_delete_key(
edit.text, edit.text_size, &anchor, edit.cursor_position,
KEY_DELETE, ui_mod_key_down(), 0);
}
if(IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER) ||
@@ -2173,7 +2207,7 @@ DrawUIHref(HrefProps link)
return 0;
}
static int
int
ui_text_line_start(const char *text, int cursor)
{
int i;
@@ -2187,7 +2221,7 @@ ui_text_line_start(const char *text, int cursor)
return 0;
}
static int
int
ui_text_line_end(const char *text, int cursor)
{
int len;
@@ -2240,6 +2274,22 @@ ui_text_cursor_from_line_x(const char *text, int start, int end, int font, int t
return end;
}
static int
ui_text_cursor_from_line_column(const char *text, int start, int end,
int column)
{
int cursor = start;
while(column-- > 0 && cursor < end) {
int next = ui_utf8_next_offset(text, cursor);
if(next <= cursor)
break;
cursor = next;
}
return cursor;
}
int
ui_text_move_vertical(const char *text, int cursor, int font, int dir)
{
@@ -2266,6 +2316,21 @@ ui_text_move_vertical(const char *text, int cursor, int font, int dir)
other_start = end + 1;
other_end = ui_text_line_end(text, other_start);
}
if(target_x <= 0 && cursor > start) {
int column = 0;
int column_cursor = start;
while(column_cursor < cursor) {
int next = ui_utf8_next_offset(text, column_cursor);
if(next <= column_cursor)
break;
column_cursor = next;
column++;
}
return ui_text_cursor_from_line_column(
text, other_start, other_end, column);
}
return ui_text_cursor_from_line_x(text, other_start, other_end, font, target_x);
}
@@ -2287,6 +2352,93 @@ ui_text_area_move_page(TextAreaProps area, int cursor, int direction)
return cursor;
}
int
ui_text_navigation_key(int multiline)
{
if(IsKeyPressed(KEY_LEFT))
return KEY_LEFT;
if(IsKeyPressed(KEY_RIGHT))
return KEY_RIGHT;
if(IsKeyPressed(KEY_HOME))
return KEY_HOME;
if(IsKeyPressed(KEY_END))
return KEY_END;
if(multiline && IsKeyPressed(KEY_UP))
return KEY_UP;
if(multiline && IsKeyPressed(KEY_DOWN))
return KEY_DOWN;
if(multiline && IsKeyPressed(KEY_PAGE_UP))
return KEY_PAGE_UP;
if(multiline && IsKeyPressed(KEY_PAGE_DOWN))
return KEY_PAGE_DOWN;
return 0;
}
int
ui_text_navigate(TextNavigationInput input, int *anchor, int *cursor)
{
int start;
int end;
int target;
if(input.text == NULL || anchor == NULL || cursor == NULL)
return 0;
start = *anchor < *cursor ? *anchor : *cursor;
end = *anchor > *cursor ? *anchor : *cursor;
target = *cursor;
switch(input.key) {
case KEY_LEFT:
if(!input.shift && end > start)
target = start;
else if(input.modifier)
target = input.secure ? 0 : ui_text_word_left(input.text, target);
else
target = ui_utf8_prev_offset(input.text, target);
break;
case KEY_RIGHT:
if(!input.shift && end > start)
target = end;
else if(input.modifier)
target = input.secure
? (int)strlen(input.text)
: ui_text_word_right(input.text, target);
else
target = ui_utf8_next_offset(input.text, target);
break;
case KEY_HOME:
target = input.area != NULL && !input.modifier
? ui_text_line_start(input.text, target) : 0;
break;
case KEY_END:
target = input.area != NULL && !input.modifier
? ui_text_line_end(input.text, target)
: (int)strlen(input.text);
break;
case KEY_UP:
case KEY_DOWN:
if(input.area == NULL)
return 0;
target = ui_text_move_vertical(
input.text, target, input.font,
input.key == KEY_UP ? -1 : 1);
break;
case KEY_PAGE_UP:
case KEY_PAGE_DOWN:
if(input.area == NULL)
return 0;
target = ui_text_area_move_page(
*input.area, target, input.key == KEY_PAGE_UP ? -1 : 1);
break;
default:
return 0;
}
*cursor = target;
if(!input.shift)
*anchor = target;
return 1;
}
static int
ui_text_area_line_font(const char *text, int start, int end, int base_font)
{
@@ -2723,6 +2875,30 @@ ui_draw_text_area_selection(const char *text, int line_start, int line_end,
color);
}
static void
ui_draw_text_area_composition(const char *text, int line_start, int line_end,
int x, int y, int font, Color color,
int composition_start, int composition_end)
{
int start;
int end;
int start_x;
int end_x;
if(text == NULL || composition_end <= composition_start)
return;
start = composition_start > line_start ? composition_start : line_start;
end = composition_end < line_end ? composition_end : line_end;
if(end <= start)
return;
start_x = x + ui_text_column_x(text, line_start, start, font);
end_x = x + ui_text_column_x(text, line_start, end, font);
if(end_x <= start_x)
end_x = start_x + Scale(2);
DrawRectangle(start_x, y + TextLineHeight(font) - Scale(2),
end_x - start_x, Scale(2), color);
}
static void
ui_draw_syntax_line(const char *line, int len, int x, int y, int font,
SyntaxMode syntax, TextInputStyle style)
@@ -2759,7 +2935,8 @@ ui_draw_text_area_text(const char *text, int cursor, int focused,
Rectangle bounds, int font, int line_gap,
int scroll_y, int wrap_width, SyntaxMode syntax,
TextInputStyle style, int selection_start,
int selection_end)
int selection_end, int composition_start,
int composition_end)
{
// The editor owns selection; rendered lines must not claim it or copy
// a second, single-line selection over the editor clipboard contents.
@@ -2810,6 +2987,10 @@ ui_draw_text_area_text(const char *text, int cursor, int focused,
else
ui_draw_syntax_line(line, line_len, text_x, draw_y,
line_font, syntax, style);
ui_draw_text_area_composition(
text, chunk_start, chunk_end, text_x, draw_y,
line_font, style.cursor, composition_start,
composition_end);
if(focused && cursor >= chunk_start && cursor <= chunk_end &&
(cursor < chunk_end || chunk_end == i) &&
ui_caret_blink_visible()) {
@@ -2900,9 +3081,10 @@ ui_text_area_reveal_cursor(TextAreaProps area, int cursor)
*area.scroll_y = ui_clampi(scroll_y, 0, max_scroll);
}
void
ui_paint_text_area(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end)
static void
ui_paint_text_area_internal(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end,
int composition_start, int composition_end)
{
int font;
int line_gap;
@@ -2959,10 +3141,29 @@ ui_paint_text_area(TextAreaProps area, int cursor, int focused,
focused && !area.read_only,
area.bounds, font, line_gap, scroll_y,
wrap_width, area.syntax, area.style,
selection_start, selection_end);
selection_start, selection_end,
composition_start, composition_end);
EndUIClip();
}
void
ui_paint_text_area(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end)
{
ui_paint_text_area_internal(area, cursor, focused, selection_start,
selection_end, 0, 0);
}
void
ui_paint_text_area_composition(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end,
int composition_start, int composition_end)
{
ui_paint_text_area_internal(area, cursor, focused, selection_start,
selection_end, composition_start,
composition_end);
}
int
TextBufferLineAtCursor(const char *text, int cursor)
{
@@ -3251,6 +3452,13 @@ RenderTextArea(TextAreaProps area)
int cut_pressed = 0;
int paste_pressed = 0;
TextEdit area_edit;
TextCompositionView composition = {0};
const char *display_text;
int display_cursor;
int composition_start = 0;
int composition_end = 0;
int committed_selection_start;
int committed_selection_end;
if(area.text == NULL || area.text_size == 0 || area.cursor_position == NULL || area.focused == NULL)
return 0;
@@ -3450,6 +3658,22 @@ RenderTextArea(TextAreaProps area)
selection_start = ui_clampi(selection_start, 0, (int)strlen(area.text));
selection_end = ui_clampi(selection_end, 0, (int)strlen(area.text));
}
{
int anchor = has_selection
? g_ui_text_area_selection.anchor : *area.cursor_position;
TextCompositionResult composition_result = ui_text_composition_apply(
area_edit, &anchor, area.focused, focused,
area.read_only || !UIKeyboardInputEnabled(), 1);
changed |= composition_result.text_changed;
if(composition_result.selection_changed) {
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
area.focused, anchor,
*area.cursor_position, 0);
has_selection = 1;
selection_start = selection_end = *area.cursor_position;
}
}
if(focused && UIKeyboardInputEnabled()) {
if(ui_mod_key_down() && IsKeyPressed(KEY_A)) {
int len = (int)strlen(area.text);
@@ -3501,16 +3725,25 @@ RenderTextArea(TextAreaProps area)
selection_key_handled = 1;
}
if(!area.read_only &&
(IsKeyPressed(KEY_BACKSPACE) || IsKeyPressed(KEY_DELETE)) &&
selection_end > selection_start) {
if(ui_text_delete_range(area.text, area.text_size,
area.cursor_position, selection_start,
selection_end)) {
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
area.focused, *area.cursor_position,
*area.cursor_position, 0);
changed = 1;
}
(IsKeyPressed(KEY_BACKSPACE) || IsKeyPressed(KEY_DELETE) ||
g_ui_text_input_backspace_count > 0)) {
int anchor = has_selection
? g_ui_text_area_selection.anchor : *area.cursor_position;
int backspace_count = g_ui_text_input_backspace_count +
ui_backspace_repeat_count();
int delete_count = IsKeyPressed(KEY_DELETE) ? 1 : 0;
while(backspace_count-- > 0)
changed |= ui_text_delete_key(
area.text, area.text_size, &anchor, area.cursor_position,
KEY_BACKSPACE, ui_mod_key_down(), 0);
while(delete_count-- > 0)
changed |= ui_text_delete_key(
area.text, area.text_size, &anchor, area.cursor_position,
KEY_DELETE, ui_mod_key_down(), 0);
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
area.focused, *area.cursor_position,
*area.cursor_position, 0);
g_ui_text_input_backspace_count = 0;
selection_key_handled = 1;
}
@@ -3588,6 +3821,33 @@ RenderTextArea(TextAreaProps area)
selection_key_handled = 1;
}
}
if(!selection_key_handled) {
int shift = IsKeyDown(KEY_LEFT_SHIFT) ||
IsKeyDown(KEY_RIGHT_SHIFT);
int cursor = *area.cursor_position;
int anchor = cursor;
int navigation_key = ui_text_navigation_key(1);
TextNavigationInput navigation = {
.text = area.text,
.area = &area,
.font = font,
.key = navigation_key,
.shift = shift,
.modifier = ui_mod_key_down()
};
if(ui_text_selection_matches(g_ui_text_area_selection, drag_id,
area.focused))
anchor = g_ui_text_area_selection.anchor;
if(ui_text_navigate(navigation, &anchor, &cursor)) {
*area.cursor_position = cursor;
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
area.focused, anchor, cursor, 0);
selection_start = anchor < cursor ? anchor : cursor;
selection_end = anchor > cursor ? anchor : cursor;
selection_key_handled = 1;
}
}
if(!area.read_only && !selection_key_handled) {
changed |= EditText(area_edit);
}
@@ -3604,19 +3864,7 @@ RenderTextArea(TextAreaProps area)
}
g_ui_text_input_enter_count = 0;
}
if(IsKeyPressed(KEY_UP))
*area.cursor_position = ui_text_move_vertical(area.text, *area.cursor_position, font, -1);
if(IsKeyPressed(KEY_DOWN))
*area.cursor_position = ui_text_move_vertical(area.text, *area.cursor_position, font, 1);
if(IsKeyPressed(KEY_PAGE_UP) || IsKeyPressed(KEY_PAGE_DOWN)) {
int direction = IsKeyPressed(KEY_PAGE_UP) ? -1 : 1;
*area.cursor_position = ui_text_area_move_page(
area, *area.cursor_position, direction);
}
if(changed || IsKeyPressed(KEY_LEFT) || IsKeyPressed(KEY_RIGHT) ||
IsKeyPressed(KEY_HOME) || IsKeyPressed(KEY_END) ||
IsKeyPressed(KEY_UP) || IsKeyPressed(KEY_DOWN) ||
IsKeyPressed(KEY_PAGE_UP) || IsKeyPressed(KEY_PAGE_DOWN)) {
if(changed && !selection_key_handled) {
if(!g_ui_text_area_selection.dragging) {
ui_text_selection_set(&g_ui_text_area_selection, drag_id,
area.focused, *area.cursor_position,
@@ -3628,17 +3876,51 @@ RenderTextArea(TextAreaProps area)
*area.cursor_position = ui_clampi(*area.cursor_position, 0, text_len);
}
if(ui_text_selection_matches(g_ui_text_area_selection, drag_id,
area.focused))
ui_selection_range(g_ui_text_area_selection, area.text,
&selection_start, &selection_end);
else
selection_start = selection_end = *area.cursor_position;
committed_selection_start = selection_start;
committed_selection_end = selection_end;
display_text = area.text;
display_cursor = *area.cursor_position;
{
const char *preedit = NULL;
int preedit_cursor = 0;
int preedit_selection_length = 0;
if(ui_text_composition_get(area.focused, &preedit, &preedit_cursor,
&preedit_selection_length) &&
ui_text_composition_view(
area.text, selection_start, selection_end, preedit,
preedit_cursor, preedit_selection_length, &composition)) {
display_text = composition.text;
display_cursor = composition.cursor;
selection_start = composition.selection_start;
selection_end = composition.selection_end;
composition_start = composition.composition_start;
composition_end = composition.composition_end;
}
}
ui_text_context_register_target(UI_TEXT_CONTEXT_AREA, drag_id,
area.focused, area.text, area.text_size,
area.cursor_position,
area.max_codepoints, area.filter,
area.filter_user_data,
&g_ui_text_area_selection,
selection_start, selection_end, 1, 0,
committed_selection_start,
committed_selection_end, 1, 0,
area.read_only);
content_h = ui_text_area_content_height(area.text, font, line_gap,
wrap_width, area.content_version,
content_h = ui_text_area_content_height(display_text, font, line_gap,
wrap_width,
composition.text != NULL
? 0 : area.content_version,
changed);
max_scroll = content_h - ((int)area.bounds.height - padding_y * 2);
if(max_scroll < 0)
@@ -3653,7 +3935,7 @@ RenderTextArea(TextAreaProps area)
if(reveal_cursor) {
int cursor_h = TextLineHeight(font);
int cursor_y = ui_text_area_cursor_y(
area.text, *area.cursor_position, font, line_gap, wrap_width,
display_text, display_cursor, font, line_gap, wrap_width,
&cursor_h);
int viewport_h = (int)area.bounds.height - padding_y * 2;
@@ -3668,6 +3950,7 @@ RenderTextArea(TextAreaProps area)
/* Keep editing usable without a renderer, as TextField already does. */
if(!IsWindowReady()) {
ui_text_composition_view_free(&composition);
EndUIWidget(&widget);
return changed;
}
@@ -3681,13 +3964,15 @@ RenderTextArea(TextAreaProps area)
DrawUIText(area.placeholder, (int)area.bounds.x + padding_x,
first_line_y, font, area.style.border);
else
ui_draw_text_area_text(area.text, *area.cursor_position,
ui_draw_text_area_text(display_text, display_cursor,
focused && !area.read_only,
area.bounds, font, line_gap, scroll_y,
wrap_width,
area.syntax, area.style, selection_start,
selection_end);
selection_end, composition_start,
composition_end);
EndUIClip();
ui_text_composition_view_free(&composition);
EndUIWidget(&widget);
return changed;
}
@@ -4072,6 +4357,12 @@ RenderTextField(TextFieldProps field)
int max_scroll_x;
int text_origin_x;
int panning_field = 0;
TextCompositionView composition = {0};
int paint_cursor;
int composition_start = 0;
int composition_end = 0;
int committed_selection_start;
int committed_selection_end;
if(field.commit_pressed != NULL)
*field.commit_pressed = 0;
@@ -4320,6 +4611,23 @@ RenderTextField(TextFieldProps field)
ui_selection_range(g_ui_text_field_selection, field.text,
&selection_start, &selection_end);
{
int anchor = ui_text_selection_matches(
g_ui_text_field_selection, field.focus_id, field.focused)
? g_ui_text_field_selection.anchor : *field.cursor_position;
TextCompositionResult composition_result = ui_text_composition_apply(
field_edit, &anchor, field.focused, focused,
field.read_only || !UIKeyboardInputEnabled(), 0);
changed |= composition_result.text_changed;
if(composition_result.selection_changed) {
ui_text_selection_set(&g_ui_text_field_selection,
field.focus_id, field.focused, anchor,
*field.cursor_position, 0);
selection_start = selection_end = *field.cursor_position;
}
}
if(focused && UIKeyboardInputEnabled()) {
if(ui_mod_key_down() && IsKeyPressed(KEY_A)) {
int len = (int)strlen(field.text);
@@ -4373,12 +4681,25 @@ RenderTextField(TextFieldProps field)
selection_handled = 1;
}
if(!field.read_only &&
(IsKeyPressed(KEY_BACKSPACE) || IsKeyPressed(KEY_DELETE)) &&
selection_end > selection_start) {
if(ui_text_delete_range(field.text, field.text_size,
field.cursor_position, selection_start,
selection_end))
changed = 1;
(IsKeyPressed(KEY_BACKSPACE) || IsKeyPressed(KEY_DELETE) ||
g_ui_text_input_backspace_count > 0)) {
int anchor = ui_text_selection_matches(
g_ui_text_field_selection, field.focus_id, field.focused)
? g_ui_text_field_selection.anchor : *field.cursor_position;
int backspace_count = g_ui_text_input_backspace_count +
ui_backspace_repeat_count();
int delete_count = IsKeyPressed(KEY_DELETE) ? 1 : 0;
while(backspace_count-- > 0)
changed |= ui_text_delete_key(
field.text, field.text_size, &anchor,
field.cursor_position, KEY_BACKSPACE, ui_mod_key_down(),
field.secure);
while(delete_count-- > 0)
changed |= ui_text_delete_key(
field.text, field.text_size, &anchor,
field.cursor_position, KEY_DELETE, ui_mod_key_down(),
field.secure);
g_ui_text_input_backspace_count = 0;
ui_text_selection_set(&g_ui_text_field_selection, field.focus_id,
field.focused, *field.cursor_position,
@@ -4386,6 +4707,32 @@ RenderTextField(TextFieldProps field)
selection_start = selection_end = *field.cursor_position;
selection_handled = 1;
}
if(!selection_handled) {
int shift = IsKeyDown(KEY_LEFT_SHIFT) ||
IsKeyDown(KEY_RIGHT_SHIFT);
int cursor = *field.cursor_position;
int anchor = cursor;
TextNavigationInput navigation = {
.text = field.text,
.key = ui_text_navigation_key(0),
.shift = shift,
.modifier = ui_mod_key_down(),
.secure = field.secure
};
if(ui_text_selection_matches(g_ui_text_field_selection,
field.focus_id, field.focused))
anchor = g_ui_text_field_selection.anchor;
if(ui_text_navigate(navigation, &anchor, &cursor)) {
*field.cursor_position = cursor;
ui_text_selection_set(&g_ui_text_field_selection,
field.focus_id, field.focused,
anchor, cursor, 0);
selection_start = anchor < cursor ? anchor : cursor;
selection_end = anchor > cursor ? anchor : cursor;
selection_handled = 1;
}
}
if(!field.read_only && !selection_handled &&
selection_end > selection_start &&
!ui_mod_key_down()) {
@@ -4437,7 +4784,14 @@ RenderTextField(TextFieldProps field)
}
}
if(!field.read_only && !selection_handled) {
changed = EditText(field_edit);
changed |= EditText(field_edit);
}
if(!field.read_only && selection_handled &&
(IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER) ||
g_ui_text_input_enter_count > 0)) {
if(field.commit_pressed != NULL)
*field.commit_pressed = 1;
g_ui_text_input_enter_count = 0;
}
if(changed || IsKeyPressed(KEY_LEFT) || IsKeyPressed(KEY_RIGHT) ||
IsKeyPressed(KEY_HOME) || IsKeyPressed(KEY_END)) {
@@ -4454,6 +4808,37 @@ RenderTextField(TextFieldProps field)
*field.cursor_position = ui_clampi(*field.cursor_position, 0, len);
}
if(ui_text_selection_matches(g_ui_text_field_selection,
field.focus_id, field.focused))
ui_selection_range(g_ui_text_field_selection, field.text,
&selection_start, &selection_end);
else
selection_start = selection_end = *field.cursor_position;
committed_selection_start = selection_start;
committed_selection_end = selection_end;
display_text = field.text;
paint_cursor = *field.cursor_position;
if(!field.secure) {
const char *preedit = NULL;
int preedit_cursor = 0;
int preedit_selection_length = 0;
if(ui_text_composition_get(field.focused, &preedit, &preedit_cursor,
&preedit_selection_length) &&
ui_text_composition_view(
field.text, selection_start, selection_end, preedit,
preedit_cursor, preedit_selection_length, &composition)) {
display_text = composition.text;
paint_cursor = composition.cursor;
selection_start = composition.selection_start;
selection_end = composition.selection_end;
composition_start = composition.composition_start;
composition_end = composition.composition_end;
}
}
if(field.secure) {
size_t len = strlen(field.text);
@@ -4475,7 +4860,7 @@ RenderTextField(TextFieldProps field)
*scroll_x_ptr = ui_clampi(*scroll_x_ptr, 0, max_scroll_x);
if(focused) {
int cursor_text_x = ui_text_width_before_cursor(
display_text, font, *field.cursor_position);
display_text, font, paint_cursor);
int margin = Scale(8);
if(cursor_text_x < *scroll_x_ptr + margin)
@@ -4492,18 +4877,22 @@ RenderTextField(TextFieldProps field)
field.max_codepoints, field.filter,
field.filter_user_data,
&g_ui_text_field_selection,
selection_start, selection_end, 0, 1,
committed_selection_start,
committed_selection_end, 0, 1,
field.read_only);
UIWidgetTextInputPaint paint = {
.style = field.style, .cursor = *field.cursor_position, .focused = focused,
.style = field.style, .cursor = paint_cursor, .focused = focused,
.editable = !field.read_only,
.caret = focused && !field.read_only && ui_caret_blink_visible(),
.font = font, .font_token = ui_active_font_token(),
.selection_start = selection_start, .selection_end = selection_end,
.composition_start = composition_start,
.composition_end = composition_end,
.scroll_x = *scroll_x_ptr
};
ui_tree_submit_text_input(field.bounds, display_text, paint, field.focus_id);
ui_text_composition_view_free(&composition);
free(masked_text);
EndUIWidget(&widget);
return changed;
@@ -4518,7 +4907,9 @@ ui_paint_text_input(Rectangle bounds, const char *text, UIWidgetTextInputPaint p
PopUIFont(paint.font_token);
DrawUITextInputEx(bounds, text, paint.cursor, paint.focused, paint.editable,
paint.caret, paint.font, paint.style,
paint.selection_start, paint.selection_end, paint.scroll_x);
paint.selection_start, paint.selection_end,
paint.composition_start, paint.composition_end,
paint.scroll_x);
PopUIFont(previous_font);
}
+46
View File
@@ -120,8 +120,23 @@ int ui_paragraph_modal_height(ParagraphModalMeasureProps measure);
int ui_title_bar_height(void);
int ui_paragraph_height(ParagraphSpec paragraph);
void DrawUIText(const char *text, int x, int y, int font_size, Color color);
typedef struct TextNavigationInput {
const char *text;
const TextAreaProps *area;
int font;
int key;
int shift;
int modifier;
int secure;
} TextNavigationInput;
int ui_text_line_start(const char *text, int cursor);
int ui_text_line_end(const char *text, int cursor);
int ui_text_move_vertical(const char *text, int cursor, int font, int direction);
int ui_text_area_move_page(TextAreaProps area, int cursor, int direction);
int ui_text_word_left(const char *text, int cursor);
int ui_text_word_right(const char *text, int cursor);
int ui_text_navigation_key(int multiline);
int ui_text_navigate(TextNavigationInput input, int *anchor, int *cursor);
void DrawUITextEx(const char *text, int x, int y, int font_size, Color color,
int selectable);
void DrawUITextStyled(const char *text, int x, int y, TextStyle style);
@@ -169,6 +184,10 @@ int ui_text_area_cursor_at_point(TextAreaProps area, int mouse_x, int mouse_y);
void ui_text_area_reveal_cursor(TextAreaProps area, int cursor);
void ui_paint_text_area(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end);
void ui_paint_text_area_composition(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end,
int composition_start,
int composition_end);
int DrawUIReadonlyTextBox(ReadonlyTextBoxProps box);
void DrawCustomIcon(int x, int y, int size, Texture2D icon, Color tint);
int DrawUIIconBtn(int x, int y, UIIconSize size, Texture2D icon, int *hover);
@@ -321,6 +340,31 @@ void ui_paint_text_input(Rectangle bounds, const char *text,
/* UTF-8 codec and text-buffer helpers (implemented in ui_text_edit.c). */
int ui_utf8_next_offset(const char *text, int offset);
int ui_utf8_prev_offset(const char *text, int offset);
typedef struct TextCompositionView {
char *text;
int cursor;
int selection_start;
int selection_end;
int composition_start;
int composition_end;
} TextCompositionView;
typedef struct TextCompositionResult {
int text_changed;
int presentation_changed;
int selection_changed;
} TextCompositionResult;
int ui_text_composition_view(const char *text, int selection_start,
int selection_end, const char *preedit,
int preedit_cursor,
int preedit_selection_length,
TextCompositionView *view);
void ui_text_composition_view_free(TextCompositionView *view);
TextCompositionResult ui_text_composition_apply(
TextEdit edit, int *anchor, const void *owner, int focused,
int read_only, int allow_newlines);
int ui_text_composition_get(const void *owner, const char **text,
int *cursor, int *selection_length);
int ui_text_composition_cancel(const void *owner);
int ui_active_font_token(void);
void ui_draw_text_with_font_token(const char *text, int x, int y,
int font_size, Color color, int token);
@@ -334,6 +378,8 @@ int ui_utf8_codepoint_count(const char *text);
int ui_utf8_encode(int codepoint, char out[5]);
int ui_text_delete_range(char *text, size_t text_size, int *cursor,
int start, int end);
int ui_text_delete_key(char *text, size_t text_size, int *anchor, int *cursor,
int key, int modifier, int secure);
int ui_text_copy_range(const char *text, int start, int end);
int ui_text_paste_clipboard(TextEdit edit, int allow_newlines);
int ui_text_insert_ascii(char *text, size_t text_size, int *cursor, char ch,
+25
View File
@@ -5,6 +5,7 @@
#include "ui_tree_layout_internal.h"
#include "ui_disabled_internal.h"
#include "dropdown_store.h"
#include "tab_bar_store.h"
#include "ui_input_clip_internal.h"
#include <stdlib.h>
#include <limits.h>
@@ -60,6 +61,7 @@ struct UIPaintLayers {
Matrix projection, modelview;
UIPopupInput *input, *previous_input;
DropdownStore *dropdowns, *previous_dropdowns;
TabBarStore *tab_bars, *previous_tab_bars;
};
static UIPaintLayers *main_layers;
@@ -69,6 +71,7 @@ static int main_frame_open;
* when no texture-backed paint-layer host can exist. */
static UIPopupInput *headless_input, *headless_previous_input;
static DropdownStore *headless_dropdowns, *headless_previous_dropdowns;
static TabBarStore *headless_tab_bars, *headless_previous_tab_bars;
static int headless_input_open;
/* Graphics scopes form one stack even when their textures belong to separate
* host contexts. Validate it before restoring any backend or borrowed state. */
@@ -85,10 +88,14 @@ void ui_frame_layers_begin(void)
if(!headless_input) headless_input = ui_popup_input_create();
if(!headless_dropdowns)
headless_dropdowns = dropdown_store_new();
if(!headless_tab_bars)
headless_tab_bars = tab_bar_store_new();
ui_popup_input_frame(headless_input);
headless_previous_input = ui_popup_input_bind(headless_input);
headless_previous_dropdowns =
dropdown_store_swap(headless_dropdowns);
headless_previous_tab_bars =
tab_bar_store_swap(headless_tab_bars);
headless_input_open = 1;
}
main_frame_open = 1;
@@ -112,15 +119,19 @@ void ui_frame_layers_end(void)
ui_paint_layers_composite(main_layers);
/* Input routing happens before the next frame redeclares owners. */
dropdown_store_swap(main_layers->dropdowns);
tab_bar_store_swap(main_layers->tab_bars);
}
if(headless_input_open) {
ui_popup_input_finish(headless_input);
ui_popup_input_bind(headless_previous_input);
dropdown_store_swap(headless_previous_dropdowns);
tab_bar_store_swap(headless_previous_tab_bars);
headless_previous_input = NULL;
headless_previous_dropdowns = NULL;
headless_previous_tab_bars = NULL;
headless_input_open = 0;
dropdown_store_swap(headless_dropdowns);
tab_bar_store_swap(headless_tab_bars);
}
main_frame_open = 0;
}
@@ -132,6 +143,8 @@ void ui_paint_layers_shutdown(void)
ui_paint_layers_composite(main_layers);
if(dropdown_store_current() == main_layers->dropdowns)
dropdown_store_swap(NULL);
if(tab_bar_store_current() == main_layers->tab_bars)
tab_bar_store_swap(NULL);
ui_paint_layers_destroy(main_layers);
main_layers = NULL;
}
@@ -140,12 +153,14 @@ void ui_paint_layers_shutdown(void)
ui_popup_input_finish(headless_input);
ui_popup_input_bind(headless_previous_input);
dropdown_store_swap(headless_previous_dropdowns);
tab_bar_store_swap(headless_previous_tab_bars);
headless_input_open = 0;
}
ui_popup_input_destroy(headless_input);
headless_input = NULL;
headless_previous_input = NULL;
headless_previous_dropdowns = NULL;
headless_previous_tab_bars = NULL;
}
if(headless_dropdowns) {
if(dropdown_store_current() == headless_dropdowns)
@@ -153,6 +168,12 @@ void ui_paint_layers_shutdown(void)
dropdown_store_free(headless_dropdowns);
headless_dropdowns = NULL;
}
if(headless_tab_bars) {
if(tab_bar_store_current() == headless_tab_bars)
tab_bar_store_swap(NULL);
tab_bar_store_free(headless_tab_bars);
headless_tab_bars = NULL;
}
main_frame_open = 0;
}
@@ -164,6 +185,7 @@ UIPaintLayers *ui_paint_layers_create(void)
layers->finished = 1;
layers->input = ui_popup_input_create();
layers->dropdowns = dropdown_store_new();
layers->tab_bars = tab_bar_store_new();
return layers;
}
@@ -179,6 +201,7 @@ void ui_paint_layers_destroy(UIPaintLayers *layers)
for(int i = 0; i < layers->allocated; i++) layer_texture_replace(layers->items[i].texture,0,0);
ui_popup_input_destroy(layers->input);
dropdown_store_free(layers->dropdowns);
tab_bar_store_free(layers->tab_bars);
free(layers->items);
free(layers);
}
@@ -197,6 +220,7 @@ void ui_paint_layers_frame(UIPaintLayers *layers, int width, int height)
ui_popup_input_frame(layers->input);
layers->previous_input = ui_popup_input_bind(layers->input);
layers->previous_dropdowns = dropdown_store_swap(layers->dropdowns);
layers->previous_tab_bars = tab_bar_store_swap(layers->tab_bars);
}
UIPaintLayerToken ui_paint_layer_begin(UIPaintLayers *layers, int owner)
@@ -308,4 +332,5 @@ void ui_paint_layers_composite(UIPaintLayers *layers)
layers->finished = 1;
ui_popup_input_bind(layers->previous_input);
dropdown_store_swap(layers->previous_dropdowns);
tab_bar_store_swap(layers->previous_tab_bars);
}
+92
View File
@@ -0,0 +1,92 @@
#include "ui_internal.h"
/* The UI has one text-focus owner, so retained and immediate editors share one
* in-progress platform composition instead of carrying widget-specific
* preedit buffers. */
typedef struct TextCompositionSession {
const void *owner;
int cursor;
int selection_length;
char text[KRY_TEXT_COMPOSITION_MAX];
} TextCompositionSession;
static TextCompositionSession text_composition;
int
ui_text_composition_cancel(const void *owner)
{
if(text_composition.owner == NULL ||
(owner != NULL && text_composition.owner != owner))
return 0;
memset(&text_composition, 0, sizeof(text_composition));
return 1;
}
int
ui_text_composition_get(const void *owner, const char **text,
int *cursor, int *selection_length)
{
if(owner == NULL || text_composition.owner != owner ||
text_composition.text[0] == '\0')
return 0;
if(text != NULL)
*text = text_composition.text;
if(cursor != NULL)
*cursor = text_composition.cursor;
if(selection_length != NULL)
*selection_length = text_composition.selection_length;
return 1;
}
TextCompositionResult
ui_text_composition_apply(TextEdit edit, int *anchor, const void *owner,
int focused, int read_only, int allow_newlines)
{
TextCompositionResult result = {0};
KryTextCompositionEvent event;
if(owner == NULL || edit.text == NULL || edit.text_size == 0 ||
edit.cursor_position == NULL || anchor == NULL)
return result;
if(!focused || read_only) {
result.presentation_changed = ui_text_composition_cancel(owner);
if(focused && read_only)
while(PollTextComposition(&event)) {}
return result;
}
while(PollTextComposition(&event)) {
if(event.phase == KRY_TEXT_COMPOSITION_START ||
event.phase == KRY_TEXT_COMPOSITION_UPDATE) {
text_composition.owner = owner;
strncpy(text_composition.text, event.text,
sizeof(text_composition.text) - 1);
text_composition.text[sizeof(text_composition.text) - 1] = '\0';
text_composition.cursor = event.cursor;
text_composition.selection_length = event.selection_length;
result.presentation_changed = 1;
} else if(event.phase == KRY_TEXT_COMPOSITION_COMMIT) {
int start = *anchor < *edit.cursor_position
? *anchor : *edit.cursor_position;
int end = *anchor > *edit.cursor_position
? *anchor : *edit.cursor_position;
if(end > start)
result.text_changed |= ui_text_delete_range(
edit.text, edit.text_size, edit.cursor_position,
start, end);
result.text_changed |= ui_text_insert_text(
edit.text, edit.text_size, edit.cursor_position, event.text,
allow_newlines, edit.filter, edit.filter_user_data,
edit.max_codepoints);
*anchor = *edit.cursor_position;
ui_text_composition_cancel(NULL);
result.presentation_changed = 1;
result.selection_changed = 1;
} else if(event.phase == KRY_TEXT_COMPOSITION_CANCEL) {
ui_text_composition_cancel(NULL);
result.presentation_changed = 1;
}
}
return result;
}
+205
View File
@@ -46,6 +46,178 @@ ui_utf8_prev_offset(const char *text, int offset)
return offset;
}
static int
ui_utf8_clamp_offset(const char *text, int offset)
{
int len;
if(text == NULL)
return 0;
len = (int)strlen(text);
offset = ui_clampi(offset, 0, len);
while(offset > 0 && offset < len &&
(((unsigned char)text[offset] & 0xc0) == 0x80))
offset--;
return offset;
}
int
ui_text_composition_view(const char *text, int selection_start,
int selection_end, const char *preedit,
int preedit_cursor, int preedit_selection_length,
TextCompositionView *view)
{
int text_len;
int preedit_len;
int start;
int end;
int cursor;
int selected_end;
size_t view_len;
if(view == NULL)
return 0;
memset(view, 0, sizeof(*view));
if(text == NULL)
text = "";
if(preedit == NULL || preedit[0] == '\0')
return 0;
text_len = (int)strlen(text);
preedit_len = (int)strlen(preedit);
start = ui_utf8_clamp_offset(text, selection_start);
end = ui_utf8_clamp_offset(text, selection_end);
if(start > end) {
int swap = start;
start = end;
end = swap;
}
cursor = ui_utf8_clamp_offset(preedit, preedit_cursor);
if(preedit_selection_length < 0)
preedit_selection_length = 0;
if(preedit_selection_length > preedit_len - cursor)
preedit_selection_length = preedit_len - cursor;
selected_end = ui_utf8_clamp_offset(
preedit, cursor + preedit_selection_length);
view_len = (size_t)text_len - (size_t)(end - start) +
(size_t)preedit_len;
view->text = malloc(view_len + 1);
if(view->text == NULL)
return 0;
memcpy(view->text, text, (size_t)start);
memcpy(view->text + start, preedit, (size_t)preedit_len);
memcpy(view->text + start + preedit_len, text + end,
(size_t)(text_len - end + 1));
view->cursor = start + cursor;
view->selection_start = start + cursor;
view->selection_end = start + selected_end;
view->composition_start = start;
view->composition_end = start + preedit_len;
return 1;
}
void
ui_text_composition_view_free(TextCompositionView *view)
{
if(view == NULL)
return;
free(view->text);
memset(view, 0, sizeof(*view));
}
static int
ui_text_codepoint_at(const char *text, int offset)
{
int codepoint_size = 0;
if(text == NULL || offset < 0 || text[offset] == '\0')
return 0;
return GetCodepointNext(text + offset, &codepoint_size);
}
static int
ui_text_is_blank(int codepoint)
{
return codepoint == ' ' || codepoint == '\t' || codepoint == 0x3000;
}
static int
ui_text_is_separator(int codepoint)
{
switch(codepoint) {
case ',': case 0x3001:
case '.': case 0x3002:
case ';': case 0xff1b:
case '(': case 0xff08:
case ')': case 0xff09:
case '{': case 0xff5b:
case '}': case 0xff5d:
case '[': case 0x300c:
case ']': case 0x300d:
case '|': case 0xff5c:
case '!': case 0xff01:
case '\\': case 0xffe5:
case '/': case 0x30fb: case 0xff0f:
case '\n': case '\r':
return 1;
default:
return 0;
}
}
static int
ui_text_is_word_boundary(const char *text, int offset)
{
int previous_offset;
int previous;
int current;
int previous_blank;
int previous_separator;
int current_blank;
int current_separator;
if(text == NULL || offset <= 0)
return 0;
previous_offset = ui_utf8_prev_offset(text, offset);
previous = ui_text_codepoint_at(text, previous_offset);
current = ui_text_codepoint_at(text, offset);
previous_blank = ui_text_is_blank(previous);
previous_separator = ui_text_is_separator(previous);
current_blank = ui_text_is_blank(current);
current_separator = ui_text_is_separator(current);
return ((previous_blank || previous_separator) &&
!(current_separator || current_blank)) ||
(current_separator && !previous_separator);
}
int
ui_text_word_left(const char *text, int cursor)
{
if(text == NULL)
return 0;
cursor = ui_clampi(cursor, 0, (int)strlen(text));
cursor = ui_utf8_prev_offset(text, cursor);
while(cursor > 0 && !ui_text_is_word_boundary(text, cursor))
cursor = ui_utf8_prev_offset(text, cursor);
return cursor;
}
int
ui_text_word_right(const char *text, int cursor)
{
int len;
if(text == NULL)
return 0;
len = (int)strlen(text);
cursor = ui_clampi(cursor, 0, len);
cursor = ui_utf8_next_offset(text, cursor);
while(cursor < len && !ui_text_is_word_boundary(text, cursor))
cursor = ui_utf8_next_offset(text, cursor);
return cursor;
}
int
ui_utf8_codepoint_count(const char *text)
{
@@ -114,6 +286,39 @@ ui_text_delete_range(char *text, size_t text_size, int *cursor, int start, int e
return 1;
}
int
ui_text_delete_key(char *text, size_t text_size, int *anchor, int *cursor,
int key, int modifier, int secure)
{
int start;
int end;
if(text == NULL || anchor == NULL || cursor == NULL)
return 0;
start = *anchor < *cursor ? *anchor : *cursor;
end = *anchor > *cursor ? *anchor : *cursor;
if(start == end) {
if(key == KEY_BACKSPACE) {
if(modifier)
start = secure ? 0 : ui_text_word_left(text, *cursor);
else
start = ui_utf8_prev_offset(text, *cursor);
} else if(key == KEY_DELETE) {
if(modifier)
end = secure
? (int)strlen(text) : ui_text_word_right(text, *cursor);
else
end = ui_utf8_next_offset(text, *cursor);
} else {
return 0;
}
}
if(!ui_text_delete_range(text, text_size, cursor, start, end))
return 0;
*anchor = *cursor;
return 1;
}
int
ui_text_insert_ascii(char *text, size_t text_size, int *cursor, char ch,
int max_codepoints)
+10 -5
View File
@@ -1252,7 +1252,8 @@ DrawUIPopupMenu(int id, int x, int y, const MenuItem *items, int item_count)
{
Rectangle panel = menu_items_panel_bounds(x,y,items,item_count);
int focused = !UIContentDisabled() && id > 0 && RegisterUIFocus(id,panel);
if(focused && IsKeyPressed(KEY_ESCAPE)) {
if(focused && !ui_popup_input_focus_captures(id) &&
IsKeyPressed(KEY_ESCAPE)) {
menu_navigation_reset(0,NULL,0);
SetUIFocus(0);
return 0;
@@ -1987,8 +1988,8 @@ ui_paint_drag_int(DragIntProps drag)
}
static int
ui_slider_ratio(int token, Rectangle bounds, int disabled, int vertical,
float *ratio)
ui_slider_ratio(int token, int focus_id, Rectangle bounds, int disabled,
int vertical, float *ratio)
{
Vector2 mouse = ui_mouse_world();
disabled = disabled || UIContentDisabled();
@@ -2004,6 +2005,8 @@ ui_slider_ratio(int token, Rectangle bounds, int disabled, int vertical,
if(pressed) {
g_slider_active = token;
g_slider_owner = ui_popup_input_owner();
if(focus_id > 0)
SetUIFocus(focus_id);
}
if(!disabled && g_slider_active == token &&
(pressed || IsMouseButtonDown(MOUSE_BUTTON_LEFT))) {
@@ -2173,7 +2176,8 @@ ui_update_slider_float(SliderFloatProps slider, int vertical)
if(range > 0.0f && ui_slider_ratio((int)(0x40000000u ^
((unsigned int)slider.id << 4) ^
(unsigned int)(i + 1)),
cell, slider.disabled, vertical, &ratio)) {
focus_id, cell, slider.disabled,
vertical, &ratio)) {
float value = slider.min + ratio * range;
if(value != slider.values[i]) {
slider.values[i] = value;
@@ -2220,7 +2224,8 @@ ui_update_slider_int(SliderIntProps slider, int vertical)
if(range > 0 && ui_slider_ratio((int)(0x50000000u ^
((unsigned int)slider.id << 4) ^
(unsigned int)(i + 1)),
cell, slider.disabled, vertical, &ratio)) {
focus_id, cell, slider.disabled,
vertical, &ratio)) {
int value = (int)((long long)slider.min +
(long long)(ratio * (double)range + 0.5));
if(value != slider.values[i]) {
+133 -164
View File
@@ -20,10 +20,6 @@ typedef struct TextFieldState {
int anchor;
int focused;
int dragging;
int composing;
int composition_cursor;
int composition_selection_length;
char composition[KRY_TEXT_COMPOSITION_MAX];
} TextFieldState;
static UIWidgetNode *ui_tree_nodes = NULL;
@@ -214,32 +210,6 @@ ui_tree_key_repeat_count(int key, double *next_repeat_at)
return count;
}
static int
ui_text_insert_utf8(TextFieldProps *field, TextFieldState *state,
const char *text)
{
int changed = 0;
int bytes;
int codepoint;
if(field == NULL || state == NULL || text == NULL)
return 0;
while(*text != '\0') {
bytes = 0;
codepoint = GetCodepointNext(text, &bytes);
if(bytes <= 0)
break;
if((field->filter == NULL ||
field->filter(codepoint, field->filter_user_data)) &&
ui_text_insert_codepoint(field->text, field->text_size,
&state->cursor, codepoint,
field->max_codepoints))
changed = 1;
text += bytes;
}
return changed;
}
static char *
ui_tree_strdup(const char *text)
{
@@ -391,6 +361,8 @@ ui_reconcile_node_changed(const UIWidgetNode *old_node,
return 1;
if(old_node->paint_capture != new_node->paint_capture)
return 1;
if(old_node->font_token != new_node->font_token)
return 1;
if(old_node->id != new_node->id ||
old_node->key != new_node->key ||
old_node->kind != new_node->kind ||
@@ -485,6 +457,7 @@ ui_tree_add(int id, UIWidgetKind kind, Rectangle bounds, const void *props)
node->has_input_clip = ui_current_input_clip(&node->input_clip);
node->paint_capture = ui_tree_capture_paint();
node->popup_input_capture = ui_tree_capture_input();
node->font_token = ui_active_font_token();
if(UIContentDisabled()) node->flags |= UI_NODE_SCOPE_DISABLED;
node->props = props;
node->parent = -1;
@@ -1262,6 +1235,11 @@ RouteInput(void)
after the editor is enabled again. */
if(id > 0 && IsUIFocusActive(id))
while(GetCharPressed() != 0) {}
if(ui_text_composition_cancel(node->state)) {
ui_text_field_event(node, UI_EVENT_COMPOSITION_CHANGED,
GetTime());
ui_tree_invalid |= UI_INVALIDATE_PAINT;
}
continue;
}
if(node->kind == UI_WIDGET_TEXT_FIELD_NODE) {
@@ -1346,11 +1324,8 @@ RouteInput(void)
if(field->focused != NULL)
*field->focused = state->focused;
int keyboard_captured = ui_popup_input_snapshot_keyboard_captures(ui_tree_input_snapshot(node));
if(state->composing && (!state->focused || field->read_only || keyboard_captured)) {
state->composing = 0;
state->composition[0] = '\0';
state->composition_cursor = 0;
state->composition_selection_length = 0;
if((!state->focused || field->read_only || keyboard_captured) &&
ui_text_composition_cancel(state)) {
ui_text_field_event(node,UI_EVENT_COMPOSITION_CHANGED,GetTime());
ui_tree_invalid |= UI_INVALIDATE_PAINT;
}
@@ -1431,49 +1406,28 @@ RouteInput(void)
selection_changed = 1;
start = end = state->cursor;
}
if(IsKeyPressed(KEY_LEFT) || IsKeyPressed(KEY_RIGHT) ||
IsKeyPressed(KEY_HOME) || IsKeyPressed(KEY_END)) {
{
int shift = IsKeyDown(KEY_LEFT_SHIFT) || IsKeyDown(KEY_RIGHT_SHIFT);
int cursor = state->cursor;
if(IsKeyPressed(KEY_HOME))
cursor = 0;
else if(IsKeyPressed(KEY_END))
cursor = (int)strlen(field->text);
else if(IsKeyPressed(KEY_LEFT))
cursor = ui_utf8_prev_offset(field->text, cursor);
else
cursor = ui_utf8_next_offset(field->text, cursor);
state->cursor = cursor;
if(!shift)
state->anchor = cursor;
selection_changed = 1;
start = state->anchor < state->cursor
? state->anchor : state->cursor;
end = state->anchor > state->cursor
? state->anchor : state->cursor;
}
if(node->kind == UI_WIDGET_TEXT_AREA_NODE &&
(IsKeyPressed(KEY_UP) || IsKeyPressed(KEY_DOWN) ||
IsKeyPressed(KEY_PAGE_UP) || IsKeyPressed(KEY_PAGE_DOWN))) {
int shift = IsKeyDown(KEY_LEFT_SHIFT) || IsKeyDown(KEY_RIGHT_SHIFT);
int direction = (IsKeyPressed(KEY_UP) || IsKeyPressed(KEY_PAGE_UP))
? -1 : 1;
int multiline = node->kind == UI_WIDGET_TEXT_AREA_NODE;
int navigation_key = ui_text_navigation_key(multiline);
int font = field->font > 0 ? field->font : GetFontSize();
TextNavigationInput navigation = {
.text = field->text,
.area = multiline ? &node->data.text_area : NULL,
.font = font,
.key = navigation_key,
.shift = shift,
.modifier = modifier,
.secure = field->secure
};
if(IsKeyPressed(KEY_PAGE_UP) || IsKeyPressed(KEY_PAGE_DOWN))
state->cursor = ui_text_area_move_page(
node->data.text_area, state->cursor, direction);
else
state->cursor = ui_text_move_vertical(
field->text, state->cursor, font, direction);
if(!shift)
state->anchor = state->cursor;
selection_changed = 1;
start = state->anchor < state->cursor
? state->anchor : state->cursor;
end = state->anchor > state->cursor
? state->anchor : state->cursor;
if(ui_text_navigate(navigation, &state->anchor, &state->cursor)) {
selection_changed = 1;
start = state->anchor < state->cursor
? state->anchor : state->cursor;
end = state->anchor > state->cursor
? state->anchor : state->cursor;
}
}
codepoint = GetCharPressed();
while(codepoint > 0) {
@@ -1496,70 +1450,37 @@ RouteInput(void)
codepoint = GetCharPressed();
}
{
KryTextCompositionEvent composition;
TextEdit edit = {
.text = field->text,
.text_size = field->text_size,
.cursor_position = &state->cursor,
.max_codepoints = field->max_codepoints,
.filter = field->filter,
.filter_user_data = field->filter_user_data
};
TextCompositionResult composition = ui_text_composition_apply(
edit, &state->anchor, state, state->focused,
field->read_only, node->kind == UI_WIDGET_TEXT_AREA_NODE);
while(PollTextComposition(&composition)) {
if(field->read_only) continue;
if(composition.phase == KRY_TEXT_COMPOSITION_START ||
composition.phase == KRY_TEXT_COMPOSITION_UPDATE) {
state->composing = 1;
strncpy(state->composition, composition.text,
sizeof(state->composition) - 1);
state->composition[sizeof(state->composition) - 1] = '\0';
state->composition_cursor = composition.cursor;
state->composition_selection_length =
composition.selection_length;
ui_text_field_event(node,
UI_EVENT_COMPOSITION_CHANGED, GetTime());
ui_tree_invalid |= UI_INVALIDATE_PAINT;
} else if(composition.phase == KRY_TEXT_COMPOSITION_COMMIT) {
if(end > start) {
changed |= ui_text_delete_range(
field->text, field->text_size, &state->cursor,
start, end);
}
changed |= ui_text_insert_utf8(field, state,
composition.text);
state->anchor = state->cursor;
state->composing = 0;
state->composition[0] = '\0';
selection_changed = 1;
ui_text_field_event(node,
UI_EVENT_COMPOSITION_CHANGED, GetTime());
} else if(composition.phase == KRY_TEXT_COMPOSITION_CANCEL) {
state->composing = 0;
state->composition[0] = '\0';
ui_text_field_event(node,
UI_EVENT_COMPOSITION_CHANGED, GetTime());
ui_tree_invalid |= UI_INVALIDATE_PAINT;
}
changed |= composition.text_changed;
selection_changed |= composition.selection_changed;
if(composition.presentation_changed) {
ui_text_field_event(node, UI_EVENT_COMPOSITION_CHANGED,
GetTime());
ui_tree_invalid |= UI_INVALIDATE_PAINT;
}
}
if(backspace_count > 0 && !field->read_only) {
if(end > start) {
changed |= ui_text_delete_range(field->text, field->text_size,
&state->cursor, start, end);
backspace_count--;
}
while(backspace_count-- > 0 && state->cursor > 0)
changed |= ui_text_delete_range(
field->text, field->text_size, &state->cursor,
ui_utf8_prev_offset(field->text, state->cursor),
state->cursor);
state->anchor = state->cursor;
while(backspace_count-- > 0)
changed |= ui_text_delete_key(
field->text, field->text_size, &state->anchor,
&state->cursor, KEY_BACKSPACE, modifier, field->secure);
selection_changed = changed;
} else if(delete_count > 0 && !field->read_only) {
if(end > start) {
changed |= ui_text_delete_range(field->text, field->text_size,
&state->cursor, start, end);
delete_count--;
}
while(delete_count-- > 0)
changed |= ui_text_delete_range(
field->text, field->text_size, &state->cursor,
state->cursor,
ui_utf8_next_offset(field->text, state->cursor));
state->anchor = state->cursor;
changed |= ui_text_delete_key(
field->text, field->text_size, &state->anchor,
&state->cursor, KEY_DELETE, modifier, field->secure);
selection_changed = changed;
}
if(IsKeyPressed(KEY_ENTER) || IsKeyPressed(KEY_KP_ENTER)) {
@@ -1799,14 +1720,41 @@ DrawTree(void)
}
case UI_WIDGET_TEXT_AREA_NODE: {
TextFieldState *state = node->state;
TextAreaProps area = node->data.text_area;
int cursor = state != NULL ? state->cursor : 0;
int anchor = state != NULL ? state->anchor : cursor;
int previous_font = ui_active_font_token();
TextCompositionView composition = {0};
const char *preedit = NULL;
int preedit_cursor = 0;
int preedit_selection_length = 0;
int composing = state != NULL && ui_text_composition_get(
state, &preedit, &preedit_cursor,
&preedit_selection_length);
node->data.text_area.bounds = node->bounds;
ui_paint_text_area(node->data.text_area, cursor,
state != NULL ? state->focused : 0,
anchor < cursor ? anchor : cursor,
anchor > cursor ? anchor : cursor);
area.bounds = node->bounds;
PopUIFont(node->font_token);
if(composing && ui_text_composition_view(
area.text,
anchor < cursor ? anchor : cursor,
anchor > cursor ? anchor : cursor,
preedit, preedit_cursor,
preedit_selection_length, &composition)) {
area.text = composition.text;
area.content_version = 0;
ui_paint_text_area_composition(
area, composition.cursor,
state->focused, composition.selection_start,
composition.selection_end, composition.composition_start,
composition.composition_end);
ui_text_composition_view_free(&composition);
} else {
ui_paint_text_area(area, cursor,
state != NULL ? state->focused : 0,
anchor < cursor ? anchor : cursor,
anchor > cursor ? anchor : cursor);
}
PopUIFont(previous_font);
break;
}
case UI_WIDGET_TEXT_FIELD_NODE: {
@@ -1814,26 +1762,37 @@ DrawTree(void)
TextFieldState *state = node->state;
const char *display;
char *masked = NULL;
TextCompositionView composition = {0};
int cursor;
int selection_start;
int selection_end;
int composition_start = 0;
int composition_end = 0;
const char *preedit = NULL;
int preedit_cursor = 0;
int preedit_selection_length = 0;
field = node->data.text_field;
display = field.text != NULL ? field.text : "";
cursor = state != NULL ? state->cursor : 0;
selection_start = state != NULL && state->anchor < cursor
? state->anchor : cursor;
selection_end = state != NULL && state->anchor > cursor
? state->anchor : cursor;
if(state != NULL && state->composing && !field.secure &&
state->composition[0] != '\0') {
size_t base_len = strlen(display);
size_t preedit_len = strlen(state->composition);
size_t cursor = (size_t)ui_clampi(state->cursor, 0,
(int)base_len);
char *composed = malloc(base_len + preedit_len + 1);
if(composed != NULL) {
memcpy(composed, display, cursor);
memcpy(composed + cursor, state->composition, preedit_len);
memcpy(composed + cursor + preedit_len, display + cursor,
base_len - cursor + 1);
display = composed;
masked = composed;
}
if(state != NULL && !field.secure &&
ui_text_composition_get(state, &preedit, &preedit_cursor,
&preedit_selection_length) &&
ui_text_composition_view(
display, selection_start, selection_end,
preedit, preedit_cursor, preedit_selection_length,
&composition)) {
display = composition.text;
cursor = composition.cursor;
selection_start = composition.selection_start;
selection_end = composition.selection_end;
composition_start = composition.composition_start;
composition_end = composition.composition_end;
}
if(field.secure) {
@@ -1841,21 +1800,31 @@ DrawTree(void)
char *secure_mask = malloc(length + 1);
if(secure_mask != NULL) {
free(masked);
masked = secure_mask;
memset(masked, '*', length);
masked[length] = '\0';
display = masked;
memset(secure_mask, '*', length);
secure_mask[length] = '\0';
display = secure_mask;
}
}
ui_draw_text_input_selection(
node->bounds, display, state != NULL ? state->cursor : 0,
state != NULL ? state->focused : 0, field.font, field.style,
state != NULL && state->anchor < state->cursor
? state->anchor : (state != NULL ? state->cursor : 0),
state != NULL && state->anchor > state->cursor
? state->anchor : (state != NULL ? state->cursor : 0));
{
UIWidgetTextInputPaint paint = {
.style = field.style,
.cursor = cursor,
.focused = state != NULL ? state->focused : 0,
.editable = !field.read_only,
.caret = state != NULL && state->focused &&
!field.read_only,
.font = field.font,
.font_token = node->font_token,
.selection_start = selection_start,
.selection_end = selection_end,
.composition_start = composition_start,
.composition_end = composition_end
};
ui_paint_text_input(node->bounds, display, paint);
}
free(masked);
ui_text_composition_view_free(&composition);
break;
}
case UI_WIDGET_SLIDER_NODE: {
+120
View File
@@ -774,6 +774,44 @@ func main() {
}
CompositionStateValue.CompositionReadOnly = false
driver.SetFocus(26102)
driver.QueueShortcut(kryon.KeyRight)
drawComposition()
if CompositionStateValue.CompositionPageCursor != 5 {
panic("generated TextArea Ctrl+Right did not stop at separator")
}
driver.QueueShiftKey(kryon.KeyLeftShift)
driver.QueueShortcut(kryon.KeyRight)
drawComposition()
if CompositionStateValue.CompositionPageCursor != 6 {
panic("generated TextArea Ctrl+Shift+Right did not extend by word")
}
driver.QueueShortcut(kryon.KeyC)
drawComposition()
if driver.ClipboardText() != "\n" {
panic("generated TextArea Ctrl+Shift+Right selection failed")
}
driver.QueueKey(kryon.KeyLeft)
drawComposition()
driver.QueueKey(kryon.KeyLeft)
drawComposition()
if CompositionStateValue.CompositionPageCursor != 4 {
panic(fmt.Sprintf("generated TextArea word-navigation reset cursor=%d, want 4", CompositionStateValue.CompositionPageCursor))
}
driver.QueueShiftKey(kryon.KeyDown)
drawComposition()
if CompositionStateValue.CompositionPageCursor != 7 {
panic("generated TextArea Shift+Down did not move")
}
driver.QueueShortcut(kryon.KeyC)
drawComposition()
if driver.ClipboardText() != "1\nc" {
panic("generated TextArea Shift+Down did not select")
}
driver.QueueKey(kryon.KeyLeft)
drawComposition()
if CompositionStateValue.CompositionPageCursor != 4 {
panic("generated TextArea Left did not collapse selection")
}
driver.QueueKey(kryon.KeyDown); drawComposition()
if CompositionStateValue.CompositionPageCursor <= 4 { panic("generated TextArea Down did not move") }
beforePage := CompositionStateValue.CompositionPageCursor
@@ -786,6 +824,12 @@ func main() {
driver.QueueKey(kryon.KeyEnter); drawComposition()
pageTextAfter := text64(CompositionStateValue.CompositionPageArea)
if len(pageTextAfter) != len(pageTextBefore)+1 || strings.Count(pageTextAfter, "\n") != strings.Count(pageTextBefore, "\n")+1 { panic("generated TextArea Enter did not insert newline") }
driver.QueueShortcut(kryon.KeyEnd); drawComposition()
driver.QueueShortcut(kryon.KeyBackspace); drawComposition()
wordDeletedText := text64(CompositionStateValue.CompositionPageArea)
if len(wordDeletedText) != len(pageTextAfter)-2 || !strings.HasSuffix(wordDeletedText, "\n") {
panic("generated TextArea Ctrl+Backspace did not delete final word")
}
fields := FieldsStateValue
focus := FocusStateValue
buttons := ButtonsLayoutStateValue
@@ -1568,6 +1612,73 @@ int main(void)
}
composition_read_only = 0;
SetUIFocus(26102);
InjectKey(KEY_LEFT_CONTROL,1);
InjectKeyTap(KEY_RIGHT);
InjectPump();
draw_composition();
InjectKey(KEY_LEFT_CONTROL,0);
InjectPump();
if(composition_page_cursor != 5) {
fprintf(stderr,"generated TextArea Ctrl+Right did not stop at separator\n");
return 1;
}
InjectKey(KEY_LEFT_CONTROL,1);
InjectKey(KEY_LEFT_SHIFT,1);
InjectKeyTap(KEY_RIGHT);
InjectPump();
draw_composition();
InjectKey(KEY_LEFT_CONTROL,0);
InjectKey(KEY_LEFT_SHIFT,0);
InjectPump();
if(composition_page_cursor != 6) {
fprintf(stderr,"generated TextArea Ctrl+Shift+Right did not extend by word\n");
return 1;
}
InjectKey(KEY_LEFT_CONTROL,1);
InjectKeyTap(KEY_C);
InjectPump();
draw_composition();
InjectKey(KEY_LEFT_CONTROL,0);
InjectPump();
if(strcmp(GetUIClipboardTextValue(),"\n") != 0) {
fprintf(stderr,"generated TextArea Ctrl+Shift+Right selection failed\n");
return 1;
}
InjectKeyTap(KEY_LEFT); InjectPump(); draw_composition(); InjectPump();
InjectKeyTap(KEY_LEFT); InjectPump(); draw_composition();
if(composition_page_cursor != 4) {
fprintf(stderr,"generated TextArea word-navigation reset cursor=%d, want 4\n",
composition_page_cursor);
return 1;
}
InjectKey(KEY_LEFT_SHIFT,1);
InjectKeyTap(KEY_DOWN);
InjectPump();
draw_composition();
InjectKey(KEY_LEFT_SHIFT,0);
InjectPump();
if(composition_page_cursor != 7) {
fprintf(stderr,"generated TextArea Shift+Down cursor=%d, want 7\n",
composition_page_cursor);
return 1;
}
InjectKey(KEY_LEFT_CONTROL,1);
InjectKeyTap(KEY_C);
InjectPump();
draw_composition();
InjectKey(KEY_LEFT_CONTROL,0);
InjectPump();
if(strcmp(GetUIClipboardTextValue(),"1\nc") != 0) {
fprintf(stderr,"generated TextArea Shift+Down did not select\n");
return 1;
}
InjectKeyTap(KEY_LEFT);
InjectPump();
draw_composition();
if(composition_page_cursor != 4) {
fprintf(stderr,"generated TextArea Left did not collapse selection\n");
return 1;
}
InjectKeyTap(KEY_DOWN); InjectPump(); draw_composition();
if(composition_page_cursor <= 4) {
fprintf(stderr,"generated TextArea Down did not move\n"); return 1;
@@ -1589,6 +1700,15 @@ int main(void)
TextBufferLineCount(composition_page_area) != composition_page_lines + 1) {
fprintf(stderr,"generated TextArea Enter did not insert newline\n"); return 1;
}
InjectKey(KEY_LEFT_CONTROL,1);
InjectKeyTap(KEY_END); InjectPump(); draw_composition();
InjectKeyTap(KEY_BACKSPACE); InjectPump(); draw_composition();
InjectKey(KEY_LEFT_CONTROL,0); InjectPump();
if((int)strlen(composition_page_area) != composition_page_length - 1 ||
composition_page_area[strlen(composition_page_area) - 1] != '\n') {
fprintf(stderr,"generated TextArea Ctrl+Backspace did not delete final word\n");
return 1;
}
InjectMousePosition(20,20);
InjectMouseButton(MOUSE_BUTTON_LEFT,1);
InjectPump(); draw_ui(drag_drop_frame);
+12
View File
@@ -29,6 +29,18 @@ if [ -n "$matches" ]; then
exit 1
fi
form_matches="$(
rg -n '\bUIForm[A-Za-z0-9_]*\b' \
include/ui_rows.h src/ui/rows.c docs/API.md docs/FEATURE_MATRIX.md \
docs/FEATURE_MATRIX.html tests/ui_tree_api_test.c || true
)"
if [ -n "$form_matches" ]; then
echo "Form cursor API must use the canonical Form names:"
echo "$form_matches"
exit 1
fi
generated_matches="$(
rg -n '\b(TextInputControl|GenericButton|TextButton|LocaleDropdown|VerticalSlider|VerticalSliderWithMarks|ReadonlyTextBox|DrawCenteredUIControlText|UIDropdownOption|DropdownEx|SetUIDropdownClipTop|SetUIDropdownClipBottom|DrawUIDropdown|DrawUIDropdownEx|UIParagraphSpec|UIParagraphLayout|UIModalAction|UINodeId|UIKey|UISide|UI_SIDE_[A-Z_]+|UIFrame|UIGrid|BeginUIFrameBox|UIFramePack|UIGridCell|UIPlace|UICanvas|BeginUICanvas|EndUICanvas|UIMenuItemKind|UIMenuItem|UIMenuBarResult|UIMenu|UI_MENU_[A-Z_]+|UIContextMenu|UIAccelerator|UIAcceleratorPressed|DispatchUIAccelerators|UIIconRowItem|UIIconRowResult|UIBottomNavItem|UIBottomNavResult|UIBottomNavOption|UIBottomNavConfigResult|UIToolbarAction|UIToolbarResult|UIToolbarHeaderResult|UITopNavAction|UITopNavResult|UISubtab|UITab|UIPaneDropZone|UIPaneTabBar|UIPaneTabBarResult|GetUIPaneDropZone|GetUITabBarHeight|UI_PANE_DROP_[A-Z_]+|UISidebarAccountHeaderSpec|UISidebarAccountHeaderResult|UIProfilePicturePickerModal|UIProfilePicturePickerResult)\b' \
go/kryon include/ui_controls.h include/ui_tree.h include/ui_tk.h include/ui_nav.h include/ui_profile.h include/ui_draw.h include/ui_modal.h src/ui/dropdown.c src/ui/ui_node_registry.c cmd/k2b examples tests/k2c_syntax_test.sh tests/k2go_syntax_test.sh docs/API.md docs/RUNTIME_PARITY.md docs/FEATURE_MATRIX.md docs/FEATURE_MATRIX.html \
+21
View File
@@ -349,6 +349,15 @@ int main(void)
BeginTextureMode(host_target);
ClearBackground(BLACK);
ui_paint_layers_frame(host_a,size,size);
int fallback_scroll = 0;
int *host_a_scroll = ui_tab_bar_owned_scroll(41200,&fallback_scroll);
if(frame == 0)
*host_a_scroll = 17;
else if(*host_a_scroll != 17) {
fprintf(stderr,"first host lost its owned tab scroll: %d\n",
*host_a_scroll);
failures++;
}
UIPaintLayerToken a_layer = ui_paint_layer_begin(host_a,1);
DrawRectangle(0,0,size,size,RED);
Rect(size-4,size-4,4,4,YELLOW,BLANK);
@@ -357,6 +366,12 @@ int main(void)
BeginTextureMode(inner);
ClearBackground(BLUE);
ui_paint_layers_frame(host_b,16,16);
int *host_b_scroll = ui_tab_bar_owned_scroll(41200,&fallback_scroll);
if(*host_b_scroll != (frame == 0 ? 0 : 9)) {
fprintf(stderr,"tab scroll crossed hosts: %d\n",*host_b_scroll);
failures++;
}
*host_b_scroll = 9;
UIPaintLayerToken b_layer = ui_paint_layer_begin(host_b,1);
DrawRectangle(0,0,4,4,GREEN);
Rect(8,8,4,4,MAGENTA,BLANK);
@@ -366,6 +381,12 @@ int main(void)
BeginTextureMode(inner);
ui_paint_layers_composite(host_b);
EndTextureMode();
host_a_scroll = ui_tab_bar_owned_scroll(41200,&fallback_scroll);
if(*host_a_scroll != 17) {
fprintf(stderr,"restored host has wrong tab scroll: %d\n",
*host_a_scroll);
failures++;
}
BeginTextureMode(host_target);
ui_paint_layers_composite(host_a);
if(frame == 1) ui_paint_layers_destroy(host_b);
+114
View File
@@ -12,8 +12,26 @@ int ui_utf8_next_offset(const char *text, int offset);
int ui_utf8_prev_offset(const char *text, int offset);
int ui_utf8_codepoint_count(const char *text);
int ui_utf8_encode(int codepoint, char out[5]);
int ui_text_word_left(const char *text, int cursor);
int ui_text_word_right(const char *text, int cursor);
typedef struct TextCompositionView {
char *text;
int cursor;
int selection_start;
int selection_end;
int composition_start;
int composition_end;
} TextCompositionView;
int ui_text_composition_view(const char *text, int selection_start,
int selection_end, const char *preedit,
int preedit_cursor,
int preedit_selection_length,
TextCompositionView *view);
void ui_text_composition_view_free(TextCompositionView *view);
int ui_text_delete_range(char *text, size_t text_size, int *cursor,
int start, int end);
int ui_text_delete_key(char *text, size_t text_size, int *anchor, int *cursor,
int key, int modifier, int secure);
int ui_text_insert_ascii(char *text, size_t text_size, int *cursor, char ch,
int max_codepoints);
int ui_text_insert_codepoint(char *text, size_t text_size, int *cursor,
@@ -24,6 +42,11 @@ int ui_text_insert_text(char *text, size_t text_size, int *cursor,
TextInputFilter filter, void *filter_user_data,
int max_codepoints);
enum {
TEST_KEY_BACKSPACE = 259,
TEST_KEY_DELETE = 261
};
static int failures = 0;
static void
@@ -129,6 +152,94 @@ test_utf8_prev_offset(void)
check_int("prev at 0 stays 0", ui_utf8_prev_offset(s, 0), 0);
}
static void
test_word_navigation(void)
{
const char *text = "alpha beta.gamma";
const char *unicode = "one\xe3\x80\x80two";
check_int("word left finds final word", ui_text_word_left(text, 16), 11);
check_int("word left treats punctuation as a stop",
ui_text_word_left(text, 11), 10);
check_int("word left crosses separator to word",
ui_text_word_left(text, 10), 6);
check_int("word right finds punctuation", ui_text_word_right(text, 6), 10);
check_int("word right crosses punctuation",
ui_text_word_right(text, 10), 11);
check_int("word right handles full-width blank",
ui_text_word_right(unicode, 0), 6);
}
static void
test_composition_view(void)
{
TextCompositionView view;
check_true("composition view builds",
ui_text_composition_view("aXYZz", 1, 4,
"\xe6\x97\xa5" "ab", 3, 1,
&view));
check_str("composition replaces committed selection", view.text,
"a\xe6\x97\xa5" "abz");
check_int("composition cursor uses UTF-8 byte offset", view.cursor, 4);
check_int("composition selection start", view.selection_start, 4);
check_int("composition selection end", view.selection_end, 5);
check_int("composition underline start", view.composition_start, 1);
check_int("composition underline end", view.composition_end, 6);
ui_text_composition_view_free(&view);
check_true("composition view free clears ownership", view.text == NULL);
check_true("composition clamps inside UTF-8 sequence",
ui_text_composition_view("ab", 1, 1,
"\xe6\x97\xa5", 2, 8, &view));
check_int("composition cursor clamps to rune boundary", view.cursor, 1);
check_int("composition selection clamps to preedit", view.selection_end, 4);
ui_text_composition_view_free(&view);
}
static void
test_delete_key(void)
{
char text[32] = "alpha beta.gamma";
int cursor = 16;
int anchor = cursor;
check_true("word backspace deletes final word",
ui_text_delete_key(text, sizeof(text), &anchor, &cursor,
TEST_KEY_BACKSPACE, 1, 0));
check_str("word backspace result", text, "alpha beta.");
check_int("word backspace cursor", cursor, 11);
check_true("word backspace deletes separator",
ui_text_delete_key(text, sizeof(text), &anchor, &cursor,
TEST_KEY_BACKSPACE, 1, 0));
check_str("word separator deletion result", text, "alpha beta");
cursor = 6;
anchor = cursor;
check_true("word delete removes next word",
ui_text_delete_key(text, sizeof(text), &anchor, &cursor,
TEST_KEY_DELETE, 1, 0));
check_str("word delete result", text, "alpha ");
strcpy(text, "alpha beta");
anchor = 0;
cursor = 5;
check_true("selection deletion takes precedence",
ui_text_delete_key(text, sizeof(text), &anchor, &cursor,
TEST_KEY_DELETE, 1, 0));
check_str("selection deletion result", text, " beta");
check_int("selection deletion collapses anchor", anchor, 0);
check_int("selection deletion collapses cursor", cursor, 0);
strcpy(text, "alpha beta");
cursor = 5;
anchor = cursor;
check_true("secure word backspace hides boundaries",
ui_text_delete_key(text, sizeof(text), &anchor, &cursor,
TEST_KEY_BACKSPACE, 1, 1));
check_str("secure word backspace result", text, " beta");
}
static void
test_utf8_codepoint_count(void)
{
@@ -274,11 +385,14 @@ main(void)
{
test_utf8_next_offset();
test_utf8_prev_offset();
test_word_navigation();
test_composition_view();
test_utf8_codepoint_count();
test_utf8_encode();
test_insert_ascii();
test_insert_codepoint();
test_delete_range();
test_delete_key();
test_insert_text_bulk();
if(failures != 0) {
fprintf(stderr, "%d text-edit test(s) failed\n", failures);
+270 -1
View File
@@ -98,10 +98,23 @@ test_slider_keyboard_navigation(void)
.value_count = 1, .min = 0, .max = 10
};
int second_focus;
int inspect_enabled;
InjectReset();
BeginUIFrame(640,480,1.0f); SliderFloat(horizontal); EndUIFrame();
SetUIFocus(600); InjectKeyTap(KEY_RIGHT); InjectPump();
inspect_enabled = UIInspectEnabled();
SetUIInspectEnabled(0);
InjectMousePosition(35,20);
InjectMouseButton(MOUSE_BUTTON_LEFT,1);
InjectPump();
BeginUIFrame(640,480,1.0f); SliderFloat(horizontal); EndUIFrame();
check_int("click focuses slider component",GetUIFocus(),600);
InjectMouseButton(MOUSE_BUTTON_LEFT,0);
InjectPump();
BeginUIFrame(640,480,1.0f); SliderFloat(horizontal); EndUIFrame();
SetUIInspectEnabled(inspect_enabled);
InjectKeyTap(KEY_RIGHT); InjectPump();
BeginUIFrame(640,480,1.0f);
check_int("slider Right changed",SliderFloat(horizontal),1);
EndUIFrame();
@@ -924,6 +937,38 @@ test_popup_menu_keyboard_ownership(void)
ui_popup_input_destroy(context);
EndUIFrame();
}
for(int inside = 0; inside < 2; inside++) {
UIPopupInput *context;
UIPopupInput *previous;
UIPopupInputToken parent;
UIPopupInputToken child;
int expected_focus = inside ? 0 : 25711;
InjectReset();
InjectKeyTap(KEY_ESCAPE);
InjectPump();
BeginUIFrame(320,240,1);
context = ui_popup_input_create();
ui_popup_input_frame(context);
previous = ui_popup_input_bind(context);
parent = ui_popup_input_begin(
context,25700,(Rectangle){180,180,40,40});
child = ui_popup_input_begin(
context,25701,(Rectangle){190,190,20,20});
if(!inside)
ui_popup_input_end(child);
SetUIFocus(25711);
(void)PopupMenu(25711,10,10,items,1);
check_int("only top popup menu handles Escape",
GetUIFocus(),expected_focus);
if(inside)
ui_popup_input_end(child);
ui_popup_input_end(parent);
ui_popup_input_finish(context);
ui_popup_input_bind(previous);
ui_popup_input_destroy(context);
EndUIFrame();
}
InjectReset();
}
@@ -1743,6 +1788,173 @@ test_text_area_page_navigation(void)
InjectKeyTap(KEY_PAGE_UP); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
check_int("TextArea PageUp moves more than one line",cursor <= before_page - 4,1);
int selection_start = 0;
int selection_end = 0;
before_page = cursor;
InjectKey(KEY_LEFT_SHIFT,1); InjectKeyTap(KEY_PAGE_DOWN); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
InjectKey(KEY_LEFT_SHIFT,0); InjectPump();
check_int("TextArea Shift+PageDown keeps anchor",
GetTextAreaSelection(area.focus_id, &selection_start,
&selection_end),1);
check_int("TextArea Shift+PageDown selection start",
selection_start,before_page);
check_int("TextArea Shift+PageDown selection end",selection_end,cursor);
InjectKeyTap(KEY_LEFT); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
check_int("TextArea Left collapses selection",cursor,before_page);
check_int("TextArea collapsed selection is empty",
GetTextAreaSelection(area.focus_id, NULL, NULL),0);
InjectKeyTap(KEY_HOME); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
check_int("TextArea Home moves to line start",cursor,6);
InjectKey(KEY_LEFT_CONTROL,1); InjectKeyTap(KEY_END); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
InjectKey(KEY_LEFT_CONTROL,0); InjectPump();
check_int("TextArea Ctrl+End moves to buffer end",cursor,(int)strlen(text));
InjectKey(KEY_LEFT_CONTROL,1); InjectKeyTap(KEY_LEFT); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
check_int("TextArea Ctrl+Left moves by word",cursor,15);
InjectPump();
InjectKey(KEY_LEFT_SHIFT,1); InjectKeyTap(KEY_LEFT); InjectPump();
BeginUIFrame(240,160,1); TextArea(area); EndUIFrame();
check_int("TextArea Ctrl+Shift+Left moves by separator",cursor,14);
check_int("TextArea Ctrl+Shift+Left keeps anchor",
GetTextAreaSelection(area.focus_id, &selection_start,
&selection_end),1);
check_int("TextArea word selection start",selection_start,14);
check_int("TextArea word selection end",selection_end,15);
InjectKey(KEY_LEFT_SHIFT,0); InjectKey(KEY_LEFT_CONTROL,0); InjectPump();
ClearTextInputFocus();
InjectReset();
}
static void
test_secure_text_field_word_navigation(void)
{
char text[32] = "alpha beta";
int cursor = 5;
int focused = 1;
TextFieldProps field = {
.bounds = {10,10,180,32}, .text = text, .text_size = sizeof(text),
.cursor_position = &cursor, .focused = &focused,
.focus_id = 25511, .secure = 1
};
InjectReset();
SetUIFocus(field.focus_id);
InjectKey(KEY_LEFT_CONTROL,1); InjectKeyTap(KEY_LEFT); InjectPump();
BeginUIFrame(240,100,1); TextField(field); EndUIFrame();
check_int("secure TextField Ctrl+Left hides word boundaries",cursor,0);
InjectPump(); InjectKeyTap(KEY_RIGHT); InjectPump();
BeginUIFrame(240,100,1); TextField(field); EndUIFrame();
check_int("secure TextField Ctrl+Right hides word boundaries",
cursor,(int)strlen(text));
InjectPump(); InjectKeyTap(KEY_BACKSPACE); InjectPump();
BeginUIFrame(240,100,1); TextField(field); EndUIFrame();
check_int("secure TextField Ctrl+Backspace clears opaque span",
strcmp(text,""),0);
InjectKey(KEY_LEFT_CONTROL,0); InjectPump();
ClearTextInputFocus();
InjectReset();
}
static void
test_immediate_text_composition(void)
{
char field_text[64] = "ab";
char area_text[64] = "aZZb";
int field_cursor = 1;
int area_cursor = 3;
int field_focused = 1;
int area_focused = 1;
const char *preedit = NULL;
int preedit_cursor = 0;
int preedit_selection = 0;
TextFieldProps field = {
.bounds = {10,10,180,32}, .text = field_text,
.text_size = sizeof(field_text), .cursor_position = &field_cursor,
.focused = &field_focused, .focus_id = 25520
};
TextAreaProps area = {
.bounds = {10,50,180,80}, .text = area_text,
.text_size = sizeof(area_text), .cursor_position = &area_cursor,
.focused = &area_focused, .focus_id = 25521
};
InjectReset();
ClearTextInputFocus();
field_focused = 1;
SetUIFocus(field.focus_id);
SubmitTextComposition(KRY_TEXT_COMPOSITION_UPDATE,
"\xE6\x97\xA5\xE6\x9C\xAC", 3, 0);
BeginUIFrame(240,160,1);
check_int("immediate TextField preedit is not committed",
TextField(field), 0);
EndUIFrame();
check_int("immediate TextField preserves committed buffer",
strcmp(field_text,"ab"), 0);
check_int("immediate TextField owns shared preedit",
ui_text_composition_get(&field_focused, &preedit,
&preedit_cursor,
&preedit_selection), 1);
check_int("immediate TextField preedit UTF-8 cursor",
preedit_cursor, 3);
SubmitTextComposition(KRY_TEXT_COMPOSITION_COMMIT,
"\xE6\x97\xA5\xE6\x9C\xAC", 6, 0);
BeginUIFrame(240,160,1);
check_int("immediate TextField commit reports change",
TextField(field), 1);
EndUIFrame();
check_int("immediate TextField commits UTF-8 at caret",
strcmp(field_text,"a\xE6\x97\xA5\xE6\x9C\xAC" "b"), 0);
check_int("immediate TextField clears preedit after commit",
ui_text_composition_get(&field_focused, NULL, NULL, NULL), 0);
ClearTextInputFocus();
area_focused = 1;
SetUIFocus(area.focus_id);
SetTextAreaSelection(area.focus_id, 1, 3);
SubmitTextComposition(KRY_TEXT_COMPOSITION_UPDATE,
"\xE3\x81\xAB", 3, 0);
BeginUIFrame(240,160,1);
check_int("immediate TextArea preedit is not committed",
TextArea(area), 0);
EndUIFrame();
check_int("immediate TextArea preserves selected text during preedit",
strcmp(area_text,"aZZb"), 0);
SubmitTextComposition(KRY_TEXT_COMPOSITION_COMMIT,
"\xE6\x97\xA5\xE6\x9C\xAC", 6, 0);
BeginUIFrame(240,160,1);
check_int("immediate TextArea commit reports change",
TextArea(area), 1);
EndUIFrame();
check_int("immediate TextArea composition replaces selection",
strcmp(area_text,"a\xE6\x97\xA5\xE6\x9C\xAC" "b"), 0);
SubmitTextComposition(KRY_TEXT_COMPOSITION_UPDATE,"blocked",7,0);
BeginUIFrame(240,160,1);
TextArea(area);
EndUIFrame();
area.read_only = 1;
SubmitTextComposition(KRY_TEXT_COMPOSITION_COMMIT,"x",1,0);
BeginUIFrame(240,160,1);
check_int("read-only immediate editor ignores IME commit",
TextArea(area), 0);
EndUIFrame();
check_int("read-only immediate editor cancels preedit",
ui_text_composition_get(&area_focused, NULL, NULL, NULL), 0);
check_int("read-only immediate editor does not mutate text",
strcmp(area_text,"a\xE6\x97\xA5\xE6\x9C\xAC" "b"), 0);
ClearTextInputFocus();
InjectReset();
}
@@ -2324,6 +2536,61 @@ test_popup_combo_keyboard_ownership(void)
dropdown_close(25400);
EndUIFrame();
}
for(int inside = 0; inside < 2; inside++) {
UIPopupInput *context;
UIPopupInput *previous;
UIPopupInputToken parent;
UIPopupInputToken child;
int selected = 0;
InjectReset();
InjectKeyTap(KEY_SPACE);
InjectPump();
BeginUIFrame(240,240,1);
SetUIFocus(25400);
(void)Combobox((ComboboxProps){
.bounds={10,10,100,28},
.id=25400,
.options=options,
.option_count=2,
.selected_index=&selected
});
EndUIFrame();
check_int("combo opens before Escape ownership test",
dropdown_captures((Vector2){20,50}),1);
InjectKeyTap(KEY_ESCAPE);
InjectPump();
BeginUIFrame(240,240,1);
context = ui_popup_input_create();
ui_popup_input_frame(context);
previous = ui_popup_input_bind(context);
parent = ui_popup_input_begin(
context,25700,(Rectangle){180,180,40,40});
child = ui_popup_input_begin(
context,25701,(Rectangle){190,190,20,20});
if(!inside)
ui_popup_input_end(child);
SetUIFocus(25400);
(void)Combobox((ComboboxProps){
.bounds={10,10,100,28},
.id=25400,
.options=options,
.option_count=2,
.selected_index=&selected
});
if(inside)
ui_popup_input_end(child);
ui_popup_input_end(parent);
DrawUIFrameOverlays();
check_int("obscured combo ignores Escape",
dropdown_captures((Vector2){20,50}),!inside);
ui_popup_input_finish(context);
ui_popup_input_bind(previous);
ui_popup_input_destroy(context);
EndUIFrame();
dropdown_close(25400);
}
InjectReset();
}
@@ -3457,6 +3724,8 @@ main(void)
test_popup_active_drag_ownership();
test_popup_text_keyboard_ownership();
test_text_area_page_navigation();
test_secure_text_field_word_navigation();
test_immediate_text_composition();
test_popup_tab_ownership();
test_popup_button_keyboard_ownership();
test_popup_choice_keyboard_ownership();
+94 -6
View File
@@ -5,6 +5,7 @@
#include <string.h>
static int failures;
static int draw_rectangle_calls;
static void
check_int(const char *name, int got, int want);
@@ -23,6 +24,11 @@ void __wrap_EndScissorMode(void);
void ui_paint_text_area(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end);
void ui_paint_text_area_composition(TextAreaProps area, int cursor, int focused,
int selection_start, int selection_end,
int composition_start,
int composition_end);
int ui_active_font_token(void);
typedef struct ScaffoldFixture {
int seen_w;
@@ -65,7 +71,7 @@ main(void)
SectionLabelProps section = {0};
CheckboxRowProps checkbox = {0};
ButtonRowProps row = {.width = 240, .height = 40};
UIForm form;
Form form;
Rectangle taken;
UIScreenScaffold scaffold;
BottomNavProps nav = {0};
@@ -98,16 +104,16 @@ main(void)
check_int("button row",
GetNodeHeight(NodeButtonRow(row)),
Scale(40));
form = UIFormBegin(10, 20, 240);
taken = UIFormTakeRect(&form, Scale(18));
form = FormBegin(10, 20, 240);
taken = FormTakeRect(&form, Scale(18));
check_int("form rect x", (int)taken.x, 10);
check_int("form rect y", (int)taken.y, 20);
check_int("form rect width", (int)taken.width, 240);
check_int("form advances", UIFormY(&form), 20 + Scale(18));
check_int("form advances", FormY(&form), 20 + Scale(18));
BeginTree(6);
UIFormSection(&form, "Account");
FormSection(&form, (SectionLabelProps){.label = "Account"});
EndTree();
check_int("form section helper advances", UIFormY(&form),
check_int("form section helper advances", FormY(&form),
20 + Scale(18) + Scale(24));
check_int("spinbox row height",
GetUISpinboxRowHeight((SpinboxRowProps){0}),
@@ -604,10 +610,34 @@ main(void)
check_int("retained textarea clamps negative scroll", scroll_y, 0);
}
{
char value[64] = "a\xe6\x97\xa5\xe6\x9c\xacz";
int cursor = 7;
int scroll_y = 0;
int ordinary_rectangles;
draw_rectangle_calls = 0;
ui_paint_text_area((TextAreaProps){
.bounds = {20,30,180,80}, .text = value,
.text_size = sizeof(value), .cursor_position = &cursor,
.scroll_y = &scroll_y, .font = 16, .line_gap = 4
}, cursor, 0, cursor, cursor);
ordinary_rectangles = draw_rectangle_calls;
draw_rectangle_calls = 0;
ui_paint_text_area_composition((TextAreaProps){
.bounds = {20,30,180,80}, .text = value,
.text_size = sizeof(value), .cursor_position = &cursor,
.scroll_y = &scroll_y, .font = 16, .line_gap = 4
}, cursor, 0, cursor, cursor, 1, 7);
check_int("textarea composition adds underline paint",
draw_rectangle_calls, ordinary_rectangles + 1);
}
/* Composition events preserve preedit separately and commit UTF-8 only
* when the platform IME finalizes it. */
{
KryTextCompositionEvent event;
char long_preedit[300];
ClearTextComposition();
check_int("submit composition update",
@@ -618,6 +648,15 @@ main(void)
KRY_TEXT_COMPOSITION_UPDATE);
check_int("composition update text", strcmp(event.text, "nihon"), 0);
check_int("composition queue drained", PollTextComposition(&event), 0);
memset(long_preedit, 'x', 254);
memcpy(long_preedit + 254, "\xe6\x97\xa5", 4);
check_int("submit truncated UTF-8 composition",
SubmitTextComposition(KRY_TEXT_COMPOSITION_UPDATE,
long_preedit, 254, 0), 1);
check_int("poll truncated UTF-8 composition",
PollTextComposition(&event), 1);
check_int("composition drops partial UTF-8 tail",
(int)strlen(event.text), 254);
}
/* The retained tree exposes a backend-neutral accessibility snapshot. */
@@ -664,12 +703,61 @@ main(void)
}
check_int("boxed text typed node", boxed_count, 1);
}
{
Font font = {0};
Rectangle font_rec = {0};
GlyphInfo font_glyph = {0};
char field_text[8] = "a";
char area_text[8] = "b";
int field_cursor = 1;
int area_cursor = 1;
int scroll_y = 0;
int previous;
int text_inputs = 0;
ClearUIFonts();
font.baseSize = 16;
font.glyphCount = 1;
font.texture.id = 1;
font.recs = &font_rec;
font.glyphs = &font_glyph;
check_int("register retained font base probe",
RegisterUIFont("retained-base", font), 1);
check_int("register retained font snapshot probe",
RegisterUIFont("retained-probe", font), 1);
previous = PushUIFont("retained-probe");
check_int("font probe preserves prior font", previous, 0);
BeginTree(1500);
TextField((TextFieldProps){.bounds = {10,10,80,24},
.text = field_text, .text_size = sizeof(field_text),
.cursor_position = &field_cursor, .focus_id = 1501});
TextArea((TextAreaProps){.bounds = {10,40,80,40},
.text = area_text, .text_size = sizeof(area_text),
.cursor_position = &area_cursor, .scroll_y = &scroll_y,
.focus_id = 1502});
EndTree();
nodes = GetTreeNodes(&count);
for(int i = 0; i < count; i++) {
if(nodes[i].kind != UI_WIDGET_TEXT_FIELD_NODE &&
nodes[i].kind != UI_WIDGET_TEXT_AREA_NODE)
continue;
text_inputs++;
check_int("retained text captures declaration font",
nodes[i].font_token, 1);
}
check_int("both retained text widgets capture fonts", text_inputs, 2);
PopUIFont(previous);
check_int("font token restores prior font",
ui_active_font_token(), 0);
ClearUIFonts();
}
return failures == 0 ? 0 : 1;
}
void
__wrap_DrawRectangle(int posX, int posY, int width, int height, Color color)
{
draw_rectangle_calls++;
(void)posX;
(void)posY;
(void)width;