Files
moonmix/gtk/gtk.mbt
T
nandi d360b51bb2
CI / check (push) Successful in 9s
CI / native (push) Successful in 1m14s
Smooth wheel scrolling: route scroll over sliders to the list or the volume (#5)
2026-11-23 06:55:50 +00:00

725 lines
16 KiB
MoonBit

// Minimal hand-written GTK4 binding (see gtk_stub.c). Only what moonmix
// needs. Signals are dispatched through a tag -> handler table.
///|
#external
pub type Widget
///|
extern "C" fn ffi_set_handler(
call : FuncRef[((Int32, Double) -> Unit, Int32, Double) -> Unit],
closure : (Int32, Double) -> Unit,
) = "mm_gtk_set_handler"
///|
extern "C" fn ffi_set_scroll_handler(
call : FuncRef[
(
(Int32, Int32, Int32, Double, Double, Int64, Double, Double) -> Double,
Int32,
Int32,
Int32,
Double,
Double,
Int64,
Double,
Double,
) -> Double,
],
closure : (Int32, Int32, Int32, Double, Double, Int64, Double, Double) -> Double,
) = "mm_gtk_set_scroll_handler"
///|
extern "C" fn ffi_init() -> Int32 = "mm_gtk_init"
///|
extern "C" fn ffi_run() = "mm_gtk_run"
///|
extern "C" fn ffi_quit() = "mm_gtk_quit"
///|
extern "C" fn ffi_now_us() -> Int64 = "mm_gtk_now_us"
///|
extern "C" fn ffi_begin_update() = "mm_gtk_begin_update"
///|
extern "C" fn ffi_end_update() = "mm_gtk_end_update"
///|
extern "C" fn ffi_timeout(ms : Int32, tag : Int32) = "mm_gtk_timeout"
///|
#borrow(css)
extern "C" fn ffi_load_css(css : Bytes) = "mm_gtk_load_css"
///|
#borrow(title)
extern "C" fn ffi_window_new(
title : Bytes,
w : Int32,
h : Int32,
tag : Int32,
) -> Widget = "mm_gtk_window_new"
///|
extern "C" fn ffi_window_set_child(win : Widget, child : Widget) = "mm_gtk_window_set_child"
///|
extern "C" fn ffi_window_present(win : Widget) = "mm_gtk_window_present"
///|
extern "C" fn ffi_box_new(vertical : Int32, spacing : Int32) -> Widget = "mm_gtk_box_new"
///|
extern "C" fn ffi_box_append(b : Widget, child : Widget) = "mm_gtk_box_append"
///|
extern "C" fn ffi_box_remove(b : Widget, child : Widget) = "mm_gtk_box_remove"
///|
extern "C" fn ffi_box_reorder_after(
b : Widget,
child : Widget,
sibling : Widget,
) = "mm_gtk_box_reorder_after"
///|
extern "C" fn ffi_null() -> Widget = "mm_gtk_null"
///|
extern "C" fn ffi_scrolled_new(child : Widget) -> Widget = "mm_gtk_scrolled_new"
///|
extern "C" fn ffi_notebook_new(tag : Int32) -> Widget = "mm_gtk_notebook_new"
///|
#borrow(label, icon)
extern "C" fn ffi_notebook_append(
nb : Widget,
child : Widget,
label : Bytes,
icon : Bytes,
) = "mm_gtk_notebook_append"
///|
extern "C" fn ffi_notebook_set_page(nb : Widget, i : Int32) = "mm_gtk_notebook_set_page"
///|
extern "C" fn ffi_separator_new() -> Widget = "mm_gtk_separator_new"
///|
#borrow(text)
extern "C" fn ffi_label_new(text : Bytes) -> Widget = "mm_gtk_label_new"
///|
#borrow(text)
extern "C" fn ffi_label_set_text(l : Widget, text : Bytes) = "mm_gtk_label_set_text"
///|
extern "C" fn ffi_label_set_width_chars(l : Widget, n : Int32) = "mm_gtk_label_set_width_chars"
///|
#borrow(icon)
extern "C" fn ffi_image_new(icon : Bytes, size : Int32) -> Widget = "mm_gtk_image_new"
///|
#borrow(icon)
extern "C" fn ffi_image_set_icon(img : Widget, icon : Bytes) = "mm_gtk_image_set_icon"
///|
extern "C" fn ffi_image_set_pixel_size(img : Widget, size : Int32) = "mm_gtk_image_set_pixel_size"
///|
#borrow(name)
extern "C" fn ffi_has_icon(name : Bytes) -> Int32 = "mm_gtk_has_icon"
///|
#borrow(key)
extern "C" fn ffi_app_icon(key : Bytes) -> Bytes = "mm_gtk_app_icon"
///|
extern "C" fn ffi_scale_new(max : Double, norm : Double, tag : Int32) -> Widget = "mm_gtk_scale_new"
///|
extern "C" fn ffi_scale_set(sc : Widget, v : Double) = "mm_gtk_scale_set"
///|
extern "C" fn ffi_scale_get(sc : Widget) -> Double = "mm_gtk_scale_get"
///|
#borrow(icon, label)
extern "C" fn ffi_toggle_new(
icon : Bytes,
label : Bytes,
tag : Int32,
) -> Widget = "mm_gtk_toggle_new"
///|
extern "C" fn ffi_toggle_set(b : Widget, active : Int32) = "mm_gtk_toggle_set"
///|
#borrow(icon)
extern "C" fn ffi_button_set_icon(b : Widget, icon : Bytes) = "mm_gtk_button_set_icon"
///|
extern "C" fn ffi_dropdown_new(tag : Int32) -> Widget = "mm_gtk_dropdown_new"
///|
#borrow(items)
extern "C" fn ffi_dropdown_set(dd : Widget, items : Bytes, selected : Int32) = "mm_gtk_dropdown_set"
///|
extern "C" fn ffi_levelbar_new() -> Widget = "mm_gtk_levelbar_new"
///|
extern "C" fn ffi_levelbar_set(lb : Widget, v : Double) = "mm_gtk_levelbar_set"
///|
#borrow(text)
extern "C" fn ffi_set_tooltip(w : Widget, text : Bytes) = "mm_gtk_widget_set_tooltip"
///|
extern "C" fn ffi_set_hexpand(w : Widget, v : Int32) = "mm_gtk_widget_set_hexpand"
///|
extern "C" fn ffi_set_margins(w : Widget, m : Int32) = "mm_gtk_widget_set_margins"
///|
#borrow(cls)
extern "C" fn ffi_add_css_class(w : Widget, cls : Bytes) = "mm_gtk_widget_add_css_class"
///|
#borrow(cls)
extern "C" fn ffi_remove_css_class(w : Widget, cls : Bytes) = "mm_gtk_widget_remove_css_class"
///|
extern "C" fn ffi_set_visible(w : Widget, v : Int32) = "mm_gtk_widget_set_visible"
///|
extern "C" fn ffi_set_sensitive(w : Widget, v : Int32) = "mm_gtk_widget_set_sensitive"
///|
extern "C" fn ffi_set_valign_center(w : Widget) = "mm_gtk_widget_set_valign_center"
///|
extern "C" fn ffi_set_halign_center(w : Widget) = "mm_gtk_widget_set_halign_center"
///|
extern "C" fn ffi_set_vexpand(w : Widget, v : Int32) = "mm_gtk_widget_set_vexpand"
///|
#borrow(path)
extern "C" fn ffi_save_png(w : Widget, path : Bytes) -> Int32 = "mm_gtk_save_png"
// ---- dispatch -------------------------------------------------------------
///|
let handlers : Map[Int32, (Double) -> Unit] = Map([])
///|
/// Scroll handlers of sliders, by the slider's tag.
let scroll_handlers : Map[Int32, (ScrollEvent) -> Double?] = Map([])
///|
let next_tag : Ref[Int32] = { val: 1, }
///|
let dispatch_installed : Ref[Bool] = { val: false, }
///|
fn install_dispatch() -> Unit {
if !dispatch_installed.val {
dispatch_installed.val = true
ffi_set_handler(fn(g, tag, v) { g(tag, v) }, fn(tag, v) {
match handlers.get(tag) {
Some(h) => h(v)
None => ()
}
})
ffi_set_scroll_handler(
fn(g, tag, phase, unit, dx, dy, since, value, extent) {
g(tag, phase, unit, dx, dy, since, value, extent)
},
fn(tag, phase, unit, dx, dy, since, value, extent) {
match scroll_handlers.get(tag) {
Some(h) => {
let ev = {
phase: match phase {
0 => Begin
2 => End
_ => Scroll
},
pixels: unit == 1,
dx,
dy,
since_list_us: since,
value,
extent,
}
match h(ev) {
Some(v) => v
None => -1.0
}
}
None => -1.0
}
},
)
}
}
///|
/// Register a handler and return its tag.
fn register(h : (Double) -> Unit) -> Int32 {
install_dispatch()
let tag = next_tag.val
next_tag.val += 1
handlers.set(tag, h)
tag
}
///|
/// Forget a handler (when its widget is destroyed).
pub fn unregister(tag : Int32) -> Unit {
handlers.remove(tag)
scroll_handlers.remove(tag)
}
///|
fn cstr(s : String) -> Bytes {
let b = @utf8.encode(s)
let n = b.length()
Bytes::makei(n + 1, fn(i) { if i < n { b[i] } else { b'\x00' } })
}
///|
fn int(b : Bool) -> Int32 {
if b {
1
} else {
0
}
}
// ---- public API ------------------------------------------------------------
///|
/// Initialise GTK. False if no display is available.
pub fn init_gtk() -> Bool {
install_dispatch()
ffi_init() != 0
}
///|
pub fn run() -> Unit {
ffi_run()
}
///|
pub fn quit() -> Unit {
ffi_quit()
}
///|
/// Monotonic clock in microseconds.
pub fn now_us() -> Int64 {
ffi_now_us()
}
///|
/// Run `f` with widget signals suppressed (programmatic updates).
pub fn updating(f : () -> Unit) -> Unit {
ffi_begin_update()
f()
ffi_end_update()
}
///|
pub fn timeout(ms : Int32, f : () -> Unit) -> Unit {
let tag_ref : Ref[Int32] = { val: 0, }
tag_ref.val = register(fn(_) {
unregister(tag_ref.val)
f()
})
ffi_timeout(ms, tag_ref.val)
}
///|
pub fn load_css(css : String) -> Unit {
ffi_load_css(cstr(css))
}
///|
extern "C" fn ffi_portal_watch(tag : Int32) -> Int32 = "mm_gtk_portal_watch"
///|
extern "C" fn ffi_portal_accent(i : Int32) -> Double = "mm_gtk_portal_accent"
///|
extern "C" fn ffi_portal_color_scheme() -> Int32 = "mm_gtk_portal_color_scheme"
///|
#borrow(css)
extern "C" fn ffi_set_accent_css(css : Bytes) = "mm_gtk_set_accent_css"
///|
extern "C" fn ffi_prefers_dark() -> Int32 = "mm_gtk_prefers_dark"
///|
extern "C" fn ffi_set_color_scheme(scheme : Int32) = "mm_gtk_set_color_scheme"
///|
/// The desktop's appearance settings, from the XDG Desktop Portal.
pub(all) struct Appearance {
/// accent-color as reported (each channel -1 when unset).
accent : (Double, Double, Double)
/// color-scheme: 0 no preference, 1 dark, 2 light.
color_scheme : Int32
}
///|
/// Follow org.freedesktop.appearance (accent-color, color-scheme) through
/// the portal's Settings interface: `f` runs once with the current values
/// and again on every change. Never runs without a portal. False without a
/// session bus.
pub fn watch_appearance(f : (Appearance) -> Unit) -> Bool {
let tag = register(fn(_) {
f({
accent: (ffi_portal_accent(0), ffi_portal_accent(1), ffi_portal_accent(2)),
color_scheme: ffi_portal_color_scheme(),
})
})
ffi_portal_watch(tag) != 0
}
///|
/// Replace the accent stylesheet (APPLICATION priority); "" removes it.
pub fn set_accent_css(css : String) -> Unit {
ffi_set_accent_css(cstr(css))
}
///|
/// Apply a color-scheme preference (0 none: back to the configured theme
/// variant, 1 dark, 2 light).
pub fn set_color_scheme(scheme : Int32) -> Unit {
ffi_set_color_scheme(scheme)
}
///|
/// Whether the theme is in its dark variant.
pub fn prefers_dark() -> Bool {
ffi_prefers_dark() != 0
}
///|
pub fn window(
title : String,
width : Int32,
height : Int32,
on_close~ : () -> Unit = fn() { },
) -> Widget {
ffi_window_new(cstr(title), width, height, register(fn(_) { on_close() }))
}
///|
pub fn Widget::set_child(self : Widget, child : Widget) -> Unit {
ffi_window_set_child(self, child)
}
///|
pub fn Widget::present(self : Widget) -> Unit {
ffi_window_present(self)
}
///|
pub fn vbox(spacing : Int32) -> Widget {
ffi_box_new(1, spacing)
}
///|
pub fn hbox(spacing : Int32) -> Widget {
ffi_box_new(0, spacing)
}
///|
pub fn Widget::append(self : Widget, child : Widget) -> Unit {
ffi_box_append(self, child)
}
///|
pub fn Widget::remove(self : Widget, child : Widget) -> Unit {
ffi_box_remove(self, child)
}
///|
/// Move `child` right after `sibling` in a box (None = first).
pub fn Widget::reorder_after(
self : Widget,
child : Widget,
sibling : Widget?,
) -> Unit {
ffi_box_reorder_after(
self,
child,
match sibling {
Some(s) => s
None => ffi_null()
},
)
}
///|
pub fn scrolled(child : Widget) -> Widget {
ffi_scrolled_new(child)
}
///|
pub fn notebook(on_switch~ : (Int32) -> Unit = fn(_) { }) -> Widget {
ffi_notebook_new(register(fn(v) { on_switch(v.to_int()) }))
}
///|
pub fn Widget::append_page(
self : Widget,
child : Widget,
label : String,
icon~ : String = "",
) -> Unit {
ffi_notebook_append(self, child, cstr(label), cstr(icon))
}
///|
pub fn Widget::set_page(self : Widget, i : Int32) -> Unit {
ffi_notebook_set_page(self, i)
}
///|
pub fn separator() -> Widget {
ffi_separator_new()
}
///|
pub fn label(text : String) -> Widget {
ffi_label_new(cstr(text))
}
///|
pub fn Widget::set_text(self : Widget, text : String) -> Unit {
ffi_label_set_text(self, cstr(text))
}
///|
pub fn Widget::set_width_chars(self : Widget, n : Int32) -> Unit {
ffi_label_set_width_chars(self, n)
}
///|
pub fn image(icon : String, size : Int32) -> Widget {
ffi_image_new(cstr(icon), size)
}
///|
pub fn Widget::set_icon(self : Widget, icon : String) -> Unit {
ffi_image_set_icon(self, cstr(icon))
}
///|
pub fn Widget::set_pixel_size(self : Widget, size : Int32) -> Unit {
ffi_image_set_pixel_size(self, size)
}
///|
#derive(Eq, Debug)
pub(all) enum ScrollPhase {
/// A scroll gesture (touchpad sequence) starts.
Begin
Scroll
/// The gesture ends.
End
}
///|
/// A scroll event over a slider.
pub(all) struct ScrollEvent {
phase : ScrollPhase
/// Deltas in surface pixels (touchpad), else in wheel detents.
pixels : Bool
/// Physical direction: dx > 0 right, dy > 0 down. 0 for Begin/End.
dx : Double
dy : Double
/// Microseconds since a list last scrolled.
since_list_us : Int64
/// The slider's value and width (px).
value : Double
extent : Double
}
///|
/// A slider from 0 to `max` with a mark at `norm`. Returns (widget, tag).
///
/// Scroll events over it go to `on_scroll`: it returns the slider's new
/// value (which then reaches `on_change`) to take the event, or `None` to
/// leave it to the scrolled list around the slider. By default sliders never
/// take scroll events.
pub fn scale(
max : Double,
norm : Double,
on_change : (Double) -> Unit,
on_scroll~ : (ScrollEvent) -> Double? = fn(_) { None },
) -> (Widget, Int32) {
let tag = register(on_change)
scroll_handlers.set(tag, on_scroll)
(ffi_scale_new(max, norm, tag), tag)
}
///|
pub fn Widget::set_value(self : Widget, v : Double) -> Unit {
ffi_scale_set(self, v)
}
///|
pub fn Widget::value(self : Widget) -> Double {
ffi_scale_get(self)
}
///|
pub fn toggle(
icon : String,
label : String,
on_toggle : (Bool) -> Unit,
) -> (Widget, Int32) {
let tag = register(fn(v) { on_toggle(v != 0.0) })
(ffi_toggle_new(cstr(icon), cstr(label), tag), tag)
}
///|
pub fn Widget::set_active(self : Widget, active : Bool) -> Unit {
ffi_toggle_set(self, int(active))
}
///|
pub fn Widget::set_button_icon(self : Widget, icon : String) -> Unit {
ffi_button_set_icon(self, cstr(icon))
}
///|
pub fn dropdown(on_select : (Int32) -> Unit) -> (Widget, Int32) {
let tag = register(fn(v) { on_select(v.to_int()) })
(ffi_dropdown_new(tag), tag)
}
///|
pub fn Widget::set_items(
self : Widget,
items : Array[String],
selected : Int32,
) -> Unit {
// '\n' separates items on the C side, so strip it from labels.
let clean = items.map(fn(s) { s.replace_all(old="\n", new=" ") })
ffi_dropdown_set(self, cstr(clean.join("\n")), selected)
}
///|
/// A 0..1 level bar (peak meter).
pub fn level_bar() -> Widget {
ffi_levelbar_new()
}
///|
pub fn Widget::set_level(self : Widget, v : Double) -> Unit {
ffi_levelbar_set(self, v)
}
///|
pub fn Widget::set_tooltip(self : Widget, text : String) -> Unit {
ffi_set_tooltip(self, cstr(text))
}
///|
pub fn Widget::set_hexpand(self : Widget, v : Bool) -> Unit {
ffi_set_hexpand(self, int(v))
}
///|
pub fn Widget::set_margins(self : Widget, m : Int32) -> Unit {
ffi_set_margins(self, m)
}
///|
pub fn Widget::add_css_class(self : Widget, cls : String) -> Unit {
ffi_add_css_class(self, cstr(cls))
}
///|
pub fn Widget::remove_css_class(self : Widget, cls : String) -> Unit {
ffi_remove_css_class(self, cstr(cls))
}
///|
pub fn Widget::set_visible(self : Widget, v : Bool) -> Unit {
ffi_set_visible(self, int(v))
}
///|
pub fn Widget::set_sensitive(self : Widget, v : Bool) -> Unit {
ffi_set_sensitive(self, int(v))
}
///|
pub fn Widget::set_valign_center(self : Widget) -> Unit {
ffi_set_valign_center(self)
}
///|
pub fn Widget::set_halign_center(self : Widget) -> Unit {
ffi_set_halign_center(self)
}
///|
pub fn Widget::set_vexpand(self : Widget, v : Bool) -> Unit {
ffi_set_vexpand(self, int(v))
}
///|
/// Render the widget offscreen to a PNG file (for headless screenshots).
pub fn Widget::save_png(self : Widget, path : String) -> Bool {
ffi_save_png(self, cstr(path)) != 0
}
///|
/// Does the current icon theme have this icon?
pub fn has_icon(name : String) -> Bool {
ffi_has_icon(cstr(name)) != 0
}
///|
/// Icon of the installed application matching `key` (desktop id, binary or
/// name) per its .desktop file, "" if there is none or the theme lacks it.
pub fn app_icon(key : String) -> String {
@utf8.decode_lossy(ffi_app_icon(cstr(key)))
}
///|
/// First entry of an icon chain (see @model.device_icon_chain) that the theme
/// has or that resolves on disk. "app:<key>" entries are looked up in the
/// .desktop files (and may resolve to a theme icon name or "file:<path>").
/// The last entry is returned if nothing matches, so the result is never empty.
pub fn resolve_icon(chain : Array[String]) -> String {
for name in chain {
if name.has_prefix("app:") {
let icon = app_icon(name[4:].to_owned())
if icon != "" {
return icon
}
} else if has_icon(name) {
return name
}
}
match chain.last() {
Some(n) => n
None => "image-missing"
}
}