ludic/examples/library/ui_keycap.ludic
Orkuncakilkaya 19fcf60599 wip(0.S3): packages and examples migrated again from their pre-0.S sources in one run
ludic migrate state packages <every example program> packages/ludic.lab/example/plate.ludic
  1804 vars into 126 states, 64 into lets; 23498 edits in 460 files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:31:34 +03:00

57 lines
2.3 KiB
Text

# ui_keycap.ludic — a key field takes a mouse button as well as a key: listening (and :capturing,
# which a stylesheet can colour), the next press of the left, right or middle button anywhere is its
# value (UI_MOUSE_LEFT / RIGHT / MIDDLE), named for what it is, and that press presses nothing else.
import "ludic.ui"
program UiKeycap {
numbers float
state UiKeycapState {
bind: int = 32
pressed: int = 0
}
view Keys (ui_keycap_st: mut UiKeycapState) {
bind = ui_keycap_st.bind
pressed = ui_keycap_st.pressed
on set_bind(v: int) { ui_keycap_st.bind = v }
on press() { ui_keycap_st.pressed = ui_keycap_st.pressed + 1 }
}
const PAGE: string = "<ui><style>.k:capturing { background: #ff0000 }</style><screen name='k'><input type='key' class='k' label='Jump' value='{bind}' on-change='set_bind(event.value)'/><button on-click='press()'>b</button></screen></ui>"
function frame(ui_st: mut UiState, x: float, y: float, b: int) -> UiNode {
let i = new UiInput
i.x = x
i.y = y
i.down = b == 0
i.down_right = b == 1
i.down_middle = b == 2
ui_input(ui_st, i)
ui_show(ui_st, "k", view_keys(), 0.0, 0.0, 400.0, 400.0)
let r: UiNode = ui_nodes(ui_st, "k", view_keys())
ui_place(ui_st, r, 0.0, 0.0, 400.0, 400.0)
return r
}
function listen(ui_st: mut UiState, k: UiNode) -> int {
frame(ui_st, k.x + 5.0, k.y + 5.0, 0)
frame(ui_st, k.x + 5.0, k.y + 5.0, -1)
return frame(ui_st, -1.0, -1.0, -1).children[0].bg
}
function take(ui_keycap_st: UiKeycapState, ui_st: mut UiState, at: UiNode, b: int) -> string {
frame(ui_st, at.x + 5.0, at.y + 5.0, b)
frame(ui_st, at.x + 5.0, at.y + 5.0, -1)
let r = frame(ui_st, -1.0, -1.0, -1)
let f = r.children[0]
return `{ui_keycap_st.bind} {f.children[1].children[0].text} {f.bg}`
}
entry (ui_keycap_st: UiKeycapState, ui_st: mut UiState) {
ui_backend(ui_st, new UiBackend)
ui_load_text(ui_st, PAGE, "k.xml")
let r = frame(ui_st, -1.0, -1.0, -1)
let k = r.children[0]
let btn = r.children[1]
let red = listen(ui_st, k)
let right = take(ui_keycap_st, ui_st, btn, 1)
listen(ui_st, k)
let middle = take(ui_keycap_st, ui_st, btn, 2)
listen(ui_st, k)
let left = take(ui_keycap_st, ui_st, btn, 0)
print(`listening {red} | {right} | {middle} | {left} | pressed {ui_keycap_st.pressed}`)
}
}