Camera: C ISP pipeline, contrast autofocus, and VFR video
CI / test (push) Canceled after 0s

- Add chandra-camera-isp.c (C/OpenMP) for Quad-Bayer unpack, CCM, and tone mapping, with a NumPy fallback when it is not built
- Add non-blocking contrast-detection VCM autofocus, with lens subdev discovery on the sensor's I2C bus
- Tune Quad-Bayer AE: a video-mode vblank cap, damped steps, and full analog gain before extending blanking
- Record variable-frame-rate video through a streaming Matroska muxer, and count dropped frames
- Ship libcamera IPA tuning files for imx376, imx519, and uncalibrated sensors
- Map camera buffers by fd and sync them with dma-buf ioctls
This commit is contained in:
nandi committed 2026-11-28 19:25:43 -08:00
1 parent 851c39d827
commit 52b42890d6
34 files changed
+2851 -364

No files matched your search

+214
View File
@@ -368,6 +368,197 @@ pub fn EmojiFont::has(self : EmojiFont, text : String) -> Bool raise EmojiFontEr
gs.length() == 1 && self.glyph_png(gs[0]) is Some(_)
}
///| Whether `cp` is an emoji skin tone modifier (Fitzpatrick Type-1-2 through Type-6).
fn is_skin_tone(cp : Int) -> Bool {
cp >= 0x1F3FB && cp <= 0x1F3FF
}
///| Whether `text` contains any code point >= U+203C (covering emoji, keycap combining
/// enclosing keycap U+20E3, and variation selector U+FE0F).
pub fn text_may_have_emoji(text : String) -> Bool {
for ch in text {
if ch.to_int() >= 0x203C {
return true
}
}
false
}
///| Default-ignorable emoji joiner / variation selectors (U+FE0E, U+FE0F, U+200D).
pub fn is_ignorable_emoji_mod(cp : Int) -> Bool {
cp == 0xFE0E || cp == 0xFE0F || cp == 0x200D
}
///| Whether a non-ASCII code point >= U+203C sits in a Unicode block that can start an emoji.
fn may_start_emoji_non_ascii(cp : Int) -> Bool {
(cp >= 0x203C && cp <= 0x21AA) ||
(cp >= 0x2300 && cp <= 0x27BF) ||
(cp >= 0x2934 && cp <= 0x2935) ||
(cp >= 0x2B00 && cp <= 0x2BFF) ||
cp == 0x3030 ||
cp == 0x303D ||
cp == 0x3297 ||
cp == 0x3299 ||
(cp >= 0x1F000 && cp <= 0x1FBFF)
}
///| Exclusive end index of the maximal candidate emoji cluster starting at `chars[start]`,
/// or `start` when `chars[start]` cannot start an emoji sequence.
pub fn candidate_end(chars : Array[Char], start : Int) -> Int {
let n = chars.length()
if start < 0 || start >= n {
return start
}
let cp = chars[start].to_int()
if is_ignorable_emoji_mod(cp) || cp == 0x20E3 {
return start
}
if cp < 0x80 {
// ASCII can only start a keycap emoji (#️⃣, *️⃣, 0️⃣..9️⃣).
let is_keycap = cp == 0x23 || cp == 0x2A || (cp >= 0x30 && cp <= 0x39)
if !is_keycap {
return start
}
if start + 1 < n && chars[start + 1].to_int() == 0x20E3 {
return start + 2
}
if start + 2 < n && chars[start + 1].to_int() == 0xFE0F && chars[start + 2].to_int() == 0x20E3 {
return start + 3
}
return start
}
if cp < 0x203C {
// Only ©️ / ®️ with explicit emoji presentation selector.
if (cp == 0xA9 || cp == 0xAE) && start + 1 < n && chars[start + 1].to_int() == 0xFE0F {
return start + 2
}
return start
}
if !may_start_emoji_non_ascii(cp) {
return start
}
if cp >= 0x1F1E6 && cp <= 0x1F1FF {
if start + 1 < n {
let next = chars[start + 1].to_int()
if next >= 0x1F1E6 && next <= 0x1F1FF {
return start + 2
}
}
return start + 1
}
let limit = if start + 16 < n { start + 16 } else { n }
if cp == 0x1F3F4 && start + 1 < limit {
let first_tag = chars[start + 1].to_int()
if first_tag >= 0xE0020 && first_tag <= 0xE007E {
let mut j = start + 1
while j < limit - 1 {
let t = chars[j].to_int()
if t >= 0xE0020 && t <= 0xE007E {
j = j + 1
} else {
break
}
}
if j < limit && chars[j].to_int() == 0xE007F {
return j + 1
}
}
}
let mut i = start + 1
if i < limit && chars[i].to_int() == 0xFE0F {
i = i + 1
}
if i < limit && is_skin_tone(chars[i].to_int()) {
i = i + 1
}
while i + 1 < limit && chars[i].to_int() == 0x200D {
let next = chars[i + 1].to_int()
if next < 0x80 || is_ignorable_emoji_mod(next) || next == 0x20E3 {
break
}
i = i + 2
if i < limit && chars[i].to_int() == 0xFE0F {
i = i + 1
}
if i < limit && is_skin_tone(chars[i].to_int()) {
i = i + 1
}
}
i
}
///| Match the longest emoji sequence starting at `chars[start]` accepted by `has_emoji`.
/// Respects U+FE0E text presentation and keeps bare BMP symbols monochrome when `has_text_glyph`
/// reports the text font has them.
pub fn match_with(
chars : Array[Char],
start : Int,
has_text_glyph : (Int) -> Bool,
has_emoji : (String) -> Bool,
) -> (Int, String)? {
let max_end = candidate_end(chars, start)
if max_end <= start {
return None
}
let cp = chars[start].to_int()
if start + 1 < chars.length() && chars[start + 1].to_int() == 0xFE0E && has_text_glyph(cp) {
return None
}
let mut end = max_end
while end > start {
if chars[end - 1].to_int() == 0x200D {
end = end - 1
continue
}
if cp < 0x80 && chars[end - 1].to_int() != 0x20E3 {
end = end - 1
continue
}
if end == start + 1 && cp < 0x1F000 && has_text_glyph(cp) {
return None
}
let sb = StringBuilder::new()
for k = start; k < end; k = k + 1 {
sb.write_char(chars[k])
}
let sub = sb.to_string()
if has_emoji(sub) {
return Some((end, sub))
}
end = end - 1
}
None
}
///| Match the longest emoji sequence starting at `chars[start]` that this font can draw.
pub fn EmojiFont::match_at(
self : EmojiFont,
chars : Array[Char],
start : Int,
has_text_glyph : (Int) -> Bool,
) -> (Int, String)? raise EmojiFontError {
if start < 0 || start >= chars.length() {
return None
}
let cp = chars[start].to_int()
if cp >= 0x80 && self.glyph(cp) == 0 {
return None
}
let mut err : EmojiFontError? = None
let res = match_with(chars, start, has_text_glyph, s => {
try self.has(s) catch {
e => {
err = Some(e)
false
}
}
})
match err {
Some(e) => raise e
None => res
}
}
///| The picture for `text`, `px` x `px` (the bitmap scaled to fit and centred), straight RGBA.
/// None when the font has no single picture for it.
pub fn EmojiFont::picture(self : EmojiFont, text : String, px : Int) -> @renderer.Pixmap? raise EmojiFontError {
@@ -515,3 +706,26 @@ pub fn EmojiSource::image(self : EmojiSource, text : String, px : Int, put : (@r
self.images.set(key, h)
h
}
///| Match the longest emoji sequence starting at `chars[start]` using the open font.
/// Opens the font lazily on first use; does not retry a failed open on every text draw call.
pub fn EmojiSource::match_at(
self : EmojiSource,
chars : Array[Char],
start : Int,
has_text_glyph : (Int) -> Bool,
) -> (Int, String)? {
if self.state is None {
ignore(self.font())
}
match self.state {
Some(Ok((_, f))) =>
try f.match_at(chars, start, has_text_glyph) catch {
EmojiFontError(why) => {
@sys.log("emoji: can't match inline emoji: " + why)
None
}
}
_ => None
}
}
+52
View File
@@ -68,3 +68,55 @@ test "a file that is not a colour emoji font is an error that says why" {
assert_true(msg.contains("no cmap table"))
assert_true(@emoji.missing_font_message("").contains("just install"))
}
///|
test "inline emoji matcher handles turtle, sequences, VS15/VS16, and BMP symbols" {
assert_false(@emoji.text_may_have_emoji("Regency 215-223 WiFi"))
assert_false(@emoji.text_may_have_emoji("Café • … — ©"))
assert_true(@emoji.text_may_have_emoji("🐢"))
assert_true(@emoji.text_may_have_emoji("Connected to 🐢 (72%)"))
assert_true(@emoji.text_may_have_emoji("#️⃣"))
assert_true(@emoji.text_may_have_emoji("©️"))
let f = open_font()
let all_have = fn(_cp : Int) { true }
let none_have = fn(_cp : Int) { false }
assert_eq(f.match_at("🐢".to_array(), 0, all_have), Some((1, "🐢")))
assert_eq(f.match_at("Connected to 🐢 (72%)".to_array(), 13, all_have), Some((14, "🐢")))
assert_eq(f.match_at("👍🏽!".to_array(), 0, all_have), Some((2, "👍🏽")))
assert_eq(f.match_at("#️⃣x".to_array(), 0, all_have), Some((3, "#️⃣")))
assert_eq(f.match_at("🇺🇸x".to_array(), 0, all_have), Some((2, "🇺🇸")))
assert_eq(f.match_at("👨‍👩‍👧‍👦x".to_array(), 0, all_have), Some((7, "👨‍👩‍👧‍👦")))
// Bare BMP symbols stay monochrome when the UI text font has them; VS16 switches to colour, VS15 keeps text.
assert_eq(f.match_at("▶".to_array(), 0, all_have), None)
assert_eq(f.match_at("▶️".to_array(), 0, all_have), Some((2, "▶️")))
assert_eq(f.match_at("▶\u{FE0E}".to_array(), 0, all_have), None)
assert_eq(f.match_at("☀".to_array(), 0, none_have), Some((1, "☀")))
// Non-emoji ASCII / CJK / unsupported Emoji 18.0 characters do not match.
assert_eq(f.match_at("#1".to_array(), 0, all_have), None)
assert_eq(f.match_at("日本語".to_array(), 0, none_have), None)
let cracking = @emoji.all().filter(e => e.name == "cracking face")[0]
assert_eq(f.match_at(cracking.text.to_array(), 0, none_have), None)
// Noto Color Emoji's turtle renders olive-green opaque pixels at inline size.
let p = f.picture("🐢", 16).unwrap()
assert_eq((p.width, p.height), (16, 16))
let mut green = 0
for i = 0; i < p.width * p.height; i = i + 1 {
let o = i * 4
let r = p.data[o].to_int()
let g = p.data[o + 1].to_int()
let b = p.data[o + 2].to_int()
let a = p.data[o + 3].to_int()
if a > 200 && g > r && g > b + 40 {
green = green + 1
}
}
assert_true(green > 10)
let src = @emoji.EmojiSource::new()
assert_eq(src.match_at("🐢".to_array(), 0, all_have), Some((1, "🐢")))
}
+40
View File
@@ -69,6 +69,40 @@ fn rasterise(slot : Int, cp : Int, size : Int, embolden : Bool) -> @renderer.Gly
}
}
///|
let loaded : FixedArray[Bool] = FixedArray::make(4, false)
///|
fn pick_slot(bold : Bool, mono : Bool) -> Int {
let has_mono = loaded[0]
let has_sans = loaded[2]
if !has_mono && !has_sans {
return -1
}
let has_bold = has_mono && loaded[1]
if mono && has_mono {
if bold && has_bold {
1
} else {
0
}
} else if has_sans {
2
} else {
0
}
}
///| Whether the face used for (`bold`, `mono`) has a glyph for `cp`.
pub fn has_glyph(cp : Int, bold : Bool, mono : Bool) -> Bool {
let slot = pick_slot(bold, mono)
if slot < 0 {
false
} else {
b_has_glyph(slot, cp)
}
}
///| Install Allo Variable (UI text, falling back to Adwaita Sans) and Adwaita Mono (code) as the renderer's
/// faces. Returns false (keeping the bitmap font) when no face can be found.
/// Slots: 0 mono, 1 mono bold, 2 sans. Sans is a variable font whose bold
@@ -77,9 +111,15 @@ pub fn install() -> Bool {
let has_mono = load_first(0, regular_paths)
let has_sans = load_first(2, sans_paths)
if !has_mono && !has_sans {
loaded[0] = false
loaded[1] = false
loaded[2] = false
return false
}
let has_bold = has_mono && load_first(1, bold_paths)
loaded[0] = has_mono
loaded[1] = has_bold
loaded[2] = has_sans
@renderer.set_glyph_source(fn(cp, size, bold, mono) {
if mono && has_mono {
if bold && has_bold {
+8
View File
@@ -24,6 +24,9 @@ extern "C" fn c_font_bitmap(
buf : Bytes,
) = "mp_font_bitmap"
///|
extern "C" fn c_font_has_glyph(slot : Int, cp : Int) -> Int = "mp_font_has_glyph"
///|
fn utf8(s : String) -> Bytes {
let out : Array[Byte] = []
@@ -68,3 +71,8 @@ fn b_glyph(slot : Int, cp : Int, size : Int) -> RawGlyph {
}
{ w, h, xoff: info[2], yoff: info[3], advance: info[4], coverage: buf }
}
///| Whether `slot` has a glyph for `cp` (not `.notdef`).
fn b_has_glyph(slot : Int, cp : Int) -> Bool {
c_font_has_glyph(slot, cp) != 0
}
+7
View File
@@ -61,3 +61,10 @@ void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h
if (w <= 0 || h <= 0 || Moonbit_array_length(buf) < w * h) return;
stbtt_MakeGlyphBitmap(fi, (unsigned char *)buf, w, h, w, scale, scale, stbtt_FindGlyphIndex(fi, cp));
}
/* 1 when `slot` has a glyph for code point `cp` (not .notdef), 0 otherwise. */
MOONBIT_FFI_EXPORT
int32_t mp_font_has_glyph(int32_t slot, int32_t cp) {
if (slot < 0 || slot >= MAX_SLOTS || !font_data[slot]) return 0;
return stbtt_FindGlyphIndex(&fonts[slot], cp) != 0 ? 1 : 0;
}
+39
View File
@@ -22,3 +22,42 @@ fn b_glyph(slot : Int, cp : Int, size : Int) -> RawGlyph {
coverage: Bytes::from_fixedarray(g.coverage),
}
}
///| Cached `.notdef` glyph (cp 0 at 16 px) per slot for wasm glyph-presence checks.
let wasm_notdef : Map[Int, RawGlyph] = {}
///| Cached `b_has_glyph` results keyed by `slot * 0x110000 + cp`.
let wasm_has_cache : Map[Int, Bool] = {}
///|
fn raw_glyph_eq(a : RawGlyph, b : RawGlyph) -> Bool {
a.w == b.w &&
a.h == b.h &&
a.xoff == b.xoff &&
a.yoff == b.yoff &&
a.advance == b.advance &&
a.coverage == b.coverage
}
///| Whether `slot` has a glyph for `cp` (not `.notdef`).
fn b_has_glyph(slot : Int, cp : Int) -> Bool {
if cp >= 0x1F000 {
return false
}
let key = slot * 0x110000 + cp
match wasm_has_cache.get(key) {
Some(v) => return v
None => ()
}
let notdef = match wasm_notdef.get(slot) {
Some(g) => g
None => {
let g = b_glyph(slot, 0, 16)
wasm_notdef.set(slot, g)
g
}
}
let has = !raw_glyph_eq(b_glyph(slot, cp, 16), notdef)
wasm_has_cache.set(key, has)
has
}
+1
View File
@@ -341,6 +341,7 @@ pub fn ChandraCompositor::new(
output_h : Int,
) -> ChandraCompositor? {
ignore(@font.install()) // Adwaita Mono; keeps the bitmap font if it's missing
@raster.install_emoji_text(fn(cp, bold, mono) { @font.has_glyph(cp, bold, mono) })
let server = match @wayland.WaylandServer::listen(socket_path, output_w, output_h) {
Some(s) => s
None => return None
+37
View File
@@ -298,3 +298,40 @@ test "desktop screenshots: icons, starfield, the Desktop tab" {
}
ignore(@sys.write_file_bytes("_build/desktop_settings.png", @renderer.encode_png(comp.compose_frame())))
}
///|
test "mobile tap on desktop icon with finger drift launches without moving any icon" {
let socket_path = "/tmp/wayland-moon-desk-mobile-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 540, 1170).unwrap()
comp.shell.apps.clear()
for i = 0; i < 6; i = i + 1 {
let id = "app" + i.to_string()
comp.shell.apps.push({
id,
name: ["Files", "Browser", "Terminal", "Editor", "Mail", "Music"][i],
comment: "",
category: "",
glyph: "",
})
comp.shell.exec.set(id, "true")
}
comp.shell.apps_dirty = true
assert_true(comp.shell.set_desktop("icon-desktop"))
ignore(comp.compose_frame())
// At 540x1170 with 96px medium cells and 20px margin, app5 is at column 0, row 5: center (68, 548).
// Tap with an 18 px touch-drift between press and release: must launch app5 and keep every icon in place.
comp.handle_input(@nested.InputEvent::PointerMove(68.0, 548.0), 10U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 11U)
comp.handle_input(@nested.InputEvent::PointerMove(86.0, 548.0), 12U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 13U)
ignore(comp.compose_frame())
assert_eq(comp.shell.recents[0], "app5")
assert_eq(comp.shell.apps[0].id, "app5")
let places = desk_setting(comp, "places")
assert_true(places.contains("app0=0,0"))
assert_true(places.contains("app5=0,5"))
// A deliberate drag (> 50 px) to column 1, row 0 (center 164, 68) still moves app5 there.
desk_drag(comp, 68, 548, 164, 68, 30U)
assert_true(desk_setting(comp, "places").contains("app5=1,0"))
comp.close()
}
+60
View File
@@ -129,3 +129,63 @@ test "the Wi-Fi and airplane switches, and status only without NetworkManager" {
click_row(comp, 1, 20U)
assert_eq(fake.actions.length(), n)
}
///| Whether any pixel in `r` looks like Noto Color Emoji's olive-green turtle (`g > r && g > b + 40`).
fn has_turtle_pixels(px : @renderer.Pixmap, r : @scene.Rect) -> Bool {
for y = r.y; y < r.y + r.h; y = y + 1 {
for x = r.x; x < r.x + r.w; x = x + 1 {
match px.pixel(x, y) {
Some(c) => {
let cr = c.r.to_int()
let cg = c.g.to_int()
let cb = c.b.to_int()
if cg > cr && cg > cb + 40 {
return true
}
}
None => ()
}
}
}
false
}
///| Whether any Text draw op inside `ops` contains `sub`.
fn ops_have_text(ops : Array[@scene.DrawOp], sub : String) -> Bool {
for op in ops {
match op {
Text(_, _, s, _, _, _, _) | MonoText(_, _, s, _, _, _, _) =>
if s.contains(sub) {
return true
}
_ => ()
}
}
false
}
///|
test "Wi-Fi SSID with turtle emoji survives wasm boundary and renders in colour" {
let comp = new_comp("net-turtle")
let fake = @network.FakeNet::new(
{ ..net_status(), name: "🐢" },
[
{ ssid: "🐢", signal: 72, secured: true, active: true, saved: true },
{ ssid: "🐢 5G", signal: 55, secured: true, active: false, saved: false },
],
)
comp.shell.set_network_backend(fake as &@network.NetBackend)
click_module(comp, "network", 1U)
comp.damage.mark_full()
let sg = comp.compose_scene().unwrap()
assert_true(ops_have_text(sg.panel_ops, "🐢"))
assert_true(ops_have_text(sg.panel_ops, "Connected to 🐢 (72%)"))
assert_true(ops_have_text(sg.panel_ops, "🐢 5G"))
let px = @renderer.render_scene(sg)
let slot = comp.shell.slot_of("network")
let btn = comp.shell.slot_rect(slot)
let pop = comp.shell.slot_popup_rect(slot)
assert_true(btn.w > 0 && pop.w > 0)
assert_true(has_turtle_pixels(px, btn))
assert_true(has_turtle_pixels(px, pop))
}
+5 -2
View File
@@ -35,7 +35,7 @@
#define BTN_LEFT_CODE 0x110
#define BTN_RIGHT_CODE 0x111
#define TOUCH_LONG_MS 500
#define TOUCH_DRAG_PX 12
#define TOUCH_DRAG_PX 18
/* ---- damage ---- */
@@ -451,7 +451,7 @@ static void handle_li_event(struct libinput_event *ev) {
if (g_touch_state == TOUCH_PENDING) {
int dx = g_px - g_touch_x0;
int dy = g_py - g_touch_y0;
if (dx < -TOUCH_DRAG_PX || dx > TOUCH_DRAG_PX || dy < -TOUCH_DRAG_PX || dy > TOUCH_DRAG_PX) {
if (dx * dx + dy * dy > TOUCH_DRAG_PX * TOUCH_DRAG_PX) {
touch_timer_disarm();
g_touch_state = TOUCH_DRAG;
q_push(EV_MOVE, g_touch_x0, g_touch_y0, 0, 0);
@@ -473,9 +473,12 @@ static void handle_li_event(struct libinput_event *ev) {
touch_timer_disarm();
g_touch_state = TOUCH_IDLE;
if (st == TOUCH_PENDING) {
g_px = g_touch_x0;
g_py = g_touch_y0;
q_push(EV_MOVE, g_px, g_py, 0, 0);
q_push(EV_BUTTON, BTN_LEFT_CODE, 1, 0, 0);
q_push(EV_BUTTON, BTN_LEFT_CODE, 0, 0, 0);
cursor_apply();
} else if (st == TOUCH_DRAG) {
q_push(EV_BUTTON, BTN_LEFT_CODE, 0, 0, 0);
}
+10
View File
@@ -90,3 +90,13 @@ pub fn emoji_has(texts : Array[String]) -> Array[Bool] {
pub fn emoji_image(text : String, px : Int) -> UInt {
emoji_source.image(text, px, p => @renderer.add_image(p))
}
///| Enable inline colour emoji fallback for general UI text.
pub fn install_emoji_text(has_glyph : (Int, Bool, Bool) -> Bool) -> Unit {
@renderer.set_emoji_source(
fn(chars, start, bold, mono) {
emoji_source.match_at(chars, start, cp => has_glyph(cp, bold, mono))
},
emoji_image,
)
}
+26
View File
@@ -163,3 +163,29 @@ pub fn emoji_has(texts : Array[String]) -> Array[Bool] {
pub fn emoji_image(text : String, px : Int) -> UInt {
@hostraster.emoji_image(text, px)
}
///| Cached emoji availability by sequence string for wasm-side `text_width` calculations.
let wasm_emoji_has : Map[String, Bool] = {}
///|
fn wasm_has_emoji(seq : String) -> Bool {
match wasm_emoji_has.get(seq) {
Some(v) => v
None => {
let res = @hostraster.emoji_has([seq])
let ok = res.length() > 0 && res[0]
wasm_emoji_has.set(seq, ok)
ok
}
}
}
///| Enable inline colour emoji matching for `@renderer.text_width` in the wasm compositor.
pub fn install_emoji_text(has_glyph : (Int, Bool, Bool) -> Bool) -> Unit {
@renderer.set_emoji_source(
fn(chars, start, bold, mono) {
@emoji.match_with(chars, start, cp => has_glyph(cp, bold, mono), wasm_has_emoji)
},
emoji_image,
)
}
+5 -1
View File
@@ -20,14 +20,18 @@ pub fn encode_png_compressed(Pixmap) -> Bytes
pub fn encode_ppm(Pixmap) -> Bytes
pub fn inline_emoji_px(Int32) -> Int32
pub fn render_scene(@scene.SceneGraph) -> Pixmap
pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap
pub fn set_image(UInt32, Pixmap) -> UInt32
pub fn set_emoji_source((Array[Char], Int32, Bool, Bool) -> (Int32, String)?, (String, Int32) -> UInt32) -> Unit
pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit
pub fn set_image(UInt32, Pixmap) -> UInt32
pub fn shm_thumbnail(@scene.ShmBufferSnapshot, Int32, Int32) -> Pixmap?
pub fn text_width(String, Int32, Bool, Bool) -> Int32
+130 -17
View File
@@ -496,10 +496,99 @@ pub fn set_glyph_source(f : (Int, Int, Bool, Bool) -> Glyph) -> Unit {
glyph_source.val = Some(f)
}
///| Pixel square size for inline colour emoji at font `size` (~1.2em, matching UI line height).
pub fn inline_emoji_px(size : Int) -> Int {
if size <= 0 {
0
} else {
(size * 6 + 4) / 5
}
}
///| Optional inline emoji matcher and image provider for general UI text.
let emoji_match_source : Ref[((Array[Char], Int, Bool, Bool) -> (Int, String)?)?] = {
val: None,
}
///|
let emoji_image_source : Ref[((String, Int) -> UInt)?] = { val: None }
///| Register inline colour emoji lookup (`match_at`) and image rasteriser (`image`).
pub fn set_emoji_source(
match_at : (Array[Char], Int, Bool, Bool) -> (Int, String)?,
image : (String, Int) -> UInt,
) -> Unit {
emoji_match_source.val = Some(match_at)
emoji_image_source.val = Some(image)
}
///|
priv enum TextPiece {
TextGlyph(Glyph)
TextEmoji(String)
}
///|
fn renderer_may_have_emoji(text : String) -> Bool {
for ch in text {
if ch.to_int() >= 0x203C {
return true
}
}
false
}
///|
fn renderer_ignorable_mod(cp : Int) -> Bool {
cp == 0xFE0E || cp == 0xFE0F || cp == 0x200D
}
///| Segment `text` into text glyphs and inline emoji clusters, returning `(pieces, total_w)`.
fn layout_text(
src : (Int, Int, Bool, Bool) -> Glyph,
match_at : (Array[Char], Int, Bool, Bool) -> (Int, String)?,
text : String,
size : Int,
bold : Bool,
mono : Bool,
) -> (Array[TextPiece], Int) {
let chars = text.to_array()
let epx = inline_emoji_px(size)
let pieces : Array[TextPiece] = []
let mut total_w = 0
let mut i = 0
while i < chars.length() {
match match_at(chars, i, bold, mono) {
Some((next, seq)) => {
pieces.push(TextEmoji(seq))
total_w = total_w + epx
i = next
}
None => {
let cp = chars[i].to_int()
if !renderer_ignorable_mod(cp) {
let g = src(cp, size, bold, mono)
pieces.push(TextGlyph(g))
total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 })
}
i = i + 1
}
}
}
(pieces, total_w)
}
///| Pixel width `text` would occupy when drawn with the given face.
pub fn text_width(text : String, size : Int, bold : Bool, mono : Bool) -> Int {
match glyph_source.val {
Some(src) => {
match emoji_match_source.val {
Some(match_at) if renderer_may_have_emoji(text) => {
let (_, w) = layout_text(src, match_at, text, size, bold, mono)
return w
}
_ => ()
}
let mut w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
@@ -525,12 +614,20 @@ fn draw_text_font(
bold : Bool,
clip : @scene.Rect?,
) -> Unit {
let glyphs : Array[Glyph] = []
let mut total_w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
glyphs.push(g)
total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 })
let epx = inline_emoji_px(size)
let (pieces, total_w) = match (emoji_match_source.val, emoji_image_source.val) {
(Some(match_at), Some(_)) if renderer_may_have_emoji(text) =>
layout_text(src, match_at, text, size, bold, mono)
_ => {
let pieces : Array[TextPiece] = []
let mut total_w = 0
for ch in text {
let g = src(ch.to_int(), size, bold, mono)
pieces.push(TextGlyph(g))
total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 })
}
(pieces, total_w)
}
}
let start_x = match align {
Left => x
@@ -545,21 +642,37 @@ fn draw_text_font(
let cb = color.b.to_int()
let ca = color.a.to_int()
let mut pen = start_x
for g in glyphs {
for row = 0; row < g.h; row = row + 1 {
for col = 0; col < g.w; col = col + 1 {
let cov = g.coverage[row * g.w + col].to_int()
if cov > 0 {
let px = pen + g.xoff + col
let py = baseline + g.yoff + row
blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip)
if g.embolden {
blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip)
for piece in pieces {
match piece {
TextGlyph(g) => {
for row = 0; row < g.h; row = row + 1 {
for col = 0; col < g.w; col = col + 1 {
let cov = g.coverage[row * g.w + col].to_int()
if cov > 0 {
let px = pen + g.xoff + col
let py = baseline + g.yoff + row
blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip)
if g.embolden {
blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip)
}
}
}
}
pen = pen + g.advance + (if g.embolden { 1 } else { 0 })
}
TextEmoji(seq) => {
match emoji_image_source.val {
Some(img_fn) if epx > 0 => {
let h = img_fn(seq, epx)
if h != 0U {
draw_image(dst, h, @scene.Rect::new(pen, y - epx / 2, epx, epx), clip)
}
}
_ => ()
}
pen = pen + epx
}
}
pen = pen + g.advance + (if g.embolden { 1 } else { 0 })
}
}
+55
View File
@@ -137,3 +137,58 @@ test "shm_thumbnail scales a client buffer; set_image swaps an image in place" {
@renderer.draw_ops(dst, [@scene.DrawOp::Image(@scene.Rect::new(0, 0, 2, 1), h)], 0, 0)
assert_eq(dst.pixel(0, 0), Some(@scene.Rgba::new(0, 0, 255, 255)))
}
///|
test "inline emoji source integrates into text_width and draw_ops" {
assert_eq(@renderer.inline_emoji_px(0), 0)
assert_eq(@renderer.inline_emoji_px(12), 15)
assert_eq(@renderer.inline_emoji_px(13), 16)
assert_eq(@renderer.inline_emoji_px(14), 17)
let epx = @renderer.inline_emoji_px(13)
let turtle = @renderer.Pixmap::new(epx, epx)
for y = 0; y < epx; y = y + 1 {
for x = 0; x < epx; x = x + 1 {
let o = (y * epx + x) * 4
turtle.data[o] = (110).to_byte()
turtle.data[o + 1] = (130).to_byte()
turtle.data[o + 2] = (58).to_byte()
turtle.data[o + 3] = b'\xff'
}
}
let th = @renderer.add_image(turtle)
let block = Bytes::make(4 * 8, b'\xff')
@renderer.set_glyph_source(fn(cp, _size, _bold, _mono) {
if cp == 0x1F422 {
{ w: 0, h: 0, xoff: 0, yoff: 0, advance: 6, coverage: b"", embolden: false }
} else if cp == 32 {
{ w: 0, h: 0, xoff: 0, yoff: 0, advance: 6, coverage: b"", embolden: false }
} else {
{ w: 4, h: 8, xoff: 0, yoff: -8, advance: 6, coverage: block, embolden: false }
}
})
@renderer.set_emoji_source(
fn(chars, start, _bold, _mono) {
if start < chars.length() && chars[start].to_int() == 0x1F422 {
Some((start + 1, "🐢"))
} else {
None
}
},
fn(seq, _px) { if seq == "🐢" { th } else { 0U } },
)
assert_eq(@renderer.text_width("Hi 🐢", 13, false, false), 18 + epx)
assert_eq(@renderer.text_width("Hi \u{200D}🐢\u{FE0F}", 13, false, false), 18 + epx)
let pm = @renderer.Pixmap::new(64, 40)
@renderer.draw_ops(
pm,
[@scene.DrawOp::Text(10, 20, "Hi 🐢", 13, @scene.Rgba::new(255, 255, 255, 255), Left, false)],
0,
0,
)
// 'H' at x=10..13, y=(20 + 8/2) - 8 .. = 16..23 is white; inline turtle at x=28..28+epx-1 is olive-green.
assert_eq(pm.pixel(11, 20), Some(@scene.Rgba::new(255, 255, 255, 255)))
assert_eq(pm.pixel(28 + epx / 2, 20), Some(@scene.Rgba::new(110, 130, 58, 255)))
}
+8 -2
View File
@@ -404,12 +404,18 @@ pub fn build_breeze_decoration(
let label = if title.length() > 0 { title } else { app_id }
let char_w = if tokens.font_size >= 14 { 12 } else { 6 }
let max_chars = (min_x - 8 - 14) / char_w
let chars = label.to_array()
let shown = if max_chars < 3 {
""
} else if label.length() <= max_chars {
} else if chars.length() <= max_chars {
label
} else {
label[:max_chars - 2].to_string() + ".."
let sb = StringBuilder::new()
for i = 0; i < max_chars - 2; i = i + 1 {
sb.write_char(chars[i])
}
sb.write_string("..")
sb.to_string()
}
ops.push(
Text(14, title_h / 2, shown, tokens.font_size, title_fg, Left, focused),
+9 -4
View File
@@ -93,6 +93,11 @@ fn module_dirs() -> Array[String] {
}
}
}
let checkout_dirs = ["build/components", "../build/components", "../../build/components"]
let test_cfg = @sys.getenv("CHANDRA_TEST_CONFIG") != ""
if test_cfg {
dirs.append(checkout_dirs)
}
let data_home = {
let x = @sys.getenv("XDG_DATA_HOME")
if x.length() > 0 { x } else { @sys.getenv("HOME") + "/.local/share" }
@@ -101,10 +106,10 @@ fn module_dirs() -> Array[String] {
dirs.push("/usr/local/share/chandra/modules")
dirs.push("/usr/share/chandra/modules")
dirs.push("modules") // the login session runs from /usr/local/share/chandra
// In a source checkout (and from a package directory when running its tests).
dirs.push("build/components")
dirs.push("../build/components")
dirs.push("../../build/components")
if !test_cfg {
// In a source checkout (and from a package directory when running its tests).
dirs.append(checkout_dirs)
}
dirs
}
+22 -2
View File
@@ -235,8 +235,28 @@ fn Plasmoid::str(self : Plasmoid, ptr : Int, len : Int) -> String {
None => ""
Some(b) => {
let sb = StringBuilder::new()
for i = 0; i < len; i = i + 1 {
sb.write_char((b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8)).unsafe_to_char())
let mut i = 0
while i < len {
let u = b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8)
if u >= 0xD800 && u <= 0xDBFF {
if i + 1 < len {
let lo = b[2 * (i + 1)].to_int() | (b[2 * (i + 1) + 1].to_int() << 8)
if lo >= 0xDC00 && lo <= 0xDFFF {
let cp = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00)
sb.write_char(cp.unsafe_to_char())
i = i + 2
continue
}
}
sb.write_char('\u{FFFD}')
i = i + 1
} else if u >= 0xDC00 && u <= 0xDFFF {
sb.write_char('\u{FFFD}')
i = i + 1
} else {
sb.write_char(u.unsafe_to_char())
i = i + 1
}
}
sb.to_string()
}
+6 -1
View File
@@ -189,7 +189,12 @@ static char *guest_str(Inst *in, int32_t ptr, int32_t units) {
size_t o = 0;
for (int i = 0; i < units; i++) {
uint32_t cp = u[i];
if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units) { cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); i++; }
if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units && u[i + 1] >= 0xDC00 && u[i + 1] < 0xE000) {
cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00);
i++;
} else if (cp >= 0xD800 && cp < 0xE000) {
cp = 0xFFFD;
}
if (cp < 0x80) out[o++] = (char)cp;
else if (cp < 0x800) { out[o++] = (char)(0xC0 | (cp >> 6)); out[o++] = (char)(0x80 | (cp & 0x3F)); }
else if (cp < 0x10000) { out[o++] = (char)(0xE0 | (cp >> 12)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); }