kui-ffi 0.1.0-alpha.53

C API for kui (cdylib, staticlib on request, + include/kui.h)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Resources: images, fonts and sounds registered through a context, and
//! the playback commands a host with its own loop drains.

use super::*;

/// The byte length of a `w × h` RGBA buffer at `rgba`, or `None` for a
/// null pointer, an empty size, or one whose length overflows (or passes
/// `isize::MAX`, which no slice may) — checked before the slice is made,
/// since a wrapped length is undefined behaviour even unread.
fn rgba_len(rgba: *const u8, w: u32, h: u32) -> Option<usize> {
    if rgba.is_null() || w == 0 || h == 0 {
        return None;
    }
    (w as usize)
        .checked_mul(h as usize)?
        .checked_mul(4)
        .filter(|&n| n <= isize::MAX as usize)
}

/// Registers a w×h RGBA image (pixels copied); returns its handle, 0 on
/// failure. Draw it with `kui_image`; free it with `kui_image_remove`.
#[unsafe(no_mangle)]
pub extern "C" fn kui_image_add(ptr: *mut KuiCtx, w: u32, h: u32, rgba: *const u8) -> u64 {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        let Some(len) = rgba_len(rgba, w, h) else {
            return 0;
        };
        let data = unsafe { std::slice::from_raw_parts(rgba, len) }.to_vec();
        c.core().resources.add_image(w, h, data).to_ffi()
    })
}

/// Replaces an image's pixels in place (copied): the handle is unchanged,
/// so every node showing it draws the new pixels next frame; `w`/`h` may
/// differ from the registration. From the first update on the image is
/// drawn from a texture of its own, as a `KUI_QUAD_TEXTURE` quad. A dead
/// or foreign handle warns `foreign-resource` and changes nothing.
#[unsafe(no_mangle)]
pub extern "C" fn kui_image_update(ptr: *mut KuiCtx, id: u64, w: u32, h: u32, rgba: *const u8) {
    guard((), || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return;
        };
        let Some(len) = rgba_len(rgba, w, h) else {
            return;
        };
        let data = unsafe { std::slice::from_raw_parts(rgba, len) };
        // Into a buffer the core recycles, not a fresh copy a frame.
        c.core()
            .update_image_with(kui_core::ImageId::from_ffi(id), w, h, |px| {
                px.copy_from_slice(data)
            });
    });
}

/// The pixels behind an image handle, for a host that renders the draw
/// list itself and meets a `KUI_QUAD_TEXTURE` quad: `w`, `h` and `rgba`
/// (w×h×4 bytes) are written and true returned when the handle is live
/// here. The bytes are borrowed and valid until the next call of this
/// function or `kui_image_update` on the same handle.
#[unsafe(no_mangle)]
pub extern "C" fn kui_image_pixels(
    ptr: *mut KuiCtx,
    id: u64,
    w: *mut u32,
    h: *mut u32,
    rgba: *mut *const u8,
) -> bool {
    guard(false, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return false;
        };
        if w.is_null() || h.is_null() || rgba.is_null() {
            return false;
        }
        let Some((iw, ih, px)) = c.core().image_pixels(kui_core::ImageId::from_ffi(id)) else {
            return false;
        };
        // Kept on the context so the pointer outlives this call — the
        // `Arc` holds the bytes even if an update replaces the entry's.
        c.image_pixels = Some(px);
        unsafe {
            *w = iw;
            *h = ih;
            *rgba = c.image_pixels.as_ref().unwrap().as_ptr();
        }
        true
    })
}

/// Registers a font from file bytes (TTF/OTF/TTC, copied); returns its
/// handle for `KuiTextStyle.font`, 0 when the data holds no usable face.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_add(ptr: *mut KuiCtx, data: *const u8, len: usize) -> u64 {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        if data.is_null() || len == 0 {
            return 0;
        }
        let bytes = unsafe { std::slice::from_raw_parts(data, len) }.to_vec();
        c.core().add_font_data(bytes).map_or(0, |id| id.to_ffi())
    })
}

/// Registers an installed font by family name; 0 when none matches.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_add_system(ptr: *mut KuiCtx, name: KuiStr) -> u64 {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        c.core()
            .add_system_font(&kstr(name))
            .map_or(0, |id| id.to_ffi())
    })
}

/// The family names `kui_font_add_system` can take — every face the
/// context knows, installed or loaded, sorted and deduplicated — written
/// into `out` up to `cap` and the total returned, so a short array can be
/// resized and the call repeated. Strings are borrowed until the next
/// call on this context. What Node's `systemFontFamilies()` answers.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_families(ptr: *mut KuiCtx, out: *mut KuiStr, cap: usize) -> usize {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        c.font_families = c.core().system_font_families();
        let n = c.font_families.len();
        if out.is_null() {
            return n;
        }
        for (i, name) in c.font_families.iter().take(cap).enumerate() {
            unsafe {
                out.add(i).write(KuiStr {
                    ptr: name.as_ptr(),
                    len: name.len(),
                })
            };
        }
        n
    })
}

/// Every family [`kui_font_families`] names, one per family and in its
/// order, with what its faces say they are (monospaced, the weights, an
/// italic), written into `out` up to `cap` and the total
/// returned, as `kui_font_families` does. Read from what the font database
/// recorded when it scanned each face: nothing is loaded or shaped. The
/// names and weight arrays are borrowed until the next call on this
/// context. What Node's `systemFonts()` answers.
#[unsafe(no_mangle)]
pub extern "C" fn kui_system_fonts(ptr: *mut KuiCtx, out: *mut KuiSystemFont, cap: usize) -> usize {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        c.system_fonts = c.core().system_fonts();
        let n = c.system_fonts.len();
        if out.is_null() {
            return n;
        }
        for (i, font) in c.system_fonts.iter().take(cap).enumerate() {
            unsafe {
                out.add(i).write(KuiSystemFont {
                    family: KuiStr {
                        ptr: font.family.as_ptr(),
                        len: font.family.len(),
                    },
                    weights: font.weights.as_ptr(),
                    weight_count: font.weights.len() as u32,
                    monospaced: u32::from(font.monospaced),
                    italic: u32::from(font.italic),
                })
            };
        }
        n
    })
}

/// Registers a WGSL fragment function; 0 when it does not compile, with a
/// `fragment-rejected` warning carrying the message. Idempotent by source.
#[unsafe(no_mangle)]
pub extern "C" fn kui_fragment_add(ptr: *mut KuiCtx, wgsl: KuiStr) -> u64 {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        c.core()
            .add_fragment(&kstr(wgsl))
            .map_or(0, |id| id.to_ffi())
    })
}

/// Forgets a registered fragment; nodes still naming it draw nothing.
#[unsafe(no_mangle)]
pub extern "C" fn kui_fragment_remove(ptr: *mut KuiCtx, id: u64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().remove_fragment(kui_core::FragmentId::from_ffi(id));
        }
    })
}

/// The whole WGSL module behind a handle — the app's source between the
/// core's prelude and epilogue — for a host that compiles it itself. The
/// string is borrowed and valid until the next call; false when the handle
/// is not live in this session.
#[unsafe(no_mangle)]
pub extern "C" fn kui_fragment_source(ptr: *mut KuiCtx, id: u64, out: *mut KuiStr) -> bool {
    guard(false, || {
        let (Some(c), false) = (unsafe { ctx(ptr) }, out.is_null()) else {
            return false;
        };
        let Some(src) = c
            .core()
            .fragment_module_source(kui_core::FragmentId::from_ffi(id))
        else {
            return false;
        };
        // Kept on the context so the pointer outlives this call, the way
        // every other borrowed string this header hands out is.
        c.fragment_source = src;
        unsafe {
            *out = KuiStr {
                ptr: c.fragment_source.as_ptr(),
                len: c.fragment_source.len(),
            }
        };
        true
    })
}

/// Registers a font file by path (memory-mapped); 0 when it cannot be read
/// or holds no usable face.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_load_file(ptr: *mut KuiCtx, path: KuiStr) -> u64 {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        let path = kstr(path).into_owned();
        c.core().load_font_file(path).map_or(0, |id| id.to_ffi())
    })
}

/// Loads every font file under a folder (recursively) so its families can
/// be picked by name with `kui_font_add_system`; returns the face count.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_load_dir(ptr: *mut KuiCtx, dir: KuiStr) -> usize {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        let dir = kstr(dir).into_owned();
        c.core().load_fonts_dir(dir)
    })
}

/// Scans the system's fonts again, so a font installed while the app runs
/// is found (`Core::reload_system_fonts`); returns how many faces came and
/// went, 0 when nothing did.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_reload_system(ptr: *mut KuiCtx) -> usize {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        c.core().reload_system_fonts()
    })
}

/// The families asked, in order, for a character the text's own family
/// has no glyph for, before the platform's fallback list
/// (`Core::set_fallback_fonts`): `len` font handles at `ids`, none (NULL
/// or 0) for the platform's list alone. A handle that names no font is
/// left out. KUI_FONT_MONO text asks them straight after its own face,
/// ahead of the machine's other monospaced faces. A new list shapes every
/// text again; the same list twice is nothing.
///
/// # Safety
/// `ids` points at `len` handles, or is NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn kui_font_set_fallback(ptr: *mut KuiCtx, ids: *const u64, len: usize) {
    guard((), || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return;
        };
        let ids: Vec<kui_core::FontId> = if ids.is_null() {
            Vec::new()
        } else {
            unsafe { std::slice::from_raw_parts(ids, len) }
                .iter()
                .map(|&id| kui_core::FontId::from_ffi(id))
                .collect()
        };
        c.core().set_fallback_fonts(&ids);
    });
}

/// Forgets a registered font; text still naming it falls back to the
/// family.
#[unsafe(no_mangle)]
pub extern "C" fn kui_font_remove(ptr: *mut KuiCtx, id: u64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().remove_font(kui_core::FontId::from_ffi(id));
        }
    });
}

// -- Audio -------------------------------------------------------------------
// Sounds are resources, playback is commands the driver drains; kui_run
// plays them itself, a host with its own loop drains kui_take_audio_commands.

/// Registers a sound from its encoded file bytes (wav/ogg/mp3/flac, copied);
/// returns its handle for `KuiSpec.click_sound` / `kui_audio` / `kui_play`,
/// 0 when empty.
#[unsafe(no_mangle)]
pub extern "C" fn kui_sound_add(ptr: *mut KuiCtx, data: *const u8, len: usize) -> u64 {
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        if data.is_null() || len == 0 {
            return 0;
        }
        let bytes = unsafe { std::slice::from_raw_parts(data, len) }.to_vec();
        c.core().add_sound(bytes).to_ffi()
    })
}

/// Forgets a registered sound and stops its playbacks.
#[unsafe(no_mangle)]
pub extern "C" fn kui_sound_remove(ptr: *mut KuiCtx, id: u64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().remove_sound(kui_core::SoundId::from_ffi(id));
        }
    });
}

/// Starts a playback; returns its id for kui_stop / kui_set_volume /
/// kui_pause / kui_resume. `opts` may be NULL (defaults). A non-NULL `tag`
/// (consumed) asks for a `{kind="sound", phase="ended", playback, tag}`
/// event when the playback finishes on its own.
#[unsafe(no_mangle)]
pub extern "C" fn kui_play(
    ptr: *mut KuiCtx,
    sound: u64,
    opts: *const KuiPlay,
    tag: *mut KuiValue,
) -> u64 {
    guard(0, || {
        let tag = take_msg(tag);
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        let mut po = kui_core::PlayOptions::default();
        if let Some(o) = unsafe { opts.as_ref() } {
            po.volume = o.volume;
            po.looped = o.looped != 0;
            po.fade_in_ms = o.fade_in_ms;
        }
        po.tag = tag;
        c.core().play(kui_core::SoundId::from_ffi(sound), po).0
    })
}

/// Stops a playback from [`kui_play`], fading out over `fade_ms` (0 for
/// at once).
#[unsafe(no_mangle)]
pub extern "C" fn kui_stop(ptr: *mut KuiCtx, playback: u64, fade_ms: f32) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().stop(kui_core::PlaybackId(playback), fade_ms);
        }
    });
}

/// Sets a playback's volume (linear amplitude, 0..1), easing to it over
/// `tween_ms`.
#[unsafe(no_mangle)]
pub extern "C" fn kui_set_volume(ptr: *mut KuiCtx, playback: u64, volume: f32, tween_ms: f32) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core()
                .set_volume(kui_core::PlaybackId(playback), volume, tween_ms);
        }
    });
}

/// Pauses a playback, fading out over `fade_ms`.
#[unsafe(no_mangle)]
pub extern "C" fn kui_pause(ptr: *mut KuiCtx, playback: u64, fade_ms: f32) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().pause(kui_core::PlaybackId(playback), fade_ms);
        }
    });
}

/// Resumes a paused playback, fading in over `fade_ms`.
#[unsafe(no_mangle)]
pub extern "C" fn kui_resume(ptr: *mut KuiCtx, playback: u64, fade_ms: f32) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().resume(kui_core::PlaybackId(playback), fade_ms);
        }
    });
}

/// Sets the master volume every playback is scaled by (0..1), easing to
/// it over `tween_ms`.
#[unsafe(no_mangle)]
pub extern "C" fn kui_set_master_volume(ptr: *mut KuiCtx, volume: f32, tween_ms: f32) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().set_master_volume(volume, tween_ms);
        }
    });
}

/// An audio node: a playback retained by key while the frame declares it
/// (present = playing, gone = stopped; volume/paused apply live, a changed
/// src restarts). `finish` changes what gone means — the playback is
/// released to play itself out rather than stopped, except for a loop.
/// Empty label = a key from the tree position. `tag` (nullable, consumed)
/// rides the `ended` event, and survives a release. Returns the node key.
#[unsafe(no_mangle)]
pub extern "C" fn kui_audio(
    ptr: *mut KuiCtx,
    label: KuiStr,
    spec: *const KuiAudio,
    tag: *mut KuiValue,
) -> u64 {
    guard(0, || {
        let tag = take_msg(tag);
        let (Some(c), Some(a)) = (unsafe { ctx(ptr) }, unsafe { spec.as_ref() }) else {
            return 0;
        };
        let mut s = kui_core::AudioSpec::new(kui_core::SoundId::from_ffi(a.src))
            .volume(a.volume)
            .paused(a.paused != 0);
        if a.looped != 0 {
            s = s.looped();
        }
        if a.finish != 0 {
            s = s.finish();
        }
        s.tag = tag;
        let core = c.core();
        if label.ptr.is_null() || label.len == 0 {
            core.audio_node(s).0
        } else {
            core.audio_node_keyed(&kstr(label), s).0
        }
    })
}

/// Drains queued audio commands into `out` (up to `cap`; the rest are
/// dropped, so size it generously); returns the count. Only for hosts
/// driving their own audio device — kui_run plays them itself.
#[unsafe(no_mangle)]
pub extern "C" fn kui_take_audio_commands(
    ptr: *mut KuiCtx,
    out: *mut KuiAudioCommand,
    cap: usize,
) -> usize {
    use kui_core::AudioCommand as A;
    guard(0, || {
        let Some(c) = (unsafe { ctx(ptr) }) else {
            return 0;
        };
        if out.is_null() || cap == 0 {
            return 0;
        }
        let cmds = c.core().take_audio_commands();
        let n = cmds.len().min(cap);
        for (i, cmd) in cmds.into_iter().take(n).enumerate() {
            let mut o = KuiAudioCommand::default();
            match cmd {
                A::Play {
                    playback,
                    sound,
                    volume,
                    looped,
                    fade_in_ms,
                } => {
                    o.kind = KUI_AUDIO_PLAY;
                    o.playback = playback.0;
                    o.sound = sound.to_ffi();
                    o.volume = volume;
                    o.ms = fade_in_ms;
                    o.looped = looped as u32;
                }
                A::Stop { playback, fade_ms } => {
                    o.kind = KUI_AUDIO_STOP;
                    o.playback = playback.0;
                    o.ms = fade_ms;
                }
                A::SetVolume {
                    playback,
                    volume,
                    tween_ms,
                } => {
                    o.kind = KUI_AUDIO_SET_VOLUME;
                    o.playback = playback.0;
                    o.volume = volume;
                    o.ms = tween_ms;
                }
                A::Pause { playback, fade_ms } => {
                    o.kind = KUI_AUDIO_PAUSE;
                    o.playback = playback.0;
                    o.ms = fade_ms;
                }
                A::Resume { playback, fade_ms } => {
                    o.kind = KUI_AUDIO_RESUME;
                    o.playback = playback.0;
                    o.ms = fade_ms;
                }
                A::MasterVolume { volume, tween_ms } => {
                    o.kind = KUI_AUDIO_MASTER_VOLUME;
                    o.volume = volume;
                    o.ms = tween_ms;
                }
                A::Unload { sound } => {
                    o.kind = KUI_AUDIO_UNLOAD;
                    o.sound = sound.to_ffi();
                }
            }
            unsafe { out.add(i).write(o) };
        }
        n
    })
}

/// A host driving its own device reports a playback finished on its own;
/// a tagged one becomes a `sound` event for kui_poll_event.
#[unsafe(no_mangle)]
pub extern "C" fn kui_audio_ended(ptr: *mut KuiCtx, playback: u64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().audio_ended(kui_core::PlaybackId(playback));
            let pending = c.core().take_pending_events();
            c.absorb(pending);
        }
    });
}

/// The same host reports that a stop it drained landed on a playback
/// still running, `at` seconds in: a one-shot `audio` node that went away
/// without `finish` is named in a `truncated-playback` warning
/// ([`kui_take_warnings`]); any other stop reports nothing.
#[unsafe(no_mangle)]
pub extern "C" fn kui_audio_truncated(ptr: *mut KuiCtx, playback: u64, at: f64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().audio_truncated(kui_core::PlaybackId(playback), at);
        }
    });
}

/// The same host reports that its device refused a play it drained: a
/// tagged playback becomes a `sound` event with phase `refused` for
/// kui_poll_event, and the node that asked is named in a
/// `playback-refused` warning either way.
#[unsafe(no_mangle)]
pub extern "C" fn kui_audio_refused(ptr: *mut KuiCtx, playback: u64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().audio_refused(kui_core::PlaybackId(playback));
            let pending = c.core().take_pending_events();
            c.absorb(pending);
        }
    });
}

/// Forgets a registered image; nodes still naming it draw nothing.
#[unsafe(no_mangle)]
pub extern "C" fn kui_image_remove(ptr: *mut KuiCtx, id: u64) {
    guard((), || {
        if let Some(c) = unsafe { ctx(ptr) } {
            c.core().remove_image(kui_core::ImageId::from_ffi(id));
        }
    });
}